AWS X-Ray Explained: Traces, Segments, Sampling, and When to Use It

AWS X-Ray is a distributed tracing service that follows requests through your application: Lambda, API Gateway, DynamoDB, external services. It shows you exactly where time was spent and where things went wrong.

This page covers what X-Ray is as a tool, how it works practically, and when to reach for it. For the underlying concept of distributed tracing, see the Distributed Tracing in AWS guide.

Simple explanation

Analogy

Think of X-Ray like a parcel tracking system for your HTTP requests. Every depot a parcel passes through scans it and logs the time. At the end of the journey you can see the full route: where it waited, where it moved fast, and if something went wrong.

X-Ray does the same for requests. When a request arrives at API Gateway, X-Ray stamps it with a unique trace ID. Every service it touches records its slice of work under that same ID. X-Ray then assembles those slices into a single timeline you can inspect in the console.

A request hitting a typical serverless API might trace like this:

  1. API Gateway receives the request, records 5ms
  2. Lambda invokes, records 820ms total
  3. Lambda calls DynamoDB, records 650ms as a subsegment
  4. Lambda returns a response, segment closes
  5. API Gateway returns to the client, trace complete

That 650ms DynamoDB subsegment is immediately obvious. Without tracing, your Lambda metrics only show “Lambda took 820ms” with no hint that the database was the bottleneck.

How AWS X-Ray works

Trace IDs

Every traced request gets a unique trace ID injected into the X-Amzn-Trace-Id HTTP header. AWS services that support X-Ray read this header, record their work under that ID, and pass it downstream. This is what links all the individual records into one complete trace. The distributed tracing guide explains how propagation works across service boundaries in detail.

Segments

A segment is one service’s record in the trace. It captures:

  • Service name and type
  • Start time, end time, and duration
  • Whether the call succeeded, errored (4xx), or faulted (5xx)
  • Any annotations or metadata you attach manually

Subsegments

A subsegment is a child record inside a segment. When your Lambda function queries DynamoDB, X-Ray automatically creates a subsegment for that query, recording its duration and outcome. Subsegments let you see exactly where time goes within a single service, not just across service boundaries.

Annotations and metadata

You can attach extra data to any segment or subsegment. Annotations are indexed key-value pairs you can filter on in the console. For example, find all traces where orderId = “789”. Metadata is stored but not indexed, useful for larger debug payloads you would inspect manually but do not need to search on.

Service map

X-Ray automatically builds a visual service map from all segments it receives. Each node is a service; each edge is a call between services, annotated with average latency and error rate. Red or yellow nodes signal elevated errors, making the service map the fastest starting point during an incident. Access it at CloudWatch → X-Ray traces → Service map.

Sampling

X-Ray does not trace every request. You can configure custom sampling rules to trace more aggressively on specific paths, for example 100% of /checkout requests, while leaving the default rule in place for everything else.

Default sampling rule

X-Ray traces the first request per second per service, then 5% of subsequent requests in that second. At 200 requests per second, roughly 10 to 11 requests get traced. Enough to see error patterns and latency distribution without generating enormous data volumes. See the distributed tracing guide for sampling rule configuration examples.

When to use AWS X-Ray

X-Ray is the right tool when you need to trace requests across multiple services and pinpoint where latency or errors originate. It adds clear value in these situations:

  • API Gateway and Lambda architectures. Both integrate with X-Ray natively. Enable active tracing on Lambda and turn on tracing on the API Gateway stage and you get end-to-end traces with no code changes. See Monitoring Lambda with CloudWatch for how tracing fits alongside Lambda metrics and logs.

  • Microservices on ECS or EKS. When a request touches multiple containers, the service map shows the dependency graph automatically. See the EKS monitoring guide for X-Ray daemon setup on Kubernetes.

  • Slow downstream dependency debugging. If a DynamoDB query or a third-party API is adding latency, a trace waterfall isolates it in seconds, far faster than grepping through CloudWatch Logs.

  • Production incident investigation. When a CloudWatch alarm fires, the X-Ray service map is the fastest way to see which service is the source. For structured incident workflows, see Incident Response with Monitoring.

  • Lambda cold start analysis. X-Ray traces include an Initialization segment on cold starts, making it easy to measure how much startup time is affecting your end-to-end latency.

When not to use AWS X-Ray

  • When metrics and logs are enough. For a single-service application or a standalone Lambda function, CloudWatch metrics and CloudWatch Logs usually give you everything you need. Tracing adds the most value when requests cross service boundaries.

  • When your team needs vendor-neutral instrumentation. The X-Ray SDK locks you into AWS. If your organization runs across multiple clouds or wants portability, starting with OpenTelemetry is the better long-term choice.

  • When you are building something new. AWS now recommends OpenTelemetry for new instrumentation. Starting with the X-Ray SDK today means a migration later.

  • When structured log correlation already meets your needs. X-Ray shows timing and call outcomes, not log messages. If structured logging with trace ID correlation already gives your team what they need to debug issues, adding X-Ray may not be worth the setup overhead.

AWS X-Ray vs CloudWatch

Amazon CloudWatch and X-Ray are complementary tools, not competing ones. CloudWatch handles metrics, logs, and alarms. X-Ray handles traces. Here is how to decide which to reach for:

Question you are askingReach for
Is my error rate above normal right now?CloudWatch alarm on Lambda Errors metric
Which specific requests are failing?X-Ray trace list, filtered by error = true
What is my p99 latency over the last 24 hours?CloudWatch metric with p99 statistic
Why did this one request take 8 seconds?X-Ray trace waterfall for that specific request
Which downstream service is causing my latency spike?X-Ray service map and subsegment breakdown
What did the Lambda log during this request?CloudWatch Logs Insights query

In practice: a CloudWatch alarm fires, you open the X-Ray service map to identify the failing service, then you read that service’s CloudWatch Logs for the exact error message. All three tools together give you the full picture.

Tip

Correlate logs with traces: The X-Ray trace ID is available inside Lambda as the environment variable _X_AMZN_TRACE_ID. Log this value in every log event using structured logging to create a direct link between your CloudWatch logs and the corresponding X-Ray trace.

AWS X-Ray vs OpenTelemetry

SDK status

The X-Ray SDK (the client library you install in your application) is in maintenance mode. AWS is not adding new features to it. New instrumentation capabilities are going into AWS Distro for OpenTelemetry (ADOT) instead. The X-Ray service backend for storing and visualizing traces remains fully supported either way.

The practical effect: if you instrument with OpenTelemetry and use the X-Ray exporter, your traces still appear in the X-Ray console with the same service map, waterfall timeline, and filtering features. The difference is that your instrumentation code is now vendor-neutral.

X-Ray SDKOpenTelemetry (ADOT)
AWS maintenance statusMaintenance mode (no new features)Actively developed
Vendor portabilityAWS-onlyWorks with any OTLP backend
X-Ray console integrationYesYes, via X-Ray exporter
Lambda auto-instrumentationBuilt-in active tracing flagLambda ADOT managed layer
Best forExisting workloads already using X-Ray SDKNew projects and multi-cloud teams

If you are running the X-Ray SDK in production and it is working, there is no urgent reason to migrate. If you are starting a new service today, ADOT is the path AWS recommends. For debugging production systems using either approach, see the debugging production systems guide.

How to enable X-Ray

For most serverless workloads, enabling X-Ray requires only a configuration flag. No code changes:

# Enable X-Ray active tracing on a Lambda function
aws lambda update-function-configuration \
  --function-name my-api-handler \
  --tracing-config Mode=Active

# Enable X-Ray tracing on an API Gateway stage
aws apigateway update-stage \
  --rest-api-id abc123def4 \
  --stage-name prod \
  --patch-operations op=replace,path=/tracingEnabled,value=true

Once active tracing is on, Lambda automatically creates a segment for each invocation and traces AWS SDK calls including DynamoDB, S3, and SQS as subsegments, with no code changes needed.

For ECS and EKS deployments, you run the X-Ray daemon as a sidecar or DaemonSet. See the EKS monitoring guide for the Kubernetes setup.

For custom subsegments and annotations in application code, AWS Powertools for Lambda is the cleanest approach for Python and TypeScript. See the AWS Lambda Overview for more on the Lambda execution model.

Common mistakes

  1. Enabling X-Ray on Lambda but not on API Gateway. If API Gateway does not propagate the trace header, Lambda starts a new trace instead of extending the existing one. Enable tracing on both services to get true end-to-end visibility.

  2. Missing IAM permissions. Your Lambda execution role needs xray:PutTraceSegments and xray:PutTelemetryRecords. The AWSXRayDaemonWriteAccess managed policy covers both.

    Silent failure

    Without these permissions, traces disappear with no error and no warning. X-Ray just stops receiving data. This is one of the most common reasons the X-Ray console appears empty after setup.

  3. Putting searchable fields in metadata instead of annotations. Only annotations are indexed. If you store orderId in metadata, you cannot filter traces by it in the console or CLI. Use annotations for anything you intend to search on.

  4. Setting sampling to 100% in production. This generates high data volumes and adds overhead on high-traffic services. Use the default rule or targeted custom rules for specific high-value paths.

  5. Expecting traces to replace logs. Traces show timing and success or failure status, not log messages or stack traces. Use X-Ray to locate the problem and CloudWatch Logs to understand the detail. They work together, not instead of each other.

Frequently asked questions

What is AWS X-Ray?

AWS X-Ray is a distributed tracing service that records the full path of a request as it travels through your application, including Lambda, API Gateway, DynamoDB, and other services. It assembles those records into a visual timeline and service map so you can see exactly where time was spent and where errors occurred.

What is the difference between a trace and a segment in X-Ray?

A trace is the complete record of one request, from entry to completion. A segment is one service contribution to that trace, recording the time it took and whether it succeeded. Subsegments capture individual operations inside a segment, like a DynamoDB query or an outbound HTTP call.

Does X-Ray capture every request?

No. X-Ray uses sampling to control which requests are traced. The default rule captures the first request per second per service, then 5% of subsequent requests. You can define custom sampling rules, for example tracing 100% of requests to a specific checkout endpoint.

Should I use the X-Ray SDK or OpenTelemetry for new projects?

For new projects, AWS recommends AWS Distro for OpenTelemetry (ADOT) rather than the X-Ray SDK directly. The X-Ray SDK is in maintenance mode. It still works, but new instrumentation features are going into the OpenTelemetry path. The X-Ray service backend remains fully supported either way, so traces from ADOT still appear in the X-Ray console.

How does X-Ray fit with CloudWatch?

They answer different questions. CloudWatch tells you something is wrong: your error rate is up, latency has spiked. X-Ray shows you which specific service in the chain caused it and why. In practice, a CloudWatch alarm is usually what prompts you to open X-Ray for the investigation.

Last verified: 3 May 2026 Cloud services change frequently. Verify details against official documentation before making infrastructure decisions.