Queues and functions
Keep one trace from the browser through your server into the queue consumers and AWS Lambda functions that finish the work, and see their errors as problems.
On this page
- How the trace travels
- Send the trace with the work
- An SQS message
- A Lambda invoke
- Outside a request
- Receive it in an SQS consumer
- Partial batch failures
- A handler that loops over the batch itself: traceSqsRecord(message, fn, options?)
- wrapSqsHandler(handle, options?)
- Receive it in a Lambda function
- wrapLambdaHandler(handler, options?)
- Who a job belongs to
- Other workers: continueTrace(carrier, name, fn, attrs?)
- What a job looks like in Sypnia
- The environment of a function
- What it costs
- Next
This page is for a Node backend that hands work to something else: a message on an Amazon SQS queue, an AWS Lambda function invoked with a payload, a function that runs on a schedule. It is part of @sypnia/telemetry/node, from version 0.1.1; @sypnia/telemetry/next apps import the same functions from @sypnia/telemetry/node.
At the end you will have: one trace that starts with the click in the browser, goes through the request your server handled, and goes on into the function that took the message off the queue; the errors of that function as problems, with their stack; and the runs a schedule starts as traces of their own.
How the trace travels
The trace travels as a W3C traceparent, the same value the SDK adds to your outgoing HTTP calls (see Linking the browser to the server). An HTTP call carries it in a header; a message and a payload have no headers, so it goes inside them:
| Work sent as | Where traceparent goes | Sending side | Receiving side |
|---|---|---|---|
| An SQS message | A message attribute named traceparent, of type String | sqsTraceAttributes(attributes) | wrapSqsHandler |
A Lambda Invoke (Event or RequestResponse) | A top-level traceparent key of the JSON payload | injectTraceContext(payload) | wrapLambdaHandler |
| An HTTP call, to API Gateway or a function URL | The traceparent header, added by the SDK on its own | nothing | wrapLambdaHandler |
| A scheduled run (EventBridge) | Nothing: it starts its own trace | nothing | wrapLambdaHandler |
The value is the span that is current when the work is sent: the request your server is handling, or the span() you are inside. The consumer’s span becomes its child, so the trace shows the job under the step that sent it.
Send the trace with the work
Install or update the SDK on the sending side:
npm install @sypnia/telemetry@^0.2.0An SQS message
Pass the message’s attributes through sqsTraceAttributes. It returns a copy with traceparent added, and leaves the ones you gave unchanged:
import { SQSClient, SendMessageCommand } from '@aws-sdk/client-sqs';
import { sqsTraceAttributes } from '@sypnia/telemetry/node';
const sqs = new SQSClient({});
export async function queueReceipt(orderId: string) {
await sqs.send(new SendMessageCommand({
QueueUrl: process.env.RECEIPTS_QUEUE_URL,
MessageBody: JSON.stringify({ orderId }),
MessageAttributes: sqsTraceAttributes({ kind: { DataType: 'String', StringValue: 'receipt' } }),
}));
}With no attributes of your own, call sqsTraceAttributes(): it returns undefined when there is nothing to send, which SendMessageCommand accepts as it is.
What it never does:
- It never replaces a
traceparentattribute you set. - It adds nothing when the message already has 10 attributes, the most SQS allows; the message is sent as it was, without the trace.
- It does not touch the body, the group or the deduplication id, so FIFO queues keep their order and their deduplication: content-based deduplication hashes the body only.
A consumer that does not read the attribute ignores it.
A Lambda invoke
Pass the payload through injectTraceContext. It returns a copy with a traceparent key:
import { LambdaClient, InvokeCommand } from '@aws-sdk/client-lambda';
import { injectTraceContext } from '@sypnia/telemetry/node';
const lambda = new LambdaClient({});
export async function refreshOrder(orderId: string) {
const payload = injectTraceContext({ orderId });
await lambda.send(new InvokeCommand({
FunctionName: 'shop-refresh-order',
InvocationType: 'Event',
Payload: Buffer.from(JSON.stringify(payload)),
}));
}It returns the same object, unchanged, when the payload already has traceparent, is not a plain object (an array, a string), or when there is no current span. If the function on the other side checks its payload strictly and refuses unknown keys, let it accept traceparent, or leave that call as it is.
Lambda’s ClientContext is not used: Lambda passes it to the function only on RequestResponse invocations.
Outside a request
Outside a traced request or job, and when the SDK is off (no key, or enabled: false), both functions return what they were given. You can call them everywhere. currentTraceparent() gives the value itself, or null, for a carrier of your own: a job row in your database, a message on another broker.
Receive it in an SQS consumer
Start the SDK at the top of the function’s file and wrap the handler. wrapSqsHandler takes a function that handles one message:
import type { SQSRecord } from 'aws-lambda';
import { identify, init, wrapSqsHandler } from '@sypnia/telemetry/node';
init({ service: 'shop-receipts' });
export const handler = wrapSqsHandler(async (message: SQSRecord) => {
const job = JSON.parse(message.body);
identify({ account: { id: job.accountId } });
await sendReceipt(job.orderId);
});With TypeScript, use 0.1.2 or newer: 0.1.1 does not accept the SQSRecord type of @types/aws-lambda (the code runs the same).
For each message of the batch, in order:
- It reads
traceparentfrom the message’s attributes. With one, the message’s span joins the sender’s trace, as a child of the span that sent it. Without one, the message starts a new trace. - It runs your function inside the message’s span. Database calls, HTTP calls and your own
span()inside it are its children, as in a request. - If your function throws, the error is reported with its stack as an
exception(sypnia.error.sourceuncaught), the span is marked failed, and the message goes inbatchItemFailures. The other messages go on.
Then it sends the spans, and only then returns { batchItemFailures }. Lambda freezes a function once it returns, so nothing is left waiting in memory.
Partial batch failures
By default the handler answers with the messages that failed, and SQS returns only those to the queue. This needs ReportBatchItemFailures on the function’s event source mapping:
aws lambda update-event-source-mapping --uuid <mapping uuid> --function-response-types ReportBatchItemFailuresWithout it, Lambda ignores the answer and deletes the whole batch, failed messages included. If you cannot turn it on, use partialBatch: false: the first message that throws stops the batch and the handler throws, so SQS returns the whole batch, as a handler that loops and throws does.
A handler that loops over the batch itself: traceSqsRecord(message, fn, options?)
If your handler already loops over event.Records and builds its own batchItemFailures, keep it, and run each message’s work inside traceSqsRecord (from 0.1.2). It gives the message the same span as wrapSqsHandler, returns what fn returns, and throws what it throws after recording it. It does not send: call flush() before the handler returns.
import type { Context, SQSEvent } from 'aws-lambda';
import { flush, reportError, traceSqsRecord } from '@sypnia/telemetry/node';
export const handler = async (event: SQSEvent, context: Context) => {
const batchItemFailures = [];
for (const message of event.Records) {
await traceSqsRecord(message, async () => {
try {
await createCharge(JSON.parse(message.body));
} catch (error) {
reportError(error);
batchItemFailures.push({ itemIdentifier: message.messageId });
}
}, { context });
}
await flush();
return { batchItemFailures };
};An error your loop catches is not thrown, so report it with reportError: it becomes an exception with its stack on the message’s span. options takes name and attributes as wrapSqsHandler does, and context (the Lambda context) for faas.invocation_id.
wrapSqsHandler(handle, options?)
Options
-
namestring | (message) => string optionalThe job’s name: the span’s name and itshttp.route. By default the last part of the message’seventSourceARN, such asshop-receipts-jobs.Default:
the queue's name -
attributes(message) => object optionalMore attributes for the message’s span: strings, numbers and booleans. -
partialBatchboolean optionaltrue: failed messages are returned inbatchItemFailures.false: the first failure stops the batch and is thrown.Default:
true -
flushTimeoutMsnumber optionalThe longest wait for the send before returning. It never takes more than the function has left minus 100 ms (context.getRemainingTimeInMillis()).Default:
2000
Receive it in a Lambda function
wrapLambdaHandler wraps any async handler, and makes one span per invocation. What the span is depends on the event:
| The event | The span |
|---|---|
A direct Invoke | A job named after the function (AWS_LAMBDA_FUNCTION_NAME), continuing the payload’s traceparent, faas.trigger other. |
A scheduled event (EventBridge: source aws.events or aws.scheduler, or detail-type Scheduled Event) | A job named after the function, in a trace of its own, faas.trigger timer. A traceparent in the event is ignored. |
| An API Gateway (REST or HTTP API) or function URL event | The HTTP request it is: method, path, route and status, continuing the traceparent header, faas.trigger http, as a request to a Node server. The status is the statusCode your handler returns, 200 when it returns none, 500 when it throws. |
| An SQS event | One span for the whole batch, continuing the message’s traceparent when the batch has one message. Prefer wrapSqsHandler: one span per message. |
import { init, wrapLambdaHandler } from '@sypnia/telemetry/node';
init({ service: 'shop-refresh-order' });
export const handler = wrapLambdaHandler(async (event: { orderId: string }) => {
await refreshOrder(event.orderId);
return { ok: true };
});It returns what your handler returns and throws what it throws, after reporting it with its stack and sending the spans. Handlers that take a callback ((event, context, callback)) are not supported: make the handler async.
wrapLambdaHandler(handler, options?)
Options
-
namestring | (event) => string optionalThe job’s name. Not used for HTTP events, which are named by their route.Default:
the function's name -
attributes(event) => object optionalMore attributes for the invocation’s span. -
flushTimeoutMsnumber optionalAs forwrapSqsHandler.Default:
2000
Who a job belongs to
A job has no browser session, so it has no person unless you say so. Call identify() inside the job, as soon as you know it. On the server, person is optional, because a job often knows the account (a team, a company, a club) and nobody in it:
identify({ account: { id: job.accountId } });The job’s span gets sypnia.account.id, and its failures count for that account. A job that continues a browser’s trace is also part of that trace’s session, through the request that sent it.
Other workers: continueTrace(carrier, name, fn, attrs?)
For a worker that is not a Lambda function, such as a long-running process that polls a queue, continueTrace runs fn as a job named name, continuing the traceparent of carrier, and returns what fn returns:
import { continueTrace, flush } from '@sypnia/telemetry/node';
for (const message of await receiveMessages()) {
await continueTrace(message, 'shop-receipts-jobs', () => sendReceipt(JSON.parse(message.Body).orderId))
.catch(error => logger.warn('will retry', error));
}
await flush();carrier can be the traceparent string itself, an object with a traceparent key (a payload, a job row), HTTP headers in any case, or an SQS message as the AWS SDK returns it (MessageAttributes) or as a Lambda event gives it (messageAttributes). Without a valid traceparent the job starts a new trace. It does not send: call flush() before the process can be frozen or stopped.
What a job looks like in Sypnia
The engine stores spans of kind SPAN_KIND_SERVER as the requests of a service, so a job is sent as one:
| On the wire | Value |
|---|---|
Span name and http.route | The job’s name: shop-receipts-jobs |
sypnia.job | The job’s name, so a reader can tell a job from an HTTP request |
faas.trigger | pubsub (SQS), timer (schedule), other (invoke), http |
faas.invocation_id | The Lambda request id |
messaging.system, messaging.operation.type | aws_sqs, process (SQS messages) |
messaging.destination.name, messaging.message.id | The queue and the message id (SQS messages) |
sypnia.job.attempt | How many times SQS has handed the message out (ApproximateReceiveCount) |
faas.coldstart | true on the first job of a new process |
There is no http.request.method and no http.response.status_code. A job that threw carries the exception event and the status ERROR.
What you see:
- In the sender’s trace, the job appears under the step that sent it, with its service’s name, even when it ran minutes later. The trace’s name stays the one of the request that started it.
- A trace started by a job (a scheduled run, a message sent outside any request) is named after the job.
- Its errors are problems, grouped like any server error: by the error’s type, message and stack. Each problem names the job as its route, and links to the trace.
- A job still running after
slowRequestMs(20 seconds) is exported as partial, as a request is. If Lambda stops the function at its timeout, the partial span is what remains, and the engine reports it as a timeout, up to 15 minutes later. - At most 200 spans are kept per job, and 5 failures, as per request.
The environment of a function
A function needs its ingest key like any service: SYPNIA_PROJECT_KEY, or project in init. The ingest key is public by design (it can only send), so when a function’s environment is short of room (AWS Lambda allows 4 KB of variables), you can write the key per environment in your code instead of adding a variable. Set service to the name of the function, or of the group of functions that make one piece of your system (a receiver and its worker), and environment to the stage: they are how you tell one from another in Sypnia. Within a service, each job is named after its queue or its function.
A function bundled with esbuild carries pg inside its bundle, where the SDK cannot find it. Give it to init (from 0.1.2), so queries are spans and a failed query keeps its code and full message (Database error details):
import pg from 'pg';
import { init } from '@sypnia/telemetry/node';
init({ service: 'shop-receipts', environment: 'production', pg });Calls made with fetch, including Supabase and PostgREST, are traced without it.
With no key, the wrappers run your handler exactly as they would with one, and return the same batchItemFailures: turning the SDK off changes nothing in what your function does.
What it costs
The wrappers add no dependency to @sypnia/telemetry/node: they add about 2 kB gzipped to it (19.9 kB gzipped in 0.1.1, measured on 2026-11-16). Per job they cost what a request costs (see Node, What it costs), plus the send before returning: one OTLP request, usually tens of milliseconds, at most flushTimeoutMs.
Next
- Every option of
init, and what is traced without code. - What a trace is and how it connects.
- How failures are grouped.
- Every attribute the server SDKs send.