aws / aws/aws-xray-sdk-node

Add a convenient way to begin a new trace in a lambda handler

Open
#393 4 comments 1 reaction 1 assignee Claimed by @srprash View on GitHub
enhancement
Dominant language
JavaScript
Stars
280
Forks
157
PR merge metrics
No merged PRs in 30d

Description

I recently encountered a problem where individual traces grew too large and reached their quota. I discovered the trace spanned many services, in particular a Step Function with a [Map state](https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-map-state.html) that invoked a Lambda. The Map state could have up to several hundred input elements, meaning several hundred lambda invocations, each with their many subsegments, from instrumented aws-sdk clients + captureHTTPs.

I decided it fit our usage of X-Ray that the Step Function's trace included the Lambda invocation, but none of its segments or subsegments. After many failed attempts at tweaking Lambda and Step Function configuration, I found an approach via the Lambda code itself. To begin a new trace, I added code as below, to wrap the Lambda handler:

Node 12.x, aws-xray-sdk-core 3.1.0.
```
import { Segment } from "aws-xray-sdk-core";
import TraceID from "aws-xray-sdk-core/lib/segments/attributes/trace_id";
import * as AWSXRay from "aws-xray-sdk";

export function startNewXrayTraceMiddleware() {
return (handler) => {
return async (event, context) => {
const newTraceId = new TraceID().toString();
process.env._X_AMZN_TRACE_ID = `Root=${newTraceId};Parent=;Sampled=1`;
const segment = new Segment("myNewSegmentName", newTraceId, null);
AWSXRay.setSegment(segment);
try {
return await handler(event, context);
} finally {
segment.close();
}
};
};
}
```
This appears to have the desired effect: the Step Function's trace includes the Lambda and it's result, but nothing downstream; and the trace that was created contains segments for all the downstream calls.

Would it be possible to have similar functionality available out-of-the-box? It's not many lines of code, but it feels brittle, and it was very difficult to discover.

This is assuming that there are no nasty side effects or edge-cases I'm unaware of, that would cause the X-Ray/Lambda/SDK teams to recommend avoiding this approach.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.