Micrometer and Zipkin: How to Trace HTTP Requests in Spring Boot 3

In a microservices architecture, it is common to have multiple services communicating with each other over the network. This distributed nature of the architecture can make it challenging to diagnose and debug issues when they arise. To address this problem, developers often use monitoring(Micrometer) and tracing tools(Zipkin) to track the flow of requests between microservices.

In this tutorial, you will learn how to trace HTTP requests using Micrometer and Zipkin.

What is Zipkin?

Zipkin is a tool that helps developers trace requests across different parts of a distributed system. Think of it as a way to see the path a request takes as it moves between different microservices. This can be really useful for understanding how long it takes for requests to be processed, where bottlenecks are, and what might be causing problems. With Zipkin, developers can quickly figure out what’s going on when things go wrong and work to optimize their systems.

Using Zipkin is straightforward: the tool collects data from the different parts of the system and then displays it in a user-friendly way. This makes it easy to see what’s happening with requests and pinpoint where things might be slowing down. Zipkin works with different programming languages and frameworks and can integrate with other tools like Prometheus and Grafana. By using Zipkin, developers can gain a better understanding of how their distributed systems are performing and make improvements to ensure they’re running smoothly.

Starting up Zipkin

Starting up Zipkin is easy! First, make sure you have Docker installed on your computer. Then, open up your terminal and enter the following command:

docker run -p 9411:9411 openzipkin/zipkin:latest

This command tells Docker to download the latest version of Zipkin and start it up on your computer. You should see some output in your terminal as Docker sets everything up.

Once Zipkin is up and running, you can open up your web browser and go to http://localhost:9411/zipkin/. This will take you to the Zipkin web interface, where you can start exploring your traces and understanding how your microservices are interacting with each other.

And that’s it! With just a few simple commands, you can start using Zipkin to monitor and debug your microservices.

No traces in Zipkin?

After starting up Zipkin using the Docker command I have mentioned, you may notice that there are no traces visible in the web interface. That’s because Zipkin only displays traces that have been generated by your microservices.

To see traces in Zipkin, you’ll need to set up your microservice application to use Micrometer. Once your application is configured to use Micrometer, you can start generating HTTP requests between your microservices. As these requests are made, Zipkin will start collecting data and displaying it in the form of traces.

So don’t worry if you don’t see any traces at first!

What is Micrometer?

Micrometer is a tool that helps developers keep track of how their microservices are performing. It does this by collecting and displaying data about things like response times, errors, and how many requests are being made. Think of it like a dashboard for a car – it gives you a quick way to see what’s going on and lets you know if anything needs attention.

By using Micrometer, developers can gain insights into the performance of their microservices and make informed decisions about optimizing their systems. The library enables easy tracking of custom metrics, giving developers greater control over monitoring specific aspects of their application’s performance.

Adding Micrometer to Spring Boot 3 Application

1. Add Micrometer Maven Dependencies

To add Micrometer to your Spring Boot application, you’ll need to include a few additional dependencies in your project. These dependencies are what allow Micrometer to collect and display data about your application’s performance.

<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-observation</artifactId>
</dependency>
<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-tracing-bridge-brave</artifactId>
</dependency>
<dependency>
    <groupId>io.zipkin.reporter2</groupId>
    <artifactId>zipkin-reporter-brave</artifactId>
</dependency>

2. Add Spring Boot Actuator Dependency

To use Micrometer with your Spring Boot application, you’ll need to add a dependency called “spring-boot-starter-actuator”. This dependency provides a range of monitoring and management features for your microservices, such as the ability to expose metrics and health information.

To add the “spring-boot-starter-actuator” dependency to your project, simply include the following line in your pom.xml file:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Once you’ve added this dependency, Micrometer will be able to collect and display data about your microservices’ performance. So make sure you include this dependency in your project if you’re planning to use Micrometer!

3. Update application.properties file

To ensure that Micrometer traces every action in your microservice application, you’ll need to configure it in the application.properties file. This can be done by adding the following property:

management.tracing.sampling.probability=1.0

By default, Micrometer only traces a fraction of the time, or 10% by default (0.1 probability). This is to reduce the amount of data collected and processed, which can be beneficial in certain cases. However, if you want to trace every action in your application, you can set the probability to 1.0.

This property configures the sampling probability for Micrometer’s tracing functionality. Essentially, it determines the likelihood that a given request or action will be traced. A probability of 1.0 means that every action will be traced, while a probability of 0.5 means that only half of the actions will be traced, and so on.

So, make sure to add this property to your application.properties file if you want to trace every action in your microservice application.

Tracing HTTP Request Sent with Rest Template

To trace HTTP request that was sent with RestTemplate, you will need to create an instance of a RestTemplate using the RestTemplateBuilder.

@Bean
public RestTemplate getRestTemplate(RestTemplateBuilder builder)
{
    return builder.build();
}

The code example above creates an instance of RestTemplate using the RestTemplateBuilder.

  • RestTemplate is a Java class that allows you to make HTTP requests to a web server and retrieve the response.
  • RestTemplateBuilder is a helper class that provides convenient methods for configuring and building RestTemplate instances.

The good news is that there is no additional configuration you need to do for tracing to start working.

You can then inject an instance of RestTemplate into your @RestController or @Service class and send HTTP request as usual.

RestTemplate restTemplate;
...

String albumsUrl = String.format(environment.getProperty("albums.url"), userId);
ResponseEntity<List<AlbumResponseModel>> albumsListResponse = restTemplate.exchange(albumsUrl, HttpMethod.GET, null, new ParameterizedTypeReference<List<AlbumResponseModel>>() { });
List<AlbumResponseModel> albumsList = albumsListResponse.getBody(); 

..

Tracing HTTP Request Sent with Feign

If you’re using OpenFeign to send HTTP requests in your Spring Boot 3 application, and you also want to use Micrometer for monitoring, then you’ll need to create a MicrometerCapability bean. Otherwise, a new TraceId will be generated for every SpanId, which can cause issues. So, it’s important to add the following code to a @Configuration class in your Spring Boot 3 application to avoid this problem. However, note that this requirement may change in the future.

@Bean
public Capability capability(final MeterRegistry registry) {
    return new MicrometerCapability(registry);
}

Once you have the following bean created, use Feign to send HTTP requests as usual. There is no other special configuration you need to make.

To learn how to use Feign to send HTTP requests, please read the following tutorial: Feign Client to call another microservice.

Once tracing starts working, you will will be able to inspect the flow of HTTP requests in Zipkin.

Tracing with Micrometer and Zipkin

Display TraceId and SpanId in a log file

To make TraceId and SpanId display in a log file, add the following configuration to the application.properties file.

logging.pattern.level=%5p [${spring.application.name:},%X{traceId:-},%X{spanId:-}]

The logging.pattern.level property is used to customize the way logging works in Spring Boot applications. When developers add the property with the value %5p [${spring.application.name:},%X{traceId:-},%X{spanId:-}] to the application.properties file, it adds some extra information to the logs.

Specifically, it includes the name of the application, the trace ID, and the span ID. The trace ID is like a unique ID for a request that goes through multiple parts of the system, while the span ID is a unique ID for a single action within that request. By adding this extra information to the logs, it makes it easier to track down problems and see how requests are moving through different parts of the system.

To get the trace ID and span ID, the system uses something called the Mapped Diagnostic Context, or MDC for short. This is a way of keeping track of information about a particular request as it moves through the system. The system uses a tool called Spring Cloud Sleuth to add the trace ID and span ID to the MDC.

Enable Logging DEBUG Level

You can also enable DEBUG mode for your application to see more logging details:

logging.level.org.springframework.web = DEBUG

Enable Debug level for specific class only

Alternatively, you can enable logging DEBUG level only for a class that is used to log information. For example, in my application the methods in the UsersServiceImpl class log information to a log file. To enable DEBUG level for this class only, I will add the following configuration property to application.properties file.

com.appsdeveloperblog.photoapp.api.users.service.UsersServiceImpl=DEBUG

Final words

I hope this tutorial helped you configure your Spring Boot 3 application to work with Micrometer and Zipkin. If you are interested to learn more about Spring Cloud, please check out other Spring Cloud tutorials.