Debugging Metrics Client in Cloudflare Workers (2026)
Why Debugging a Metrics Client in Cloudflare Workers Is Different
Cloudflare Workers are ephemeral. They spin up on demand across a global edge network, execute your code, and terminate. You cannot SSH into anything. You cannot install a traditional APM agent. There is no long-running process keeping your metrics buffer alive between requests.
This means every assumption baked into traditional metrics clients breaks. Batching assumes a persistent process. Background flush intervals assume the runtime stays alive. Connection pooling assumes a stable host. None of that applies here.
When debugging metrics client issues in Cloudflare Workers, you need a different mental model. This glossary gives you one, organized by the stage of debugging where each term becomes relevant. For a full setup walkthrough before you start troubleshooting, see the end-to-end metrics example.
The terms below cover the gap between Cloudflare’s built-in platform metrics (request counts, error rates) and the custom metrics you send from third-party or self-built clients. Most guides conflate these two categories. They are distinct, and confusing them is itself a common source of debugging frustration.
Group 1: Execution Lifecycle Terms
These are the terms that explain why your metrics client loses data. Start here.
Isolate
A V8 isolate is the lightweight sandbox where your Worker code runs. Unlike containers or VMs, isolates share a single process and start in milliseconds. The critical detail for debugging: isolates can be reused across multiple requests. Module-level variables (including any metrics buffer you initialized outside your handler) persist between invocations on the same isolate. This means state can leak between requests if you’re not careful, and it also means a buffer might contain stale data from a previous request. For more on common instrumentation pitfalls, including isolate-related bugs, see the linked guide.
Execution Context (ctx)
The ctx object is passed to your Worker’s fetch handler. It provides two methods: waitUntil() and passThroughOnException(). This object is your lifeline for debugging metrics client issues in Cloudflare Workers because waitUntil is the only mechanism to keep work running after the response is sent.
There is a well-known destructuring pitfall here. If you write const { waitUntil } = ctx, the waitUntil function loses its this binding and throws an “Illegal invocation” error. Always call ctx.waitUntil() directly on the object. Practitioners on Cloudflare’s community forums confirm this is one of the two most common waitUntil mistakes (the other being the 30-second timeout).
ctx.waitUntil()
This method accepts a Promise and tells the runtime: “Don’t terminate this isolate until this Promise resolves or 30 seconds pass, whichever comes first.” It is the correct place to flush metrics.
export default {
async fetch(request, env, ctx) {
// Handle request, record metrics...
const response = new Response("OK");
ctx.waitUntil(metrics.flush()); // Flush AFTER response
return response;
}
};
The 30-second hard limit applies after the response is sent or the client disconnects. If your metrics backend is slow or unreachable, the flush will be killed at 30 seconds with no error surfaced to your code. For a deeper look at reliable flush patterns, read about waitUntil semantics for Cloudflare Workers.
Floating Promise
A floating promise is a Promise that is neither awaited, returned, nor passed to ctx.waitUntil(). It is the single most common cause of silently lost metrics in Workers.
The Workers runtime is allowed to terminate your isolate the moment the response is sent if there are no waitUntil promises pending. A floating metrics.flush() call may or may not complete, depending on timing. Real-world evidence is stark: a bug report on the Cloudflare workers-sdk showed that during testing with the Vite plugin, a Worker sent 20 messages across 4 requests and only 8 arrived when flush was a floating promise. The waitUntil path delivered 20 of 20.
Fix: Every call to metrics.flush() must be wrapped in ctx.waitUntil(). No exceptions.
Invocation Lifecycle
The sequence matters:
- Handler is called with
(request, env, ctx) - Your code runs, records metrics, builds a response
- Response is returned to the client
- Any Promises passed to
ctx.waitUntil()continue executing (up to 30 seconds) - Isolate becomes eligible for termination (or reuse)
Your metrics flush happens in step 4. If it’s not registered with waitUntil, it’s competing with step 5. Understanding this lifecycle is essential for debugging metrics client behavior in Cloudflare Workers because it explains every “sometimes it works, sometimes it doesn’t” scenario.
Group 2: Metrics Client Configuration Terms
These terms relate to how your metrics client buffers and sends data. Misconfigured settings here cause partial data loss.
Flush
Flushing means sending buffered metric data points to your metrics backend over HTTP. In a traditional server, flush can happen on a timer because the process lives indefinitely. In Workers, flush must complete before the isolate terminates. This is why flush semantics are the core concern when collecting metrics from Cloudflare Workers.
flushAt / flushInterval
These are batching controls found in most metrics and analytics SDKs. flushAt defines how many events to buffer before automatically flushing. flushInterval defines how many milliseconds to wait before flushing, regardless of buffer size.
In serverless, both should be aggressive. PostHog’s Cloudflare Workers documentation recommends setting flushAt: 1 and flushInterval: 0 to send data immediately without batching. The reasoning: batched data is sent asynchronously, and the Worker can terminate before it’s sent.
This same pattern solved a real production issue with Langfuse. A bug report described Worker memory getting clogged with duplicate copies of agent state. Setting flushAt: 1 and flushInterval: 0 on the span processor fixed it.
const client = new MetricsClient({
flushAt: 1, // Send every event immediately
flushInterval: 0, // No timer-based batching
});
For guidance on configuring flush behavior in a JavaScript metrics client, the linked article covers the tradeoffs in detail.
Buffering
Accumulating metrics in memory before sending them. Buffering is dangerous in Workers because there is no guarantee the buffer survives between invocations (isolate reuse is not guaranteed), and an oversized buffer can push you past the Worker’s memory limit.
Fix: Flush per request. Don’t accumulate across invocations. If your SDK defaults to a large buffer size, override it.
If you want to explore buffering strategies specific to edge functions, this guide on buffer and flush for serverless covers the patterns that actually work.
Counter
A monotonically increasing metric. Examples: request count, error count, cache hits. In Workers, each invocation typically increments a counter and flushes it. There is no persistent counter state across invocations unless you write to durable storage, so your metrics backend handles the aggregation.
Histogram
A distribution metric that records observations like response times or payload sizes. Each invocation records one or more observations and flushes them. Histograms are useful for debugging performance, but they generate more data per invocation than counters. When instrumenting Workers with counters and histograms, keep label cardinality low to avoid exploding your metric volume.
Bearer Token / API Token
The authentication credential your metrics client uses to send data to its backend. A surprisingly common debugging issue: the token is misconfigured, the environment variable binding is missing, or the token has the wrong scope. If your metrics silently fail with no error, check authentication first. Most metrics APIs return a 401 or 403, but if your client swallows errors (many do by default), you won’t see it.
Looking for a metrics setup designed for Workers flush semantics? Check the metrics quickstart guide to go from code to dashboard in minutes.
Group 3: Platform Observability Terms
These are Cloudflare’s built-in tools. They help you debug whether the problem is your metrics client or the Worker itself.
Workers Metrics (Built-in)
Cloudflare provides platform-level metrics by default: request count, error rate, CPU time, wall time, and subrequest count. These are aggregate, not custom. They tell you if your Worker is running and healthy, but they won’t tell you if your metrics client successfully sent data to your backend. Don’t confuse built-in Workers Metrics with the custom metrics your client is trying to send.
Invocation Status
A Worker invocation status indicates whether a Worker executed successfully in the runtime. This is distinct from HTTP status codes. A Worker can return a 200 to the client and still have an invocation failure if something went wrong after the response was sent (like a waitUntil promise throwing).
Key statuses from Cloudflare’s documentation:
- Success — executed and returned a response
- Script Threw Exception — unhandled JavaScript exception during execution
- Exceeded CPU Time Limits — hit compute resource constraints
- Exceeded Memory — hit the memory limit
- Internal Error — something broke in the Workers runtime itself
When debugging a metrics client in Cloudflare Workers, check invocation statuses first. If you see “Exceeded Memory,” your SDK’s buffer is probably too large. If you see “Script Threw Exception,” the error might be the “Illegal invocation” from destructuring ctx.
CPU Time vs. Wall Time
CPU time measures compute consumed by your code. Wall time measures total elapsed time including I/O waits (like waiting for your metrics backend to acknowledge a flush). If wall time is high but CPU time is low, your metrics client’s HTTP call to the backend is the bottleneck, not your instrumentation logic.
Head-Based Sampling
Controlled by observability.head_sampling_rate in your Worker’s config. A rate of 1.0 logs 100% of requests. A rate of 0.01 logs 1%. A rate of 0.0 logs nothing.
Misconfigured sampling is a common reason metrics “disappear” from logs. If you set head_sampling_rate: 0.01 and then wonder why you can’t find log entries for a specific request, that’s sampling working as intended, not a bug. One practitioner’s approach, shared in a Flavio Copes tutorial: keep logs at a rate of 1 (never miss an error) and traces at 0.01, since a small sample is enough to spot performance patterns.
Workers Logs
Stored structured logs, enabled via observability.enabled: true in your wrangler.jsonc. These capture console.log, console.error, and other output. They are sampled according to head_sampling_rate. Use them for post-incident analysis of metrics client failures.
wrangler tail
Real-time log streaming from production Workers. One developer building an aurora forecast site on Workers stated bluntly that “wrangler tail --format json is the single most useful debugging tool on Workers.” Dashboard error counts tell you a Worker is failing, but wrangler tail gives you per-invocation CPU time, outcomes, and the actual exception messages.
wrangler tail --format json | jq '.logs'
Filter by status, method, or search term. This is where you’ll catch the “Illegal invocation” error or see that your metrics flush promise is being terminated.
Local Tracing (Local Explorer)
New in 2026: wrangler dev and vite dev now automatically capture OpenTelemetry traces for local Worker invocations. You can inspect traces at /cdn-cgi/explorer. This is transformative for debugging metrics client issues locally because you can see exactly when your flush call starts, how long it takes, and whether it completes.
Analytics Engine
Cloudflare’s built-in time-series database for custom metrics written from Worker code. It’s SQL-queryable, high-cardinality friendly, and cheaper than exporting to external platforms for simple use cases. If you need Cloudflare-native custom metrics without a third-party client, Analytics Engine is the tool. It is distinct from third-party metrics clients.
Server-Timing Header / cfWorker Metric
As of February 2026, the Server-Timing response header includes a cfWorker metric that measures time spent executing your Worker, including subrequests. Check it in your browser’s DevTools (Network tab, select the request, look at the Timing section). This helps answer the question: “Is my slow TTFB caused by my Worker’s metrics flush or by a slow upstream dependency?”
Issues
Launched in October 2026, Issues is built-in error monitoring that requires zero SDK installation. Add one line of configuration and it detects uncaught exceptions, 5xx responses, and console.error output. If your metrics client throws and you’re not catching the error, Issues will surface it.
Group 4: Integration and Export Terms
These terms come up when your debugging leads you to rethink how metrics leave the Worker.
OpenTelemetry (OTel) Export
Workers support exporting OTel-compliant traces and logs to any OTLP endpoint: Honeycomb, Grafana Cloud, Axiom, Sentry. If your custom metrics client isn’t working, OTel export is an alternative path. The new local tracing feature also uses OTel under the hood.
Tail Worker
A Worker that receives log and event data from another Worker. Tail Workers are more reliable than waitUntil-based logging for error cases because they run as a separate invocation. If your primary Worker crashes before waitUntil completes, a Tail Worker still gets the event. Consider this architecture if you’re losing metrics from short-lived serverless handlers during error scenarios.
Logpush
Pushes Worker logs to external storage (R2, S3, BigQuery) for long-term retention. Useful for auditing whether your metrics client’s flush calls are succeeding over time, but not useful for real-time debugging.
GraphQL Analytics API
Programmatic access to Workers platform metrics. If your dashboard shows gaps, query the GraphQL API directly to determine whether the gap is in Cloudflare’s data or in your custom client’s data. GitLab’s internal runbook documents a real incident where Workers metrics disappeared entirely from their HTTP Router dashboard for over 24 hours, and direct API queries were part of the diagnosis.
Common Debugging Scenarios
| Symptom | Likely Cause | Key Term | Fix |
|---|---|---|---|
| Metrics silently missing | Floating promise | Floating Promise, waitUntil |
Wrap metrics.flush() in ctx.waitUntil() |
| “Illegal invocation” error | Destructured ctx |
Execution Context | Call ctx.waitUntil() on the object directly, don’t destructure |
| ~30% data loss | Batched flush not completing before termination | flushAt, flushInterval |
Set flushAt: 1, flushInterval: 0 |
| Memory exceeded errors | SDK buffering too much across invocations | Buffering, Isolate | Flush per request, reset buffer, lower flushAt |
| Dashboard shows zero data | Sampling rate too low | Head-Based Sampling | Set head_sampling_rate: 1 in wrangler.jsonc |
| Metrics appear intermittently | Isolate reuse with stale state | Isolate | Initialize client per-request or verify module-level state is clean |
| Slow responses since adding metrics | Flush blocking response | ctx.waitUntil(), Wall Time |
Move flush to waitUntil so it runs after the response |
| 401/403 errors in logs | Token misconfiguration | Bearer Token | Verify env binding name and token scope |
For a deeper walkthrough of each failure mode, the guide on debugging missing metrics covers ingestion failures in detail.
Platform Metrics vs. Custom Metrics Client: The Distinction That Matters
This is a point of confusion that wastes debugging time. Cloudflare’s built-in Workers Metrics (request count, error rate, CPU time) are always available and always working. They are collected by the platform, not your code. If these metrics show data but your custom dashboard is empty, the problem is your metrics client, not Cloudflare.
Custom metrics (from a third-party SDK, your own HTTP calls, or a service like Distlang Metrics) depend on your code successfully making an HTTP request to an external backend during the Worker’s lifecycle. Every term in this glossary exists because that HTTP request can fail silently in ways that don’t happen on traditional servers.
Ready to instrument? See a working setup from code to dashboard using a metrics client built for Workers flush semantics. Or compare plan features to find the right tier.
FAQ
Why does my metrics client work locally but drop data in production?
Local development environments (like wrangler dev) are more forgiving about isolate termination timing. In production, the runtime aggressively reclaims isolates after the response is sent. If your flush is a floating promise, it completes locally because the process stays alive, but fails in production because the isolate is terminated.
Can I use await metrics.flush() instead of ctx.waitUntil()?
You can, but it means the response won’t be sent to the client until the flush completes. This adds latency to every request. Using ctx.waitUntil(metrics.flush()) lets you return the response immediately and flush in the background, which is almost always what you want.
How do I know if my metrics client is actually sending data?
Use wrangler tail --format json to watch for outbound subrequests. Check the invocation status for errors. If your client logs anything to console.log or console.error, those will appear in Workers Logs (if observability.enabled is set to true). The new local tracing feature also shows outbound HTTP calls as spans.
What’s the difference between Workers Metrics and Analytics Engine?
Workers Metrics are platform-provided aggregate statistics (request count, error rate, CPU time). You don’t write code to produce them. Analytics Engine is a write-from-code time-series database where you define and push custom data points, then query them with SQL. If you need custom business metrics, Analytics Engine is the Cloudflare-native option.
Does flushAt: 1 hurt performance?
It means one HTTP request per metric event, which increases subrequest count and adds some overhead. For low-to-moderate traffic Workers, this is fine. For high-traffic Workers, consider batching within a single invocation (buffer during the request, flush once at the end via waitUntil) rather than setting flushAt to a large number and hoping the timer fires.
Why do I see “Exceeded Memory” errors after adding a metrics client?
Some SDKs buffer aggressively by default, accumulating data in module-level arrays that persist across invocations on the same isolate. Each request adds to the buffer without clearing it. Set flushAt: 1 and ensure your buffer is emptied on each flush. Don’t store metrics in module-level variables that grow unboundedly.
How does head-based sampling affect my custom metrics client?
It doesn’t directly. Head-based sampling controls which requests produce Workers Logs and traces. Your custom metrics client sends data independently via its own HTTP calls. But if you’re using Workers Logs to debug your metrics client, low sampling means you won’t see logs for most requests, which makes debugging harder.
Should I use a Tail Worker instead of waitUntil for metrics?
Tail Workers are more resilient because they run as separate invocations. If your primary Worker crashes before waitUntil completes, a Tail Worker still receives the event. The tradeoff is complexity: you need to deploy and maintain a second Worker. For most metrics use cases, ctx.waitUntil() with proper flush configuration is sufficient. Reserve Tail Workers for cases where you cannot tolerate any data loss, even during crashes.