{"id":2628,"library":"opentelemetry-instrumentation-aws-lambda","title":"OpenTelemetry AWS Lambda Instrumentation","description":"This library provides automatic instrumentation for AWS Lambda functions, enabling OpenTelemetry tracing and metrics for incoming requests and handler execution. It is part of the `opentelemetry-python-contrib` project, following its beta release cadence (currently `0.62b0`) which aligns with the overall OpenTelemetry Python project. It helps integrate Lambda functions into distributed tracing workflows.","status":"active","version":"0.62b0","language":"en","source_language":"en","source_url":"https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation/opentelemetry-instrumentation-aws-lambda","tags":["observability","opentelemetry","aws","lambda","tracing","metrics","serverless"],"install":[{"cmd":"pip install opentelemetry-instrumentation-aws-lambda","lang":"bash","label":"Install library"},{"cmd":"pip install opentelemetry-distro aws-xray-sdk","lang":"bash","label":"Recommended for full OTel setup and X-Ray integration"}],"dependencies":[{"reason":"Core OpenTelemetry API for tracing context.","package":"opentelemetry-api"},{"reason":"Core OpenTelemetry SDK for trace and metric processing.","package":"opentelemetry-sdk"},{"reason":"Base classes and utilities for instrumentations.","package":"opentelemetry-instrumentation"},{"reason":"Used for parsing AWS X-Ray trace headers and propagating context within AWS services.","package":"aws-xray-sdk"},{"reason":"Provides AWS-specific resource detectors and utilities for the OpenTelemetry SDK.","package":"opentelemetry-sdk-extension-aws"}],"imports":[{"symbol":"configure_lambda_handler","correct":"from opentelemetry.instrumentation.aws_lambda import configure_lambda_handler"}],"quickstart":{"code":"import os\nfrom opentelemetry.instrumentation.aws_lambda import configure_lambda_handler\nfrom opentelemetry import trace\n\n# For production in AWS Lambda, typically an ADOT Layer handles OTel SDK setup.\n# For local testing, you might set up a basic console exporter (uncomment below):\n# from opentelemetry.sdk.resources import Resource\n# from opentelemetry.sdk.trace import TracerProvider\n# from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor\n# resource = Resource.create({\"service.name\": os.environ.get(\"OTEL_SERVICE_NAME\", \"my-lambda-service\")})\n# trace.set_tracer_provider(TracerProvider(resource=resource))\n# trace.get_tracer_provider().add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))\n\n@configure_lambda_handler\ndef my_lambda_handler(event, context):\n    \"\"\"\n    An example AWS Lambda handler.\n    The `@configure_lambda_handler` decorator automatically instruments\n    incoming requests, creating a span for the Lambda invocation.\n    \"\"\"\n    current_span = trace.get_current_span()\n    current_span.set_attribute(\"lambda.event_keys\", str(list(event.keys())))\n    print(f\"Processing event with keys: {list(event.keys())}\")\n\n    # Simulate some work\n    import time\n    time.sleep(0.05)\n\n    return {\n        'statusCode': 200,\n        'body': 'Handler processed successfully!'\n    }\n\n# To run locally for testing (optional, not part of typical Lambda deployment):\nif __name__ == '__main__':\n    mock_event = {\"message\": \"hello world\", \"data\": 123}\n    mock_context = type('Context', (object,), {\n        'aws_request_id': 'local-test-id',\n        'function_name': 'test-func',\n        'invoked_function_arn': 'arn:aws:lambda:us-east-1:123456789012:function:test-func',\n        'memory_limit_in_mb': 128,\n        'get_remaining_time_in_millis': lambda: 30000,\n        'function_version': '$LATEST',\n        'log_group_name': '/aws/lambda/test-func',\n        'log_stream_name': '2023/10/26/[LATEST]xxxxxxxxxxxx',\n        'identity': None,\n        'client_context': None\n    })()\n    os.environ[\"OTEL_SERVICE_NAME\"] = \"my-local-lambda\"\n    # If uncommenting SDK setup above, ensure this is also uncommented for local testing output\n    # from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor\n    # trace.get_tracer_provider().add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))\n    response = my_lambda_handler(mock_event, mock_context)\n    print(f\"Local test response: {response}\")","lang":"python","description":"This quickstart demonstrates how to instrument an AWS Lambda handler using the `@configure_lambda_handler` decorator. In a production AWS Lambda environment, you typically deploy with an AWS Distro for OpenTelemetry (ADOT) Lambda Layer, which configures the OpenTelemetry SDK and exporters. For local testing, you might manually set up a `TracerProvider` and a `ConsoleSpanExporter` as shown in the commented section."},"warnings":[{"fix":"Pin exact versions (e.g., `opentelemetry-instrumentation-aws-lambda==0.62b0`) in `requirements.txt` and review changelogs carefully when upgrading.","message":"This library is currently in beta (`0.x.xb0` versioning). APIs and behavior may change significantly between minor versions without strict adherence to semantic versioning. Always pin exact versions.","severity":"gotcha","affected_versions":"0.x.xb0 (all beta versions)"},{"fix":"Refer to the ADOT Lambda documentation for Python for proper deployment instructions. For manual setup, ensure `OTEL_PYTHON_CONFIGURATOR` is set or the OpenTelemetry SDK is initialized correctly with a `TracerProvider` and `SpanProcessor`.","message":"For production AWS Lambda environments, rely on AWS Distro for OpenTelemetry (ADOT) Lambda Layers or custom Docker images. Simply `pip install`ing this package is not sufficient for full instrumentation and exporting in a typical Lambda deployment, as it requires OpenTelemetry SDK setup (providers, exporters).","severity":"gotcha","affected_versions":"All"},{"fix":"Prefer OpenTelemetry for all tracing needs. If `aws-xray-sdk` is present, monitor traces closely to ensure correct behavior and avoid duplicate or malformed spans.","message":"While this instrumentation works with the OpenTelemetry Python SDK, it also depends on `aws-xray-sdk` and `opentelemetry-sdk-extension-aws`. Ensure there are no conflicts or unexpected behaviors if `aws-xray-sdk` is directly used elsewhere in your application, as OpenTelemetry generally aims to replace direct X-Ray SDK usage.","severity":"gotcha","affected_versions":"All"},{"fix":"Benchmark your Lambda functions with and without instrumentation. Optimize your code and OpenTelemetry configuration (e.g., sampler, batching settings) to minimize overhead. Consider using Provisioned Concurrency for latency-sensitive functions if overhead is critical.","message":"Instrumentation adds overhead, which can impact Lambda cold start times and overall execution duration. Monitor your Lambda performance metrics (duration, memory usage) after deploying OpenTelemetry.","severity":"gotcha","affected_versions":"All"}],"env_vars":null,"last_verified":"2026-04-10T00:00:00.000Z","next_check":"2026-07-09T00:00:00.000Z"}