Skip to content

    System Design

    Correlation IDs and Trace Context Across Services

    Follow one request across services with a correlation id and the W3C traceparent header, log the ids with the MDC, and run a two-service Spring lab.

    By Published 13 min read

    Share

    Standard lessonintermediateSpring Boot labBackend System Design

    Before this: Observability and SLOs

    What you'll learn: By the end of this lesson you will be able to tell a correlation id from a trace id and a span id, read and build a W3C traceparent header, say what a service must do when the header arrives, is missing or is invalid, put the ids into every log line with the logging MDC and keep them from leaking between requests, forward the ids on every outgoing call, and read the captured log lines of one request crossing two services in a Spring Boot lab.

    A parcel gets a tracking number at the depot. The van, the sorting hall and the local courier each scan it, and when the customer phones, support types one number and sees the whole journey. Without it, support guesses from timestamps, and every handover is a place where the trail goes cold. A correlation id is that number for a request, and trace context is the standard way to pass it, plus the id of the previous scan, from one service to the next.

    Observability and SLOs says to emit structured logs with trace ids on every line; this lesson is how. Metrics and OpenTelemetry in one stack are the lesson backend-observability-with-micrometer-prometheus-and-opentelemetry. Here the subject is the ids, the header and the log context. For the incident side, see alerting and on-call; for a record that must outlive the logs, audit logging.

    Verified with the W3C Trace Context Recommendation (23 November 2021), the Logback manual, Spring Boot 4.1.2 and Spring Framework documentation, and Java 25, on 2026-12-01.

    The core idea

    Give every request an id at the edge, write it on every log line, and copy it into every outgoing call. A correlation id groups the lines of one logical operation; trace context adds structure: one trace id for the whole operation and a span id for each step, so the lines form a tree and not just a pile.

    Three illustrations run through the lesson: the minimal example is the Spring lab (two services, one request); the realistic example is ShopStream checkout in "In practice"; the failure example is a hop that forgets the header (lab scenario 6).

    Three ids, three jobs

    Id Who makes it What it names Standard?
    Correlation id The first service, or a client One request, for humans and support No: a convention such as X-Correlation-Id
    Trace id The first service that sees no trace The whole trace Yes: W3C Trace Context
    Span id (parent-id in the header) Each service One step in the trace Yes: W3C Trace Context

    The correlation id is the one you can show a customer. The trace id and span ids are for tools: they let a tracing backend draw the call tree. Many systems use the trace id for both jobs; keeping them separate is useful when one business operation spans several traces (a retry, a queue hop). The lab carries both.

    The traceparent header

    W3C Trace Context is a W3C Recommendation. Its header traceparent carries four fields joined by hyphens: version-trace-id-parent-id-trace-flags. For version 00:

    • trace-id: 16 bytes as 32 lowercase hex characters; all zeroes is forbidden.
    • parent-id: 8 bytes as 16 lowercase hex characters; all zeroes is forbidden. It names the caller's operation, so for the receiver it is the parent.
    • trace-flags: 2 hex characters, a bit field. The right-most bit is the sampled flag: set means the caller may have recorded trace data.

    The specification's own example is 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01. Version ff is invalid. Vendors must expect the header name in any case and should send it in lowercase.

    One request, two services, headers on each hopClient to Order service (traceparent); Order service to Inventory service (traceparent + parent id); Order service to Log store (lines with ids); Inventory service to Log store (lines with ids)Client: sends traceparent or nothingClientsends traceparentor nothingOrder service: span 1Order servicespan 1Inventory service: span 2Inventoryservicespan 2Log store: one trace id, all linesLog storeone trace id, alllinestraceparenttraceparent + parent idlines with idslines with ids

    Figure 1. The ids travel in headers and arrive in the logs. How to read this: solid arrows are requests that carry the traceparent header; dashed arrows are log lines. Each service writes the same trace id, and the inventory service's parent-id is the order service's span.

    What a service does with the header

    flowchart TD accTitle: What a service does with an incoming traceparent accDescr: If the traceparent header is absent or cannot be parsed, create a new trace id and a new span id and drop any tracestate. If it is valid, keep its trace id, remember its parent-id as the caller's span, and create a new span id for this service. In both cases put the ids in the log context and use this service's span id as the parent-id of every outgoing call. start["Request arrives"] --> has{"traceparent present and valid?"} has -- "No" --> fresh["New trace id and span id, drop tracestate"] has -- "Yes" --> join["Keep the trace id, remember parent-id, new span id"] fresh --> mdc["Put ids in the log context (MDC)"] join --> mdc mdc --> out["Outgoing call: same trace id, parent-id = my span id"]

    Figure 2. Join, restart, then forward. How to read this: both inbound branches end in the same place, a log context with the ids, and the outgoing call always carries this service's own span id as its parent.

    The specification says a missing header means the vendor creates a new trace-id and parent-id. An invalid trace-id or parent-id (wrong length, upper-case hex, all zeroes) means the header is ignored, a new one is created and tracestate is dropped. On the way out, the parent-id must be set to a value representing the id of the current operation, which is why each hop's span id becomes the next hop's parent. A vendor must not otherwise change the header, except to update the sampled flag together with the parent-id or to restart the trace.

    sequenceDiagram accTitle: Parent ids chain through two hops accDescr: The client sends a trace id with parent id 00f067aa0ba902b7. The order service keeps the trace id, creates span 1 and calls the inventory service with parent id span 1. The inventory service creates span 2 and logs span 2 with parent span 1. participant C as Client participant O as Order service participant I as Inventory service C->>O: trace 4bf9..., parent 00f067aa0ba902b7 Note over O: new span 1, logs parent 00f067aa0ba902b7 O->>I: trace 4bf9..., parent span 1 Note over I: new span 2, logs parent span 1 I-->>O: 200 O-->>C: 200 and X-Correlation-Id

    Figure 3. The trace id stays; the parent id changes at every hop. How to read this: the trace id is identical on every line, so one search finds everything; the parent ids link each step to the one before it.

    tracestate and the sampled flag

    tracestate is a second header for vendor-specific data: a comma-separated list of key=value members, at most 32, where "modified keys should be moved to the beginning (left) of the list" and unmodified entries keep their order. If traceparent does not parse, tracestate must not be parsed either.

    The sampled flag is not a log setting. It says whether the caller may have recorded trace data, and the specification lets it change only when the parent-id is updated. The lab records no spans, so it forwards the flag unchanged and marks a trace it starts as not sampled (00).

    The log context: the MDC

    Putting the id in each message by hand does not scale. The Mapped Diagnostic Context (MDC) holds key-value pairs for the current thread, and a log pattern prints them with %X{key}. The Logback manual says it "manages contextual information on a per thread basis". Three consequences:

    1. Set it once, at the edge of the request. A servlet filter (Spring MVC supports jakarta.servlet.Filter and the base class OncePerRequestFilter) runs before the controller, so every line it writes carries the ids.
    2. Clean up in a finally block. The manual says a put() should be balanced by a remove(), in finally; otherwise a pooled server thread writes the previous request's ids on the next one.
    3. Child threads do not inherit it. For executors the manual recommends calling MDC.getCopyOfContextMap() on the original thread and restoring it in the task. A task handed to a pool without that copy logs with no ids.

    With tracing on, Spring Boot builds a correlation id from the traceId and spanId MDC values and adds it to each line by default (logging.pattern.correlation changes the format). Its documentation says to build clients from the auto-configured RestClient.Builder or WebClient.Builder; a client created without them does not propagate. OpenTelemetry's default propagator uses the W3C Trace Context headers.

    A correlation id from outside must be treated as input

    An X-Correlation-Id from a client is untrusted text that you are about to write into a log. OWASP describes log injection: unvalidated input written to a log can let an attacker forge entries, for example with a line break. The lab's defence is an allow-list: reuse the incoming value only if it is a short run of letters, digits, dot, hyphen and underscore, and otherwise generate a new one.

    Build it: two services, one request, in Spring

    This is the minimal example. Goal: see one request's ids on both sides of a call, and the ways to lose the trail. Not a real network or tracing backend: each service is a Spring MVC controller behind its own MockMvc and filter; the call between them goes through MockMvc on another thread; ids come from an injected counter so the output is deterministic; no spans are recorded.

    Setup. From the repository (Docker is not needed):

    cd examples/spring-labs
    ./gradlew :labs:correlation-and-trace-context:test

    It runs 11 tests, one of which compares the report below with the golden file examples/spring-labs/golden/correlation-and-trace-context.txt. The code is in examples/spring-labs/labs/correlation-and-trace-context/. The parsing rule is a small method; the filter's decision is the heart of the lab:

    Optional<TraceParent> incoming = TraceParent.parse(request.getHeader(TraceContext.TRACEPARENT));
    public Map<String, String> outgoingHeaders() {
        Map<String, String> headers = new LinkedHashMap<>();
        headers.put(TRACEPARENT, new TraceParent(traceId, spanId, flags).format());
        if (tracestate != null) {
            headers.put(TRACESTATE, tracestate);
        }
        headers.put(CORRELATION_ID, correlationId);
        return headers;
    }

    Scenario 1: no headers. The order service starts the trace and the outgoing call carries its span as the parent-id. The log pattern is %X{service} trace=%X{traceId} span=%X{spanId} parent=%X{parentSpanId} corr=%X{correlationId} | %msg, and the inventory thread's MDC is empty until its filter runs.

    Expected output, captured from a real run (Spring Boot 4.1.2, Java 25, Logback, 2026-12-01):

    == 1. A request with no trace headers: the first service starts the trace
    request headers: (none)
    response: 200, X-Correlation-Id: corr-0001
    headers the order service sent to the inventory service:
      traceparent: 00-00000000000000000000000000000001-0000000000000001-00
      X-Correlation-Id: corr-0001
    MDC on the inventory server thread before its filter ran: empty
    log lines, in the order written:
      order-service trace=00000000000000000000000000000001 span=0000000000000001 parent=- corr=corr-0001 | placing order 1001
      order-service trace=00000000000000000000000000000001 span=0000000000000001 parent=- corr=corr-0001 | calling inventory-service to reserve apple-1kg
      inventory-service trace=00000000000000000000000000000001 span=0000000000000002 parent=0000000000000001 corr=corr-0001 | reserving apple-1kg
      order-service trace=00000000000000000000000000000001 span=0000000000000001 parent=- corr=corr-0001 | inventory-service answered 200
      order-service trace=00000000000000000000000000000001 span=0000000000000001 parent=- corr=corr-0001 | order 1001 placed: reserved apple-1kg

    The ids are counters, valid in form but not random. After the call returns, the order service's lines still carry span 1, because the inventory call ran on another thread with its own MDC.

    Scenario 2: a caller that already has a trace. The request carries the specification's example traceparent, a tracestate and its own correlation id. The trace id is kept on every line, the caller's parent-id appears only on the order service's lines, and the order service's span becomes the next parent. tracestate is forwarded unvalidated; a real library validates it.

    Expected output, captured from a real run (the same run):

    == 2. A request that already carries a traceparent: the trace continues
    request headers: traceparent=00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01, tracestate=congo=t61rcWkgMzE, X-Correlation-Id=web-7f3a
    response: 200, X-Correlation-Id: web-7f3a
    headers the order service sent to the inventory service:
      traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-0000000000000001-01
      tracestate: congo=t61rcWkgMzE
      X-Correlation-Id: web-7f3a
    MDC on the inventory server thread before its filter ran: empty
    log lines, in the order written:
      order-service trace=4bf92f3577b34da6a3ce929d0e0e4736 span=0000000000000001 parent=00f067aa0ba902b7 corr=web-7f3a | placing order 1001
      order-service trace=4bf92f3577b34da6a3ce929d0e0e4736 span=0000000000000001 parent=00f067aa0ba902b7 corr=web-7f3a | calling inventory-service to reserve apple-1kg
      inventory-service trace=4bf92f3577b34da6a3ce929d0e0e4736 span=0000000000000002 parent=0000000000000001 corr=web-7f3a | reserving apple-1kg
      order-service trace=4bf92f3577b34da6a3ce929d0e0e4736 span=0000000000000001 parent=00f067aa0ba902b7 corr=web-7f3a | inventory-service answered 200
      order-service trace=4bf92f3577b34da6a3ce929d0e0e4736 span=0000000000000001 parent=00f067aa0ba902b7 corr=web-7f3a | order 1001 placed: reserved apple-1kg

    Scenario 3: which headers are accepted. The lab parses version 00 only. The specification asks vendors to try higher versions with the version 00 layout; the lab does not, and restarts the trace.

    Expected output, captured from a real run (the same run):

    == 3. Which traceparent values are accepted (version 00 only in this lab)
    the specification's example accepted, sampled=true
    not sampled (flags 00)      accepted, sampled=false
    upper-case hex              rejected
    all-zero trace-id           rejected
    all-zero parent-id          rejected
    version ff                  rejected
    a later version             rejected
    too short                   rejected
    flags not hex               rejected

    Scenario 4: an invalid header restarts the trace. An all-zero trace id sent with a tracestate produces a new trace and no tracestate on the outgoing call (see the golden file and the test anInvalidTraceparentStartsAFreshTraceAndDropsTracestate).

    Scenario 5: a hostile correlation id. A safe value is reused. A value with a line break and a fake log line is replaced, and the request still writes exactly five log lines.

    Expected output, captured from a real run (the same run):

    == 5. A client-supplied X-Correlation-Id is reused only when it is safe to log
    sent X-Correlation-Id: web-7f3a -> response header: web-7f3a
    sent X-Correlation-Id: a value with a line break and spaces -> response header: corr-0001
    log lines written for that request: 5

    Scenario 6: the failure. The client forgets to send the headers. The call still works, which is why the bug survives: the inventory service starts its own trace (id ...0002, another correlation id), and a search for trace ...0001 never finds its line.

    Expected output, captured from a real run (the same run):

    == 6. The failure: the order service forgets to send the headers, so the inventory service starts its own trace
    request headers: (none)
    response: 200, X-Correlation-Id: corr-0001
    headers the order service sent to the inventory service:
      (none)
    MDC on the inventory server thread before its filter ran: empty
    log lines, in the order written:
      order-service trace=00000000000000000000000000000001 span=0000000000000001 parent=- corr=corr-0001 | placing order 1001
      order-service trace=00000000000000000000000000000001 span=0000000000000001 parent=- corr=corr-0001 | calling inventory-service to reserve apple-1kg
      inventory-service trace=00000000000000000000000000000002 span=0000000000000002 parent=- corr=corr-0002 | reserving apple-1kg
      order-service trace=00000000000000000000000000000001 span=0000000000000001 parent=- corr=corr-0001 | inventory-service answered 200
      order-service trace=00000000000000000000000000000001 span=0000000000000001 parent=- corr=corr-0001 | order 1001 placed: reserved apple-1kg

    Scenario 7: nothing leaks. After the request the MDC and the per-thread context are empty, because the filter restores what it found in a finally block.

    Expected output, captured from a real run (the same run):

    == 7. Nothing leaks after the request
    MDC of the calling thread after the request: empty
    trace context of the calling thread after the request: null

    Break it. In InventoryClient.reserve, replace CurrentTrace.get().outgoingHeaders() with Map.of(): scenario 6 is what you get, and the propagation test fails. Restore the line and run the tests again.

    Left out: recording and exporting spans, sampling policy, tracestate validation, version 01 and above, a real HTTP client, asynchronous hand-offs, and any tracing backend.

    Trade-offs

    Choice Gain Cost Wrong when
    Correlation id only Simple, readable by support No call tree, no standard You need to see which call caused which
    W3C traceparent via a library Standard, parent links, tool support Setup, sampling decisions You hand-roll it and miss a hop
    Ids in the MDC on every line One search finds the request Discipline in threads Pools run tasks without an MDC copy
    Trust an incoming id Keeps the client's reference Log forging The caller is outside your trust boundary

    In practice: tracing a failed ShopStream checkout

    This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company, and every number is illustrative.

    This is a realistic scenario, not a case history.

    The situation

    A customer writes to support: "my card was charged but I have no order". The checkout call crosses the checkout service, the stock service and the payment adapter, and each logs on its own, so finding the failing hop means searching three log streams by guesswork.

    Starting architecture

    ShopStream checkout pathWeb client to Checkout service (request); Checkout service to Stock service (call); Checkout service to Payment adapter (call)Web client: shows a referenceWeb clientshows a referenceCheckout service: edge of the traceCheckoutserviceedge of the traceStock service: reserveStock servicereservePayment adapter: chargePaymentadapterchargerequestcallcall

    Figure 4. Three services in one checkout. How to read this: the checkout service is where the trace starts or continues; each call to the stock service and the payment adapter must carry the header.

    Options considered

    Option Behaviour Risk
    A. Each service logs its own request id Easy The ids do not match across services
    B. One correlation id header, copied by hand Works for HTTP Missed on any new client or hop
    C. W3C trace context through a tracing library, ids in the MDC Standard; the client library forwards it Sampling and setup to own

    The decision

    Option C for the trace, plus a correlation id created at the edge and returned in a response header so support can quote it. Every log line carries traceId, spanId and the correlation id through the MDC, incoming correlation ids must match a short allow-list, and a review rule says a new outgoing client is built from the framework's instrumented builder.

    Rollout and verification

    A rollout would first send one synthetic checkout and search the log store by the returned id: lines from all three services must appear and the parent-ids must chain. A request with an invalid traceparent must produce a new trace, not an error. The ongoing check is a count of log lines with no trace id per service, which should be near zero for request handling.

    The 2 a.m. failure

    The page says support cannot find the payment line for a customer's checkout: the trace id returns checkout and stock lines but nothing from payment. A new retry helper in the payment adapter runs the charge on its own thread pool, so the task has an empty MDC and logs without ids, and its outgoing call has no header. The checks are payment-adapter lines with an empty trace id and the thread name on them. The mitigation is to search by order id, which the message text carries. The lasting fix is to copy the MDC into the task and take the headers from the captured context, plus a test like lab scenario 6 for each outgoing client.

    Architect's notes

    • Make propagation the library's job. One instrumented client builder beats a convention each team must remember.
    • Log the ids on every line, including errors and background work.
    • Treat inbound ids as input. Validate before they reach a log or a header.
    • Return the correlation id to the caller so support can quote it.
    • Count the gaps: log lines with no trace id, and traces that start mid-chain.

    Common mistakes

    • Forgetting the header on one client. The call works; the trail just ends.
    • Not clearing the MDC. A pooled thread then writes the previous request's ids.
    • Assuming child threads inherit the MDC. Copy it into the task.
    • Generating a new id at every hop. That is the opposite of correlation.
    • Writing an incoming header straight into a log.
    • Confusing the sampled flag with log level.

    Key takeaways

    • A correlation id is a convention for people; a trace id and span ids are the standard structure for tools.
    • traceparent is version-trace-id-parent-id-trace-flags; ids are lowercase hex and never all zeroes.
    • A service joins a valid trace, restarts on a missing or invalid header, and always sends its own span id as the next parent-id.
    • The MDC is per thread: set it at the edge, clean it in finally, copy it into tasks.
    • Forward the headers on every outgoing call; a missing header is silent.
    • Validate any id that comes from outside before logging it.

    Practice exercises

    Exercise 1 (20 min). Run the lab and, from scenario 2's log lines, draw the span tree: which span is the parent of which.

    Exercise 2 (45 min). Add a third service, a payment service, called by the inventory service. Check that the trace id is the same on all lines and that its parent is the inventory service's span.

    Exercise 3 (1 hour). Run "Break it". Then write a test that fails whenever an outgoing client sends a request with no traceparent.

    The other side of this topic: in the browser, the page creates or receives the first id and shows it in an error message so a user can quote it; that is covered in the front-end lesson on logging, tracing and correlation ids from the browser to the database.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments