

# Integrating AWS X-Ray with other AWS services
<a name="xray-services"></a>

**Note**  
X-Ray SDK/Daemon Maintenance Notice – On February 25th, 2026, the AWS X-Ray SDKs/Daemon will enter maintenance mode, where AWS will limit X-Ray SDK and Daemon releases to address security issues only. For more information on the support timeline, see [X-Ray SDK and Daemon Support timeline](xray-sdk-daemon-timeline.md). We recommend to migrate to OpenTelemetry. For more information on migrating to OpenTelemetry, see [Migrating from X-Ray instrumentation to OpenTelemetry instrumentation ](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-migration.html).

Many AWS services provide varying levels of X-Ray integration, including sampling and adding headers to incoming requests, running the X-Ray daemon, and automatically sending trace data to X-Ray. Integration with X-Ray can include the following:
+ *Active instrumentation* – Samples and instruments incoming requests
+ *Passive instrumentation* – Instruments requests that have been sampled by another service
+ *Request tracing* – Adds a tracing header to all incoming requests and propagates it downstream
+ *Tooling* – Runs the X-Ray daemon to receive segments from the X-Ray SDK

**Note**  
The X-Ray SDKs include plugins for additional integration with AWS services. For example, you can use the X-Ray SDK for Java Elastic Beanstalk plugin to add information about the Elastic Beanstalk environment that runs your application, including the environment name and ID.

Here are some examples of AWS services that are integrated with X-Ray:
+ [AWS Distro for OpenTelemetry (ADOT)](xray-services-adot.md) – With ADOT, engineers can instrument their applications once and send correlated metrics and traces to multiple AWS monitoring solutions including Amazon CloudWatch, AWS X-Ray, Amazon OpenSearch Service, and Amazon Managed Service for Prometheus.
+ [AWS Lambda](xray-services-lambda.md) – Active and passive instrumentation of incoming requests on all runtimes. AWS Lambda adds two nodes to your trace map, one for the AWS Lambda service, and one for the function. When you enable instrumentation, AWS Lambda also runs the X-Ray daemon on Java and Node.js runtimes for use with the X-Ray SDK.
+ [Amazon API Gateway](xray-services-apigateway.md) – Active and passive instrumentation. API Gateway uses sampling rules to determine which requests to record, and adds a node for the gateway stage to your service map. 
+ [AWS Elastic Beanstalk](xray-services-beanstalk.md) – Tooling. Elastic Beanstalk includes the X-Ray daemon on the following platforms:
  + *Java SE* – 2.3.0 and later configurations
  + *Tomcat* – 2.4.0 and later configurations
  + *Node.js* – 3.2.0 and later configurations
  + *Windows Server* – All configurations other than Windows Server Core that have been released after December 9th, 2016

  You can use the Elastic Beanstalk console to tell Elastic Beanstalk to run the daemon on these platforms, or use the `XRayEnabled` option in the `aws:elasticbeanstalk:xray` namespace. 
+ [Elastic Load Balancing](xray-services-elb.md) – Request tracing on Application Load Balancers. The Application Load Balancer adds the trace ID to the request header before sending it to a target group.
+ [Amazon EventBridge](xray-services-eventbridge.md) – Passive instrumentation. If a service that publishes events to EventBridge is instrumented with the X-Ray SDK, event targets will receive the tracing header and can continue to propagate the original trace ID. 
+ [Amazon Simple Notification Service](xray-services-sns.md) – Passive instrumentation. If an Amazon SNS publisher traces its client with the X-Ray SDK, subscribers can retrieve the tracing header and continue to propagate the original trace from the publisher with the same trace ID. 
+ [Amazon Simple Queue Service](xray-services-sqs.md) – Passive instrumentation. If a service traces requests by using the X-Ray SDK, Amazon SQS can send the tracing header and continue to propagate the original trace from the sender to the consumer with a consistent trace ID. 
+ [Amazon Bedrock AgentCore](xray-services-sqs.md) – AgentCore supports distributed tracing through X-Ray integration, allowing you to track requests as they flow through your agent applications. When you enable observability for your AgentCore resources, you can propagate trace context across service boundaries and gain visibility into the performance of your AI agents and tools. 

Choose from the following topics to explore the full set of integrated AWS services.

**Topics**
+ [Amazon Bedrock AgentCore and AWS X-Ray](xray-services-agentcore.md)
+ [Amazon Elastic Compute Cloud and AWS X-Ray](xray-services-ec2.md)
+ [Amazon SNS and AWS X-Ray](xray-services-sns.md)
+ [Amazon SQS and AWS X-Ray](xray-services-sqs.md)
+ [Amazon S3 and AWS X-Ray](xray-services-s3.md)
+ [AWS Distro for OpenTelemetry and AWS X-Ray](xray-services-adot.md)
+ [Tracking X-Ray encryption configuration changes with AWS Config](xray-api-config.md)
+ [AWS AppSync and AWS X-Ray](xray-services-appsync.md)
+ [Amazon API Gateway active tracing support for AWS X-Ray](xray-services-apigateway.md)
+ [Amazon EC2 and AWS App Mesh](xray-services-appmesh.md)
+ [AWS App Runner and X-Ray](xray-services-app-runner.md)
+ [Logging X-Ray API calls with AWS CloudTrail](xray-api-cloudtrail.md)
+ [CloudWatch integration with X-Ray](xray-services-cloudwatch.md)
+ [AWS Elastic Beanstalk and AWS X-Ray](xray-services-beanstalk.md)
+ [Elastic Load Balancing and AWS X-Ray](xray-services-elb.md)
+ [Amazon EventBridge and AWS X-Ray](xray-services-eventbridge.md)
+ [AWS Lambda and AWS X-Ray](xray-services-lambda.md)
+ [AWS Step Functions and AWS X-Ray](xray-services-stepfunctions.md)

# Amazon Bedrock AgentCore and AWS X-Ray
<a name="xray-services-agentcore"></a>

Amazon Bedrock AgentCore integrates with AWS X-Ray to provide distributed tracing capabilities for your AI agents and tools. This integration allows you to track requests as they flow through your agent applications, helping you identify performance bottlenecks and troubleshoot issues.

AgentCore supports distributed tracing through X-Ray integration, allowing you to monitor the performance of your AI agents and tools. When you enable observability for your AgentCore resources, you can propagate trace context across service boundaries and gain visibility into how your agents interact with other AWS services. For more information, see [Amazon Bedrock AgentCore](https://docs.aws.amazon.com//bedrock-agentcore/latest/devguide/what-is-genesis.html). 

AgentCore supports the following X-Ray features:
+ Propagation of trace context to downstream services
+ Custom instrumentation using the AWS Distro for OpenTelemetry (ADOT) SDK

## Setting up X-Ray with AgentCore
<a name="xray-services-agentcore-settingup"></a>

To use X-Ray with AgentCore, you need to enable CloudWatch Transaction Search in your AWS account. This is a one-time setup that allows AgentCore to send trace data to X-Ray. For more information, see [Enable transaction search ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Transaction-Search.html).

For more information about setting up observability for AgentCore, see [Add observability to your Amazon Bedrock AgentCore agent or tool ](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/observability-configure.html).

## Using trace headers with AgentCore
<a name="xray-services-agentcore-trace"></a>

AgentCore supports the X-Ray trace header format for distributed tracing. You can include the `X-Amzn-Trace-Id` header in your requests to AgentCore to maintain trace context across service boundaries.

# Amazon Elastic Compute Cloud and AWS X-Ray
<a name="xray-services-ec2"></a>

You can install and run the X-Ray daemon on an Amazon EC2 instance with a user data script. See [Running the X-Ray daemon on Amazon EC2](xray-daemon-ec2.md) for instructions.

Use an instance profile to grant the daemon permission to upload trace data to X-Ray. For more information, see [Giving the daemon permission to send data to X-Ray](xray-daemon.md#xray-daemon-permissions).

# Amazon SNS and AWS X-Ray
<a name="xray-services-sns"></a>

You can use AWS X-Ray with Amazon Simple Notification Service (Amazon SNS) to trace and analyze requests as they travel through your SNS topics to your [SNS-supported subscription services](https://docs.aws.amazon.com/sns/latest/dg/sns-active-tracing.html). Use X-Ray tracing with Amazon SNS to analyze latencies in your messages and their back-end services, such as how long a request spends in a topic, and how long it takes to deliver the message to each of the topic’s subscriptions. Amazon SNS supports X-Ray tracing for both standard and FIFO topics.

If you publish to an Amazon SNS topic from a service that’s already instrumented with X-Ray, Amazon SNS passes the trace context from publisher to subscribers. In addition, you can turn on active tracing to send segment data about your Amazon SNS subscriptions to X-Ray for messages published from an instrumented SNS client. [Turn on active tracing](https://docs.aws.amazon.com/sns/latest/dg/sns-active-tracing.html) for an Amazon SNS topic by using the Amazon SNS console, or by using the Amazon SNS API or CLI. See [Instrumenting your application](xray-instrumenting-your-app.md) for more information about instrumenting your SNS clients. 

## Configure Amazon SNS active tracing
<a name="xray-services-sns-configuration"></a>

You can use the Amazon SNS console or the AWS CLI or SDK to configure Amazon SNS active tracing. 

When you use the Amazon SNS console, Amazon SNS attempts to create the necessary permissions for SNS to call X-Ray. The attempt can be rejected if you don't have sufficient permissions to modify X-Ray resource policies. For more information about these permissions, see [Identity and access management in Amazon SNS](https://docs.aws.amazon.com/sns/latest/dg/sns-authentication-and-access-control.html) and [Example cases for Amazon SNS access control](https://docs.aws.amazon.com/sns/latest/dg/sns-access-policy-use-cases.html) in the Amazon Simple Notification Service Developer Guide. For more information about turning on active tracing using the Amazon SNS console, see [Enabling active tracing on an Amazon SNS topic](https://docs.aws.amazon.com/sns/latest/dg/sns-active-tracing.html) in the Amazon Simple Notification Service Developer Guide. 

When using the AWS CLI or SDK to turn on active tracing, you must manually configure the permissions using resource-based policies. Use [https://docs.aws.amazon.com/xray/latest/api/API_PutResourcePolicy.html](https://docs.aws.amazon.com/xray/latest/api/API_PutResourcePolicy.html) to configure X-Ray with the necessary resource-based policy to allow Amazon SNS to send traces to X-Ray. 

**Example X-Ray resource-based policy for Amazon SNS active tracing**  
This example policy document specifies the permissions that Amazon SNS needs to send trace data to X-Ray:  

```
{
    Version: "2012-10-17",		 	 	 
    Statement: [
      {
        Sid: "SNSAccess",
        Effect: Allow,
        Principal: {
          Service: "sns.amazonaws.com",
        },
        Action: [
          "xray:PutTraceSegments",
          "xray:GetSamplingRules",
          "xray:GetSamplingTargets"
        ],
        Resource: "*",
        Condition: {
          StringEquals: {
            "aws:SourceAccount": "account-id"
          },
          StringLike: {
            "aws:SourceArn": "arn:partition:sns:region:account-id:topic-name"
          }
        }
      }
    ]
  }
```
Use the CLI to create a resource-based policy that gives Amazon SNS permissions to send trace data to X-Ray:   

```
aws xray put-resource-policy --policy-name MyResourcePolicy --policy-document '{ "Version": "2012-10-17",		 	 	  "Statement": [ { "Sid": "SNSAccess", "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": [ "xray:PutTraceSegments", "xray:GetSamplingRules", "xray:GetSamplingTargets" ], "Resource": "*", "Condition": { "StringEquals": { "aws:SourceAccount": "account-id" }, "StringLike": { "aws:SourceArn": "arn:partition:sns:region:account-id:topic-name" } } } ] }'
```
To use these examples, replace *`partition`*, *`region`*, *`account-id`*, and *`topic-name`* with your specific AWS partition, region, account ID, and Amazon SNS topic name. To give all Amazon SNS topics permission to send trace data to X-Ray, replace the topic name with `*`. 

## View Amazon SNS publisher and subscriber traces in the X-Ray console
<a name="xray-services-sns-view-traces"></a>

Use the X-Ray console to view a trace map and trace details that display a connected view of Amazon SNS publishers and subscribers. When Amazon SNS active tracing is turned on for a topic, the X-Ray trace map and trace details map displays connected nodes for Amazon SNS publishers, the Amazon SNS topic, and downstream subscribers: 

![\[Trace map with Amazon SNS publisher and subscriber\]](http://docs.aws.amazon.com/xray/latest/devguide/images/services-sns-activetracing-map.png)


After choosing a trace that spans an Amazon SNS publisher and subscriber, the X-Ray trace details page displays a trace details map and segment timeline. 

**Example timeline with Amazon SNS publisher and subscriber**  
This example shows a timeline that includes an Amazon SNS publisher that sends a message to an Amazon SNS topic, which is processed by an Amazon SQS subscriber.   

![\[Segment timeline for Amazon SNS publisher and subscriber\]](http://docs.aws.amazon.com/xray/latest/devguide/images/services-sns-activetracing-timeline.png)


The example timeline above provides details about the Amazon SNS message flow: 
+ The **SNS** segment represents the round-trip duration of the `Publish` API call from the client.
+ The **myTopic** segment represents the latency of the Amazon SNS response to the publish request.
+ The **SQS** subsegment represents the round-trip time it takes Amazon SNS to publish the message to an Amazon SQS queue.
+ The time between the **myTopic** segment and the **SQS** subsegment represents the time that the message spends in the Amazon SNS system.

**Example timeline with batched Amazon SNS messages**  
If multiple Amazon SNS messages are batched within a single trace, the segment timeline displays segments that represent each message that's processed.   

![\[Segment timeline for Amazon SNS batched messages\]](http://docs.aws.amazon.com/xray/latest/devguide/images/services-sns-activetracing-batch-timeline.png)


# Amazon SQS and AWS X-Ray
<a name="xray-services-sqs"></a>

AWS X-Ray integrates with Amazon Simple Queue Service (Amazon SQS) to trace messages that are passed through an Amazon SQS queue. If a service traces requests by using the X-Ray SDK, Amazon SQS can send the tracing header and continue to propagate the original trace from the sender to the consumer with a consistent trace ID. Trace continuity enables users to track, analyze, and debug throughout downstream services.

AWS X-Ray supports tracing event-driven applications using Amazon SQS and AWS Lambda. Use the CloudWatch console to see a connected view of each request as it's queued with Amazon SQS and processed by a downstream Lambda function. Traces from upstream message producers are automatically linked to traces from downstream Lambda consumer nodes, creating an end-to-end view of the application. For more information, see [tracing event-driven applications](xray-tracelinking.md). 

![\[Trace map from Lambda through the Amazon SQS queue.\]](http://docs.aws.amazon.com/xray/latest/devguide/images/console-batch-servicemap-linkededge.png)


Amazon SQS supports the following tracing header instrumentation:
+ **Default HTTP Header** – The X-Ray SDK automatically populates the trace header as an HTTP header when you call Amazon SQS through the AWS SDK. The default trace header is carried by `X-Amzn-Trace-Id` and corresponds to all messages included in a [https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html) or [https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessageBatch.html](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessageBatch.html) request. To learn more about the default HTTP header, see [Tracing header](xray-concepts.md#xray-concepts-tracingheader).
+ **`AWSTraceHeader` System Attribute** – The `AWSTraceHeader` is a [message system attribute](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_MessageSystemAttributeValue.html) reserved by Amazon SQS to carry the X-Ray trace header with messages in the queue. `AWSTraceHeader` is available for use even when auto-instrumentation through the X-Ray SDK is not, for example when building a tracing SDK for a new language. When both header instrumentations are set, the message system attribute overrides the HTTP trace header.

When running on Amazon EC2, Amazon SQS supports processing one message at a time. This applies when running on an on-premises host, and when using container services, such as AWS Fargate, Amazon ECS, or AWS App Mesh. 

The trace header is excluded from both Amazon SQS message size and message attribute quotas. Enabling X-Ray tracing will not exceed your Amazon SQS quotas. To learn more about AWS quotas, see [Amazon SQS Quotas](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-limits.html).

## Send the HTTP trace header
<a name="xray-services-sqs-sending"></a>

Sender components in Amazon SQS can send the trace header automatically through the [https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessageBatch.html](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessageBatch.html) or [https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html) call. When AWS SDK clients are instrumented, they can be automatically tracked through all languages supported through the X-Ray SDK. Traced AWS services and resources that you access within those services (for example, an Amazon S3 bucket or Amazon SQS queue), appear as downstream nodes on the trace map in the X-Ray console.

To learn how to trace AWS SDK calls with your preferred language, see the following topics in the supported SDKs:
+ Go – [Tracing AWS SDK calls with the X-Ray SDK for Go](xray-sdk-go-awssdkclients.md)
+ Java – [Tracing AWS SDK calls with the X-Ray SDK for Java](xray-sdk-java-awssdkclients.md)
+ Node.js – [Tracing AWS SDK calls with the X-Ray SDK for Node.js](xray-sdk-nodejs-awssdkclients.md)
+ Python – [Tracing AWS SDK calls with the X-Ray SDK for Python](xray-sdk-python-awssdkclients.md)
+ Ruby – [Tracing AWS SDK calls with the X-Ray SDK for Ruby](xray-sdk-ruby-awssdkclients.md)
+ .NET – [Tracing AWS SDK calls with the X-Ray SDK for .NET](xray-sdk-dotnet-sdkclients.md)

## Retrieve the trace header and recover trace context
<a name="xray-services-sqs-retrieving"></a>

If you are using a Lambda downstream consumer, trace context propagation is automatic. To continue context propagation with other Amazon SQS consumers, you must manually instrument the handoff to the receiver component.

There are three main steps to recovering the trace context:
+ Receive the message from the queue for the `AWSTraceHeader` attribute by calling the [https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ReceiveMessage.html](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ReceiveMessage.html) API.
+ Retrieve the trace header from the attribute.
+ Recover the trace ID from the header. Optionally, add more metrics to the segment.

The following is an example implementation written with the X-Ray SDK for Java.

**Example : Retrieve the trace header and recover trace context**  

```
// Receive the message from the queue, specifying the "AWSTraceHeader"
ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest()
        .withQueueUrl(QUEUE_URL)
        .withAttributeNames("AWSTraceHeader");
List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();

if (!messages.isEmpty()) {
    Message message = messages.get(0);
    
    // Retrieve the trace header from the AWSTraceHeader message system attribute
    String traceHeaderStr = message.getAttributes().get("AWSTraceHeader");
    if (traceHeaderStr != null) {
        TraceHeader traceHeader = TraceHeader.fromString(traceHeaderStr);

        // Recover the trace context from the trace header
        Segment segment = AWSXRay.getCurrentSegment();
        segment.setTraceId(traceHeader.getRootTraceId());
        segment.setParentId(traceHeader.getParentId());
        segment.setSampled(traceHeader.getSampled().equals(TraceHeader.SampleDecision.SAMPLED));
    }
}
```

# Amazon S3 and AWS X-Ray
<a name="xray-services-s3"></a>

AWS X-Ray integrates with Amazon S3 to trace upstream requests to update your application's S3 buckets. If a service traces requests by using the X-Ray SDK, Amazon S3 can send the tracing headers to downstream event subscribers such as AWS Lambda, Amazon SQS, and Amazon SNS. X-Ray enables trace messages for Amazon S3 event notifications.

You can use the X-Ray trace map to view the connections between Amazon S3 and other services that your application uses. You can also use the console to view metrics such as average latency and failure rates. For more information about the X-Ray console, see [Use the X-Ray console](aws-xray-interface-console.md#xray-console).

Amazon S3 supports the *default http header* instrumentation. The X-Ray SDK automatically populates the trace header as an HTTP header when you call Amazon S3 through the AWS SDK. The default trace header is carried by `X-Amzn-Trace-Id`. To learn more about tracing headers, see [Tracing header](xray-concepts.md#xray-concepts-tracingheader) on the concept page. Amazon S3 trace context propagation supports the following subscribers: Lambda, SQS and SNS. Because SQS and SNS don't emit segment data themselves, they won't appear in your trace or trace map when triggered by S3, even though they will propagate the tracing header to downstream services.

## Configure Amazon S3 event notifications
<a name="xray-services-s3-notification"></a>

With the Amazon S3 notification feature, you receive notifications when certain events happen in your bucket. These notifications can then be propagated to the following destinations within your application:
+ Amazon Simple Notification Service (Amazon SNS)
+ Amazon Simple Queue Service (Amazon SQS)
+ AWS Lambda

For a list of supported events, see [Supported event types in the Amazon S3 developer guide](https://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html#supported-notification-event-types).

### Amazon SNS and Amazon SQS
<a name="xray-services-s3-notifications-snssqs"></a>

To publish notifications to an SNS topic or an SQS queue, you must first grant Amazon S3 permissions. To grant these permissions, you attach an AWS Identity and Access Management (IAM) policy to the destination SNS topic or SQS queue. To learn more about the IAM policies required, see [Granting permissions to publish messages to an SNS topic or an SQS queue](https://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html#grant-sns-sqs-permission-for-s3). 

For information about integrating SNS and SQS with X-Ray see, [Amazon SNS and AWS X-Ray](xray-services-sns.md) and [Amazon SQS and AWS X-Ray](xray-services-sqs.md).

### AWS Lambda
<a name="xray-services-s3-notifications-lambda"></a>

When you use the Amazon S3 console to configure event notifications on an S3 bucket for a Lambda function, the console sets up the necessary permissions on the Lambda function so that Amazon S3 has permissions to invoke the function from the bucket. For more information, see [How Do I Enable and Configure Event Notifications for an S3 Bucket?](https://docs.aws.amazon.com/AmazonS3/latest/user-guide/enable-event-notifications.html) in the Amazon Simple Storage Service Console User Guide.

You can also grant Amazon S3 permissions from AWS Lambda to invoke your Lambda function. For more information, see [Tutorial: Using AWS Lambda with Amazon S3](https://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html) in the AWS Lambda Developer Guide. 

For more information about integrating Lambda with X-Ray, see [Instrumenting Java code in AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/java-tracing.html).

# AWS Distro for OpenTelemetry and AWS X-Ray
<a name="xray-services-adot"></a>

Use the AWS Distro for OpenTelemetry (ADOT) to collect and send metrics and traces to AWS X-Ray and other monitoring solutions, such as Amazon CloudWatch, Amazon OpenSearch Service, and Amazon Managed Service for Prometheus. 

## AWS Distro for OpenTelemetry
<a name="xray-services-adot-intro"></a>

The AWS Distro for OpenTelemetry (ADOT) is an AWS distribution based on the Cloud Native Computing Foundation (CNCF) OpenTelemetry project. OpenTelemetry provides a single set of open source APIs, libraries, and agents to collect distributed traces and metrics. This toolkit is a distribution of upstream OpenTelemetry components including SDKs, auto-instrumentation agents, and collectors that are tested, optimized, secured, and supported by AWS. 

With ADOT, engineers can instrument their applications once and send correlated metrics and traces to multiple AWS monitoring solutions including Amazon CloudWatch, AWS X-Ray, Amazon OpenSearch Service, and Amazon Managed Service for Prometheus.

ADOT is integrated with a growing number of AWS services to simplify sending traces and metrics to monitoring solutions such as X-Ray. Some examples of services integrated with ADOT include: 
+ *AWS Lambda* – AWS managed Lambda layers for ADOT provides a plug-and-play user experience by automatically instrumenting a Lambda function, packaging OpenTelemetry together with an out-of-the-box configuration for AWS Lambda and X-Ray in an easy to setup layer. Users can enable and disable OpenTelemetry for their Lambda function without changing code. For more information, see [AWS Distro for OpenTelemetry Lambda](https://aws-otel.github.io/docs/getting-started/lambda) 
+ *Amazon Elastic Container Service (ECS)* – Collect metrics and traces from Amazon ECS applications using the AWS Distro for OpenTelemetry Collector, to send to X-Ray and other monitoring solutions. For more information, see [Collecting application trace data](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/trace-data.html) in the Amazon ECS developer guide. 
+ *AWS App Runner* – App Runner supports sending traces to X-Ray using the AWS Distro for OpenTelemetry (ADOT). Use ADOT SDKs to collect trace data for your containerized applications, and use X-Ray to analyze and gain insights into your instrumented application. For more information, see [AWS App Runner and X-Ray](xray-services-app-runner.md). 

For more information about the AWS Distro for OpenTelemetry, including integration with additional AWS services, see the [AWS Distro for OpenTelemetry Documentation](https://aws-otel.github.io/docs/introduction). 

For more information about instrumenting your application with AWS Distro for OpenTelemetry and X-Ray, see [Instrumenting your application with the AWS Distro for OpenTelemetry](xray-instrumenting-your-app.md#xray-instrumenting-opentel). 

# Tracking X-Ray encryption configuration changes with AWS Config
<a name="xray-api-config"></a>

AWS X-Ray integrates with AWS Config to record configuration changes made to your X-Ray encryption resources. You can use AWS Config to inventory X-Ray encryption resources, audit the X-Ray configuration history, and send notifications based on resource changes.

AWS Config supports logging the following X-Ray encryption resource changes as events:
+ **Configuration changes** – Changing or adding an encryption key, or reverting to the default X-Ray encryption setting.

Use the following instructions to learn how to create a basic connection between X-Ray and AWS Config. 

## Creating a Lambda function trigger
<a name="LambdaFunctionTrigger"></a>

You must have the ARN of a custom AWS Lambda function before you can generate a custom AWS Config rule. Follow these instructions to create a basic function with Node.js that returns a compliant or non-compliant value back to AWS Config based on the state of the `XrayEncryptionConfig` resource.

**To create a Lambda function with an AWS::XrayEncryptionConfig change trigger**

1. Open the [Lambda console](https://console.aws.amazon.com/lambda/home). Choose **Create function**.

1. Choose **Blueprints**, and then filter the blueprints library for the **config-rule-change-triggered** blueprint. Either click the link in the blueprint's name or choose **Configure** to continue.

1. Define the following fields to configure the blueprint:
   + For **Name**, type a name.
   + For **Role**, choose **Create new role from template(s)**.
   + For **Role name**, type a name.
   + For **Policy templates**, choose **AWS Config Rules permissions**.

1. Choose **Create function** to create and display your function in the AWS Lambda console.

1. Edit your function code to replace `AWS::EC2::Instance` with `AWS::XrayEncryptionConfig`. You can also update the description field to reflect this change.

   **Default Code**

   ```
       if (configurationItem.resourceType !== 'AWS::EC2::Instance') {
           return 'NOT_APPLICABLE';
       } else if (ruleParameters.desiredInstanceType === configurationItem.configuration.instanceType) {
           return 'COMPLIANT';
       }
           return 'NON_COMPLIANT';
   ```

   **Updated Code**

   ```
       if (configurationItem.resourceType !== 'AWS::XRay::EncryptionConfig') {
           return 'NOT_APPLICABLE';
       } else if (ruleParameters.desiredInstanceType === configurationItem.configuration.instanceType) {
           return 'COMPLIANT';
       }
           return 'NON_COMPLIANT';
   ```

1. Add the following to your execution role in IAM for access to X-Ray. These permissions allow read-only access to your X-Ray resources. Failure to provide access to the appropriate resources will result in an out of scope message from AWS Config when it evaluates the Lambda function associated with the rule.

   ```
       {
           "Sid": "Stmt1529350291539",
           "Action": [
               "xray:GetEncryptionConfig"
           ],
           "Effect": "Allow",
           "Resource": "*"
        }
   ```

## Creating a custom AWS Config rule for x-ray
<a name="ConfigRule"></a>

When the Lambda function is created, note the function's ARN, and go to the AWS Config console to create your custom rule. 

**To create an AWS Config rule for X-Ray**

1. Open the [**Rules** page of the AWS Config console](https://console.aws.amazon.com/config/home#/rules/view).

1. Choose **Add rule**, and then choose **Add custom rule**.

1. In **AWS Lambda Function ARN**, insert the ARN associated with the Lambda function you want to use.

1. Choose the type of trigger to set:
   + **Configuration changes** – AWS Config triggers the evaluation when any resource that matches the rule's scope changes in configuration. The evaluation runs after AWS Config sends a configuration item change notification.
   + **Periodic** – AWS Config runs evaluations for the rule at a frequency that you choose (for example, every 24 hours).

1. For **Resource type**, choose **EncryptionConfig** in the X-Ray section.

1. Choose ****Save****.

The AWS Config console begins to evaluate the rule's compliance immediately. The evaluation can take several minutes to complete.

Now that this rule is compliant, AWS Config can begin to compile an audit history. AWS Config records resource changes in the form of a timeline. For each change in the timeline of events, AWS Config generates a table in a from/to format to show what changed in the JSON representation of the encryption key. The two field changes associated with EncryptionConfig are `Configuration.type` and `Configuration.keyID`.

## Example results
<a name="Examples"></a>

Following is an example of an AWS Config timeline showing changes made at specific dates and times.

![\[AWS Config timeline.\]](http://docs.aws.amazon.com/xray/latest/devguide/images/ConfigTimeline.png)


Following is an example of an AWS Config change entry. The from/to format illustrates what changed. This example shows that the default X-Ray encryption settings were changed to a defined encryption key.

![\[X-Ray encryption configuration change entry.\]](http://docs.aws.amazon.com/xray/latest/devguide/images/ConfigChanges.png)


## Amazon SNS notifications
<a name="SNSNotifs"></a>

To be notified of configuration changes, set AWS Config to publish Amazon SNS notifications. For more information, see [Monitoring AWS Config Resource Changes by Email](https://docs.aws.amazon.com/config/latest/developerguide/monitoring-resource-changes-by-email.html).

# AWS AppSync and AWS X-Ray
<a name="xray-services-appsync"></a>

You can enable and trace requests for AWS AppSync. For more information, see [Tracing with AWS X-Ray](https://docs.aws.amazon.com/appsync/latest/devguide/x-ray-tracing.html) for instructions.

When X-Ray tracing is enabled for an AWS AppSync API, an AWS Identity and Access Management [service-linked role](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html) is automatically created in your account with the appropriate permissions. This allows AWS AppSync to send traces to X-Ray in a secure way.

# Amazon API Gateway active tracing support for AWS X-Ray
<a name="xray-services-apigateway"></a>

You can use X-Ray to trace and analyze user requests as they travel through your Amazon API Gateway APIs to the underlying services. API Gateway supports X-Ray tracing for all API Gateway endpoint types: Regional, edge-optimized, and private. You can use X-Ray with Amazon API Gateway in all AWS Regions where X-Ray is available. For more information, see [Trace API Gateway API Execution with AWS X-Ray](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-xray.html) in the Amazon API Gateway Developer Guide.

**Note**  
X-Ray only supports tracing for REST APIs through API Gateway.

Amazon API Gateway provides [active tracing](xray-services.md) support for AWS X-Ray. Enable active tracing on your API stages to sample incoming requests and send traces to X-Ray.

**To enable active tracing on an API stage**

1. Open the API Gateway console at [https://console.aws.amazon.com/apigateway/](https://console.aws.amazon.com/apigateway/). 

1. Choose an API.

1. Choose a stage.

1. On the **Logs/Tracing** tab, choose **Enable X-Ray Tracing** and then choose **Save Changes**.

1. Choose **Resources** in the left side navigation panel.

1. To redeploy the API with the new settings, choose the **Actions** dropdown, and then choose **Deploy API**.

API Gateway uses sampling rules that you define in the X-Ray console to determine which requests to record. You can create rules that only apply to APIs, or that apply only to requests that contain certain headers. API Gateway records headers in attributes on the segment, along with details about the stage and request. For more information, see [Configuring sampling rules](xray-console-sampling.md).

**Note**  
When tracing REST APIs with API Gateway [HTTP integration](https://docs.aws.amazon.com/apigateway/latest/developerguide/setup-http-integrations.html), each segment's service name is set to the request URL path from API Gateway to your HTTP integration endpoint, resulting in a service node on the X-Ray trace map for each unique URL path. A large number of URL paths may cause the trace map to exceed the limit of 10,000 nodes, resulting in an error.  
To minimize the number of service nodes created by API Gateway, consider passing parameters within the URL query string or in the request body via POST. Either approach will ensure parameters are not part of the URL path, which may result in fewer distinct URL paths and service nodes. 

For all incoming requests, API Gateway adds a [tracing header](xray-concepts.md#xray-concepts-tracingheader) to incoming HTTP requests that don't already have one.

```
X-Amzn-Trace-Id: Root=1-5759e988-bd862e3fe1be46a994272793
```

**X-Ray trace ID format**

An X-Ray `trace_id` consists of three numbers separated by hyphens. For example, `1-58406520-a006649127e371903a2de979`. This includes:
+ The version number, which is `1`.
+ The time of the original request in Unix epoch time using **8 hexadecimal digits**.

  For example, 10:00AM December 1st, 2016 PST in epoch time is `1480615200` seconds or `58406520` in hexadecimal digits.
+ A globally unique 96-bit identifier for the trace in **24 hexadecimal digits**.

If active tracing is disabled, the stage still records a segment if the request comes from a service that sampled the request and started a trace. For example, an instrumented web application can call an API Gateway API with an HTTP client. When you instrument an HTTP client with the X-Ray SDK, it adds a tracing header to the outgoing request that contains the sampling decision. API Gateway reads the tracing header and creates a segment for sampled requests.

If you use API Gateway to [generate a Java SDK for your API](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-generate-sdk.html), you can instrument the SDK client by adding a request handler with the client builder, in the same way that you would manually instrument an AWS SDK client. See [Tracing AWS SDK calls with the X-Ray SDK for Java](xray-sdk-java-awssdkclients.md) for instructions.

# Amazon EC2 and AWS App Mesh
<a name="xray-services-appmesh"></a>

AWS X-Ray integrates with [AWS App Mesh](https://docs.aws.amazon.com/app-mesh/latest/userguide/what-is-app-mesh.html) to manage Envoy proxies for microservices. App Mesh provides a version of Envoy that you can configure to send trace data to the X-Ray daemon running in a container of the same task or pod. X-Ray supports tracing with the following App Mesh compatible services: 
+ Amazon Elastic Container Service (Amazon ECS)
+ Amazon Elastic Kubernetes Service (Amazon EKS)
+ Amazon Elastic Compute Cloud (Amazon EC2)

Use the following instructions to learn how to enable X-Ray tracing through App Mesh.

![\[A trace map that shows traces between clients and App Mesh services.\]](http://docs.aws.amazon.com/xray/latest/devguide/images/appmesh-traceContents.png)


To configure the Envoy proxy to send data to X-Ray, set the `ENABLE_ENVOY_XRAY_TRACING` [environment variable](https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html#envoy-config) in its container definition.

**Note**  
The App Mesh version of Envoy does not currently send traces based on configured [sampling rules](https://docs.aws.amazon.com/xray/latest/devguide/xray-console-sampling.html). Instead, it uses a fixed sampling rate of 5% for Envoy version 1.16.3 or newer, or a 50% sampling rate for Envoy versions prior to 1.16.3. 

**Example Envoy container definition for Amazon ECS**  

```
{
      "name": "envoy",
      "image": "public.ecr.aws/appmesh/aws-appmesh-envoy:envoy-version",
      "essential": true,
      "environment": [
        {
          "name": "APPMESH_VIRTUAL_NODE_NAME",
          "value": "mesh/myMesh/virtualNode/myNode"
        },
        {
          "name": "ENABLE_ENVOY_XRAY_TRACING",
          "value": "1"
        }
      ],
      "healthCheck": {
        "command": [
          "CMD-SHELL",
          "curl -s http://localhost:9901/server_info | cut -d' ' -f3 | grep -q live"
        ],
        "startPeriod": 10,
        "interval": 5,
        "timeout": 2,
        "retries": 3
      }
```

**Note**  
To learn more about available Envoy region addresses, see [Envoy image](https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html) in the AWS App Mesh User Guide.

For details on running the X-Ray daemon in a container, see [Running the X-Ray daemon on Amazon ECS](xray-daemon-ecs.md). For a sample application that includes a service mesh, microservice, Envoy proxy, and X-Ray daemon, deploy the `colorapp` sample in the [App Mesh Examples GitHub repository](https://github.com/aws/aws-app-mesh-examples/tree/master/examples).

**Learn More**
+ [Getting Started with AWS App Mesh](https://docs.aws.amazon.com/app-mesh/latest/userguide/getting_started.html)
+ [Getting Started with AWS App Mesh and Amazon ECS](https://docs.aws.amazon.com/app-mesh/latest/userguide/mesh-getting-started-ecs.html)

# AWS App Runner and X-Ray
<a name="xray-services-app-runner"></a>

 AWS App Runner is an AWS service that provides a fast, simple, and cost-effective way to deploy from source code or a container image directly to a scalable and secure web application in the AWS Cloud. You don't need to learn new technologies, decide which compute service to use, or know how to provision and configure AWS resources. See [What is AWS App Runner](https://docs.aws.amazon.com/apprunner/latest/dg/what-is-apprunner.html) for more information. 

 AWS App Runner sends traces to X-Ray by integrating with the [AWS Distro for OpenTelemetry](xray-services-adot.md) (ADOT). Use ADOT SDKs to collect trace data for your containerized applications, and use X-Ray to analyze and gain insights into your instrumented application. For more information, see [Tracing for your App Runner application with X-Ray](https://docs.aws.amazon.com/apprunner/latest/dg/monitor-xray.html). 

# Logging X-Ray API calls with AWS CloudTrail
<a name="xray-api-cloudtrail"></a>

AWS X-Ray is integrated with [AWS CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html), a service that provides a record of actions taken by a user, role, or an AWS service. CloudTrail captures all API calls for X-Ray as events. The calls captured include calls from the X-Ray console and code calls to the X-Ray API operations. Using the information collected by CloudTrail, you can determine the request that was made to X-Ray, the IP address from which the request was made, when it was made, and additional details.

Every event or log entry contains information about who generated the request. The identity information helps you determine the following:
+ Whether the request was made with root user or user credentials.
+ Whether the request was made on behalf of an IAM Identity Center user.
+ Whether the request was made with temporary security credentials for a role or federated user.
+ Whether the request was made by another AWS service.

CloudTrail is active in your AWS account when you create the account and you automatically have access to the CloudTrail **Event history**. The CloudTrail **Event history** provides a viewable, searchable, downloadable, and immutable record of the past 90 days of recorded management events in an AWS Region. For more information, see [Working with CloudTrail Event history](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/view-cloudtrail-events.html) in the *AWS CloudTrail User Guide*. There are no CloudTrail charges for viewing the **Event history**.

For an ongoing record of events in your AWS account past 90 days, create a trail or a [CloudTrail Lake](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-lake.html) event data store.

**CloudTrail trails**  
A *trail* enables CloudTrail to deliver log files to an Amazon S3 bucket. All trails created using the AWS Management Console are multi-Region. You can create a single-Region or a multi-Region trail by using the AWS CLI. Creating a multi-Region trail is recommended because you capture activity in all AWS Regions in your account. If you create a single-Region trail, you can view only the events logged in the trail's AWS Region. For more information about trails, see [Creating a trail for your AWS account](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-create-and-update-a-trail.html) and [Creating a trail for an organization](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/creating-trail-organization.html) in the *AWS CloudTrail User Guide*.  
You can deliver one copy of your ongoing management events to your Amazon S3 bucket at no charge from CloudTrail by creating a trail, however, there are Amazon S3 storage charges. For more information about CloudTrail pricing, see [AWS CloudTrail Pricing](https://aws.amazon.com/cloudtrail/pricing/). For information about Amazon S3 pricing, see [Amazon S3 Pricing](https://aws.amazon.com/s3/pricing/).

**CloudTrail Lake event data stores**  
*CloudTrail Lake* lets you run SQL-based queries on your events. CloudTrail Lake converts existing events in row-based JSON format to [ Apache ORC](https://orc.apache.org/) format. ORC is a columnar storage format that is optimized for fast retrieval of data. Events are aggregated into *event data stores*, which are immutable collections of events based on criteria that you select by applying [advanced event selectors](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-lake-concepts.html#adv-event-selectors). The selectors that you apply to an event data store control which events persist and are available for you to query. For more information about CloudTrail Lake, see [Working with AWS CloudTrail Lake](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-lake.html) in the *AWS CloudTrail User Guide*.  
CloudTrail Lake event data stores and queries incur costs. When you create an event data store, you choose the [pricing option](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-lake-manage-costs.html#cloudtrail-lake-manage-costs-pricing-option) you want to use for the event data store. The pricing option determines the cost for ingesting and storing events, and the default and maximum retention period for the event data store. For more information about CloudTrail pricing, see [AWS CloudTrail Pricing](https://aws.amazon.com/cloudtrail/pricing/).

**Topics**
+ [X-Ray management events in CloudTrail](#xray-api-cloudtrail-mgmt)
+ [X-Ray data events in CloudTrail](#cloudtrail-data-events)
+ [X-Ray event examples](#xray-cloudtrail-examples)

## X-Ray management events in CloudTrail
<a name="xray-api-cloudtrail-mgmt"></a>

AWS X-Ray integrates with AWS CloudTrail to record API actions made by a user, a role, or an AWS service in X-Ray. You can use CloudTrail to monitor X-Ray API requests in real time and store logs in Amazon S3, Amazon CloudWatch Logs, and Amazon CloudWatch Events. X-Ray supports logging the following actions as events in CloudTrail log files:

**Supported API Actions**
+ [https://docs.aws.amazon.com/xray/latest/api/API_PutEncryptionConfig.html](https://docs.aws.amazon.com/xray/latest/api/API_PutEncryptionConfig.html)
+ [https://docs.aws.amazon.com/xray/latest/api/API_GetEncryptionConfig.html](https://docs.aws.amazon.com/xray/latest/api/API_GetEncryptionConfig.html)
+ [https://docs.aws.amazon.com/xray/latest/api/API_CreateGroup.html](https://docs.aws.amazon.com/xray/latest/api/API_CreateGroup.html)
+ [https://docs.aws.amazon.com/xray/latest/api/API_UpdateGroup.html](https://docs.aws.amazon.com/xray/latest/api/API_UpdateGroup.html)
+ [https://docs.aws.amazon.com/xray/latest/api/API_DeleteGroup.html](https://docs.aws.amazon.com/xray/latest/api/API_DeleteGroup.html)
+ [https://docs.aws.amazon.com/xray/latest/api/API_GetGroup.html](https://docs.aws.amazon.com/xray/latest/api/API_GetGroup.html)
+ [https://docs.aws.amazon.com/xray/latest/api/API_GetGroups.html](https://docs.aws.amazon.com/xray/latest/api/API_GetGroups.html)
+ [https://docs.aws.amazon.com/xray/latest/api/API_GetInsight.html](https://docs.aws.amazon.com/xray/latest/api/API_GetInsight.html)
+ [https://docs.aws.amazon.com/xray/latest/api/API_GetInsightEvents.html](https://docs.aws.amazon.com/xray/latest/api/API_GetInsightEvents.html)
+ [https://docs.aws.amazon.com/xray/latest/api/API_GetInsightImpactGraph.html](https://docs.aws.amazon.com/xray/latest/api/API_GetInsightImpactGraph.html)
+ [https://docs.aws.amazon.com/xray/latest/api/API_GetInsightSummaries.html](https://docs.aws.amazon.com/xray/latest/api/API_GetInsightSummaries.html)
+ [https://docs.aws.amazon.com/xray/latest/api/API_GetSamplingStatisticSummaries.html](https://docs.aws.amazon.com/xray/latest/api/API_GetSamplingStatisticSummaries.html)

## X-Ray data events in CloudTrail
<a name="cloudtrail-data-events"></a>

[Data events](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-data-events-with-cloudtrail.html#logging-data-events) provide information about the resource operations performed on or in a resource (for example, [https://docs.aws.amazon.com/xray/latest/api/API_PutTraceSegments.html](https://docs.aws.amazon.com/xray/latest/api/API_PutTraceSegments.html), which uploads segment documents to X-Ray).

These are also known as data plane operations. Data events are often high-volume activities. By default, CloudTrail doesn’t log data events. The CloudTrail **Event history** doesn't record data events.

Additional charges apply for data events. For more information about CloudTrail pricing, see [AWS CloudTrail Pricing](https://aws.amazon.com/cloudtrail/pricing/).

You can log data events for the X-Ray resource types by using the CloudTrail console, AWS CLI, or CloudTrail API operations. For more information about how to log data events, see [Logging data events with the AWS Management Console](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-data-events-with-cloudtrail.html#logging-data-events-console) and [Logging data events with the AWS Command Line Interface](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-data-events-with-cloudtrail.html#creating-data-event-selectors-with-the-AWS-CLI) in the *AWS CloudTrail User Guide*.

The following table lists the X-Ray resource types for which you can log data events. The **Data event type (console)** column shows the value to choose from the **Data event type** list on the CloudTrail console. The **resources.type value** column shows the `resources.type` value, which you would specify when configuring advanced event selectors using the AWS CLI or CloudTrail APIs. The **Data APIs logged to CloudTrail** column shows the API calls logged to CloudTrail for the resource type. 


| Data event type (console) | resources.type value | Data APIs logged to CloudTrail | 
| --- | --- | --- | 
| X-Ray trace |  AWS::XRay::Trace  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/xray/latest/devguide/xray-api-cloudtrail.html)  | 

You can configure advanced event selectors to filter on the `eventName` and `readOnly` fields to log only those events that are important to you. However, you cannot select events by adding the `resources.ARN` field selector, because X-Ray traces do not have ARNs. For more information about these fields, see [https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_AdvancedFieldSelector.html](https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_AdvancedFieldSelector.html) in the *AWS CloudTrail API Reference*. The following is an example of how to run the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/put-event-selectors.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/put-event-selectors.html) AWS CLI command to log data events on a CloudTrail trail. You must run the command in or specify the Region in which the trail was created; otherwise, the operation returns an `InvalidHomeRegionException` exception.

```
aws cloudtrail put-event-selectors --trail-name myTrail --advanced-event-selectors \
'{
   "AdvancedEventSelectors": [ 
      {
         "FieldSelectors": [
            { "Field": "eventCategory", "Equals": ["Data"] },
            { "Field": "resources.type", "Equals": ["AWS::XRay::Trace"] },
            { "Field": "eventName", "Equals": ["PutTraceSegments","GetSamplingTargets"] }
         ],
         "Name": "Log X-Ray PutTraceSegments and GetSamplingTargets data events"
      }
   ]
}'
```

## X-Ray event examples
<a name="xray-cloudtrail-examples"></a>

### Management event example, `GetEncryptionConfig`
<a name="xray-example-management"></a>

The following is an example of the X-Ray GetEncryptionConfig log entry in CloudTrail.

**Example**  

```
{
    "eventVersion"=>"1.05",
    "userIdentity"=>{
        "type"=>"AssumedRole",
        "principalId"=>"AROAJVHBZWD3DN6CI2MHM:MyName",
        "arn"=>"arn:aws:sts::123456789012:assumed-role/MyRole/MyName",
        "accountId"=>"123456789012",
        "accessKeyId"=>"AKIAIOSFODNN7EXAMPLE",
        "sessionContext"=>{
            "attributes"=>{
                "mfaAuthenticated"=>"false",
                "creationDate"=>"2023-7-01T00:24:36Z"
            },
            "sessionIssuer"=>{
                "type"=>"Role",
                "principalId"=>"AROAJVHBZWD3DN6CI2MHM",
                "arn"=>"arn:aws:iam::123456789012:role/MyRole",
                "accountId"=>"123456789012",
                "userName"=>"MyRole"
            }
        }
    },
    "eventTime"=>"2023-7-01T00:24:36Z",
    "eventSource"=>"xray.amazonaws.com",
    "eventName"=>"GetEncryptionConfig",
    "awsRegion"=>"us-east-2",
    "sourceIPAddress"=>"33.255.33.255",
    "userAgent"=>"aws-sdk-ruby2/2.11.19 ruby/2.3.1 x86_64-linux",
    "requestParameters"=>nil,
    "responseElements"=>nil,
    "requestID"=>"3fda699a-32e7-4c20-37af-edc2be5acbdb",
    "eventID"=>"039c3d45-6baa-11e3-2f3e-e5a036343c9f",
    "eventType"=>"AwsApiCall",
    "recipientAccountId"=>"123456789012"
}
```

### Data event example, `PutTraceSegments`
<a name="xray-example-data"></a>

The following is an example of the X-Ray PutTraceSegments data event log entry in CloudTrail.

**Example**  

```
{
  "eventVersion": "1.09",
  "userIdentity": {
    "type": "AssumedRole",
    "principalId": "AROAWYXPW54Y4NEXAMPLE:i-0dzz2ac111c83zz0z",
    "arn": "arn:aws:sts::012345678910:assumed-role/my-service-role/i-0dzz2ac111c83zz0z",
    "accountId": "012345678910",
    "accessKeyId": "AKIAIOSFODNN7EXAMPLE",
    "sessionContext": {
      "sessionIssuer": {
        "type": "Role",
        "principalId": "AROAWYXPW54Y4NEXAMPLE",
        "arn": "arn:aws:iam::012345678910:role/service-role/my-service-role",
        "accountId": "012345678910",
        "userName": "my-service-role"
      },
      "attributes": {
        "creationDate": "2024-01-22T17:34:11Z",
        "mfaAuthenticated": "false"
      },
      "ec2RoleDelivery": "2.0"
    }
  },
  "eventTime": "2024-01-22T18:22:05Z",
  "eventSource": "xray.amazonaws.com",
  "eventName": "PutTraceSegments",
  "awsRegion": "us-west-2",
  "sourceIPAddress": "198.51.100.0",
  "userAgent": "aws-sdk-ruby3/3.190.0 md/internal ua/2.0 api/xray#1.0.0 os/linux md/x86_64 lang/ruby#2.7.8 md/2.7.8 cfg/retry-mode#legacy",
  "requestParameters": {
    "traceSegmentDocuments": [
      "trace_id:1-00zzz24z-EXAMPLE4f4e41754c77d0000",
      "trace_id:1-00zzz24z-EXAMPLE4f4e41754c77d0000",
      "trace_id:1-00zzz24z-EXAMPLE4f4e41754c77d0001",
      "trace_id:1-00zzz24z-EXAMPLE4f4e41754c77d0002"
    ]
  },
  "responseElements": {
    "unprocessedTraceSegments": []
  },
  "requestID": "5zzzzz64-acbd-46ff-z544-451a3ebcb2f8",
  "eventID": "4zz51z7z-77f9-44zz-9bd7-6c8327740f2e",
  "readOnly": false,
  "resources": [
    {
      "type": "AWS::XRay::Trace"
    }
  ],
  "eventType": "AwsApiCall",
  "managementEvent": false,
  "recipientAccountId": "012345678910",
  "eventCategory": "Data",
  "tlsDetails": {
    "tlsVersion": "TLSv1.2",
    "cipherSuite": "ZZZZZ-RSA-AAA128-GCM-SHA256",
    "clientProvidedHostHeader": "example.us-west-2.xray.cloudwatch.aws.dev"
  }
}
```

# CloudWatch integration with X-Ray
<a name="xray-services-cloudwatch"></a>

AWS X-Ray integrates with [CloudWatch Application Signals](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Monitoring-Sections.html), CloudWatch RUM, and CloudWatch Synthetics to make it easier to monitor the health of your applications. Enable your application for Application Signals to monitor and troubleshoot the operational health of your services, client pages, Synthetics canaries, and service dependencies.

By correlating CloudWatch metrics, logs, and X-Ray traces, the X-Ray trace map provides an end-to-end view of your services to help you quickly pinpoint performance bottlenecks and identify impacted users.

With CloudWatch RUM, you can perform real user monitoring to collect and view client-side data about your web application performance from actual user sessions in near-real time. With AWS X-Ray and CloudWatch RUM, you can analyze and debug the request path starting from end users of your application through downstream AWS managed services. This helps you identify latency trends and errors that impact your end users. 

**Topics**
+ [CloudWatch RUM and AWS X-Ray](xray-services-RUM.md)
+ [Debugging CloudWatch synthetics canaries using X-Ray](xray-services-cloudwatch-synthetics.md)

# CloudWatch RUM and AWS X-Ray
<a name="xray-services-RUM"></a>

With Amazon CloudWatch RUM, you can perform real user monitoring to collect and view client-side data about your web application performance from actual user sessions in near-real time. With AWS X-Ray and CloudWatch RUM, you can analyze and debug the request path starting from end users of your application through downstream AWS managed services. This helps you identify latency trends and errors that impact your end users. 

After you turn on X-Ray tracing of user sessions, CloudWatch RUM adds an X-Ray trace header to allowed HTTP requests, and records an X-Ray segment for allowed HTTP requests. You can then see traces and segments from these user sessions in the X-Ray and CloudWatch consoles, including the X-Ray trace map. 

**Note**  
CloudWatch RUM doesn't integrate with X-Ray sampling rules. Instead, choose a sampling percentage when you set up your application to use CloudWatch RUM. Traces sent from CloudWatch RUM might incur additional costs. For more information, see [AWS X-Ray pricing](https://aws.amazon.com/xray/pricing/). 

By default, client-side traces sent from CloudWatch RUM aren't connected to server-side traces. To connect client-side traces with server-side traces, configure the CloudWatch RUM web client to add an X-Ray trace header to these HTTP requests. 

**Warning**  
Configuring the CloudWatch RUM web client to add an X-Ray trace header to HTTP requests can cause cross-origin resource sharing (CORS) to fail. To avoid this, add the `X-Amzn-Trace-Id` HTTP header to the list of allowed headers on your downstream service's CORS configuration. If you are using API Gateway as your downstream, see [Enabling CORS for a REST API resource](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html). We strongly recommend that you test your application before adding a client-side X-Ray trace header in a production environment. For more information, see the [ CloudWatch RUM web client documentation](https://github.com/aws-observability/aws-rum-web/blob/main/docs/cdn_installation.md#http).

For more information about real user monitoring in CloudWatch, see [Use CloudWatch RUM](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-RUM.html). To set up your application to use CloudWatch RUM, including tracing user sessions with X-Ray, see [Set up an application to use CloudWatch RUM](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-RUM-get-started.html). 

# Debugging CloudWatch synthetics canaries using X-Ray
<a name="xray-services-cloudwatch-synthetics"></a>

CloudWatch Synthetics is a fully managed service that enables you to monitor your endpoints and APIs using scripted canaries that run 24 hours per day, once per minute. 

You can customize canary scripts to check for changes in: 
+ Availability
+ Latency
+ Transactions
+ Broken or dead links
+ Step-by-step task completions
+ Page load errors
+ Load Latencies for UI assets
+ Complex wizard flows
+ Checkout flows in your application

Canaries follow the same routes and perform the same actions and behaviors as your customers, and continually verify the customer experience.

To learn more about setting up Synthetics tests, see [Using Synthetics to Create and Manage Canaries](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html).

![\[Example canary node in x-ray trace map.\]](http://docs.aws.amazon.com/xray/latest/devguide/images/synthetics-show-canary-active.png)


The following examples show common use cases for debugging issues that your Synthetics canaries raise. Each example demonstrates a key strategy for debugging using either the trace map or the X-Ray Analytics console.

For more information about how to read and interact with the trace map, see [Viewing the Service Map](https://docs.aws.amazon.com/xray/latest/devguide/xray-console.html#xray-console-servicemap). 

For more information about how to read and interact with the X-Ray Analytics console, see [Interacting with the AWS X-Ray Analytics Console](https://docs.aws.amazon.com/xray/latest/devguide/xray-console-analytics.html). 

**Topics**
+ [View canaries with increased error reporting in the trace map](#xray-services-cloudwatch-synthetics-workflows-which-canary)
+ [Use trace details maps for individual traces to view each request in detail](#xray-services-cloudwatch-synthetics-workflows-trace-map)
+ [Determine the root cause of ongoing failures in upstream and downstream services](#xray-services-cloudwatch-synthetics-workflows-root-cause)
+ [Identify performance bottlenecks and trends](#xray-services-cloudwatch-synthetics-workflows-bottlenecks)
+ [Compare latency and error or fault rates before and after changes](#xray-services-cloudwatch-synthetics-workflows-latency)
+ [Determine the required canary coverage for all APIs and URLs](#xray-services-cloudwatch-synthetics-workflows-impact)
+ [Use groups to focus on synthetics tests](#xray-services-cloudwatch-synthetics-groups)

## View canaries with increased error reporting in the trace map
<a name="xray-services-cloudwatch-synthetics-workflows-which-canary"></a>

 To see which canaries have an increase in errors, faults, throttling rates, or slow response times within your X-Ray trace map, you can highlight Synthetics canary client nodes using the `Client::Synthetic` [filter](xray-console-filters.md). Clicking a node displays the response time distribution of the entire request. Clicking an edge between two nodes shows details about the requests that traveled that connection. You can also view "remote" inferred nodes for related downstream services in your trace map. 

When you click the Synthetics node, there is a **View in Synthetics** button on side panel which redirects you to the Synthetics console where you can check the canary details.

![\[Example canary node in x-ray trace map with service details.\]](http://docs.aws.amazon.com/xray/latest/devguide/images/synthetics-canary-servicedetail.png)


## Use trace details maps for individual traces to view each request in detail
<a name="xray-services-cloudwatch-synthetics-workflows-trace-map"></a>

To determine which service results in the most latency or is causing an error, invoke the trace details map by selecting the trace in the trace map. Individual trace details maps display the end-to-end path of a single request. Use this to understand the services invoked, and visualize the upstream and downstream services.

![\[Example canary node in x-ray trace details map.\]](http://docs.aws.amazon.com/xray/latest/devguide/images/synthetics-canary-tracemap.png)


## Determine the root cause of ongoing failures in upstream and downstream services
<a name="xray-services-cloudwatch-synthetics-workflows-root-cause"></a>

Once you receive a CloudWatch alarm for failures in a Synthetics canary, use the statistical modeling on trace data in X-Ray to determine the probable root cause of the issue within the X-Ray Analytics console. In the Analytics console, the **Response Time Root Cause** table shows recorded entity paths. X-Ray determines which path in your trace is the most likely cause for the response time. The format indicates a hierarchy of entities that are encountered, ending in a response time root cause. 

The following example shows that the Synthetics test for API “XXX” running on API Gateway is failing due to a throughput capacity exception from the Amazon DynamoDB table.

![\[Example canary node in x-ray trace map.\]](http://docs.aws.amazon.com/xray/latest/devguide/images/synthetics-canary-active-select.png)


![\[Example canary node root cause.\]](http://docs.aws.amazon.com/xray/latest/devguide/images/synthetics-canary-rootcause.png)


![\[Example annotation filter indicating the canary node.\]](http://docs.aws.amazon.com/xray/latest/devguide/images/synthetics-canary-showannot.png)


## Identify performance bottlenecks and trends
<a name="xray-services-cloudwatch-synthetics-workflows-bottlenecks"></a>

You can view trends in the performance of your endpoint over time using continuous traffic from your Synthetics canaries to populate a trace details map over a period of time. 

![\[Example annotation filter indicating the canary node.\]](http://docs.aws.amazon.com/xray/latest/devguide/images/synthetics-canary-distribution.png)


## Compare latency and error or fault rates before and after changes
<a name="xray-services-cloudwatch-synthetics-workflows-latency"></a>

Pinpoint the time a change occurred to correlate that change to an increase in issues caught by your canaries. Use the X-Ray Analytics console to define the before and after time ranges as different trace sets, creating a visual differentiation in the response time distribution.

![\[Example annotation filter indicating the canary node.\]](http://docs.aws.amazon.com/xray/latest/devguide/images/synthetics-canary-compare.png)


## Determine the required canary coverage for all APIs and URLs
<a name="xray-services-cloudwatch-synthetics-workflows-impact"></a>

 Use X-Ray Analytics to compare the experience of canaries with the users. The UI below shows a blue trend line for canaries and a green line for the users. You can also identify that two out of the three URLs don’t have canary tests.

![\[Example annotation filter indicating the canary node.\]](http://docs.aws.amazon.com/xray/latest/devguide/images/synthetics-canary-vs-customer.png)


## Use groups to focus on synthetics tests
<a name="xray-services-cloudwatch-synthetics-groups"></a>

 You can create an X-Ray group using a filter expression to focus on a certain set of workflows, such as a Synthetics tests for application “www” running on AWS Elastic Beanstalk. Use the [complex keywords](xray-console-filters.md#console-filters-complex) `service()` and `edge()` to filter through services and edges.

**Example Group filter expression**  

```
"edge(id(name: "www", type: "client::Synthetics"), id(name: "www", type: "AWS::ElasticBeanstalk::Environment"))" 
```

![\[Example nodes for Elastic Beanstalk www.\]](http://docs.aws.amazon.com/xray/latest/devguide/images/synthetics-canary-active-www.png)


# AWS Elastic Beanstalk and AWS X-Ray
<a name="xray-services-beanstalk"></a>

**Note**  
X-Ray SDK/Daemon Maintenance Notice – On February 25th, 2026, the AWS X-Ray SDKs/Daemon will enter maintenance mode, where AWS will limit X-Ray SDK and Daemon releases to address security issues only. For more information on the support timeline, see [X-Ray SDK and Daemon Support timeline](xray-sdk-daemon-timeline.md). We recommend to migrate to OpenTelemetry. For more information on migrating to OpenTelemetry, see [Migrating from X-Ray instrumentation to OpenTelemetry instrumentation ](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-migration.html).

AWS Elastic Beanstalk platforms include the X-Ray daemon. You can [run the daemon](xray-daemon-beanstalk.md) by setting an option in the Elastic Beanstalk console or with a configuration file.

On the Java SE platform, you can use a Buildfile file to build your application with Maven or Gradle on-instance. The X-Ray SDK for Java and AWS SDK for Java are available from Maven, so you can deploy only your application code and build on-instance to avoid bundling and uploading all of your dependencies.

You can use Elastic Beanstalk environment properties to configure the X-Ray SDK. The method that Elastic Beanstalk uses to pass environment properties to your application varies by platform. Use the X-Ray SDK's environment variables or system properties depending on your platform.
+ **[Node.js platform](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_nodejs.container.html)** – Use [environment variables](xray-sdk-nodejs-configuration.md#xray-sdk-nodejs-configuration-envvars)
+ **[Java SE platform](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/java-se-platform.html)** – Use [environment variables](xray-sdk-java-configuration.md#xray-sdk-java-configuration-envvars)
+ **[Tomcat platform](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/java-tomcat-platform.html)** – Use [system properties](xray-sdk-java-configuration.md#xray-sdk-java-configuration-sysprops)

For more information, see [Configuring AWS X-Ray Debugging](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-configuration-debugging.html) in the AWS Elastic Beanstalk Developer Guide.

# Elastic Load Balancing and AWS X-Ray
<a name="xray-services-elb"></a>

Elastic Load Balancing application load balancers add a trace ID to incoming HTTP requests in a header named `X-Amzn-Trace-Id`.

```
X-Amzn-Trace-Id: Root=1-5759e988-bd862e3fe1be46a994272793
```

**X-Ray trace ID format**

An X-Ray `trace_id` consists of three numbers separated by hyphens. For example, `1-58406520-a006649127e371903a2de979`. This includes:
+ The version number, which is `1`.
+ The time of the original request in Unix epoch time using **8 hexadecimal digits**.

  For example, 10:00AM December 1st, 2016 PST in epoch time is `1480615200` seconds or `58406520` in hexadecimal digits.
+ A globally unique 96-bit identifier for the trace in **24 hexadecimal digits**.

Load balancers do not send data to X-Ray, and do not appear as a node on your service map.

For more information, see [Request Tracing for Your Application Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-request-tracing.html) in the Elastic Load Balancing Developer Guide.

# Amazon EventBridge and AWS X-Ray
<a name="xray-services-eventbridge"></a>

AWS X-Ray integrates with Amazon EventBridge to trace events that are passed through EventBridge. If a service that is instrumented with the X-Ray SDK sends events to EventBridge, the trace context is propagated to downstream event targets within the [tracing header](xray-concepts.md#xray-concepts-tracingheader). The X-Ray SDK automatically picks up the tracing header and applies it to any subsequent instrumentation. This continuity enables users to trace, analyze, and debug throughout downstream services and provides a more complete view of their system. 

For more information, see [EventBridge X-Ray Integration](https://docs.aws.amazon.com//eventbridge/latest/userguide/eb-xray-integ.html) in the *EventBridge User Guide*.

## Viewing source and targets on the X-Ray service map
<a name="xray-services-eventbridge-service-map"></a>

The X-Ray [trace map](xray-console-servicemap.md) displays an EventBridge event node that connects source and target services, as in the following example:

![\[X-Ray displays an EventBridge event node that connects source and target services\]](http://docs.aws.amazon.com/xray/latest/devguide/images/service-map-eventbridge.png)


## Propagate the trace context to event targets
<a name="xray-services-eventbridge-auto-inject"></a>

The X-Ray SDK enables the EventBridge event source to propagate trace context to downstream event targets. The following language-specific examples demonstrate calling EventBridge from a Lambda function on which [active tracing is enabled](https://docs.aws.amazon.com//lambda/latest/dg/services-xray.html#services-xray-api):

------
#### [ Java ]

Add the necessary dependencies for X-Ray:
+ [AWS X-Ray SDK for Java](https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-xray/)
+ [AWS X-Ray Recorder SDK for Java](https://mvnrepository.com/artifact/com.amazonaws/aws-xray-recorder-sdk-aws-sdk/)

```
package example;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.SQSEvent;
import com.amazonaws.xray.AWSXRay;
import com.amazonaws.services.eventbridge.AmazonEventBridge;
import com.amazonaws.services.eventbridge.AmazonEventBridgeClientBuilder;
import com.amazonaws.services.eventbridge.model.PutEventsRequest;
import com.amazonaws.services.eventbridge.model.PutEventsRequestEntry;
import com.amazonaws.services.eventbridge.model.PutEventsResult;
import com.amazonaws.services.eventbridge.model.PutEventsResultEntry;
import com.amazonaws.xray.handlers.TracingHandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.StringBuilder;
import java.util.Map;
import java.util.List;
import java.util.Date;
import java.util.Collections;

/*
   Add the necessary dependencies for XRay:
   https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-xray
   https://mvnrepository.com/artifact/com.amazonaws/aws-xray-recorder-sdk-aws-sdk
*/
public class Handler implements RequestHandler<SQSEvent, String>{
  private static final Logger logger = LoggerFactory.getLogger(Handler.class);

  /*
    build EventBridge client
  */
  private static final AmazonEventBridge eventsClient = AmazonEventBridgeClientBuilder
          .standard()
          // instrument the EventBridge client with the XRay Tracing Handler.
          // the AWSXRay globalRecorder will retrieve the tracing-context 
          // from the lambda function and inject it into the HTTP header.
          // be sure to enable 'active tracing' on the lambda function.
          .withRequestHandlers(new TracingHandler(AWSXRay.getGlobalRecorder()))
          .build();

  @Override
  public String handleRequest(SQSEvent event, Context context)
  {
    PutEventsRequestEntry putEventsRequestEntry0 = new PutEventsRequestEntry();
    putEventsRequestEntry0.setTime(new Date());
    putEventsRequestEntry0.setSource("my-lambda-function");
    putEventsRequestEntry0.setDetailType("my-lambda-event");
    putEventsRequestEntry0.setDetail("{\"lambda-source\":\"sqs\"}");
    PutEventsRequest putEventsRequest = new PutEventsRequest();
    putEventsRequest.setEntries(Collections.singletonList(putEventsRequestEntry0));
    // send the event(s) to EventBridge
    PutEventsResult putEventsResult = eventsClient.putEvents(putEventsRequest);
    try {
      logger.info("Put Events Result: {}", putEventsResult);
    } catch(Exception e) {
      e.getStackTrace();
    }
    return "success";
  }
}
```

------
#### [ Python ]

 Add the following dependency to your requirements.txt file: 

```
aws-xray-sdk==2.4.3        
```

```
import boto3
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.core import patch_all

# apply the XRay handler to all clients.
patch_all()

client = boto3.client('events')

def lambda_handler(event, context):
    response = client.put_events(
        Entries=[
            {
                'Source': 'foo',
                'DetailType': 'foo',
                'Detail': '{\"foo\": \"foo\"}'
            },
        ]
    )
    return response
```

------
#### [ Go ]

```
package main

import (
  "context"
  "github.com/aws/aws-lambda-go/lambda"
  "github.com/aws/aws-lambda-go/events"
  "github.com/aws/aws-sdk-go/aws/session"
  "github.com/aws/aws-xray-sdk-go/xray"
  "github.com/aws/aws-sdk-go/service/eventbridge"
  "fmt"
)

var client = eventbridge.New(session.New())


func main() {
 //Wrap the eventbridge client in the AWS XRay tracer
  xray.AWS(client.Client)
  lambda.Start(handleRequest)
}

func handleRequest(ctx context.Context, event events.SQSEvent) (string, error) {
  _, err := callEventBridge(ctx)
  if err != nil {
    return "ERROR", err
  }
  return "success", nil
}


func callEventBridge(ctx context.Context) (string, error) {
    entries := make([]*eventbridge.PutEventsRequestEntry, 1)
    detail := "{ \"foo\": \"foo\"}"
    detailType := "foo"
    source := "foo"
    entries[0] = &eventbridge.PutEventsRequestEntry{
        Detail: &detail,
        DetailType: &detailType,
        Source: &source,
    }

  input := &eventbridge.PutEventsInput{
     Entries: entries,
  }

  // Example sending a request using the PutEventsRequest method.
  resp, err := client.PutEventsWithContext(ctx, input)

  success := "yes"
  if err == nil { // resp is now filled
      success = "no"
      fmt.Println(resp)
  }
  return success, err
}
```

------
#### [ Node.js ]

```
const AWSXRay = require('aws-xray-sdk')
//Wrap the aws-sdk client in the AWS XRay tracer
const AWS = AWSXRay.captureAWS(require('aws-sdk'))
const eventBridge = new AWS.EventBridge()

exports.handler = async (event) => {

  let myDetail = { "name": "Alice" }

  const myEvent = { 
    Entries: [{
      Detail: JSON.stringify({ myDetail }),
      DetailType: 'myDetailType',
      Source: 'myApplication',
      Time: new Date
    }]
  }

  // Send to EventBridge
  const result = await eventBridge.putEvents(myEvent).promise()

  // Log the result
  console.log('Result: ', JSON.stringify(result, null, 2))

}
```

------
#### [ C\$1 ]

 Add the following X-Ray packages to your C\$1 dependencies: 

```
<PackageReference Include="AWSXRayRecorder.Core" Version="2.6.2" />
<PackageReference Include="AWSXRayRecorder.Handlers.AwsSdk" Version="2.7.2" />
```

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon;
using Amazon.Util;
using Amazon.Lambda;
using Amazon.Lambda.Model;
using Amazon.Lambda.Core;
using Amazon.EventBridge;
using Amazon.EventBridge.Model;
using Amazon.Lambda.SQSEvents;
using Amazon.XRay.Recorder.Core;
using Amazon.XRay.Recorder.Handlers.AwsSdk;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace blankCsharp
{
  public class Function
  {
    private static AmazonEventBridgeClient eventClient;

    static Function() {
      initialize();
    }

    static async void initialize() {
      //Wrap the AWS SDK clients in the AWS XRay tracer
      AWSSDKHandler.RegisterXRayForAllServices();
      eventClient = new AmazonEventBridgeClient();
    }

    public async Task<PutEventsResponse> FunctionHandler(SQSEvent invocationEvent, ILambdaContext context)
    {
      PutEventsResponse response;
      try
      {
        response = await callEventBridge();
      }
      catch (AmazonLambdaException ex)
      {
        throw ex;
      }

      return response;
    }

    public static async Task<PutEventsResponse> callEventBridge()
    {
      var request = new PutEventsRequest();
      var entry = new PutEventsRequestEntry();
      entry.DetailType = "foo";
      entry.Source = "foo";
      entry.Detail = "{\"instance_id\":\"A\"}";
      List<PutEventsRequestEntry> entries = new List<PutEventsRequestEntry>();
      entries.Add(entry);
      request.Entries = entries;
      var response = await eventClient.PutEventsAsync(request);
      return response;
    }
  }
}
```

------

# AWS Lambda and AWS X-Ray
<a name="xray-services-lambda"></a>

**Note**  
X-Ray SDK/Daemon Maintenance Notice – On February 25th, 2026, the AWS X-Ray SDKs/Daemon will enter maintenance mode, where AWS will limit X-Ray SDK and Daemon releases to address security issues only. For more information on the support timeline, see [X-Ray SDK and Daemon Support timeline](xray-sdk-daemon-timeline.md). We recommend to migrate to OpenTelemetry. For more information on migrating to OpenTelemetry, see [Migrating from X-Ray instrumentation to OpenTelemetry instrumentation ](https://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-migration.html).

You can use AWS X-Ray to trace your AWS Lambda functions. Lambda runs the [X-Ray daemon](xray-daemon.md) and records a segment with details about invoking and running the function. For further instrumentation, you can bundle the X-Ray SDK with your function to record outgoing calls and add annotations and metadata.

If your Lambda function is called by another instrumented service, Lambda traces requests that have already been sampled without any additional configuration. The upstream service can be an instrumented web application or another Lambda function. Your service can invoke the function directly with an instrumented AWS SDK client, or by calling an API Gateway API with an instrumented HTTP client.

AWS X-Ray supports tracing event-driven applications using AWS Lambda and Amazon SQS. Use the CloudWatch console to see a connected view of each request as it's queued with Amazon SQS and processed by a downstream Lambda function. Traces from upstream message producers are automatically linked to traces from downstream Lambda consumer nodes, creating an end-to-end view of the application. For more information, see [tracing event-driven applications](xray-tracelinking.md). 

**Note**  
If you have traces enabled for a downstream Lambda function, you must also have traces enabled for the root Lambda function that calls the downstream function in order for the downstream function to generate traces.

If your Lambda function runs on a schedule, or is invoked by a service that is not instrumented, you can configure Lambda to sample and record invocations with active tracing.

**To configure X-Ray integration on an AWS Lambda function**

1. Open the [AWS Lambda console](https://console.aws.amazon.com/lambda).

1. Select **Functions** from the left navigation bar.

1. Choose your function.

1. On the **Configuration** tab, scroll down to the **Additional monitoring tools** card. You can also find this card by selecting **Monitoring and operations tools** on the left navigation pane.

1. Select **Edit**.

1. Under **AWS X-Ray**, enable **Active tracing**.

On runtimes with a corresponding X-Ray SDK, Lambda also runs the X-Ray daemon.

**X-Ray SDKs on Lambda**
+ **X-Ray SDK for Go** – Go 1.7 and newer runtimes
+ **X-Ray SDK for Java** – Java 8 runtime
+ **X-Ray SDK for Node.js** – Node.js 4.3 and newer runtimes
+ **X-Ray SDK for Python** – Python 2.7, Python 3.6, and newer runtimes
+ **X-Ray SDK for .NET** – .NET Core 2.0 and newer runtimes

To use the X-Ray SDK on Lambda, bundle it with your function code each time you create a new version. You can instrument your Lambda functions with the same methods that you use to instrument applications running on other services. The primary difference is that you don't use the SDK to instrument incoming requests, make sampling decisions, and create segments.

The other difference between instrumenting Lambda functions and web applications is that the segment that Lambda creates and sends to X-Ray can't be modified by your function code. You can create subsegments and record annotations and metadata on them, but you can't add annotations and metadata to the parent segment.

For more information, see [Using AWS X-Ray](https://docs.aws.amazon.com/lambda/latest/dg/lambda-x-ray.html) in the *AWS Lambda Developer Guide*.

# AWS Step Functions and AWS X-Ray
<a name="xray-services-stepfunctions"></a>

AWS X-Ray integrates with AWS Step Functions to trace and analyze requests for Step Functions. You can visualize the components of your state machine, identify performance bottlenecks, and troubleshoot requests that resulted in an error. For more information, see [AWS X-Ray and Step Functions ](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-xray-tracing.html) in the AWS Step Functions Developer Guide.

**To enable X-Ray tracing when creating a new state machine**

1. Open the Step Functions console at [https://console.aws.amazon.com/states/](https://console.aws.amazon.com/states/).

1. Choose **Create a state machine**.

1. On the **Define state machine** page, choose either **Author with code snippets** or **Start with a template**. If you choose to run a sample project, you can't enable X-Ray tracing during creation. Instead, enable X-Ray tracing after you create your state machine.

1. Choose **Next**.

1. On the **Specify details** page, configure your state machine.

1. Choose **Enable X-Ray tracing**.

**To enable X-Ray tracing in an existing state machine**

1. In the Step Functions console, select the state machine for which you want to enable tracing.

1. Choose **Edit**.

1. Choose **Enable X-Ray tracing**.

1. (Optional) Auto-generate a new role for your state machine to include X-Ray permissions by choosing **Create new role** from the Permissions window.  
![\[Permissions section with options to create a new role, choose existing, or enter ARN.\]](http://docs.aws.amazon.com/xray/latest/devguide/images/stepfunctions-permissions.png)

1. Choose **Save**.

**Note**  
When you create a new state machine, it's automatically traced if the request is sampled and tracing is enabled in an upstream service such as Amazon API Gateway or AWS Lambda. For any existing state machine not configured through the console, for example through an CloudFormation template, check that you have an IAM policy that grants sufficient permissions to enable X-Ray traces.