# 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.

Applies to: the Sypnia engine (open source, self-hosted) and Sypnia Cloud (paid service).  
Source: https://telemetry.docs.sypnia.com/sdks/queues-and-functions/

For agents: Read this to trace work a Node app hands to an SQS queue or a Lambda function with @sypnia/telemetry/node. Sending side: injectTraceContext(payload) for a Lambda Invoke payload, sqsTraceAttributes(attributes) for SQS MessageAttributes, currentTraceparent(). Receiving side: wrapSqsHandler(handle, options) (one span per message, partial batch failures, flush before returning), wrapLambdaHandler(handler, options) (direct invoke continues the payload's traceparent, scheduled runs start their own trace, API Gateway events are HTTP requests), traceSqsRecord(message, fn, options) (0.1.2) for handlers that loop over the batch themselves, continueTrace(carrier, name, fn) for other workers, identify({ account }) inside a job, init({ pg }) (0.1.2) for bundled functions. A job is a SERVER span whose http.route is the job's name.

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`](https://telemetry.docs.sypnia.com/sdks/node), from version **0.1.1**; [`@sypnia/telemetry/next`](https://telemetry.docs.sypnia.com/sdks/nextjs) 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.

> **In plain words**
>
> When your app says «process this receipt later» and puts the job on a queue, the trace used to stop there. With two lines, one where the job is sent and one where it is received, Sypnia follows the job to the end and shows you where it failed.

## 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](https://telemetry.docs.sypnia.com/sdks/node#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()`](https://telemetry.docs.sypnia.com/sdks/node#spanname-fn-attrs) 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:

```bash
npm install @sypnia/telemetry@^0.2.0
```

### An SQS message

Pass the message's attributes through `sqsTraceAttributes`. It returns a copy with `traceparent` added, and leaves the ones you gave unchanged:

`src/jobs/receipts.ts`

```ts
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 `traceparent` attribute 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:

`src/orders/refresh.ts`

```ts
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:

`workers/receipts.ts`

```ts
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:

1. It reads `traceparent` from 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.
2. 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.
3. If your function throws, the error is reported with its stack as an `exception` (`sypnia.error.source` `uncaught`), the span is marked failed, and the message goes in `batchItemFailures`. 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:

```bash
aws lambda update-event-source-mapping --uuid <mapping uuid> --function-response-types ReportBatchItemFailures
```

Without 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.

`workers/charges.ts`

```ts
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:**

None.

## 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](https://telemetry.docs.sypnia.com/sdks/node#what-is-traced-without-any-code). 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.                                                                                                                                                                                      |

`functions/refresh-order.ts`

```ts
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:**

None.

## Who a job belongs to

A job has no browser session, so it has no person unless you say so. Call [`identify()`](https://telemetry.docs.sypnia.com/sdks/node#identifywho) 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:

```ts
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:

`worker.ts`

```ts
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.

> **Note: Many messages, many traces**
>
> Each message is its own span and keeps the trace of the request that sent it. A batch of ten messages sent by ten requests is ten spans in ten traces, not one span with ten links.

## 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](https://telemetry.docs.sypnia.com/sdks/node#database-error-details)):

```ts
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](https://telemetry.docs.sypnia.com/sdks/node#what-it-costs)), plus the send before returning: one OTLP request, usually tens of milliseconds, at most `flushTimeoutMs`.

## Next
