The labs on this site need JavaScript to run. The same content is written out below.
Learn › Architecture and operations › Observability
Distributed tracing
One request is slow, but which service is to blame?
Why it exists — A request handled on a single server could be followed through that server's logs alone, but once services were split and began calling each other over the network, one request passes through several servers and the time it takes is divided among them. Distributed tracing ties together the span records that each service leaves, using the same ID, and lays them out on a time axis, so you can see which span is slow across service boundaries.
Where it's used today — It is used in systems split into several services (microservice architecture) to find a slow request or the service that caused an error. In Spring Boot, Micrometer Tracing passes the trace ID along automatically and also prints it in the logs, and the collected records are viewed with tools such as Zipkin, Jaeger, and Grafana Tempo. Recording every request produces a large amount of stored data, so usually only a portion is collected as a sample.
One order request passes through the gateway, the order service, the payment service, and the external payment provider in turn. Logs pile up separately in each service, so without a common ID that ties together the logs of the same request, it is hard to find where the time went.
Checked against real execution · Eight combinations run and compared with three Spring Boot 4.1.1 servers (the gateway role played by a Spring MVC server), an untraced external payment provider server, and MySQL 8.4.11. Tracing with Micrometer Tracing 1.7.1 and the OpenTelemetry 1.62.0 bridge (sampling probability 1.0); spans received by a SpanExporter bean to check the parent relationships and self times of seven spans, the traceparent headers, and the trace IDs in the logs. Times are shown as the added delays
Concepts in this lab
- Distributed tracing (trace ID, span)
- A technique for tracking the whole path of a single request as it is processed across several services. A unique trace ID is assigned when the request first arrives, and it is passed along with every call between services. The segment handled by each service is called a span, and collecting the spans with the same trace ID shows which segment took the time.
- Observability (logs, metrics, traces)
- The ability to understand the internal state of a system from its external outputs alone. Logs are records of individual events, metrics are values aggregated as numbers, such as request counts and response times, and traces are records of the path one request takes through several services and the time spent in each segment. You need all three together to detect problems and find their causes.
- MDC
- Why it exists — If you attach a request ID to each log statement by hand, some places get missed, and there is no way to attach it to the logs that libraries write. MDC makes the log format print the request ID, so that the same value appears on every line without changing the code that writes the logs.
- Where it's used today — In a filter, you set the request ID with MDC.put when a request comes in, and print it with %X{key name} in the Logback or Log4j2 log format. When logs from several servers are gathered in one place for searching, you use this value to see the logs of one request together.
- A logging feature that automatically prints context information about the current request (such as the request ID and the user ID) with each log entry. It keeps values per thread: if you put the values in when a request starts, the same values appear in every log entry written by the thread that processes that request. Even when the logs of many requests are mixed together, you can pick out the logs of a single request.
- APM
- Why it exists — To find the cause of slowness from logs alone, you have to repeat the work of adding code that measures time at each suspect place and redeploying. An APM keeps collecting the time spent in methods, queries, and external calls from the running application, so you can look at the record from that time even after a problem has occurred.
- Where it's used today — It is used when a certain API suddenly becomes slow in production: you pick one slow request and trace which query or external call took the time, and compare response times and error rates before and after a deployment.
- A tool that monitors the performance of an application. It collects and shows the response time of each request, which methods or queries took the time, the errors that occurred, and more. In Java, it is usually applied as an agent, with no code changes. Examples are Pinpoint, Scouter, and Datadog.
- Monolithic architecture and microservice architecture
- Why it exists — An application that has grown to hold many features has to be rebuilt and redeployed as a whole even for a small change, and several teams that share the same code and deployment schedule end up waiting for each other. Microservice architecture is a way to split the system into services so that each team changes and releases its own service separately.
- Where it's used today — Organizations in which several teams share the work on a large service use microservice architecture. Small teams and new services often start as a monolith and split off services when the boundaries to split on become clear and the need arises.
- A monolithic architecture builds all features as one application and deploys them together. A microservice architecture splits the features into small services, and each one is developed, deployed, and scaled independently. With microservices, each service can be deployed and scaled separately and failures are isolated, but the complexity of communication between services, data consistency, and operations grows a lot.
Try these
- Default settings — The external payment provider is slow. You can see it at a glance on the tracing screen.
- Without a trace ID — Each service has logs, but you cannot connect the ones that belong to the same request.
- When the database query is slow — The slow span moves inside the order service.
- When the inside of the payment service is slow — The time of the payment service minus the time of its external call is long.
Running with the default settings
- The request arrives at the gateway: the incoming request has no trace header, so a new trace ID is created (for example 4bf92f35…; it is 32 hexadecimal digits and chosen randomly for each request). This ID goes along with the request until it ends, and the gateway's handling of the request is the first span (a server span).
- The gateway calls the order service: this call becomes one span on the gateway side (a client span), and the trace ID and the ID of this client span are sent in the HTTP header traceparent. The order service picks up the same trace ID and records its own processing as a new server span, whose parent is the gateway's client span.
- The order service queries the database (added delay 30ms). This query is wrapped with the Observation API, so it is recorded as one span. Spring Boot does not turn JDBC queries into spans by itself.
- The order service calls the payment service: again the call is left as a client span, and the trace ID is passed in the traceparent header. Each time a log is written, the trace ID and span ID held in the MDC are printed on the log line automatically.
- The payment service calls the external payment provider API (added delay 2000ms). The request to the external payment provider also carries the traceparent header, but the provider does not record traces, so this part shows up only as one client span measured by the payment service. As the response comes back, the spans close from the innermost outward. The added delays sum to 2095ms, and the actual response time is a little longer because of processing time.
- You look up a single trace ID in the tracing system (Zipkin, Tempo, and so on): the seven spans left by the three services are drawn on a time axis in a staircase shape, following their parent relationships. The span with the longest self time (its inner calls excluded) is "Payment provider API call". You can see right away where it is slow.
Result of this run
- A trace ID is a number attached to a whole request, and a span is one part of it. The processing of one service (a server span), a call to another service (a client span), and one query each become a span. Each span records the ID of its parent span, so the call relationships can be rebuilt as a tree.
- Logs tell you "what happened", metrics tell you "how much overall", and traces tell you "where and for how long for this request". If you also print the trace ID in the logs, you can find the slow span on the tracing screen and then search the logs by that ID.
- Spring Boot's default sampling probability (management.tracing.sampling.probability) is 0.1, so spans are exported for only about 1 in 10 requests. A request that is not sampled still gets a trace ID, which is printed in the logs and passed to the next service (the trace-flags of traceparent is 02, or 03 when sampled). This lab sets it to 1.0 so that every request is seen.
Code
// build.gradle (Spring Boot 4.1.1; Boot manages the versions)
implementation 'org.springframework.boot:spring-boot-micrometer-tracing-opentelemetry'
implementation 'io.micrometer:micrometer-tracing-bridge-otel'
implementation 'org.springframework.boot:spring-boot-restclient' // records RestClient calls as spans
# application.yml
management.tracing.sampling.probability: 1.0 # default 0.1 (spans are exported for only about 1 in 10 requests)
// Order service: record the DB query as one span (field declarations omitted; the span name order.db.query is made up for this example)
Observation.createNotStarted("order.db.query", observationRegistry)
.observe(() -> jdbcTemplate.queryForObject(sql, Integer.class));
# Header added automatically when services call each other (W3C Trace Context; the values are examples)
# Format: version-trace-id-parent-id-trace-flags
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-03
# trace-id (32 hex digits): the same for the whole request
# parent-id (16 hex digits): the id of the sender's call span (client span); it becomes the parent of the receiver's server span
# trace-flags 03: sampled (01) + the trace-id was generated randomly (02)
# [traceId-spanId] is added to each log line automatically (taken from the MDC)
# INFO 1 --- [order] [nio-8080-exec-3] [4bf92f3577b34da6a3ce929d0e0e4736-5b8aa5a2d2c872e8] ... : Order processing started orderId=1024
Assumptions of this model
This is a simple structure in which three services (gateway, order, payment) and an external payment provider are called in turn. All eight combinations were actually run and compared. The three services run as Spring Boot 4.1.1 servers (Spring MVC, embedded Tomcat 11.0.24) that call each other in turn with RestClient, and when tracing is on, Micrometer Tracing 1.7.1 and the OpenTelemetry 1.62.0 bridge (micrometer-tracing-bridge-otel) are added. The gateway role is played not by Spring Cloud Gateway but by a Spring MVC server that forwards the request it receives to the order service, and the external payment provider is a separate server with no tracing library. The slow parts were made with real delays (the DB query is a SELECT SLEEP on MySQL 8.4.11, and the inside of the payment service and the external payment provider wait for that long). For each combination, five requests warmed up the servers, and the five requests sent after them all gave the same result. The times on screen are the added delays, and the response time actually measured is a little longer because of processing time (30 to 110ms on this computer). The longest span was checked with the self time of the actual spans (the span's time minus the time of its child spans). No trace collector (Zipkin and so on) was run; instead, the spans exported by the OpenTelemetry SDK were received by a SpanExporter bean and written to a file for checking. The sampling probability was set to 1.0 (the default is 0.1), and the combinations that do not pass the trace ID were run without the tracing library. The trace ID value (4bf92f35…) and the traceparent value are examples; in reality they are chosen randomly for each request. The format of traceparent follows the W3C Trace Context standard.
Previous lab: Averages and percentiles · Next lab: Merge and rebase