Cloudflare Workers 10 min read

Effect and Alchemy on Cloudflare Workers: OpenTelemetry tracing

One layer traces an Effect Worker over OTLP. One resource in the Alchemy stack uploads its source maps, so error stacks name your files. Destinations for Cloudflare's own spans are optional, and Alchemy can create those too.

David Granzin By David Granzin

A Cloudflare Worker has no long-lived process, so nothing exports spans in the background unless the runtime is asked to wait. It also ships as a bundle, so an error's stack trace names a position in a file like index-D3yLFpFl.js, not the file you wrote.

With Effect and Alchemy both problems are solved in the code you already have. The Worker gets a telemetry layer that exports OpenTelemetry data over OTLP, and the stack that deploys it uploads the bundle's source maps. This guide walks through both, then covers when a Workers Observability destination is worth adding. The examples send to Maple.

Not using Effect or Alchemy?

For a plain Worker deployed with Wrangler, see Cloudflare Workers tracing with OpenTelemetry. It uses the OpenTelemetry JS SDK and the native OTLP export.

Key takeaways

  • The Telemetry layer records a server span per request and flushes after the response. You write no flush code.
  • It exports from inside the Worker, so tracing needs no Workers Observability destination.
  • Inside a running Worker, error.stack always points at the bundle. The backend needs its own copy of the map.
  • Maple.SourceMaps uploads the maps Alchemy already writes. The release must equal the Worker's service.version.
  • Keep each map under 10 MiB. sourcemapExcludeSources is usually enough.
  • A destination adds the runtime's own spans for bindings and subrequests. Alchemy can create it with Cloudflare.Workers.ObservabilityDestination.

What you need

  • An Alchemy stack that deploys the Worker, with alchemy and @alchemy.run/cloudflare 2.0.0-beta.84 or later and effect 4. Earlier betas have no Bundle.outputDirectory, which the source map upload uses. This guide was written against 2.0.0-beta.87.
  • @maple-dev/alchemy 0.8.0 or later.
  • A Maple API key from Settings → Keys, set as MAPLE_API_KEY where you run alchemy deploy. It must belong to an org admin, because Maple.IngestKeys reads the organization's ingest keys. It carries both the ingest_keys:read and source_maps:write scopes, or no scopes at all, which is full access.
  • A release id for each deploy that both the Worker and the upload can read. This guide uses the git commit, which GitHub Actions sets as GITHUB_SHA.
npm install @maple-dev/alchemy

For an EU organization, also set MAPLE_API_URL=https://api.eu.maple.dev for the deploy and pass endpoint: "https://ingest.eu.maple.dev" to Telemetry.

Trace an Effect Worker with OpenTelemetry

The Effect SDK records spans and logs and sends them as OTLP over HTTP. On an Alchemy Worker it comes as one layer, Telemetry. Declare the ingest key as a resource, then provide the layer:

src/maple.ts

// src/maple.ts
import * as Maple from "@maple-dev/alchemy"

export const Ingest = Maple.IngestKeys("ingest")

src/worker.ts

// src/worker.ts
import * as Cloudflare from "@alchemy.run/cloudflare"
import { Telemetry } from "@maple-dev/alchemy/telemetry"
import { Config, Effect } from "effect"
import { HttpServerResponse } from "effect/http"
import { Ingest } from "./maple.ts"

export const SERVICE_NAME = "api"

// Plan-time only: the deployed bundle folds __ALCHEMY_RUNTIME__ to true and skips the env read.
const props = Effect.gen(function* () {
  if (globalThis.__ALCHEMY_RUNTIME__) return { main: import.meta.url }
  const release = yield* Config.String("GITHUB_SHA")
  return { main: import.meta.url, env: { COMMIT_SHA: release } }
})

export default Cloudflare.Worker(
  "api",
  props,
  Effect.gen(function* () {
    const fetch = Effect.succeed(HttpServerResponse.text("Hello from Maple"))
    return { fetch }
  }).pipe(Effect.provide(Telemetry({ serviceName: SERVICE_NAME, ingestKey: Ingest }))),
)

Telemetry records a server span for each request, attaches Effect logs and spans to it, and flushes after the response. A failure in the handler becomes an exception event with exception.stacktrace on the span, which is what Maple turns into an issue.

Three details:

  • The key is bound for you. ingestKey: Ingest binds the organization's private ingest key onto the Worker as the MAPLE_INGEST_KEY secret at deploy time. If that secret is already set another way, call Telemetry without ingestKey.
  • Import from the subpath. Telemetry is exported from @maple-dev/alchemy/telemetry, not from the package root.
  • Your spans join the request. Anything you wrap in Effect.withSpan inside the handler is a child of the request's server span.

Every SDK option is listed in Effect SDK on Cloudflare Workers.

Report the release as service.version

Source maps are matched by release, so the Worker has to say which release it is. The SDK sets service.version from the first of:

  1. The serviceVersion option.
  2. service.version in attributes or in the OTEL_RESOURCE_ATTRIBUTES env var.
  3. A commit SHA in the Worker's env: COMMIT_SHA, RAILWAY_GIT_COMMIT_SHA, VERCEL_GIT_COMMIT_SHA, CF_PAGES_COMMIT_SHA or RENDER_GIT_COMMIT.

The props effect above uses the third. It reads GITHUB_SHA at deploy time and binds it as COMMIT_SHA, so the Worker's spans carry the commit as service.version. The read sits behind the __ALCHEMY_RUNTIME__ check because props is also part of the deployed bundle, where there is no GITHUB_SHA to read.

A deploy without GITHUB_SHA fails on the Config.String read. Set it for local deploys too, for example export GITHUB_SHA=$(git rev-parse HEAD) before alchemy deploy. If you use your own release ids instead of commits, bind that value as COMMIT_SHA and upload under the same value.

A deploy where only the commit changed still gets maps. Reading Alchemy 2.0.0-beta.87, a changed env value counts as a change to the Worker, and updating the Worker bundles it again, so the maps are on disk for the upload. We read that in the source and have not measured it in a deploy.

Why the stack trace names the Alchemy bundle

Alchemy deploys the Worker as a bundle: your files, Effect and every other dependency in a few JavaScript files with hashed names. A failure's stack is built from what is running, so it names the bundle:

Illustrative

Error: plan not found
    at resolvePlan (file:///bundle/index-D3yLFpFl.js:1874:31887)
    at file:///bundle/index-D3yLFpFl.js:2210:40212

The stack on the span's exception event is that same string. The backend has to map it back, with a map you upload. The Wrangler guide explains why Cloudflare's own source map upload does not change this.

Upload a Worker's source maps with Alchemy

Alchemy bundles the Worker with source maps on and hidden: each .map file sits beside its JS file and no sourceMappingURL comment ships. It writes the bundle to .alchemy/bundles/<stack>-<stage>-<worker id>, and Bundle.outputDirectory returns that path. Point Maple.SourceMaps at it:

alchemy.run.ts

// alchemy.run.ts
import * as Alchemy from "alchemy"
import * as Bundle from "alchemy/Bundle"
import { Stack } from "alchemy/Stack"
import * as Cloudflare from "@alchemy.run/cloudflare"
import * as Maple from "@maple-dev/alchemy"
import { Effect, Layer } from "effect"
import Api, { SERVICE_NAME } from "./src/worker.ts"

export default Alchemy.Stack(
  "my-app",
  {
    providers: Layer.mergeAll(Cloudflare.providers(), Maple.providers()),
    state: Cloudflare.state(),
  },
  Effect.gen(function* () {
    const api = yield* Api

    const stack = yield* Stack
    const dir = yield* Bundle.outputDirectory({ stack: stack.name, stage: stack.stage, fqn: "api" })
    yield* Maple.SourceMaps("api-sourcemaps", {
      dir,
      service: SERVICE_NAME,
      release: process.env.GITHUB_SHA,
      matchBy: "release",
      after: api.versionId,
    })

    return { url: api.url }
  }),
)
  • fqn is the Worker's id, the first argument to Cloudflare.Worker, for a Worker declared at the top level of the stack. For a Worker inside a namespace it is the namespace path and the id joined with /.
  • service is the serviceName you passed to Telemetry.
  • matchBy: "release" is required, because Worker telemetry reports no debug ids.
  • after: api.versionId orders the upload after the Worker's build and deploy.

Deploy from CI with the API key in the environment. GitHub Actions sets GITHUB_SHA itself. --yes approves the plan, which a deploy without a terminal needs:

- run: npx alchemy deploy --stage prod --yes
  env:
    CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
    CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
    MAPLE_API_KEY: ${{ secrets.MAPLE_API_KEY }}

The resource uploads only when the maps, service, release, prefix or matchBy changed. A deploy that skips an unchanged build finds no maps on disk, logs a warning and uploads nothing. The next deploy that builds uploads them. Removing the resource deletes no maps, because errors from earlier releases still need them.

Not yet confirmed end to end

This upload mirrors the setup Maple runs on one of its own Workers. We have not yet confirmed a mapped stack from that Worker in production, so run the verify steps after your first deploy.

What has to line up: service, release and path

Worker telemetry reports no debug ids, so Maple picks a map by three values. Each has one source on the Worker and one on the upload:

ValueOn the errorOn the upload
Serviceservice.name, from serviceNameservice
Releaseservice.version, from COMMIT_SHArelease
PathThe file path in the stack frameThe JS file's path inside the bundle directory

Service and release both come from values you set, and both sides here read GITHUB_SHA. A Worker deployed without COMMIT_SHA reports no service.version and gets no mapped frames, whatever was uploaded.

Each JS file uploads under its path inside the bundle directory, such as index-D3yLFpFl.js, and Maple matches a frame whose path ends with that. On one of Maple's own Workers, production frames read file:///bundle/scheduled-D3yLFpFl.js:1874:31887, which ends with the uploaded path, so no urlPrefix is set. That is one Worker. Check yours in the issue's Raw stack, and set urlPrefix if the path there has a directory the uploaded one lacks. The matching rules are covered in more depth in the Wrangler guide.

Maps over 10 MiB: sourcemapExcludeSources

Maple refuses a map over 10 MiB, and Maple.SourceMaps skips such a map with a warning. An Effect Worker bundles many dependencies and can pass that size. Leave the embedded source files out in the Worker's props:

return {
  main: import.meta.url,
  env: { COMMIT_SHA: release },
  build: { output: { sourcemapExcludeSources: true } },
}

Frames still map to your file, function and line, but the issue page shows no code around the line. On one of Maple's own Workers this took the main chunk's map from 12.8 MB to 2.7 MB.

Do you need a Workers Observability destination?

Cloudflare can export a Worker's telemetry by itself. You create a destination, a named OTLP endpoint with its headers, and the Workers runtime sends the spans and logs it records there. That is a second, separate source from the Telemetry layer.

You wantDestination needed?
A trace per request, with your Effect spans and logsNo. Telemetry exports them from inside the Worker
Errors as issues, with source mapped stacksNo. The stack and service.version come from the SDK
Spans the runtime records itself: binding calls such as KV, R2 and Durable Objects, and outbound fetch callsYes, a traces destination
console output and Cloudflare's invocation log for each requestYes, a logs destination

So the layer alone is a complete setup. Add destinations when you want the runtime's view next to your own. Before you do:

  • Error noise. The runtime marks any non-2xx response as an error span, including a 404 from a bot.
  • Service name. Cloudflare names the service after the Worker script, not after your serviceName.
  • Billing. Cloudflare's export docs name no plan requirement, as of November 29, 2026. From December 1, 2026, the copy of logs and traces that Cloudflare stores counts toward the account's Observability usage, on Free and Paid plans. See Cloudflare's pricing page. Set persist: false on traces and logs to export without storing that copy.

Alchemy also ships its own Cloudflare.Telemetry() layer. Its source comments say it turns runtime traces on and mirrors Effect.withSpan into them. We have not tried it, alone or next to Maple's Telemetry.

We have not verified that the native export carries exception.stacktrace or lets you set service.version, and we have not verified that its spans share a trace ID with the SDK's. Treat it as an addition to the layer, not a replacement for it.

Create the destinations with Alchemy

Alchemy has a resource for this, Cloudflare.Workers.ObservabilityDestination. A destination carries one signal, so declare two. The header takes the private key from the same Ingest resource that Telemetry uses, so there is no second secret to manage:

src/destinations.ts

// src/destinations.ts
import * as Cloudflare from "@alchemy.run/cloudflare"
import * as Output from "alchemy/Output"
import { Effect, Redacted } from "effect"
import { Ingest } from "./maple.ts"

export const Destinations = Effect.gen(function* () {
  const ingest = yield* Ingest
  // The same private ingest key Telemetry binds, as the header Cloudflare sends.
  const authorization = Output.map(Output.asOutput(ingest.privateKey), (key) =>
    Redacted.make(`Bearer ${Redacted.value(key)}`),
  )

  const traces = yield* Cloudflare.Workers.ObservabilityDestination("maple-traces", {
    name: "maple-traces",
    url: "https://ingest.maple.dev/v1/traces", // EU: https://ingest.eu.maple.dev/v1/traces
    headers: { authorization },
    logpushDataset: "opentelemetry-traces",
  })
  const logs = yield* Cloudflare.Workers.ObservabilityDestination("maple-logs", {
    name: "maple-logs",
    url: "https://ingest.maple.dev/v1/logs", // EU: https://ingest.eu.maple.dev/v1/logs
    headers: { authorization },
    logpushDataset: "opentelemetry-logs",
  })

  return { traces, logs }
})
  • url is the full signal URL, ending in /v1/traces or /v1/logs.
  • logpushDataset picks the signal: opentelemetry-traces or opentelemetry-logs.
  • name and logpushDataset cannot change after creation. Changing either replaces the destination. url, headers and enabled update in place.
  • Cloudflare sends a test POST to the URL on create and on every update, and the endpoint has to answer 2xx. skipPreflightCheck: true skips the test on create only.
  • Destinations belong to the Cloudflare account. If one with the same name already exists and this stack did not create it, the deploy refuses to take it over unless you run it with --adopt.

Then reference them from the Worker's observability prop, by slug. Alchemy's field names are the Cloudflare API's in camelCase, so the optional keys are headSamplingRate and persist.

src/worker.ts

// src/worker.ts
import { Destinations } from "./destinations.ts"

const props = Effect.gen(function* () {
  if (globalThis.__ALCHEMY_RUNTIME__) return { main: import.meta.url }
  const release = yield* Config.String("GITHUB_SHA")
  const { traces, logs } = yield* Destinations
  return {
    main: import.meta.url,
    env: { COMMIT_SHA: release },
    observability: {
      enabled: true,
      traces: { enabled: true, destinations: [traces.slug] },
      logs: { enabled: true, invocationLogs: true, destinations: [logs.slug] },
    },
  }
})

Without an observability prop, Alchemy turns Workers Logs on and leaves traces off.

What Maple runs, and what it does not

Maple's own stack creates a traces and a logs destination with this resource. Its asset Workers export logs through the logs destination and keep runtime traces off, because Cloudflare marks every non-2xx response as an error span and bot 404s would fill the error list. So the logs half of this example is a pattern we run, and the traces half is not. We have not deployed the example as printed, including the header built from Ingest.privateKey, so read the first deploy's plan.

Or create them in the Cloudflare dashboard

Destinations are account-wide, so one stack should own them. If several stacks or stages deploy to the same account, or the destinations already exist, create them once in the Cloudflare dashboard under the account-level Observability → Destinations. The Wrangler guide has the fields and the common failures. Then list them in each Worker's props:

observability: {
  enabled: true,
  traces: { enabled: true, destinations: ["maple-traces"] },
  logs: { enabled: true, invocationLogs: true, destinations: ["maple-logs"] },
}

Alchemy takes a destination's slug, which Cloudflare derives from the name. Maple's destination named maple-workers-logs has that same string as its slug, so a lowercase, hyphenated name is the safe choice.

Verify and debug

  1. Deploy, then check the log for Uploaded N source map(s) for api.
  2. List the maps with GET /v2/source_maps?service=api&version=<commit>.
  3. Make the Worker fail in a way that becomes an issue, for example a handler that dies with an error and answers 500.
  4. In Explore → Traces, open the request's span. The span has an exception event, and its resource has service.version equal to the commit.
  5. Open the issue in Errors. The stack trace shows Source mapped or Partly source mapped, with your original file, function and line on each mapped frame. Raw shows the stack as the Worker sent it.

When a step fails:

SymptomCause
Skipped the source map for …: it is over 10 MiBSet build.output.sourcemapExcludeSources: true on the Worker
A skipped map that says matchBy: "release" needs a releaserelease was empty. With the props above a missing GITHUB_SHA fails the deploy earlier, on the Config.String read, so this only appears if the Worker gets its release another way
No source maps in …The Worker's build did not run in this deploy, or fqn does not name the Worker. Check that the bundle directory exists after a deploy that rebuilt the Worker
Frames stay bundledservice.version on the error differs from the uploaded release or is missing, or service.name differs from service. Compare the span's resource attributes with the GET /v2/source_maps listing
Service and release match, frames still bundledA frame's path in the Raw stack does not end with an uploaded path. Set urlPrefix to the part that is missing
No issue to look atThe error never became an issue, such as a 4xx span with no exception attached. Fail with an error so the span carries an exception event
Frames map but show no codeThe map has no sourcesContent, which is expected with sourcemapExcludeSources: true

Maple

Set it up step by step

The docs have this setup as a reference page, with every SDK option and the other resources Alchemy can manage next to the Worker.

Sources and further reading

FAQ

よくある質問

How do I trace a Cloudflare Worker written with Effect over OpenTelemetry?
Provide a telemetry layer on the Worker. With Alchemy and Maple that is Telemetry from @maple-dev/alchemy/telemetry: it records a server span for each request, attaches Effect logs and spans to it, and flushes after the response. A failure in the handler becomes an exception event with the stack trace on the span.
Does an Effect Worker need a Workers Observability destination?
Not for its own traces, logs or errors. The Telemetry layer exports those from inside the Worker straight to the ingest endpoint. A destination is still useful when you also want the spans the Workers runtime records itself, such as binding calls and outbound fetch calls, or console output.
Can Alchemy create Workers Observability destinations?
Yes. @alchemy.run/cloudflare has a Cloudflare.Workers.ObservabilityDestination resource that takes a name, the OTLP url, headers and a logpushDataset of opentelemetry-traces or opentelemetry-logs. A Worker references a destination by its slug in the observability prop, under traces.destinations or logs.destinations.
How do I upload a Cloudflare Worker's source maps with Alchemy?
Declare a Maple.SourceMaps resource in the stack. Point dir at the Worker's bundle directory from Bundle.outputDirectory, set service to the Worker's service name and release to the commit, set matchBy to release, and pass after: api.versionId so the upload runs after the Worker's build. It uploads on each deploy where the maps or the release changed.
Where does Alchemy write a Worker's source maps?
Alchemy bundles the Worker with hidden source maps into .alchemy/bundles/<stack>-<stage>-<worker id>. Each .map file sits beside its JS file and no sourceMappingURL comment ships. Bundle.outputDirectory returns that path.
How does an Alchemy Worker report its release?
Bind the commit into the Worker's env as COMMIT_SHA in the props effect, reading GITHUB_SHA at deploy time. The Effect SDK reports it as service.version. Pass the same value as release to Maple.SourceMaps, because the two must be equal for a frame to find its map.
How do I make an Alchemy Worker's source map smaller?
Set build.output.sourcemapExcludeSources to true in the Worker's props. That leaves sourcesContent out of the map and keeps the file, function and line mapping. Maple refuses a map over 10 MiB.

今日、最初のトレースを。

SDKを追加し、OTLPエクスポーターをMapleに向ければトレースが届きます。

maple.dev:OpenTelemetryの上のオブザーバビリティ