# Node

> Trace every request your Node server handles and every call it makes, without OpenTelemetry, send them as OTLP, link them to the browser session that caused them, and report server errors, with one import.

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

This page is for whoever runs a Node server: an API, a backend for a web app, a server-rendered site. `@sypnia/telemetry/node` is open source (MIT) and identical for the open-source engine and for Sypnia Cloud; only the address and the origin of the key differ. For Next.js use [`@sypnia/telemetry/next`](https://telemetry.docs.sypnia.com/sdks/nextjs), which includes this.

It is Sypnia's own tracer, small on purpose: it does not depend on OpenTelemetry and installs no module loader. What it sends is standard, though: traces in the OpenTelemetry protocol (OTLP/HTTP, protobuf), with OpenTelemetry's attribute names and a few `sypnia.*` ones, listed in the [semantic conventions](https://telemetry.docs.sypnia.com/reference/semantic-conventions). If your app already uses OpenTelemetry, or you want its instrumentations for more libraries, use the [OpenTelemetry bridge](https://telemetry.docs.sypnia.com/sdks/otel-bridge) instead.

**At the end you will have:** every incoming request traced without placing any call by hand, its database and service calls as spans, server errors as problems, and each trace joined to the browser session that started it.

## Install

**npm**

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

**pnpm**

```bash
pnpm add @sypnia/telemetry
```

**yarn**

```bash
yarn add @sypnia/telemetry
```

**bun**

```bash
bun add @sypnia/telemetry
```

Create one file that starts Sypnia, and import it before anything else in your server's entry file.

**Sypnia Cloud**

`src/instrument.ts`

```ts
import { init } from '@sypnia/telemetry/node';

init({
  project: process.env.SYPNIA_PROJECT_KEY,
  service: 'shop-api',
  environment: process.env.SYPNIA_ENVIRONMENT ?? 'production',
  release: process.env.SYPNIA_RELEASE,
});
```

**Self-hosted**

`src/instrument.ts`

```ts
import { init } from '@sypnia/telemetry/node';

init({
  project: process.env.SYPNIA_PROJECT_KEY,
  endpoint: 'https://sypnia.example.com',
  service: 'shop-api',
  environment: process.env.SYPNIA_ENVIRONMENT ?? 'production',
  release: process.env.SYPNIA_RELEASE,
});
```

`src/server.ts`

```ts
import './instrument';
import express from 'express';

const app = express();
app.post('/api/checkout', checkout);
app.listen(3000);
```

`.env`

```bash
SYPNIA_PROJECT_KEY=spk_7d1f0c9e4b8a2f6d3c5e1a9b0f4d8c2e
SYPNIA_ENVIRONMENT=production
SYPNIA_RELEASE=4f2a91c
```

Use the same project as your frontend, and the same `environment` and `release` naming. A trace connects parts of one project in one environment.

> **Note: The key is an ingest key**
>
> The server uses an ingest key (`spk_…`), like the browser. It can only send. Never give a server SDK an API token (`sps_…`): ingest refuses it.

## Check that it works

1. Start your server with `debug: true` in `init`.
2. Call any route: `curl -i http://localhost:3000/api/checkout -X POST`.
3. The console prints the request as a tree of spans, then one line per call (for the shop's checkout: `POST /api/checkout 400 · 3,842 ms`, `SELECT carts`, `POST /v1/payments`), and within 2 seconds `exported 3 spans (200)`.

## What is traced without any code

| What                         | Covers                                                                                                                         | Becomes                                                                                                                                                              | How                                                                                                                                                                                                       |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Incoming requests            | Every request to a server built on Node's `http` or `https` module: Express, Fastify, Koa, NestJS, Hono on Node, plain `http`. | A server span (`SPAN_KIND_SERVER`) with method, path, route, status and duration.                                                                                    | Node's own `http.server.request.start` diagnostics channel, and the response's `finish` and `close` events. The request's context lives in an `AsyncLocalStorage`.                                        |
| Outgoing HTTP calls          | `fetch`, and `http.request` / `https.request` (so also axios, got and most SDKs).                                              | A client span of kind `http`, named `POST /v1/payments`.                                                                                                             | The diagnostics channels Node publishes for `http` clients and for `fetch` (undici). No function of yours is wrapped; the platform's `fetch` is, only to read [database errors](#database-error-details). |
| Postgres queries             | The `pg` package.                                                                                                              | A client span of kind `db`, named by operation and table: `SELECT carts`. Never the statement's values.                                                              | `init` finds `pg` in your app's dependencies and wraps `Client.prototype.query` once. Pools use the same client, so they are covered.                                                                     |
| Supabase and PostgREST calls | Recognized among the outgoing calls by their path (`/rest/v1/…`).                                                              | A client span of kind `db`: `SELECT orders`, `INSERT orders`, `CALL create_order`, with `sypnia.db.via` `postgrest`. A `PUT`, PostgREST's upsert, is named `INSERT`. | Read from the outgoing call's method and path, and, when the call fails, from its answer: see [Database error details](#database-error-details).                                                          |
| Errors                       | Listed under [Errors](#errors).                                                                                                | An `exception` event on the span where it happened, or a failed span.                                                                                                | Process handlers for uncaught exceptions and unhandled rejections; the request's own span for the rest.                                                                                                   |

Other database drivers (MySQL, MongoDB, Redis, Prisma's own engine) are not traced by themselves. Wrap the call in [`span()`](#spanname-fn-attrs), or use their OpenTelemetry instrumentation through the [bridge](https://telemetry.docs.sypnia.com/sdks/otel-bridge), at OpenTelemetry's cost.

**Not traced by default:** `OPTIONS` requests, and requests for static files (a path that ends in `.js`, `.css`, `.map`, `.png`, `.jpg`, `.jpeg`, `.gif`, `.svg`, `.ico`, `.webp`, `.avif`, `.woff`, `.woff2`, `.ttf`, `.txt`, `.xml` or `.webmanifest`). Add your health check with `ignoreRoutes`.

**Never read:** request bodies, the answers of calls that succeeded, cookies, headers other than `traceparent` and `x-sypnia-session`, and query strings. A span's name and attributes carry the method, the host, the path and the status, nothing else: `url.query`, `url.full` and `db.query.text` are never sent. There is one exception, on by default: what the database answers when a database call returns an error, described next.

### Database error details

When a database call answers with an error, the SDK reads what the database said. It is the only answer the SDK reads.

| Call                                                                 | What is read                                                                                   | What is kept                                                                                               |
| -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| A Supabase or PostgREST call through `fetch` answered `400` or above | The first 4 KB of a copy of the answer's body. Your code still reads the whole body, as before | `code`, and `message` with `details` and `hint` on lines of their own, as PostgREST wrote them             |
| A `pg` query that throws                                             | The error `pg` gives your code                                                                 | Its SQLSTATE, and its `message` with its `detail` and `hint` on lines of their own, as Postgres wrote them |

The code goes to `db.response.status_code`: the SQLSTATE, such as `22P02`, or PostgREST's own code, such as `PGRST116`. The message goes to `sypnia.db.message`, up to 2,000 characters, as `message`, then `Detail: …` and `Hint: …` on their own lines when the database sent them (the way `psql` prints an error), and when the call failed (no answer, `400`, `500` or above, or a `pg` error) it is also the span's status message. An answer such as `404` or `409` is not a failure: the span stays `ok` and carries the code and the message as attributes. **Nothing in the message is replaced.** When the shop's code looks up an order with an e-mail where an id belongs, the span's message is:

```text
invalid input syntax for type uuid: "maria@example.com"
```

When a customer signs up with an e-mail that already has an account, the database puts the value in the detail:

```text
duplicate key value violates unique constraint "users_email_key"
Detail: Key (email)=(maria@example.com) already exists.
```

- **It can contain personal data.** Whatever the database puts in its message is sent as it is: an e-mail, a name, an amount or an id from the call that failed. It is stored with the trace and the problem, and everyone who can read the project sees it.
- **It is on by default**, because the exact message, with its value, is what tells you what failed.
- **A successful answer is never read**, whatever the setting.
- **Grouping still works.** A failed database call's fingerprint uses its code and the first line of its message, normalized as for every error (quoted values, numbers, UUIDs and URLs are replaced first), so the values in a message and its `Detail:` and `Hint:` lines do not split a problem. A problem's title carries the code, never the message. See [Problem grouping](https://telemetry.docs.sypnia.com/architecture/problem-grouping#the-algorithm).
- **The agent's analysis** gets the message after its own redaction, which replaces e-mail addresses, long numbers and tokens and leaves other values: see [Models and what is sent](https://telemetry.docs.sypnia.com/agent/models-and-what-is-sent).
- **At the end of a request** the SDK waits at most 50 ms for an error body still being read.
- **Not covered:** PostgREST called through `http.request` (Supabase's client uses `fetch`), and a Supabase client created with a `fetch` your code captured before `init` ran.

Reading those answers is the one place where the SDK wraps a function: the platform's `globalThis.fetch`, because Node publishes no body on its diagnostics channels. Your own functions are never wrapped, and properties frameworks put on `fetch` are kept.

To keep these details out, set `captureDbErrors: false` in `init`:

`src/instrument.ts`

```ts
import { init } from '@sypnia/telemetry/node';

init({
  service: 'shop-api',
  captureDbErrors: false,
});
```

Then no answer is read at all: a failed Supabase or PostgREST call carries its HTTP status as its code and no message, and a failed `pg` query keeps its SQLSTATE, which holds no value, and no message.

### When a call has failed

A call your server makes has failed when it gets no answer, answers `400`, or answers `500` or above. A request your server receives has failed when it answers `500` or above, or throws. Answers such as `401`, `404` and `409` are answers, not failures.

### Requests that never finish

A request still running after 20 seconds is exported at that moment as a partial span (`sypnia.partial`): the spans that finished, and the calls still in flight marked `sypnia.running`. If the request finishes, the SDK exports the same span again in full and it replaces the partial one. If the platform kills it, the partial span is what you have, and when no full span has come 15 minutes later it becomes a timeout problem. Change the threshold with `slowRequestMs`.

## Linking the browser to the server

The browser SDK adds two headers to calls to your API. The Node SDK reads them, so you do nothing:

| Header             | Read as                                                                                                                                                                                          |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `traceparent`      | The trace id and the parent span: the server span takes the browser call's span id as `parentSpanId`, so the server's spans join the browser's trace. Without it, the server starts a new trace. |
| `x-sypnia-session` | The session id, sent as the attribute `session.id`. The request appears in that session's timeline, and its failures count for the person of that session.                                       |

On every outgoing call, the SDK adds `traceparent` with the current trace, so the next service continues it: another Node server with this SDK, or any backend with an OpenTelemetry SDK. It never forwards `x-sypnia-session`, and it never replaces a `traceparent` your code already set. On a Node 20 release that does not publish the `http.client.request.created` diagnostics channel, calls made with `http.request` (and the libraries built on it) cannot be given `traceparent`; `fetch` calls can.

If the browser calls your API on another origin, the API must allow both headers in CORS. See [Browser](https://telemetry.docs.sypnia.com/sdks/browser#calls-to-your-api-and-traces).

## What it sends, and where

Every 2 seconds, and at the end of a serverless invocation, the SDK exports the spans of the requests that finished: one OTLP/HTTP request, in protobuf, gzipped, to `<endpoint>/v1/otlp/v1/traces`, with the ingest key in `Authorization`. At most 512 spans per export, and the spans of one request always travel together. While the engine cannot be reached, at most 5,120 spans wait in memory; past that, the oldest requests without a failure are dropped first. A failed export is retried after 1, 4 and 15 seconds, only after a network error or a `429`, `502`, `503` or `504` answer, and never sooner than the answer's `Retry-After`, counted up to 60 seconds. It is the same [endpoint](https://telemetry.docs.sypnia.com/api/otlp) any OpenTelemetry exporter can use, so you can point a Collector or a debugging proxy at it and read what the SDK sends with ordinary tools.

| On the wire                                                                                             | From                                                 |
| ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- |
| Resource `service.name`, `deployment.environment.name`, `service.version`                               | `service`, `environment`, `release` in `init`        |
| Server span: `http.request.method`, `http.route`, `url.path`, `http.response.status_code`               | The request                                          |
| `session.id`, `user.id`, `sypnia.account.id`                                                            | `x-sypnia-session`, and [`identify()`](#identifywho) |
| Client spans: `server.address`, `url.path`, `db.system.name`, `db.operation.name`, `db.collection.name` | The calls                                            |
| `db.response.status_code`, `sypnia.db.message`                                                          | [Database error details](#database-error-details)    |
| `exception` events, status `ERROR` with its message: a database's as it wrote it, any other redacted    | [Errors](#errors)                                    |

The full list, with types and examples, is the [semantic conventions](https://telemetry.docs.sypnia.com/reference/semantic-conventions).

## `init(options)`

| Option                  | Type                           | Default                                                                     | What it does                                                                                                                                                                                                                                                           |
| ----------------------- | ------------------------------ | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `project`               | `string`                       | `process.env.SYPNIA_PROJECT_KEY`                                            | The ingest key, `spk_…`. Without it the SDK does nothing and prints one warning.                                                                                                                                                                                       |
| `endpoint`              | `string`                       | `process.env.SYPNIA_ENDPOINT`, else `'https://telemetry.ingest.sypnia.com'` | Where to send. A self-hosted engine's base URL.                                                                                                                                                                                                                        |
| `service`               | `string`, up to 80 characters  | `process.env.SYPNIA_SERVICE`, else `'server'`                               | The name of this service in traces.                                                                                                                                                                                                                                    |
| `environment`           | `string`, 1 to 40 characters   | `process.env.SYPNIA_ENVIRONMENT`, else `'production'`                       | The environment. Use the same names as the frontend.                                                                                                                                                                                                                   |
| `release`               | `string`, up to 40 characters  | `process.env.SYPNIA_RELEASE`, else none                                     | The release. Use the short git commit.                                                                                                                                                                                                                                 |
| `enabled`               | `boolean`                      | `true`                                                                      | `false` turns the SDK into a no-op.                                                                                                                                                                                                                                    |
| `debug`                 | `boolean`                      | `false`                                                                     | Prints every request as a tree of spans, and every export, to the console.                                                                                                                                                                                             |
| `allowRoutes`           | `(string \| RegExp)[]`         | none: every path                                                            | When set, only these incoming paths are traced; requests to any other path are not. Same matching as `ignoreRoutes`, which still applies inside them. For apps that observe some areas only.                                                                           |
| `anonymousRoutes`       | `(string \| RegExp)[]`         | none                                                                        | 0.3.0. Public paths traced without identity: `identify()` is ignored in their requests, which carry `sypnia.anonymous = true`. Traced even when `allowRoutes` does not list them. See [Anonymous visitors](https://telemetry.docs.sypnia.com/sdks/anonymous-visitors). |
| `ignoreRoutes`          | `(string \| RegExp)[]`         | `[]`                                                                        | Incoming paths that are not traced, on top of the defaults above. A string matches the path and everything under it; a RegExp is tested against the path.                                                                                                              |
| `routeFor`              | `(pathname: string) => string` | the built-in rule                                                           | Your own way to turn a path into a route. By default the SDK uses the route pattern of Express and Fastify when it can read it (`/orders/:id`), and otherwise the same rule as the browser.                                                                            |
| `capture.outgoing`      | `boolean`                      | `true`                                                                      | Spans for outgoing HTTP calls.                                                                                                                                                                                                                                         |
| `capture.db`            | `boolean`                      | `true`                                                                      | Spans for `pg`, and naming of Supabase and PostgREST calls.                                                                                                                                                                                                            |
| `pg`                    | the `pg` module                | none: the SDK looks for `pg` from the working directory                     | The `pg` module itself (`import pg from 'pg'`), for a bundled app, such as an AWS Lambda function bundled with esbuild, where `pg` is not in `node_modules` for the SDK to find. From 0.1.2.                                                                           |
| `captureDbErrors`       | `boolean`                      | `true`                                                                      | Reads the error answer of a database call and keeps its code and full message, values included, up to 2,000 characters. `false`: nothing is read; a `pg` error keeps only its SQLSTATE. See [Database error details](#database-error-details).                         |
| `capture.consoleErrors` | `boolean`                      | `true`                                                                      | Reports `console.error` during a request as a failure.                                                                                                                                                                                                                 |
| `capture.uncaught`      | `boolean`                      | `true`                                                                      | Reports uncaught exceptions and unhandled rejections.                                                                                                                                                                                                                  |
| `propagate`             | `boolean`                      | `true`                                                                      | Adds `traceparent` to outgoing calls.                                                                                                                                                                                                                                  |
| `slowRequestMs`         | `number`                       | `20000`                                                                     | When a request still running is reported as partial. `0` turns it off.                                                                                                                                                                                                 |
| `flushBudgetMs`         | `number`                       | `50`                                                                        | The longest the SDK waits for a send at the end of a serverless invocation.                                                                                                                                                                                            |
| `beforeSend`            | `(span) => span \| null`       | none                                                                        | Called with each finished span (`name`, `kind`, `attributes`, `status`) before it is queued. Change it and return it, or return `null` to drop it; dropping a server span drops its request's spans too.                                                               |

Fixed limits: 200 spans kept per request (the rest are counted in `sypnia.dropped_spans`), 64 attributes per span, 5 failures per request of which 3 from `console.error`, one per fingerprint. They are in the [semantic conventions](https://telemetry.docs.sypnia.com/reference/semantic-conventions#limits-and-constants).

## Errors

| Caught without code                                           | How it appears                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| An exception nobody caught, or an unhandled rejection         | A failure with its stack: an `exception` event on the request's span, or, outside any request, on a span of its own marked `sypnia.error.standalone`. The SDK watches through Node's `uncaughtExceptionMonitor`, so what Node does next does not change. A rejection your app handles with its own `unhandledRejection` listener is not seen. When the process dies right after, the request in flight is sent at once as partial; that send is best effort.                              |
| A call that failed (see above)                                | A failed span, which Sypnia names after the call, such as `HTTP 400` or `DB 23505`. A failed HTTP call carries its status only: the SDK does not read its answer. A failed database call carries the database's code and its full message, unless you turned that off: see [Database error details](#database-error-details). Any other message is redacted before it leaves your server: e-mail addresses, URLs, UUIDs, quoted values, long tokens and every run of digits are replaced. |
| A request answered with `500` or above, with no other failure | A failure named `HTTP 500`, with the route.                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `console.error` while handling a request                      | An `exception` event with the logged text (`sypnia.error.source` `log`), and the stack if an `Error` was logged.                                                                                                                                                                                                                                                                                                                                                                          |

Frameworks catch errors thrown in your handlers and turn them into a `500`. Sypnia then knows the request failed, and not why. Hand the error over with one line, so the problem has its stack:

**Express**

`src/server.ts`

```ts
import { reportError } from '@sypnia/telemetry/node';

// after all routes
app.use((error, req, res, next) => {
  reportError(error);
  next(error);
});
```

**Fastify**

`src/server.ts`

```ts
import { reportError } from '@sypnia/telemetry/node';

app.addHook('onError', async (request, reply, error) => {
  reportError(error);
});
```

**Koa**

`src/server.ts`

```ts
import { reportError } from '@sypnia/telemetry/node';

app.on('error', (error) => reportError(error));
```

**Hono**

`src/server.ts`

```ts
import { reportError } from '@sypnia/telemetry/node';

app.onError((error, c) => {
  reportError(error);
  return c.json({ error: 'internal_error' }, 500);
});
```

## The functions you call

### `reportError(error)`

Reports an error your code caught, as an `exception` event (`sypnia.error.source` `manual`). Inside a request it is attached to that request's trace and session.

### `identify(who)`

Says who a request belongs to. You need it only for requests that do not come from an identified browser session: a mobile app, an API client, a webhook. For the others, Sypnia already knows the person from the session.

`src/auth-middleware.ts`

```ts
import { identify } from '@sypnia/telemetry/node';

app.use((req, res, next) => {
  if (req.user) identify({ person: { id: req.user.id }, account: { id: req.user.accountId } });
  next();
});
```

It applies to the current request only: the server span gets `user.id` and `sypnia.account.id`. Only ids travel; names and e-mail addresses are never sent from the server. See [Identifying people](https://telemetry.docs.sypnia.com/sdks/identifying-people).

### `span(name, fn, attrs?)`

Records your own step as a span of kind `internal`, around a function. It returns what the function returns, and marks the span failed if the function throws. The function receives the span, a handle with `setAttribute(name, value)` and `setAttributes(values)`, to set attributes while it runs or after it ends.

`src/checkout.ts`

```ts
import { span } from '@sypnia/telemetry/node';

const total = await span('price cart', s => {
  const t = priceCart(cart);
  s.setAttribute('cart.discounted', t.discount > 0);
  return t;
}, { 'cart.items': cart.items.length });
```

`name` has at most 120 characters. Attribute values are strings of at most 256 characters, numbers or booleans; other values are left out.

### `activeSpan()` and `setSpanAttributes(values)`

From version 0.4.0. They set attributes on the span the current code runs in: the `span()` being run, else the request's or the job's own span. You can still set them after the work ended, until the request is sent. That is how a use case carries `sypnia.case` from when it starts and `sypnia.case.outcome` from when it ends ([Use cases and places](https://telemetry.docs.sypnia.com/concepts/use-cases-and-places)).

`src/checkout.ts`

```ts
import { setSpanAttributes } from '@sypnia/telemetry/node';

setSpanAttributes({ 'sypnia.case': 'place-order' });
const order = await placeOrder(cart);
setSpanAttributes({ 'sypnia.case.outcome': 'OrderPlaced' });
```

`setSpanAttributes` returns `false` when there is no span to set (outside a traced request, or with the SDK off), and does nothing. `activeSpan()` returns the same handle `span()` gives its function; with no span, a handle that does nothing. `sypnia.case` is kept up to 128 characters and `sypnia.case.outcome` up to 80. In Next.js, import both from `@sypnia/telemetry/next/server`.

### `flush(timeoutMs?)` and `shutdown(timeoutMs?)`

`flush` sends what is waiting and resolves when it is sent or after `timeoutMs` (default 2,000). `shutdown` does the same and then stops the SDK.

### `wrapFetchHandler(handler)`

For runtimes where a server is a function from a `Request` to a `Response`. See [Serverless](#serverless-and-other-runtimes).

### `traceRequest(request, handle, options?)`

For framework integrations, not for apps: it traces one request on a host where no Node server announces requests, and runs `handle` inside it. `wrapFetchHandler` is built on it, and so is the [OpenNext adapter](https://telemetry.docs.sypnia.com/sdks/nextjs#on-aws-lambda-with-opennext) of `@sypnia/telemetry/next`.

Custom events (`track`) are sent from the browser only.

## Graceful shutdown

Finished spans wait in memory for up to 2 seconds before they are exported together, in one OTLP request. When your process is asked to stop, send them first:

`src/server.ts`

```ts
import { shutdown } from '@sypnia/telemetry/node';

process.on('SIGTERM', async () => {
  server.close();
  await shutdown(2000);
  process.exit(0);
});
```

The SDK flushes by itself when the event loop empties (`beforeExit`). It does not install signal handlers: that would change how your process stops.

## Serverless and other runtimes

| Where it runs                                                                                                   | What to do                                                                                                                              |
| --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| A long-running Node server, Node 20 or newer                                                                    | `import './instrument'` first. Everything on this page.                                                                                 |
| Next.js                                                                                                         | [`@sypnia/telemetry/next`](https://telemetry.docs.sypnia.com/sdks/nextjs).                                                              |
| Functions written as `(request: Request) => Response`: Vercel Functions, Supabase Edge Functions, Hono          | `wrapFetchHandler`, below.                                                                                                              |
| Next.js on AWS Lambda through OpenNext (what SST's `Nextjs` deploys)                                            | `@sypnia/telemetry/next/opennext`: [Next.js, On AWS Lambda](https://telemetry.docs.sypnia.com/sdks/nextjs#on-aws-lambda-with-opennext). |
| Your own AWS Lambda handlers: API Gateway or function URL events, SQS consumers, direct invokes, scheduled runs | `wrapLambdaHandler` and `wrapSqsHandler`: [Queues and functions](https://telemetry.docs.sypnia.com/sdks/queues-and-functions).          |
| Bun, Deno and Cloudflare Workers                                                                                | `wrapFetchHandler` uses only web-standard APIs and `AsyncLocalStorage`, so it may work there. Sypnia does not test on these.            |

`api/checkout.ts`

```ts
import { init, wrapFetchHandler } from '@sypnia/telemetry/node';

init({ project: process.env.SYPNIA_PROJECT_KEY, service: 'shop-api' });

export default wrapFetchHandler(async (request: Request) => {
  const order = await createOrder(await request.json());
  return Response.json(order);
});
```

`wrapFetchHandler` traces the request like any other and exports its spans after the response. Where the platform offers a way to keep working after the response (`waitUntil`), it uses it. Where it does not, it waits at most `flushBudgetMs` (50 ms) before returning the response; a send that takes longer goes on in the background and can be lost if the platform freezes the function.

A function that is frozen between invocations does not run timers. If you do not use `wrapFetchHandler`, call `await flush()` before you return.

## What it costs

### What was measured

On 2026-11-15 we measured what tracing costs a Node server, with a light tracer of our own (the design of this SDK, in its smallest form) and with the official OpenTelemetry Node SDK. One machine: a laptop under WSL2, Node 22. The server's handler made two calls to a local service that answered after 2 ms, standing for a database and a payment API. Load: autocannon, 10 connections, 5 seconds of warm-up and 15 measured, about 1,400 requests a second. CPU per request is the process's CPU time divided by the requests. Two runs; the numbers are their range.

|                                           | No tracing       | Light own tracer            | OpenTelemetry Node SDK 2.12 (HTTP instrumentation, OTLP/HTTP JSON exporter, batch every 2 s) |
| ----------------------------------------- | ---------------- | --------------------------- | -------------------------------------------------------------------------------------------- |
| CPU per request                           | ≈ 580 µs         | ≈ 730–740 µs (**+0.15 ms**) | ≈ 1,140–1,330 µs (**+0.55–0.75 ms**)                                                         |
| Requests served when the CPU is the limit | ≈ 22,100 in 15 s | ≈ 19,800–20,000 (−10 %)     | ≈ 11,600–13,400 (−40 %)                                                                      |
| Mean latency under that load              | 6.3 ms           | 7.0 ms                      | 10.7–12.5 ms                                                                                 |
| Time added before the server listens      | —                | ≈ 0                         | +600–800 ms                                                                                  |
| Resident memory                           | 77 MB            | 111 MB (+34 MB)             | 137–139 MB (+60–62 MB)                                                                       |
| Data sent per 1,000 requests              | —                | 278 KB                      | 2,560 KB                                                                                     |

Read it as a comparison, not as this SDK's figures. The tracer measured was minimal (two spans per request, sent as JSON); `@sypnia/telemetry/node` does more work, and sends protobuf. OpenTelemetry can be made cheaper than in this test, with its protobuf exporter, sampling and fewer instrumentations. The startup difference matters most on serverless, where every cold start pays it.

### Measured on this SDK

On 2026-11-16 we measured `@sypnia/telemetry/node` 0.1.0 itself, on the same laptop. The method is simpler than the one above, so compare the two tables with care: an `http` server in the same process as the load, whose handler makes two outgoing calls, 10 connections, 10,000 requests, with and without the SDK. CPU per request is the process's CPU time divided by the requests.

|                       | Measured                                                 | Target                                                      |
| --------------------- | -------------------------------------------------------- | ----------------------------------------------------------- |
| CPU per request       | ≈ 1,080 µs with the SDK, ≈ 705 µs without (**+0.37 ms**) | under 1 ms at the median, for a request with up to 20 spans |
| Time added at startup | ≈ 20 ms to import the package, ≈ 2 ms for `init`         | under 50 ms added to a cold start                           |
| Package size          | 16 kB gzipped                                            | none                                                        |

The targets stay as the SDK's commitments; a new measurement is published here with its date and its method. The SDK installs no module loader and patches no file as it loads, which is why its startup is short. It never delays a response on a long-running server: spans are exported in the background, in batches.

What holds by design, not by measurement:

- A failure inside the SDK never reaches your code: every entry point is wrapped, and an export that fails is retried and then dropped, with one warning a minute at most.
- When the project reaches a usage limit, the engine answers with `Sypnia-Slow-Down` and the SDK exports only requests that carry a failure until the date it names.

## Next
