AWS X-Ray SDK for Python

raw JSON →
2.15.0 verified Tue May 12 auth: no python install: verified maintenance

The AWS X-Ray SDK for Python (the SDK) enables Python developers to record and emit information from within their applications to the AWS X-Ray service. The library is currently at version 2.15.0 and receives regular updates, though it will enter maintenance mode on February 25, 2026, with end-of-support on February 25, 2027, with a recommendation to migrate to OpenTelemetry.

pip install aws-xray-sdk
error ModuleNotFoundError: No module named 'aws_xray_sdk'
cause The 'aws_xray_sdk' module is not included in the deployment package or is not installed in the environment.
fix
Ensure 'aws_xray_sdk' is installed in your environment using 'pip install aws-xray-sdk' and included in your deployment package.
error ImportError: No module named 'jsonpickle'
cause The 'jsonpickle' module, a dependency of 'aws_xray_sdk', is missing from the environment.
fix
Install 'jsonpickle' using 'pip install jsonpickle' and include it in your deployment package.
error AttributeError: 'NoneType' object has no attribute 'put_segment'
cause The X-Ray recorder is not properly initialized, leading to a 'NoneType' error when attempting to put a segment.
fix
Ensure the X-Ray recorder is correctly configured and initialized before use.
error Runtime.ImportModuleError: Unable to import module 'lambda_function': No module named 'aws_xray_sdk'
cause The 'aws_xray_sdk' library is not included in the Lambda deployment package or an accessible Lambda layer for the Python function.
fix
Ensure the 'aws_xray_sdk' is installed and packaged with your Lambda deployment. For custom layers, include it in your zip file or specify 'aws-xray-sdk' in your requirements.txt if using tools that build layers. If using aws-lambda-powertools, ensure aws-lambda-powertools[tracer] is in your requirements.txt to include the X-Ray SDK.
error cannot find the current segment/subsegment, please make sure you have a segment open
cause X-Ray SDK methods (such as `begin_subsegment`, `current_segment`, `put_annotation`) are called when there is no active X-Ray segment or subsegment in the current execution context, often in initialization code, background threads, or untraced sections of code.
fix
Ensure all X-Ray SDK operations are performed within an active segment or subsegment. For scenarios where a segment might not always be present (e.g., local testing or startup code), configure the recorder with xray_recorder.configure(context_missing='LOG_ERROR') to log warnings instead of raising exceptions. For new threads, ensure the X-Ray context is properly propagated.
breaking The AWS X-Ray SDKs will enter maintenance mode on February 25, 2026, and reach end-of-support on February 25, 2027. AWS recommends migrating to AWS Distro for OpenTelemetry (ADOT) or OpenTelemetry Instrumentation for future tracing needs.
fix Plan migration to AWS Distro for OpenTelemetry or OpenTelemetry Instrumentation before February 25, 2027.
breaking Version 2.x of the SDK dropped support for Python 2.7 and Python 3.4. All versions 2.x and higher require Python >= 3.7.
fix Upgrade your Python environment to 3.7 or newer. If stuck on older Python, you must use a 1.x version of the SDK, which is no longer actively maintained.
breaking Version 2.x introduced an incompatibility with `pynamodb` and `aiobotocore` if those libraries require `botocore < 1.11.3`. Ensure these dependencies are compatible with newer `botocore` versions if upgrading to `aws-xray-sdk` 2.x.
fix Ensure `pynamodb` and `aiobotocore` versions support `botocore >= 1.11.3` when using `aws-xray-sdk` 2.x, or remain on `aws-xray-sdk` 1.x.
breaking The `Subsegment.set_user()` API was removed in version 2.x as the corresponding attribute is not supported by the X-Ray backend.
fix Remove any calls to `subsegment.set_user()` from your code. Consider using `put_annotation` or `put_metadata` if you need to associate user information, although direct user association may be better handled at the segment level if applicable.
gotcha Context propagation for traces and subsegments across threads (non-asyncio) can be tricky and may not work as expected, potentially leading to `SegmentNotFoundException` or incomplete traces. The Python SDK doesn't explicitly detail multi-threading context management as clearly as other language SDKs.
fix Carefully manage segment/subsegment context in multi-threaded applications using explicit `with xray_recorder.in_segment()` blocks or custom context passing. Consider if asynchronous patterns (like `asyncio` with appropriate instrumentation) or process-based parallelism might be better suited for X-Ray tracing.
breaking The script failed because the 'boto3' module was not found. 'boto3' is a common AWS SDK dependency for many Python applications interacting with AWS services.
fix Ensure 'boto3' is included in your project's dependencies and is installed in the environment (e.g., via pip install boto3) where the script is executed.
breaking The library `aws-xray-sdk` typically depends on `boto3` to interact with AWS services. If `boto3` is not installed in the environment, importing it will result in a `ModuleNotFoundError`.
fix Ensure `boto3` is installed in your Python environment, for example, by adding `boto3` to your project's `requirements.txt` or installing it via `pip install boto3`.
python os / libc status wheel install import disk
3.10 alpine (musl) wheel - 0.99s 50.2M
3.10 alpine (musl) - - 1.01s 49.9M
3.10 slim (glibc) wheel 3.7s 0.73s 51M
3.10 slim (glibc) - - 0.73s 50M
3.11 alpine (musl) wheel - 1.29s 53.1M
3.11 alpine (musl) - - 1.34s 52.8M
3.11 slim (glibc) wheel 3.7s 1.09s 54M
3.11 slim (glibc) - - 1.04s 53M
3.12 alpine (musl) wheel - 1.07s 44.7M
3.12 alpine (musl) - - 1.17s 44.4M
3.12 slim (glibc) wheel 3.0s 1.11s 45M
3.12 slim (glibc) - - 1.15s 45M
3.13 alpine (musl) wheel - 1.13s 44.5M
3.13 alpine (musl) - - 1.12s 44.1M
3.13 slim (glibc) wheel 2.9s 1.12s 45M
3.13 slim (glibc) - - 1.13s 45M
3.9 alpine (musl) wheel - 0.91s 49.6M
3.9 alpine (musl) - - 0.96s 49.4M
3.9 slim (glibc) wheel 4.2s 0.83s 50M
3.9 slim (glibc) - - 0.83s 50M

This quickstart demonstrates how to configure the X-Ray recorder, patch supported libraries for automatic instrumentation, and use the `@xray_recorder.capture` decorator to create subsegments for function calls. It also shows manual segment creation for contexts not covered by middleware.

import os
from aws_xray_sdk.core import xray_recorder, patch_all
import boto3

# Configure the X-Ray recorder globally
# For local development without a daemon, set sampling=False to prevent errors
# In deployed AWS environments, the daemon address is often discovered automatically.
xray_recorder.configure(
    service='MyPythonApp',
    sampling=False, # Set to True or rely on daemon for actual sampling rules in production
    context_missing='LOG_ERROR', # Other options: 'RUNTIME_ERROR', 'IGNORE'
    daemon_address=os.environ.get('AWS_XRAY_DAEMON_ADDRESS', '127.0.0.1:2000')
)

# Patch supported libraries to automatically instrument calls (e.g., boto3)
patch_all()

# Example: Instrumenting an AWS SDK call with a decorator
@xray_recorder.capture('s3_list_buckets')
def list_s3_buckets():
    # Ensure AWS credentials/config are set in environment or ~/.aws/config
    s3_client = boto3.client('s3', region_name='us-east-1')
    try:
        response = s3_client.list_buckets()
        bucket_names = [bucket['Name'] for bucket in response.get('Buckets', [])]
        # Add custom metadata to the current subsegment
        xray_recorder.current_subsegment().put_metadata('bucket_count', len(bucket_names))
        return bucket_names
    except Exception as e:
        # Record exceptions to the current subsegment
        xray_recorder.current_subsegment().add_exception(e)
        raise

# Manual segment creation (if not using web framework middleware or a top-level decorator)
# This mimics an incoming request context.
with xray_recorder.in_segment(xray_recorder.begin_segment('MyApplicationRootTrace')):
    print("Starting application trace...")
    try:
        buckets = list_s3_buckets()
        print(f"Successfully listed {len(buckets)} S3 buckets.")
        # Add an annotation to the root segment
        xray_recorder.current_segment().put_annotation('result', 'success')
    except Exception as e:
        print(f"An error occurred: {e}")
        xray_recorder.current_segment().put_annotation('result', 'failure')
        xray_recorder.current_segment().add_exception(e)

print("Trace completed.")