Skip to main content

Monitoring Spring WebFlux Microservices with New Relic

 In this guide, we’ll go over how to monitor a reactive Spring Boot application using WebFlux, with New Relic’s @Trace annotation for detailed transaction tracking, custom parameters, and distributed tracing for complex service chains.

Prerequisites

  1. A Spring Boot WebFlux application.
  2. The New Relic Java agent configured in your application.
  3. Enable distributed tracing in newrelic.yml:
distributed_tracing:
  enabled: true

Step 1: Instrument the Main Endpoint

Our main entry point is the processRequest endpoint, which handles validation, external API calls, and data processing. Here’s how we add @Trace with dispatcher = true to make it a main transaction.



@RestController
public class SampleController {

    private static final Logger logger = LoggerFactory.getLogger(SampleController.class);
    private final SampleService sampleService;
    private final WebClient webClient;

    public SampleController(SampleService sampleService, WebClient.Builder webClientBuilder) {
        this.sampleService = sampleService;
        this.webClient = webClientBuilder.baseUrl("https://jsonplaceholder.typicode.com/todos/1").build();
    }

    @GetMapping("/process")
    @Trace(dispatcher = true, metricName = "Custom/processRequest")
    public Mono<String> processRequest(@RequestParam String input) {
        NewRelic.addCustomParameter("inputParam", input);
        logger.info("Starting process for Trace ID: {}", NewRelic.getAgent().getTransaction().getTraceId());

        return sampleService.validateInput(input)
                .flatMap(validatedInput -> callExternalService(validatedInput))
                .flatMap(externalData -> sampleService.processData(input, externalData))
                .doOnSuccess(result -> logger.debug("Processing complete with result: {}", result))
                .doOnError(e -> logger.error("Error processing request", e));
    }

    @Trace(async = true, metricName = "Custom/callExternalService")
    private Mono<String> callExternalService(String validatedInput) {
        NewRelic.addCustomParameter("validatedInput", validatedInput);
        return webClient.get()
                .retrieve()
                .bodyToMono(String.class)
                .doOnNext(data -> NewRelic.addCustomParameter("externalData", data))
                .doOnError(e -> logger.error("Failed to call external service", e));
    }
}


Step 2: Instrument Sub-Methods for Traceability

Here, we add @Trace on the validateInput and processData methods. This allows each method to show up as segments within the main transaction trace. Setting async = true supports WebFlux’s non-blocking nature.

@Service
public class SampleService {

    @Trace(async = true, metricName = "Custom/validateInput")
    public Mono<String> validateInput(String input) {
        NewRelic.addCustomParameter("validatedInput", input);
        return Mono.just("Validated: " + input);
    }

    @Trace(async = true, metricName = "Custom/processData")
    public Mono<String> processData(String input, String externalData) {
        NewRelic.addCustomParameter("combinedData", input + " " + externalData);
        return Mono.just("Processed Data: " + input + " at " + LocalTime.now());
    }
}

Step 3: Viewing Results in New Relic

Main Transaction: In New Relic APM under Transactions, locate Custom/processRequest to analyze the main endpoint’s performance.

Sub-Method Tracking: Under Distributed Traces or Transaction Traces, view the breakdown of validateInput, callExternalService, and processData as segments within each transaction.

Custom Parameters: View specific data by setting custom parameters (inputParam, validatedInput, etc.), which appear in Transaction Attributes and allow deeper filtering in NRQL queries.

Step 4: Using NRQL to Query Performance Data

With New Relic’s NRQL, query average durations and segment-specific data:

Average Duration of Validation:

NRQL

SELECT average(duration) 
FROM Span 
WHERE name = 'Custom/validateInput' 
SINCE 1 week ago
External Call Monitoring:



SELECT average(duration) 
FROM Span 
WHERE name = 'Custom/callExternalService' 
SINCE 1 week ago
Overall Transaction Time:



SELECT average(duration) 
FROM Transaction 
WHERE name = 'Custom/processRequest' 
SINCE 1 week ago


Ref doc for Newrelic account setup & Integration 

https://docs.newrelic.com/install/java/?deployment=gradle&framework=springboot

Let me know if you need a codebase as well.

Comments

Popular posts from this blog

Stay Updated As Software Engineer

Are you a software engineer looking to stay updated and grow in your field? We've got you covered with over 50 valuable resources to keep you on the cutting edge of technology. From newsletters to books, we've curated a diverse list just for you.   Newsletters:   Pragmatic Engineer: Link   TLDR: Link   Level-up software engineering: Link   Coding challenges: Link   Engineers Codex: Link   Techlead Mentor: Link   Saiyan Growth letter: Link   Wes Kao: Link   Addy Osmani: Link   And many more (see link below)   Books:   Engineering:   A Philosophy of Software Design Link   Clean Code Link   Communication & Soft Skills:   Smart Brevity Link   Connect: Building Exceptional Relationships Link   Crucial Conversations Link   Engineers Survival Guide Link   Leadership:   The Manager's Path Link   Staff Engineer: Leadership Beyond the Management Track Link   The Coaching Habit: Say Less, Ask More Link   While we can't list all 50+ resources here, this is a fantastic sta

12 Must-Know LeetCode+ Links for Coding Excellence

Introduction: Welcome to a comprehensive guide on mastering essential coding techniques and strategies! Whether you're a beginner or an experienced coder, these LeetCode+ links will elevate your skills and make you a more proficient problem solver. Let's dive into the world of algorithms, data structures, and coding patterns that will empower you to tackle complex challenges with confidence. 1. Sliding Window Learn the art of efficient sliding window techniques: Sliding Window - Part 1 and Sliding Window - Part 2 . Enhance your coding prowess and optimize algorithms with these invaluable insights. 2. Backtracking Unlock the power of backtracking algorithms: Backtracking . Discover how to systematically explore possibilities and find optimal solutions to a variety of problems. 3. Greedy Algorithm Master the art of making locally optimal choices for a globally optimal solution: Greedy Algorithm . Dive into strategies that prioritize immediate gains and lead to optimal outcomes

Tree Based Common problems and patterns

  Find the height of the tree. public class BinaryTreeHeight { public static int heightOfBinaryTree (TreeNode root) { if (root == null ) { return - 1 ; // Height of an empty tree is -1 } int leftHeight = heightOfBinaryTree(root.left); int rightHeight = heightOfBinaryTree(root.right); // Height of the tree is the maximum of left and right subtree heights plus 1 for the root return Math.max(leftHeight, rightHeight) + 1 ; } Find the Level of the Node. private static int findLevel (TreeNode root, TreeNode node, int level) { if (root == null ) { return - 1 ; // Node not found, return -1 } if (root == node) { return level; // Node found, return current level } // Check left subtree int leftLevel = findLevel(root.left, node, level + 1 ); if (leftLevel != - 1 ) { return leftLevel; // Node found in t