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

Learning How to Map One-to-Many Relationships in JPA Spring Boot with PostgreSQL

  Introduction In this blog post, we explore how to effectively map one-to-many relationships using Spring Boot and PostgreSQL. This relationship type is common in database design, where one entity (e.g., a post) can have multiple related entities (e.g., comments). We'll dive into the implementation details with code snippets and provide insights into best practices. Understanding One-to-Many Relationships A one-to-many relationship signifies that one entity instance can be associated with multiple instances of another entity. In our case: Post Entity : Represents a blog post with fields such as id , title , content , and a collection of comments . Comment Entity : Represents comments on posts, including fields like id , content , and a reference to the post it belongs to. Mapping with Spring Boot and PostgreSQL Let's examine how we define and manage this relationship in our Spring Boot application: Post Entity  @Entity @Getter @Setter @Builder @AllArgsConstructor @NoArgsCon...

Understanding the Advertisement Domain: A Comprehensive Overview Part 2

 The advertisement domain is a complex and dynamic ecosystem that involves various technologies and platforms working together to deliver ads to users in a targeted and efficient manner. The primary goal is to connect advertisers with their target audience, increasing brand visibility, user engagement, and revenue generation. In this blog, we will delve into the different components of the advertisement ecosystem, key concepts like programmatic advertising and real-time bidding (RTB), and provide a practical example to illustrate how it all works. Key Components of the Advertisement Domain The advertisement domain broadly consists of the following components: Advertisers : These are brands or companies that want to promote their products or services through advertisements. They set up ad campaigns targeting specific user segments. Publishers : These are websites, mobile apps, or digital platforms that display ads to users. Publishers monetize their content by selling ad space to ad...

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 ...