Distributed Tracing with X-Ray and OpenTelemetry

Follow a request across API Gateway, Lambda, queues and databases with traces to find where time and errors come from.

Intermediate · about 3 hours · difficulty 3/5

Learn first: CloudWatch Metrics, Logs and Alarms

In a distributed system a single click might touch API Gateway, three Lambdas, SQS and DynamoDB. Logs from each service do not tell you which step was slow. Distributed tracing does.

Concepts

  • A trace is the full journey of one request. It is made of segments and subsegments (spans), each with timing and metadata.
  • A trace ID is passed along between services in headers so the pieces join up.
  • The service map draws your architecture from real traffic and highlights failing or slow nodes.

AWS X-Ray

  • Turn on active tracing for Lambda and API Gateway with a checkbox or one line of IaC.
  • Instrument code with the SDK or Powertools to add subsegments around database and HTTP calls, plus annotations (user ID, order ID) you can filter on.
  • Traces and the service map appear in the CloudWatch console.

OpenTelemetry

OpenTelemetry (OTel) is the vendor-neutral standard for traces, metrics and logs. The AWS Distro for OpenTelemetry (ADOT) sends OTel data to X-Ray, CloudWatch or third-party tools like Datadog, Grafana and New Relic. New projects should prefer OTel instrumentation so they are not locked in. Azure Application Insights and Google Cloud Trace both accept OTel too.

Pitfalls

  • Tracing 100 percent of high-volume traffic and paying for it; use sampling rules.
  • Not propagating trace headers through queues, breaking the trace into pieces.
  • Putting personal data in annotations.

You are ready to move on when you can open a trace for a slow request and point to the exact downstream call that caused the delay.

Key concepts

  • Traces, segments and spans
  • Trace context propagation
  • X-Ray service map
  • Annotations and metadata
  • Sampling rules
  • OpenTelemetry and ADOT

Mini project

Enable active tracing on your API Gateway and Lambda functions, add a subsegment around the DynamoDB call and an annotation for user ID, then add an artificial 2 second sleep and find it in the trace. X-Ray has a free monthly allowance; turn tracing off afterwards.

Check yourself

What is the difference between logs, metrics and traces, and which one answers 'which service made this request slow'?

Free resources