> ## Documentation Index
> Fetch the complete documentation index at: https://docs.uselemma.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Send traces from serverless and edge runtimes

> Finish trace delivery before a serverless or edge runtime stops, and set up the TypeScript SDK on Cloudflare Workers and Durable Objects

Serverless and edge runtimes cancel or freeze work that’s still running once the response is sent, which can cut a trace’s delivery short. Once your traces have ended, pass `lemma.flush()` to the runtime’s `waitUntil()`, call it inside `after()`, or await it last, so delivery finishes first. On Cloudflare Workers, the SDK also needs Node.js compatibility and credentials from the Worker’s bindings. When a Durable Object run outlives its request, build its trace when the run ends and send it with `ingest()`.

## Finish delivery with `lemma.flush()`

`lemma.flush()` waits until every trace the client has started sending is delivered or dropped, and it never rejects. It also waits for a callback trace held open by its returned stream, a plain `ReadableStream` or a native async generator, so it covers a streamed response. It doesn’t wait for:

* A trace handle you haven’t ended
* A callback trace whose callback is still running

A flush can wait up to about 31 seconds when Lemma doesn’t respond, since each send it waits for keeps its own timeout. Leave that headroom under the runtime’s own limit.

The flush waits only for what has started by the time you call it: `ctx.waitUntil(lemma.flush())` before `trace.end()` waits for nothing. Call it after the trace ends, or inside `after()`, which runs once the response is sent.

The flush also covers the whole client. On a client shared across requests, it also waits for other requests’ sends and streams, and a returned stream that nobody reads or cancels holds it until the runtime’s own limit. A client built per request, as in the Workers example below, scopes the flush to that request.

Pass it to the runtime where the response is sent:

| Runtime | Call |
| - | - |
| Cloudflare Workers | `ctx.waitUntil(lemma.flush())` |
| Next.js | `after(() => lemma.flush())`, with `after` from `next/server` |
| Vercel Functions outside Next.js | `waitUntil(lemma.flush())`, with `waitUntil` from `@vercel/functions` |
| AWS Lambda | `await lemma.flush()` before the handler returns |

On Workers, a callback that returns the agent’s stream as a plain `ReadableStream` keeps its trace open until the response body is sent, and `ctx.waitUntil(lemma.flush())` keeps the Worker running until that trace is delivered:

```typescript theme={null}
export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext) {
    const lemma = lemmaFor(env);
    const { message } = await request.json<{ message: string }>();
    const stream = await lemma.trace(
      { name: "support-agent", input: message },
      async (trace) => streamAgent(message, trace),
    );
    ctx.waitUntil(lemma.flush());
    return new Response(stream);
  },
};
```

`lemmaFor()` builds the client from the Worker’s bindings, as [Pass credentials from bindings](#pass-credentials-from-bindings) shows. Return the stream `lemma.trace()` gives back, not the one your callback built: the SDK ends the trace when that one is read to the end, cancelled, or fails. Other stream types, such as a LangChain or OpenAI SDK stream, end the trace when the callback returns; [Serverless or streaming handlers](https://docs.uselemma.ai/tracing/troubleshooting/debug-mode.md#serverless-or-streaming-handlers) lists them.

In a Next.js route, end the trace, also when the agent throws, then schedule the flush with `after()`, which runs once the response is sent:

```typescript theme={null}
import { after } from "next/server";

export async function POST(request: Request) {
  const { message } = await request.json();
  const trace = lemma.trace({ name: "support-agent", input: message });
  after(() => lemma.flush());
  try {
    const answer = await runAgent(message, trace);
    void trace.end({ output: answer });
    return Response.json({ answer });
  } catch (error) {
    trace.fail(error);
    void trace.end();
    throw error;
  }
}
```

On AWS Lambda, nothing runs after the handler returns, so await `lemma.flush()` last. With response streaming, await the pipe into `responseStream` first, then `await lemma.flush()`. Awaiting the flush before the stream is read would wait for it until the function times out.

## Flush a framework integration

The `vercelAI()`, `openAIAgents()`, and `langChain()` integrations track their own runs, so each has its own flush: `lemmaTelemetry.flush()`, `processor.forceFlush()`, and `lemmaHandler.flush()`. Call an integration’s flush once the response is complete: each waits only for runs that have already finished, so a flush called earlier finds nothing to wait for. `shutdown()` also sends the runs still in progress, for a process that is about to exit.

Where to call the integration’s flush, shown here for `lemmaTelemetry`:

* **Next.js**: `after(() => lemmaTelemetry.flush())`
* **AWS Lambda**: `await lemmaTelemetry.flush()` after the run, before the handler returns
* **Cloudflare Workers or Vercel Functions, response not streamed**: pass the integration’s flush to `ctx.waitUntil()` or `waitUntil()` after the run
* **Cloudflare Workers or Vercel Functions, streamed response**: flush once the body is sent, as below

To flush once a streamed body is sent, pipe it through a `TransformStream` and flush when the pipe settles, also when the client disconnects:

```typescript theme={null}
const response = result.toUIMessageStreamResponse();
const { readable, writable } = new TransformStream();
const flush = () => lemmaTelemetry.flush();
ctx.waitUntil(response.body!.pipeTo(writable).then(flush, flush));
return new Response(readable, response);
```

## Set up Cloudflare Workers

The SDK runs on Cloudflare Workers and in Durable Objects once the Worker has Node.js compatibility and builds its client from its bindings.

### Turn on Node.js compatibility

The SDK’s entry point imports `node:crypto`, so the Worker needs Node.js compatibility, or it fails to start. Use a compatibility date of 2024-09-23 or later. With a compatibility date before 2026-08-04, also add the `nodejs_compat` flag to your Wrangler config; from that compatibility date on, it’s on by default:

```toml theme={null}
compatibility_date = "2025-09-01"
compatibility_flags = ["nodejs_compat"]
```

In `wrangler.jsonc`, the same settings are `"compatibility_date"` and `"compatibility_flags"`.

### Pass credentials from bindings

Store the ingest key and the project ID as Wrangler secrets, with the commands the [setup command](https://docs.uselemma.ai/reference/setup-command.md#files-written-to-the-app-directory) prints:

```bash theme={null}
npx wrangler secret put LEMMA_API_KEY
npx wrangler secret put LEMMA_PROJECT_ID
```

Each command prompts for the value and deploys the change immediately. With gradual deployments, use `npx wrangler versions secret put`, then deploy the version with `npx wrangler versions deploy`. For a named Wrangler environment, add `--env <name>` to each.

Don’t also list them under `vars`: wrangler refuses a secret whose name a deployed var uses, and deploying a var deletes the secret of the same name. `LEMMA_RELEASE` isn’t a secret, so it can go under `vars`.

Wrangler reads the `.env` files only while there’s no `.dev.vars`. For `wrangler dev`, put `LEMMA_API_KEY` and `LEMMA_PROJECT_ID` in `.dev.vars` when it exists or the app has no `.env` file, and in `.env` otherwise. For a Worker, the setup command writes the same file. When a `.dev.vars.<name>` file exists, `wrangler dev --env <name>` reads it in place of either file, so add the names there too.

When the Wrangler config declares `secrets`, wrangler loads `LEMMA_API_KEY` and `LEMMA_PROJECT_ID` from that file only when `secrets.required` lists them. Add both to it.

Build the client from the handler’s `env`, so it doesn’t depend on whether the runtime fills `process.env`:

```typescript theme={null}
import { enableDebugMode, Lemma } from "@uselemma/tracing";

type Env = {
  LEMMA_API_KEY: string;
  LEMMA_PROJECT_ID: string;
  LEMMA_RELEASE?: string;
  LEMMA_DEBUG?: string;
};

function lemmaFor(env: Env) {
  if (env.LEMMA_DEBUG === "1") enableDebugMode();
  return new Lemma({
    apiKey: env.LEMMA_API_KEY,
    projectId: env.LEMMA_PROJECT_ID,
    release: env.LEMMA_RELEASE,
  });
}
```

The client sends through the Worker’s own `fetch`, so you don’t pass one. Up to `@uselemma/tracing` 7.14.0, pass `fetch: (input, init) => fetch(input, init)` as well: those versions call the Worker’s `fetch` in a way the runtime rejects, and the SDK drops every trace.

### Send the first trace from the Worker

Bindings, `ctx.waitUntil()`, and Node.js compatibility behave as they do in production only inside the Workers runtime, so a Node test or script can pass while the deployed Worker sends nothing. Send the first trace from the Worker itself:

**1. Run the Worker with debug mode on**

Append `--var LEMMA_DEBUG:1` to the command that starts your Worker, keeping its other flags such as `--env <name>`, and send it a request that runs the agent:

```bash theme={null}
npx wrangler dev --var LEMMA_DEBUG:1
# or, when the dev script runs wrangler dev:
npm run dev -- --var LEMMA_DEBUG:1
```

For a Pages project, append `--binding LEMMA_DEBUG=1` to its `wrangler pages dev` command. Either flag sets `LEMMA_DEBUG` for this run only. It overrides any value in `.dev.vars` or `.env`, even when `secrets.required` leaves it out, and no deploy includes it. `lemmaFor()` above turns on debug mode when it’s `1`.

The Cloudflare Vite plugin takes no `--var`, so replace the `if` in `lemmaFor()` with a bare `enableDebugMode()` call for the run, and restore it afterwards.

Don’t put `LEMMA_DEBUG` under `vars` or `secrets.required`: under `vars`, the next deploy turns on debug mode in production; under `secrets.required`, every deploy fails until you set that secret.

**2. Check the log**

Look for `trace sent` in the dev server’s output. [Debug mode](https://docs.uselemma.ai/tracing/troubleshooting/debug-mode.md) explains the rest of the log.

## Trace a Durable Object run that outlives its request

A Durable Object can keep an agent run going across requests and alarms, after the request that started it has ended. Store the run in the object’s storage as it happens, then build one trace when it finishes and send it with [`ingest()`](https://docs.uselemma.ai/tracing/instrumentation/traces#send-a-trace-you-built-yourself). The stored run holds:

* **Identity**: a stable `id`, the `input`, and the `threadId`
* **Steps**: one record per tool call, with its `name`, a stable span `id`, `input`, `output`, `startedAt`, and `endedAt`
* **Outcome**: the `answer`, or the `error` when the run failed
* **Timing**: `startedAt` and `endedAt` as ISO strings

```typescript theme={null}
import { Lemma, TraceContext } from "@uselemma/tracing";

async function sendRun(lemma: Lemma, run: StoredRun) {
  const trace = new TraceContext({
    id: run.id,
    name: "support-agent",
    input: run.input,
    threadId: run.threadId,
  });
  for (const step of run.steps) trace.recordTool(step);
  if (run.error) trace.fail(run.error);
  else trace.output(run.answer);
  await lemma.ingest(trace, {
    startedAt: new Date(run.startedAt),
    endedAt: new Date(run.endedAt),
  });
}
```

`ingest()` sends once and throws when the send fails, so keep the stored run until it succeeds. Await `sendRun()` in the alarm handler that finishes the run: Cloudflare retries an alarm that throws. When the run’s `endedAt` is already stored, have the alarm call only `sendRun()`. The retry then resends the same payload from storage, and Lemma skips spans it already stored.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.