DEV Community

Kay for AWS Community Builders

Posted on

6 1

X-Ray tracing from SQS to Lambda

SQS supports X-Ray tracing but it does not propagate the trace to Lambda function. Lambda always starts a new trace with an immutable facade segment.

This is a known issue, see:

Workaround

There were some workaround discussions in the above issues.

The following is a solution I implemented for a demo:

  • Create a new segment to replace the facade segment created by Lambda, and
  • assign with the retrieved trace ID and parent ID from the trace header of the SQS segment.

Example in typescript:

import { Handler, SQSEvent, SQSRecord } from "aws-lambda"
import { Segment, setSegment, utils } from "aws-xray-sdk"
...

// Create a new Segment
const traceHeaderStr = sqsRecord.attributes.AWSTraceHeader
const traceData = utils.processTraceData(traceHeaderStr)
const sqsSegmentEndTime = Number(sqsRecord.attributes.ApproximateFirstReceiveTimestamp) / 1000

const lambdaSegment = new Segment(
    functionName,
    traceData.root,
    traceData.parent
)
lambdaSegment.origin = "AWS::Lambda::Function"
lambdaSegment.start_time = lambdaExecStartTime - (lambdaExecStartTime - sqsSegmentEndTime)
lambdaSegment.addPluginData({
    function_arn: functionArn,
    region: sqsRecord.awsRegion,
    request_id: awsRequestId
})

// Set it as the current Segment
setSegment(lambdaSegment)

// Do something

// Close the segment
lambdaSegment.close()
Enter fullscreen mode Exit fullscreen mode

From Trace Map console:

Alt Text

Example code can be found here on GitHub kyhau/aws-tools/b/X-Ray/xray-sqs-to-lambda/handler.ts.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (1)

Collapse
 
alexey2baranov profile image
alexey2baranov

hope this work. i will try to use tomorrow.
btw: why don't you use new Date() for Lambda start Time. You can make it optional at least

Create a simple OTP system with AWS Serverless cover image

Create a simple OTP system with AWS Serverless

Implement a One Time Password (OTP) system with AWS Serverless services including Lambda, API Gateway, DynamoDB, Simple Email Service (SES), and Amplify Web Hosting using VueJS for the frontend.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay