Cloudflare Workers
Heystack uses Cloudflare's native OpenTelemetry export as the default Workers integration. Cloudflare creates the invocation tree, supplies platform-owned coverage for supported operations, and exports trace-correlated logs. The Heystack SDK adds business context to that same native tree, plus spans for the few things Cloudflare does not trace; it does not install a second exporter when the native API is available. A direct export is the fallback when native tracing is unavailable (for example Pages Functions). Exact native coverage varies by Cloudflare execution model and platform release, and the coverage table below separates what is expected from what has been verified on a live deployment.
Next.js on OpenNext should use the Next.js guide. Other frameworks on Workers are in Cloudflare frameworks; Containers, Pages Functions and Workers for Platforms are in Cloudflare platforms. This page is for Workers, Durable Objects, Workflows, Queues, cron handlers, and Agents SDK applications.
Every Workers language, one connection
Connect the Cloudflare export destination at the Worker level. Heystack accepts the native OTLP traces and logs Cloudflare emits, independently of the application's source language. This is the starting path for JavaScript, TypeScript, Python, Rust, and other languages compiled to WebAssembly. It does not require importing a JavaScript SDK into Python or Rust.
| Your app | Starting connection | Extra application detail |
|---|---|---|
| JavaScript / TypeScript Worker | Native Cloudflare export | @heystack/otel/workers business spans and identity |
| Pages Function | Direct SDK export only (see platforms) | @heystack/otel/workers with nativeTracing: "direct" |
| Python Worker | Native Cloudflare export | The platform's emitted events; standard OTLP for additional supported instrumentation |
| Rust / other Wasm Worker | Native Cloudflare export | Platform invocation and binding activity; language-level function tracing is not automatic |
| Durable Objects, Queues, Workflows, Agents | Native export on each participating Worker | Exercise each handler and verify delivered evidence |
| D1, KV, R2, Workers AI, Vectorize and service bindings | Operation evidence emitted by the calling Worker | Direct-mode JS instrumentation where listed below |
| Hyperdrive, Containers, Email, media and other connected products | Emitted Worker events and app-provided OTLP | Check coverage explicitly; arbitrary internals are not automatically traced |
Cloudflare's native export currently covers traces and logs. Use the Analytics connector for available Worker infrastructure metrics; native OTLP metrics export is not yet provided by Cloudflare. Coverage follows actual received evidence.
In direct JS mode, binding instrumentation also covers D1 batch/exec/sessions, KV metadata reads, R2 listing and multipart operations, Queue metrics, Workflow creation/lookups, rate limits, and Analytics Engine writes. Rate-limit keys and Analytics Engine datapoint payloads are never attached. See the SDK README for operation-level details.
Sources: Cloudflare languages, native export, observability, and tracing limits.
1. Create two Cloudflare destinations
In Workers Observability → Add destination, create separate destinations because Cloudflare destinations have one signal type each:
| Name | Type | OTLP endpoint |
|---|---|---|
heystack-traces | Traces | https://ingest.heystack.dev/v1/traces |
heystack-logs | Logs | https://ingest.heystack.dev/v1/logs |
For both destinations add the custom header:
Authorization: Bearer sk_live_your_key_here
Cloudflare currently exports OTLP/JSON, which Heystack accepts. Heystack also accepts OTLP/JSON and OTLP/protobuf from other SDKs and collectors.
2. Enable traces and logs explicitly
Use the exact destination names from the dashboard:
[observability.traces]
enabled = true
destinations = ["heystack-traces"]
head_sampling_rate = 1
persist = false
[observability.logs]
enabled = true
destinations = ["heystack-logs"]
head_sampling_rate = 1
persist = false
persist = false avoids paying separately to store the same events in Cloudflare when Heystack is your system of record. Remove it or set it to true if you also want the Cloudflare dashboard copy. Reduce head_sampling_rate on high-volume services after validating the integration.
Deploy and make requests through every handler you use. Delivery can take a few minutes; the destination status in Cloudflare shows the most recent successful export or error.
Native export currently requires Workers Paid or a contract plan. Cloudflare exports traces and logs, but not Worker infrastructure or custom metrics.
3. Add business spans with @heystack/otel
Install version 0.19 or newer (the native-first options below need it). In a Worker, import only from @heystack/otel/workers; never import @heystack/otel/node, which cannot run on the Workers runtime.
npm install "@heystack/otel@>=0.19.1"
Wrap the default handler:
import { instrument, withCloudflareSpan } from "@heystack/otel/workers";
const worker = {
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
const order = await withCloudflareSpan(
ctx,
"order.load",
{ "order.id": new URL(request.url).searchParams.get("id") ?? "unknown" },
async () => env.DB.prepare("SELECT * FROM orders WHERE id = ?").first(),
);
return Response.json(order);
},
};
export default instrument(worker, {
service: "orders-worker",
nativeTracing: "auto", // default: native first, direct OTLP only when unavailable
routes: ["/orders/:id", "/files/*"], // optional http.route templates
version: "1.4.2",
build: "<git-sha>",
getUser: (request) => ({
id: request.headers.get("x-user-id") ?? undefined,
session: request.headers.get("x-session-id") ?? undefined,
}),
});
In native mode:
- no
HEYSTACK_API_KEYsecret is required in the Worker; authentication lives on the Cloudflare destination; - Heystack does not re-trace what Cloudflare already spans (fetch, D1, KV, R2, Durable Object storage, Queues, rate limits, service bindings), so nothing is reported twice. It adds native child spans only for the kinds Cloudflare does not trace: Workers AI, Vectorize, Workflows and Analytics Engine, plus Hyperdrive when you wrap the database client with
wrapSqlClient. Override per kind withnativeEnrichment, for examplenativeEnrichment: { ai: false }, or force a covered kind with{ d1: true }. Itsfetchhook addstraceparentto outbound calls (see Trace context) and tags calls to a detected AI provider or configured AI gateway with a nativechat <provider>span andgen_ai.*attributes (see AI / LLM calls below); - default-export fetch, queue, scheduled, email, and generic Tail handlers are placed inside named Heystack business spans;
withCloudflareSpan(ctx, ...)is async-safe even withoutnodejs_compat;- a narrowed
ctx.tracingvalue can be passed directly towithCloudflareSpan()orwithCloudflareAgentSpan(); the SDK types follow Cloudflare's callback-scopedenterSpancontract and do not require platform spans to exposeend(); withSpan(...)also uses the native tree when an active context is available.
Route templates
Set routes to templates such as ["/users/:id", "/files/*"] (first match wins; a trailing * matches the rest) so http.route groups requests. Use routeTemplate: (req) => string | undefined to compute it per request; it wins over routes. In native mode the template is set on the Heystack request span, and on the platform request span when the runtime exposes it; otherwise Service Health groups that span with the automatic rule. With neither, Heystack templates ID-like path segments on the server.
Trace context and propagation
Cloudflare's native spans do not expose trace or span IDs, and the SDK never invents them. In native mode:
- an inbound
traceparentis recorded as a parent link on the request span; the native trace keeps Cloudflare's own trace ID, so the caller's trace is linked, not adopted; - outbound
fetchcalls carry a synthetictraceparent, recorded as a propagation link, so a downstream service that reads it can be correlated back; - Cloudflare does not propagate W3C trace context to external (non-Cloudflare) hosts on its own. Limit which hosts receive the header with
propagateTargets(exact hostnames or RegExps;[]turns it off). The default is every host except Heystack's own ingest endpoint; - Worker-to-Worker calls over service bindings are propagated by Cloudflare itself.
In direct mode the trace ID is continued from the inbound header and the outbound header uses the client span's real ID.
Native settings at a glance
| Option | Purpose |
|---|---|
nativeTracing | "auto" (default), "native" or "direct" |
tracing | Explicit Cloudflare tracer for contexts without ctx.tracing, such as Durable Objects |
routes / routeTemplate | http.route templates |
nativeEnrichment | Per-kind override of which bindings the SDK enriches on top of Cloudflare's spans |
propagateTargets | Hosts that receive traceparent on outbound fetches |
ai.gateways / ai.gatewayExport | AI gateway detection and single counting (below) |
instrumentBindings | Direct mode only: which bindings to proxy |
Wrap RPC entrypoint classes with wrapWorkerEntrypointClass(MyEntrypoint, { service: "api" }) (native mode passes RPC calls through because Cloudflare emits the RPC spans) and Hyperdrive clients with wrapSqlClient(client, { name: "HYPERDRIVE", dbSystem: "postgresql" }).
Direct mode (fallback)
Use nativeTracing: "direct" only as a compatibility fallback on a runtime without native export. Direct mode requires wrangler secret put HEYSTACK_API_KEY, and options such as instrumentBindings and sampling apply only to that fallback (LLM enrichment works on both). Do not enable direct mode and a native trace destination together: that produces duplicate traces.
Personal data and keys
Storage keys (KV, R2, Durable Object storage) are hashed before they are stored: the first segment is kept through the first : or / (for example user: or avatars/) and the rest becomes a short hash, so grouping by key family still works without exposing identifiers. Email sender and recipient addresses are hashed on the local part and keep the domain. SQL statements are stored with literal values replaced by ?, and rate-limit keys and Analytics Engine payloads are never attached. This applies to what Cloudflare sends as well as to SDK spans.
Privacy defaults in direct mode
Direct-mode request and outbound spans record URLs with secrets removed (?key=, ?apikey=, ?token=, ?code=, #access_token=, userinfo, … — see Privacy); add names with redactQueryParams. The visitor's IP (client.address) is off unless captureClientIp: true, and geo is country-only unless captureGeo: "full". Under native tracing, request and subrequest spans are recorded by Cloudflare itself, so these SDK options apply to the spans Heystack's SDK creates (business spans, gen_ai spans).
With sampling: { rate }, a request carrying a sampled traceparent header is always recorded so browser→Worker traces stay whole. On a public endpoint anyone can send that header; set trustInboundSampling: false to let your own rate decide for inbound traces too (the trace id is still continued, so correlation keeps working).
AI / LLM calls (gen_ai)
Calls your Worker makes to an LLM API are recognised automatically and tagged with the OpenTelemetry gen_ai.* conventions — provider, model, token usage, finish reason — with no extra code. Direct hosts detected: OpenAI (api.openai.com), Anthropic (api.anthropic.com), Mistral (api.mistral.ai), Google (generativelanguage.googleapis.com) and Cloudflare AI Gateway. Under native tracing each call becomes a native span named <operation> <provider> (for example chat mistral); under the direct exporter the same attributes land on the outbound client span.
Calling providers through an AI gateway of your own (for example gateway.example.com/<provider>/…)? Declare the gateway so the provider can be read off the URL:
export default instrument(worker, {
service: "my-api",
ai: {
gateways: [{ hostSuffix: "gateway.example.com", pathPattern: "/:provider" }],
},
});
The :provider segment accepts openai, anthropic, google, gemini (→ google), mistral, cloudflare and workers-ai (→ cloudflare). Gateway-resolved calls also carry heystack.ai.gateway=<host>.
Cloudflare AI Gateway. Calls to gateway.ai.cloudflare.com are recognised as provider cloudflare. The gateway can export its own OpenTelemetry spans for the same call; if you have that export configured, set ai: { gatewayExport: true } and the SDK's span is marked delegated so the call is counted once, by the gateway. The trade-off: with gatewayExport: true an AI call is not counted at all if the gateway's own export is not working, so leave it off (the default) unless you have confirmed the gateway export is delivering. The cf-aig-otel-* headers are sent either way.
Streaming responses (text/event-stream) are covered: the stream is split, your handler receives it untouched, and Heystack reads its copy only for the usage/model/id metadata each provider emits (Mistral and OpenAI in the last chunk — for OpenAI send stream_options: { include_usage: true }; Anthropic in message_start/message_delta; Google in usageMetadata). No prompt or completion text is ever read from a stream, and the span closes when the stream does.
Calls the hook cannot see. Under native tracing env.AI.run is recorded automatically as an ai_run span; do not wrap it by hand. If you add a manual span around it (for example to capture usage), set nativeEnrichment: { ai: false } so the call is counted once. For an SDK that does not use fetch, or for direct mode without instrumentBindings, use a manual span with the two helpers exported from @heystack/otel/workers:
import { withSpan, genAiRequestAttrs, genAiResponseAttrs } from "@heystack/otel/workers";
const model = "@cf/meta/llama-3.1-8b-instruct-fast";
const result = await withSpan(
"chat cloudflare",
{ ...genAiRequestAttrs("cloudflare", { model, max_tokens: 256 }), "gen_ai.operation.name": "chat" },
async (span) => {
const out = await env.AI.run(model, { prompt, max_tokens: 256 });
span.setAttributes(genAiResponseAttrs("cloudflare", out)); // maps usage.prompt_tokens / completion_tokens
return out;
},
);
Prompt and completion text are never captured unless you opt in with ai.captureContent: true (JSON responses only; provide ai.redact to scrub). Under native tracing the automatic hook relies on the request context surviving awaits, which needs the nodejs_compat flag; without it, use the manual withCloudflareSpan(ctx, …) form above (and, for env.AI.run, set nativeEnrichment: { ai: false } when you wrap it yourself).
Direct export performance and retries
Heystack remains outside your application's request path. In direct mode, instrument() ends and serializes telemetry locally, starts the export, and passes its drain promise to ctx.waitUntil. Handler ctx.waitUntil(work) calls retain their host behavior and get a telemetry drain after work settles, so spans created after an await in background work are included. The response does not wait for the export network request or Heystack storage, although ending spans and serializing the payload add a small amount of synchronous work. This is non-blocking network delivery, not zero overhead.
The direct exporter retries once after a network error, HTTP 429, or HTTP 5xx. A Retry-After header in seconds on a 429 is honored within the same 2-second total retry-wait cap. Other 4xx responses are not retried. There is no persistent buffer: a payload is dropped after the retry fails.
The /workers entry has no node:* imports and loads without nodejs_compat. Native mode does not need the flag. Direct mode should enable it (compatibility dates of 2026-08-04 or later enable it by default) for AsyncLocalStorage and reliable parent/child context across await; without it, export suppression and binding-parent fallback still work, but outbound-fetch and manual withSpan parenting after an await is best-effort.
Direct binding opt-in
instrumentBindings defaults to false and applies only to direct mode. Set it to true to auto-detect all supported bindings, or pass env keys to select only those bindings:
export default instrument(worker, {
service: "orders-worker",
nativeTracing: "direct",
instrumentBindings: ["DB", "COUNTER", "ORDERS_WORKFLOW"],
});
Detection is conservative and unrecognized bindings pass through unchanged:
| Binding | Detection | Covered operations |
|---|---|---|
| D1 | prepare | statement all, first, run, raw |
| R2 | get + put + head | get, put, head, delete |
| KV | get + put + list | get, put, list, delete |
| Vectorize | query + upsert | query, upsert, insert, deleteByIds, getByIds |
| Workers AI | run | inference metadata and available token usage |
| Queue producer | send + sendBatch | send operations and batch count |
| Durable Object namespace | idFromName + get + newUniqueId | synchronous get / getByName return wrapped stubs without spans; stub fetch and dynamically exposed callable RPC methods get CLIENT spans while platform/reserved members remain untouched |
| Workflow binding | create + createBatch + get | binding create, createBatch, get; returned instance pause, resume, terminate, restart, status, sendEvent |
| Service binding | fetch | request plus W3C trace-context propagation |
Native and direct coverage
Cloudflare's native tree is authoritative where ctx.tracing is available. It commonly includes the invocation, handler entrypoint, outbound subrequests, and supported binding operations, but the SDK does not claim that every direct-mode operation has a native equivalent. Heystack retains the platform context Cloudflare sends, including execution model, outcome, CPU/wall time, location, binding, and operation fields.
Cloudflare's custom span API is callback-scoped: it does not expose manual parent wiring, span IDs, or arbitrary span lifetime management. withCloudflareSpan follows those rules and maps OTel-style errors/events into native span attributes where the platform API has no equivalent yet.
| Execution path | Native mode | Direct mode |
|---|---|---|
Default fetch | Cloudflare invocation tree plus Heystack business/identity attributes | Request, outbound fetch, streaming completion, errors, and trace propagation |
Default queue | Cloudflare platform coverage plus a Heystack batch business span | One real batch span; explicit message.ack() / message.retry() child spans |
Default scheduled | Cloudflare platform coverage plus a Heystack business span | Invocation span with cron metadata |
Default email | Cloudflare platform coverage plus a Heystack business span | Sender/recipient domains and envelope size only, never addresses or content |
Generic default tail | Cloudflare platform coverage plus a Heystack business span | Event count only, never Tail payload contents |
| Bindings/outbound calls | Platform-owned for operations Cloudflare supports | Outbound fetch automatically; binding proxies only with instrumentBindings |
| Named Durable Object/Workflow classes | Platform-owned where Cloudflare exposes it | Apply the class wrappers below |
Signal coverage
The table lists what each mode captures. Native entries are marked as expected until they have been verified against a live Cloudflare deployment.
| Signal | Native mode | Direct mode | Notes |
|---|---|---|---|
| Worker fetch handler | Cloudflare (expected; not yet verified live) | Heystack SDK | |
| Cron (scheduled) handler | Heystack SDK | Heystack SDK | Native mode: the SDK adds its own span; Cloudflare's scheduled span shape is not in the documented list. |
| Queue consumer handler | Cloudflare (expected; not yet verified live) | Heystack SDK | |
| Email handler | Cloudflare (expected; not yet verified live) | Heystack SDK | Addresses are hashed; direct mode records only domains. |
| Tail handler | Heystack SDK | Heystack SDK | |
| Durable Object alarm handler | Not covered | Heystack SDK | Class wrappers need the SDK provider; native mode has no alarm handler span. |
| Durable Object WebSocket handlers | Not covered | Heystack SDK | |
| WorkerEntrypoint RPC method | Cloudflare (expected; not yet verified live) | Heystack SDK | Native mode: the SDK adds no RPC span (Cloudflare owns jsrpc). Span name not yet verified against a live deployment. |
| Workflow run and steps | Not covered | Heystack SDK | Via wrapWorkflowEntrypointClass; no native workflow handler span is documented. |
| D1 | Cloudflare (expected; not yet verified live) | Heystack SDK | |
| KV | Cloudflare (expected; not yet verified live) | Heystack SDK | Keys are hashed. |
| R2 | Cloudflare (expected; not yet verified live) | Heystack SDK | |
| Durable Object storage (KV API) | Cloudflare (expected; not yet verified live) | Heystack SDK | Native span name durable_object_storage_get is not yet verified against a live deployment. |
| Durable Object storage (SQL API) | Cloudflare (expected; not yet verified live) | Heystack SDK | |
| Durable Object alarms API | Cloudflare (expected; not yet verified live) | Heystack SDK | |
| Queue producer | Cloudflare (expected; not yet verified live) | Heystack SDK | |
| Workers AI | Heystack SDK | Heystack SDK | Native mode: SDK enrichment (Cloudflare does not span it). |
| Vectorize | Heystack SDK | Heystack SDK | Native mode: SDK enrichment. |
| Workflows binding | Heystack SDK | Heystack SDK | Native mode: SDK enrichment. |
| Failing binding call | Heystack SDK | Heystack SDK | A throwing binding marks its span as an error and the error still reaches the app. |
| Hyperdrive (SQL client) | Heystack SDK | Heystack SDK | Needs wrapSqlClient around the database client. |
| Analytics Engine | Heystack SDK | Heystack SDK | Native mode: SDK enrichment. |
| Rate limit | Cloudflare (expected; not yet verified live) | Heystack SDK | |
| Service binding | Cloudflare (expected; not yet verified live) | Heystack SDK | Native mode: Cloudflare propagates context between Workers itself. Span name not yet verified against a live deployment. |
| LLM provider call (OpenAI, Anthropic, ...) | Heystack SDK | Heystack SDK | |
| Cloudflare AI Gateway call | Heystack SDK | Heystack SDK | Counted once; pass ai.gatewayExport to defer to the gateway's own export. |
| Inbound traceparent | Heystack SDK | Heystack SDK | Native mode records a parent link; it cannot adopt the caller's trace id. |
| Outbound traceparent | Heystack SDK | Heystack SDK | Native mode sends a synthetic id linked to the request; Cloudflare spans carry no ids. |
| Pages Functions | Direct mode only | Heystack SDK | Use the SDK's direct export in Pages Functions. |
For queue consumers, direct mode passes the original batch to your handler once. It records explicit per-message ack() and retry() decisions while preserving their synchronous void contract, but deliberately does not create a fake per-message processing span or split the batch, because that would change Cloudflare's acknowledgement and retry semantics.
For fetch handlers, direct mode preserves streaming backpressure and finalizes the request span once on clean completion, source error, consumer cancellation, or request abort. A status-0 Response.error() is returned unchanged and marked as an error because it cannot be reconstructed or carry an injected response header.
Named Durable Objects and Workflows
Keep native trace export enabled on every Worker involved, including queue consumers, Workflow classes, Durable Object classes, and Tail Workers. In native mode, rely on Cloudflare for platform coverage and use its custom tracing API for additional class-level business work.
In direct mode, instrument() wraps only the default export. Initialize the provider inside each named class isolate, then wrap the named export under the binding name from wrangler.toml:
import { DurableObject } from "cloudflare:workers";
import {
initHeystackWorkers,
wrapDurableObjectClass,
} from "@heystack/otel/workers";
class CounterImpl extends DurableObject<Env> {
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
initHeystackWorkers({ apiKey: env.HEYSTACK_API_KEY, service: "counter-do" });
}
async fetch(): Promise<Response> {
const value = (await this.ctx.storage.get<number>("value")) ?? 0;
return Response.json({ value });
}
async increment(): Promise<number> {
const value = ((await this.ctx.storage.get<number>("value")) ?? 0) + 1;
await this.ctx.storage.put("value", value);
return value;
}
}
export const Counter = wrapDurableObjectClass(CounterImpl);
wrapDurableObjectClass() covers fetch, alarm, prototype RPC methods, and state.storage.get / put / delete / list, and flushes each root operation with the Durable Object state's waitUntil. Storage calls made through a transaction callback are not wrapped. Instance arrow-function RPC methods are not discoverable on the prototype and are skipped.
import { WorkflowEntrypoint, type WorkflowEvent, type WorkflowStep } from "cloudflare:workers";
import {
initHeystackWorkers,
wrapWorkflowEntrypointClass,
} from "@heystack/otel/workers";
type Params = { orderId: string };
class OrderWorkflowImpl extends WorkflowEntrypoint<Env, Params> {
constructor(ctx: ExecutionContext, env: Env) {
super(ctx, env);
initHeystackWorkers({ apiKey: env.HEYSTACK_API_KEY, service: "order-workflow" });
}
async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
return step.do("load-order", async () => ({ orderId: event.payload.orderId }));
}
}
export const OrderWorkflow = wrapWorkflowEntrypointClass(OrderWorkflowImpl);
wrapWorkflowEntrypointClass() covers run() and the callback form step.do(name, fn). Run spans retain the real Workflow name, instance ID, event timestamp, and optional cron schedule metadata, never payload content. It emits short marker spans for sleep, sleepUntil, waitForEvent, and, when the runtime exposes it, waitForName rather than holding a span open while the workflow sleeps, and hands each marker to the entrypoint state's waitUntil before suspension. Engine retries appear as run replays; the wrapper does not invent a retry count.
Advanced manual initialization
Prefer instrument(). If a framework forces you to call initHeystackWorkers() directly, use wrapExecutionContext(ctx) and route at least one waitUntil call through the wrapped context; constructing the wrapper alone does not schedule a drain:
import {
initHeystackWorkers,
wrapExecutionContext,
} from "@heystack/otel/workers";
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
initHeystackWorkers({ apiKey: env.HEYSTACK_API_KEY, service: "manual-worker" });
const tracedCtx = wrapExecutionContext(ctx);
try {
return await handle(request, env, tracedCtx);
} finally {
tracedCtx.waitUntil(Promise.resolve());
}
},
};
The wrapper registers the original background promise unchanged and schedules its telemetry drain after that promise settles. It also preserves the input's ExecutionContext<Props> type, including typed ctx.props. The explicit fallback after your spans end is:
import { flushHeystack } from "@heystack/otel/workers";
ctx.waitUntil(flushHeystack());
If neither instrument(), an explicit/OpenNext waitUntil handoff, nor a manual flush is observed, the SDK warns once per isolate. There is no persistent queue behind that warning, so delivery can be lost at isolate teardown.
The wrapped context forwards props, cache, tracing, and future context properties to the original host object. Direct export is bounded to 512 concurrent requests; excess exports fail before starting network work and increment the exporter's droppedPending counter.
Cloudflare Agents SDK
The Agents SDK emits structured events for RPC, state, message/tool, scheduling, workflow, MCP, lifecycle, email, fiber, and recovery operations. Heystack can retain all of them as trace-correlated native logs:
import { Agent } from "agents";
import { createCloudflareAgentsObservability } from "@heystack/otel/workers/agents";
const agentObservability = createCloudflareAgentsObservability({
attributes: { environment: "production" },
});
export class SupportAgent extends Agent<Env> {
override observability = agentObservability;
}
Tokens, authorization, cookies, prompts, completions, content, and message fields are redacted by default. Error events are emitted at error severity. Safe scalar metadata is also added to the active span.
For production diagnostics channels, attach a Tail Worker and use createCloudflareAgentsTailHandler(). This preserves events even when no subscriber runs in the Agent and keeps the hot Agent path free of export requests:
import { createCloudflareAgentsTailHandler } from "@heystack/otel/workers/agents";
export default createCloudflareAgentsTailHandler();
Enable native logs on the Tail Worker and point them at heystack-logs.
Worker metrics
Cloudflare does not export Worker metrics over OTLP yet. Heystack fills that gap with an optional GraphQL Analytics connector:
- Create a Cloudflare API token with only Account Analytics Read.
- In Heystack, open the app's Settings › Cloudflare.
- Enter the 32-character account ID, an optional script name, an optional dispatch namespace (Workers for Platforms only), and the token. The token is write-only: it is never shown again, and replacing the connection needs a new token.
- Click Sync now to validate it.
The connector imports Workers request, error, subrequest, and CPU p50/p99 series, plus the account-level datasets listed below, every five minutes. Heystack normally makes one Cloudflare request per account, using the token of the oldest enabled connector in each (organization, account, dispatch namespace) group, so connectors on the same account share a pull. Each script is mapped to an app by matching the app's service name first, then a connector pinned to that script name, then the single whole-account connector; scripts that match none are dropped. Windows are half-open and lag five minutes behind real time, so each minute is imported exactly once. For Workers for Platforms, set the Dispatch namespace field in Settings › Cloudflare (or dispatch_namespace on PUT /api/apps/:id/cloudflare-connector; 1 to 63 letters, digits, _ or -). Tokens are AES-256-GCM encrypted in D1 and never returned by the API. Heystack also derives RED request/error/latency metrics directly from traces.
Connector datasets. Every dataset below was checked field by field against Cloudflare's live GraphQL schema (31 October 2026) and is grouped by minute. The metric names are what you see in Explore › Metrics:
| Cloudflare product | Metrics | Per |
|---|---|---|
| Workers | cloudflare.workers.requests, .errors, .subrequests, .cpu_time (p50/p99, ms) | script |
| Queues | cloudflare.queues.operations, .lag_ms, .retries, .dlq (dead-lettered messages), .backlog and .backlog_bytes (messages waiting), .consumer_concurrency | queue ID |
| Durable Objects | cloudflare.durable_objects.requests, .errors, .wall_time_ms (p50/p99), .rows_read, .rows_written, .storage_read_units, .storage_write_units, .storage_deletes, .websocket_messages_in, .websocket_messages_out, .active_websockets, .exceeded_cpu_errors, .exceeded_memory_errors | namespace |
| D1 | cloudflare.d1.read_queries, .write_queries, .rows_read, .rows_written, .query_batch_time_ms (p50/p95) | database ID |
| KV | cloudflare.kv.operations, .errors, .latency_ms (p50/p99) | namespace ID and operation |
| R2 | cloudflare.r2.operations, .errors | bucket and operation |
| Workflows | cloudflare.workflows.events, .retries | workflow and event type |
| Hyperdrive | cloudflare.hyperdrive.queries, .query_latency_ms, .connection_latency_ms | config ID and cache status |
| Workers AI | cloudflare.workers_ai.requests, .neurons, .input_tokens, .output_tokens | model |
| AI Gateway | cloudflare.ai_gateway.requests, .cached_requests, .errors, .tokens_in, .tokens_out, .cost (USD, as Cloudflare estimates it) | gateway, provider and model |
Each pull asks for all of them in one request. If Cloudflare refuses some of them (for example a product your plan does not include), Heystack asks for each dataset separately, keeps what Cloudflare answered, and records the refused names on the connector, shown under Technical detail in Settings › Cloudflare. If Cloudflare refuses even the Workers dataset on its own, the token or account is wrong, so the pull stops there. A pull never makes more than 32 Cloudflare requests. Workers data is per script; every other dataset is account-level, so it is pulled once per account (by the whole-account group, else the oldest namespace group) and attributed to the account's whole-account connector app, or to the oldest connector's app when every connector is pinned to a script. Each pull reads half-open time windows that end about five minutes in the past, because Cloudflare's analytics lag behind real time; the newest few minutes therefore appear later, and a window is never counted twice.
Where it shows. In Explore › Workers, Queues shows each queue's latest backlog ("Waiting"), delay, retries and dead letters as Cloudflare reports them, next to the queues your traces show (the two are listed separately because Cloudflare names a queue by ID and your traces by name). Cloudflare usage shows the other products above, one table per product. Figures Cloudflare did not report in the range read Unknown, never 0. The Environment filter narrows what your traces show; Cloudflare's figures cover the whole account, whatever environment you pick. Durable Object alarm errors and WebSocket activity per object still come only from traces, because Cloudflare reports Durable Objects per namespace.
What Heystack can see. Settings › Cloudflare has a Check coverage button. It runs only when you press it, never on page load or on a timer, because it reads analytics. It lists which request types and connected services have actually shown up, as Seen or Not seen yet, plus any known blind spots. "Not seen yet" is the absence of evidence, not a verdict. If there was too much activity to list every blind spot, the page says the list may be incomplete.
Validation checklist
- Cloudflare destinations show a recent successful delivery.
- A request trace contains the invocation plus supported platform operations and Heystack business spans as applicable.
- A
console.loginside a business span is correlated with that trace. - Queue, cron, email, generic Tail, Durable Object, Workflow, and Agents paths appear after exercising each deployed handler.
- Failure outcomes such as exceptions or CPU limits appear as errors with the Cloudflare outcome and runtime fields.
- Explore › Metrics contains derived RED metrics and, when connected,
cloudflare.workers.*metrics; for the account-level products you use, Explore › Workers › Cloudflare usage shows figures after the next pull.
Current platform limits
- Native export is still marked beta and available on paid plans.
- Native coverage in the table above is expected from Cloudflare's documentation and is confirmed only when the live-run record shows it. Treat "expected" rows as unconfirmed.
- Pages Functions have no native export; use direct mode.
- Cloudflare does not export metrics through OTLP.
- Custom spans cannot expose their span context, manually choose a parent, or be ended outside their callback.
- Tail Workers are the recommended production transport for Agents diagnostics channels.