SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
  • Three Pillars of Observability
  • Logging Best Practices
  • Log Aggregation
  • Metrics and Instrumentation
  • Distributed Tracing
  • Alerts and Monitoring
  • Dashboards and Runbooks
  • SLOs and Error Budgets
  • Incident Management and Postmortems
  • Profiling
  • Audit Logs
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Operations and Security/Observability

Distributed Tracing

Follow one request through many services and see where the time went.

⏱ 14 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Distributed tracing follows one request as it travels through many services, and records how long each step took.

  • A trace is the whole journey of one request. It is made of spans: one span for each piece of work (a service call, a database query).
  • Every service passes a trace id to the next one in a header, so all the spans can be joined into one picture.
  • The picture (a waterfall) shows you where the time went, and which service failed.

02Concept: What is it?

In a monolith, a slow request is easy to study: one process, one log, one profiler. With microservices, one click can trigger calls to ten services, three databases and a cache. Each service has its own logs and its own metrics. A metric can say "checkout is slow", but not "the bank call inside payment-service is slow".

Tracing solves this. When a request enters the system, it gets a unique trace id. Each unit of work creates a span with a start time, a duration, a name, and a parent span id. The spans form a tree: the gateway span is the parent, and every call it makes is a child.

One trace, many spans
πŸšͺGateway spanthe root
→↓calls
πŸ”Auth span
πŸ›’Cart span
πŸ’³Payment span
→↓calls
πŸ—„οΈDB query span
🏦Bank API span
Each box is a span. The parent waits for its children, so the parent is always at least as long as the work below it.

How the trace id travels (context propagation)

The caller adds the trace context to the outgoing request (an HTTP header, or a message header on a queue). The next service reads it, creates its own spans under the same trace id, and passes it on. The standard header is W3C Trace Context, called traceparent.

The traceparent header (version - trace id - parent span id - flags)
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
🧠A broken chain means a broken trace
If one service forgets to pass the header on, the trace is cut in two. Everything after that point shows up as a separate trace, and you lose the full picture. Try turning propagation off in the visualizer.

03Real-Life Example

🍡A Parcel With a Tracking Number
You order a parcel. It gets a tracking number. The parcel goes through a warehouse, a sorting centre, a plane, a local depot and a van. Every stop scans the number and writes down the time. When the parcel is late, you open the tracking page and see: "It sat 3 days at the sorting centre." You did not need to call every company. A trace is the tracking page for one request.
Parcel tracking
Distributed tracing
Tracking number
Trace id
One stop, with arrival and leave time
A span with start time and duration
The sorting centre handing over to the plane
A parent span calling a child span
Number written on the label at each hand-over
The traceparent header
The tracking page with all stops
The trace waterfall view
A stop that forgets to scan
A service that drops the trace context
Tracking only some parcels
Sampling
The same request, as a timeline
  1. 1
    Gateway receives GET /checkout
    root span starts, trace id created
  2. 2
    Auth checks the token
    child span, 30 ms
  3. 3
    Cart loads the items
    child span with a cache and a DB span below it
  4. 4
    Payment charges the card
    child span, calls the bank
  5. 5
    Gateway answers
    root span ends, trace is complete

04Why Do We Need It?

πŸ”Find the slow step
The waterfall shows which span used the time, so you stop guessing.
🧩Understand dependencies
See which services really call which others. The real map, not the one on the wiki.
πŸ’₯Locate failures
An error is marked on the exact span where it started, not just where it was noticed.
πŸ”Spot waste
Traces reveal the same call made ten times in a loop (the N+1 problem) or calls that could run in parallel.
🀝Cross-team debugging
One shared picture ends the argument about whose service is slow.
🎯Tune the right thing
Optimise the span that dominates the time, not the one that is easy to change.
Metrics tell you a request class is slow. A trace tells you which step of one request made it slow.

05Where Do We Use It?

🧱Microservices
The main use. Any request that crosses more than two or three services is hard to follow without a trace.
πŸ“¬Async work
Pass the trace context in message headers, so a job on a queue links back to the request that created it.
πŸ—„οΈDatabase and cache calls
Client libraries can create a span for each query, so you see slow SQL inside a request.
🌐Browser and mobile
A trace can start in the client, so you see network time as well as server time.
πŸ•ΈοΈService mesh and gateways
Proxies can create spans for every hop, but your code must still forward the trace headers.
πŸ§ͺRelease checks
Compare traces before and after a deployment to see which step changed.

06Types / Parts / How It Works

The parts of a trace

PartWhat it isTypical content
TraceThe full journey of one requestA trace id shared by all spans
SpanOne unit of workName, start time, duration, status, own span id and parent span id
Attributes (tags)Facts about a spanhttp.method, db.statement (careful), user tier, region
Events / logs on a spanThings that happened inside a spanRetry 2 of 3, cache miss
ContextWhat is passed between servicesTrace id, parent span id, sampling flag

Sampling: you cannot keep every trace

At high traffic, storing every trace is too costly. So systems sample: they keep only some. The big question is when to decide.

Head sampling vs tail sampling
Head sampling
🎲Decide at the startkeep 10% at random
↓cheap
❌May drop the slow or failed ones
Tail sampling
⏳Decide at the endkeep all errors and slow ones
↓needs memory and a collector
βœ…Keeps the interesting ones
Head sampling is cheap but blind. Tail sampling sees the result, but must hold all spans until the request ends.

The tooling around it

PieceJob
Instrumentation (SDK or agent)Creates spans in your code and libraries. OpenTelemetry is the common standard.
CollectorReceives spans, can batch, filter, sample and forward them
Storage and UIStores traces and draws the waterfall (Jaeger, Zipkin, Grafana Tempo, and commercial tools)
VisualizerRead a trace waterfall, break it, and sample itPick a slow span and see which bar is longest. Turn off propagation and watch the trace fall apart. Then compare head and tail sampling for the slow requests.

1. One request through four services

Which span is slow?
Pass the trace id between services?
gateway: GET /checkout
775 ms
auth-service: verify token
30 ms
cart-service: load cart
135 ms
cache: GET cart
15 ms
db: SELECT items
80 ms
payment-service: charge
590 ms
fraud-check
40 ms
bank API call
520 ms
Total time
775 ms
the root span
Spans in this trace
8 of 8
Most own time
520 ms
bank API call
The request took 775 ms. The waterfall points straight at "bank API call", which spent 520 ms of its own time. That is the span to investigate, not the gateway.

2. Keeping every trace is too costly: sampling

When is the keep-or-drop decision made?
Traces stored
1,000
of 10,000 requests
Slow traces kept
20 of 200
the ones you need
Head sampling flips a coin before the request runs, so it cannot know which requests will be slow. Keeping 10% of traces keeps only about 10% of the slow ones.

Span timings and request counts are illustrative (a fixed example, not a real system). In this model 2% of requests are slow.

07How to Use It / Steps / Implementation

Adding tracing to a system

  1. 1
    Pick a standard
    Use OpenTelemetry and the W3C traceparent header, so every language and tool speaks the same format.
  2. 2
    Turn on auto-instrumentation first
    Agents and libraries create spans for incoming HTTP calls, outgoing calls and database queries with almost no code.
  3. 3
    Propagate everywhere
    Make sure every outgoing call, thread hand-off, queue message and background job carries the trace context.
  4. 4
    Add your own spans
    Wrap the important business steps (calculate price, charge card). Give spans clear names and a few useful attributes.
  5. 5
    Link logs to traces
    Write the trace id into every log line, so you can jump from a log to its trace and back.
  6. 6
    Choose a sampling plan
    Start with a low head-sampling rate, and add tail sampling to always keep errors and slow requests.
  7. 7
    Use traces in real work
    Open the trace of a slow request during every incident and review. A tool that nobody opens is not worth its cost.
Example: a log line that carries the trace id
{"time":"2026-12-03T10:15:02Z","level":"error","service":"payment",
 "trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","span_id":"00f067aa0ba902b7",
 "msg":"bank API timeout after 3000 ms"}
⚠️Do not put secrets or personal data in spans
Attributes are stored and shown to many people. Never record passwords, card numbers, tokens or full request bodies. Be careful with SQL text that contains values.

08Key Terms to Know

TermMeaning in easy words
TraceThe complete record of one request as it moves through the system
SpanOne timed unit of work inside a trace
Trace idA unique id shared by every span of one trace
Span id / parent span idThe id of this span, and the id of the span that called it
Root spanThe first span of a trace, which has no parent
Context propagationPassing the trace id and parent id from one service to the next
traceparentThe W3C standard HTTP header that carries trace context
InstrumentationCode or an agent that creates spans automatically or by hand
OpenTelemetry (OTel)An open standard and toolkit for traces, metrics and logs
Head / tail samplingDeciding to keep a trace at the start, or after the request has finished
Waterfall (flame) viewThe chart that shows spans as bars along a time axis

09Pros, Cons and Trade-offs

βœ… Pros
  • Shows exactly where time and errors come from
  • Works across services, languages and teams
  • Reveals real dependencies and wasteful call patterns
  • Links well with logs and metrics
  • Open standards (OpenTelemetry, W3C) avoid lock-in
⚠️ Cons
  • Needs every service to propagate context
  • Storing all traces is very expensive, so you sample
  • Adds a small cost to each request
  • Spans can leak sensitive data if careless
  • Hard to read when a trace has thousands of spans

Trade-offs

ChoiceWe gainWe lose
Keep every traceNothing is missingVery high storage and network cost
Head samplingSimple and cheapMay drop the rare slow or failed requests
Tail samplingKeeps all errors and slow requestsNeeds memory and a collector that sees all spans of a trace
Auto-instrumentation onlyQuick start, little codeMisses your business steps and may be noisy
Many custom spansRich detailMore overhead, more clutter and more cost
Vendor agentEasy and feature richHarder to move away later (use OpenTelemetry to reduce this)

10Common Problems and Mistakes

Common mistakes

  1. Dropping the context. A custom HTTP client, a thread pool or a queue consumer that does not forward the trace headers cuts the trace.
  2. Sampling blindly at 1%. The one failing request in 1,000 is exactly the one you want, and it is probably gone.
  3. Tracing without logs links. Without the trace id in logs, you cannot move between the two tools.
  4. Sensitive data in attributes. Tokens, emails or card data end up in a tool that many people can open.
  5. Too many tiny spans. Spans for every loop turn add cost and make the waterfall unreadable.
  6. Unsynchronised clocks. Spans from different machines can look as if a child started before its parent.
  7. Never looking at traces. The tool is installed, but incidents are still solved by guessing.

Things to watch

βœ‚οΈBroken traces
Many one-span traces mean some hop is not passing the context on.
βš–οΈOverhead
Measure the cost of instrumentation. Sampling and batching keep it small.
πŸ•°οΈClock skew
Compare durations inside one span, and treat cross-machine start times with care.
πŸ”’Data privacy
Review what goes into attributes, and set retention limits.

11Real-World Examples

πŸ”­OpenTelemetry
The common open standard and set of SDKs, supported by most vendors and tools.
πŸ•΅οΈJaeger and Zipkin
Open-source trace backends with a UI. Zipkin and Jaeger came out of large companies' internal tools.
☁️Cloud tracing
AWS X-Ray, Google Cloud Trace and Azure Application Insights trace calls across their own services.
πŸ“„Google's Dapper paper
A well-known paper describing Google's internal tracing system. Many later tools follow its ideas.
πŸ•ΈοΈService meshes
Envoy-based meshes can emit spans for each hop, but apps must forward the headers.
πŸ›οΈSlow checkout hunts
Online shops use traces to find a slow payment or inventory call inside a long checkout.
πŸ“Note
Tools and defaults change. Check the current documentation for your language and backend before you set up sampling.
Mini case: why was one checkout slow?
🐒Checkout1,100 ms
→↓trace
πŸ’³Payment span700 ms
→↓inside
🏦Bank API600 ms
Slow Parent
The trace answered in one look what three teams could not agree on.

12Related Topics to Read Next

Three Pillars of Observability→

Traces are one of the three pillars, with logs and metrics.

Metrics and Instrumentation→

Metrics tell you which requests are slow, traces show why.

Logging Best Practices→

Put the trace id into logs to connect them.

Microservices→

The architecture where tracing becomes a must.

Service Mesh→

Sidecar proxies can create spans for every hop.

Message Queues→

Queues need trace context in message headers.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”Trace: the whole journey of one request. Span: one timed step inside it.
  • βœ”Link: every span has a trace id and a parent span id.
  • βœ”Propagate: pass the traceparent header on every call, message and thread hand-off.
  • βœ”Waterfall: the longest own-time bar is where to look first.
  • βœ”Sampling: head = cheap but blind. Tail = keeps errors and slow requests, costs more.
  • βœ”Connect: put the trace id in your logs.
  • βœ”Careful: no secrets or personal data in span attributes.
  • βœ”One line: β€œA trace is the tracking page for one request across all your services.”
← Previous
Metrics and Instrumentation
Next β†’
Alerts and Monitoring