How to Instrument Cloudflare Workers Serverless Metrics 2026


Why Serverless Metrics Require Different Thinking

If you’ve monitored a Node.js server before, you probably installed an agent, let it hook into the runtime, and scraped metrics on a schedule. None of that works on Cloudflare Workers.

Workers execute inside V8 isolates distributed across Cloudflare’s global network of 330+ cities. There’s no persistent process to attach an agent to. There’s no server to SSH into. Each invocation spins up, handles a request, and can terminate immediately after. Standard OpenTelemetry Node.js SDKs (like @opentelemetry/sdk-trace-node) assume a long-running process and will fail or behave unpredictably in this environment.

This means monitoring must happen at the application layer. You instrument your code directly, record metrics during the request, and push them to an external service before the isolate shuts down. That’s the core pattern for instrumenting Cloudflare Workers with serverless metrics using a JavaScript client: record, buffer, flush.

Get started quickly: follow the metrics quickstart guide to go from zero to a working dashboard in minutes.

The rest of this guide defines every term you’ll encounter and explains why each one matters in the Workers context specifically.

Core Metric Types

Understanding metric types is the foundation. Each type answers a different question about your Worker’s behavior, and choosing the wrong one in a serverless context creates problems.

Counter

A counter represents a cumulative total that can only go up or reset to zero. In Workers, counters track things like total request count, error count, and cache hit count. They’re the most natural fit for serverless because each invocation simply increments a value, and the backend aggregates totals across all isolates.

Delta Counter

A delta counter reports the change since the last flush rather than a cumulative total. This is particularly useful in serverless environments because there’s no persistent process maintaining a running sum. Each Worker invocation reports its own deltas, and the metrics backend reconstructs the full picture. Most JavaScript metrics clients designed for serverless use delta temporality by default.

Histogram

A histogram collects individual observations and groups them into configurable buckets. The classic use case is request latency: instead of knowing only the average, you see the full distribution (p50, p95, p99). Histograms are powerful but expensive. A histogram with 10 buckets multiplied by 5 label dimensions produces 50 time series for a single metric. Plan your buckets carefully.

For a deeper walkthrough, see how to instrument counters and histograms in JavaScript.

Gauge

A gauge represents a single value that can go up and down, like memory usage or active connections. Here’s the problem: gauges assume a persistent process that holds state between measurements. Workers don’t have that. An isolate can’t meaningfully report “current active connections” because it only sees its own request. Avoid gauges in Workers unless you’re reporting a point-in-time snapshot (like the size of a response body). Prefer counters and histograms for almost everything.

Metric Set

A metric set is a logical grouping of related metrics that share a common purpose. Think of it as a namespace: your “api-worker” metric set might contain a request counter, an error counter, and a latency histogram. Grouping metrics this way keeps your instrumentation organized and makes dashboards easier to build.

Instrumentation Fundamentals

What “Instrumentation” Means in Workers

Instrumentation is the act of adding measurement code to your application. In a traditional server, that might mean installing a library that auto-patches HTTP modules. In Workers, it means explicitly calling methods on a metrics client within your fetch handler.

The pattern is straightforward:

  1. Record metrics during request handling (increment counters, observe latencies)
  2. Buffer those recordings in memory
  3. Flush the buffer to an external metrics API before the isolate terminates

This is code-level instrumentation, not agent-based. You control exactly what gets measured and when it gets sent.

JavaScript Metrics Client

A JavaScript metrics client is a lightweight library that handles the record-buffer-flush cycle. The best ones for serverless are small (some are under 200 lines with zero runtime dependencies), use HTTP-based push rather than pull, and are designed around the waitUntil() lifecycle.

The key properties to look for: delta temporality support, configurable flush behavior, and compatibility with the Workers runtime (no Node.js-specific APIs).

API-First Metrics

An API-first approach means the metrics backend exposes an HTTP endpoint that accepts metric payloads directly. There’s no collector to deploy, no pipeline to configure, and no time-series database to manage. Your JavaScript client sends a POST request with metric data, authenticates with a bearer token, and that’s it.

This model fits serverless architecture and edge observability perfectly because it eliminates infrastructure dependencies that don’t exist in the Workers world anyway.

Bearer Token Authentication

Most metrics APIs authenticate clients using a bearer token in the Authorization header. For Workers, a single long-lived API token per project is the simplest approach. Store it as an environment variable (a Worker secret), and the client includes it with every flush request. No key rotation complexity, no OAuth flows, no multi-token management for small projects.

The Serverless Lifecycle and Flush Mechanics

This section covers the concepts that cause the most confusion and the most production bugs. Getting the flush lifecycle wrong means lost data, and practitioners on forums and GitHub issues confirm this is the single biggest source of instrumentation failures in Workers.

V8 Isolate

A V8 isolate is the lightweight execution environment that runs your Worker code. Unlike a container or a VM, an isolate shares the V8 engine with other isolates on the same machine but has its own memory space. Isolates start fast (often under 5 milliseconds) and terminate quickly. This speed is what makes Workers performant at the edge, but it’s also why you can’t rely on background processes or long-running connections for metrics delivery.

ctx.waitUntil()

This is the most important API for anyone instrumenting Cloudflare Workers with serverless metrics using a JavaScript client. The ctx.waitUntil() method accepts a Promise and tells the runtime: “don’t shut down the isolate until this Promise resolves, even after the response has been sent to the client.”

The critical detail: waitUntil() extends execution for up to 30 seconds after the response, not 30 seconds of guaranteed compute. If your flush takes 2 seconds, the isolate can terminate after those 2 seconds. If something goes wrong and the Promise never resolves, the runtime kills it at the 30-second mark.

For a detailed examination of the edge cases, read about waitUntil semantics for Workers instrumentation.

Framework-Specific waitUntil Access

How you access waitUntil() depends on your framework:

Framework Access Pattern
Raw Workers ctx.waitUntil(promise)
Hono c.executionCtx.waitUntil(promise)
SvelteKit platform.ctx.waitUntil(promise)
Astro 5 Astro.locals.runtime.ctx.waitUntil(promise)

Getting the access pattern wrong means your flush call runs synchronously (blocking the response) or doesn’t run at all.

Flush

Flushing is the act of sending buffered metrics from the client to the remote API. In a long-running server, you might flush every 10 or 60 seconds on an interval. In Workers, you flush once per request, inside waitUntil(), after the response has been returned.

PostHog’s Cloudflare integration documentation makes this point explicitly: they recommend setting flushAt to 1 and flushInterval to 0 to send data without batching, because batched data sent asynchronously can be lost when the Worker terminates before delivery completes.

The flush-after-response pattern is the single most common use of waitUntil() in instrumented Workers. A deeper guide on buffering and flush strategies for edge code covers the tradeoffs in detail.

The Flush Rejection Bug

This is a real production pitfall. A well-documented Sentry GitHub issue (#21950) showed that if client.flush() rejects inside waitUntil(), the entire Worker invocation is marked as failed. The fix: always wrap your flush call in .catch().

ctx.waitUntil(
  metricsClient.flush().catch((err) => {
    console.error('Metrics flush failed:', err);
  })
);

This five-line pattern prevents your observability code from taking down the application it’s supposed to be observing.

Buffering Strategies

There are two main approaches to buffering metrics in Workers:

Per-request flush: Buffer metrics during a single request, flush at the end. Simple, reliable, slightly higher overhead per request. Practitioners on Reddit report this is the safer default because Workers may reuse global state across requests on the same isolate in unpredictable ways.

Batched flush: Accumulate metrics across multiple requests and flush periodically or when the buffer reaches a size threshold. Lower overhead per request but riskier, because there’s no guarantee the isolate survives long enough between flushes. Data loss is more likely.

For most Workers, per-request flushing is the right default. The overhead of one extra HTTP call per request is usually negligible compared to the risk of losing an entire batch. See configuring buffering and flush behavior for implementation specifics.

Per-Request vs. Global Client Instantiation

Should you create a new metrics client instance for every request, or reuse a global singleton? The answer leans toward per-request instantiation in Workers. While isolates can reuse globals across requests, the shutdown and flush lifecycle makes this dangerous. A global client might hold buffered metrics from a previous request that never got flushed. Per-request creation keeps the lifecycle clean: one request, one client, one flush.

What to Measure

Knowing what to instrument matters as much as knowing how. Here are the essential metrics for any Worker in production.

CPU Time vs. Wall Time

This is the most confused distinction in Workers monitoring.

CPU time measures how long the V8 engine spent actually executing your JavaScript. It excludes time spent waiting for I/O (fetch calls, KV reads, Durable Object requests). On the Workers Free plan, you get 10ms of CPU time per invocation; on Paid, you get up to 30 seconds (or more with certain configurations).

Wall time measures the total elapsed time from the start of the invocation to the end, including all I/O waits. A Worker with 5ms of CPU time but 200ms of wall time is spending 195ms waiting on external calls.

Track both. CPU time tells you about code efficiency. Wall time tells you about the user experience. A spike in wall time with flat CPU time means a downstream dependency is slow, not your code.

The Minimum Viable Metrics Set

At a minimum, every production Worker should track:

  • Request count: Total invocations. The baseline for everything else.
  • Error rate: Errors divided by total requests. Alert on this first.
  • CPU time: Per-invocation CPU consumption. Catches runaway code and plan limit risks.
  • Latency distribution (p50, p95, p99): A histogram of response times. Averages hide tail latency.
  • Subrequest count: How many fetch() calls each invocation makes. Workers have subrequest limits (50 on Free, 1000 on Paid), and hitting them silently breaks functionality.

For a broader treatment of essential metrics, the metrics for Workers developer glossary covers additional options.

Labels, Cardinality, and Schema Design

Labels (sometimes called tags) are key-value pairs attached to metric data points. They’re what turn a single “request_count” metric into something queryable, like “request_count where method=GET and route=/api/users and status=200.”

They’re also where cardinality problems start.

What Cardinality Means

Cardinality is the total number of unique time series generated by a metric. It’s calculated by multiplying the number of unique values for each label:

total series = unique(label1) × unique(label2) × unique(labelN)

A request counter with labels for HTTP method (4 values), status code bucket (5 values), and route pattern (10 values) produces 4 × 5 × 10 = 200 time series. Manageable. But add a user ID label with 50,000 unique values, and you’re at 10 million time series. That’s a cardinality explosion.

The Golden Rule

Never use unbounded values as metric labels. Request IDs, user IDs, full URL paths with query parameters, session tokens: none of these belong in labels. If you need per-user data, use traces or logs.

Good labels for Workers:

  • method: GET, POST, PUT, DELETE (bounded, small set)
  • status_bucket: 2xx, 3xx, 4xx, 5xx (bounded, 4 values)
  • route: /api/users, /api/orders (bounded, known set)
  • colo: The Cloudflare data center that handled the request (bounded by number of PoPs)

Bad labels: request_id, user_id, url (with query strings), timestamp. Read more on label naming and low-cardinality strategies.

Metric Schema Design

A metric schema is the structure you define upfront: which metrics exist, what labels they carry, and what types they use. Designing this before writing code saves you from expensive refactoring later. Group related metrics into metric sets, keep label sets consistent across metrics in the same set, and document what each label value represents.

For serverless applications specifically, the metric schema design guide walks through practical patterns.

Monitoring Approaches Compared

There are several ways to get observability data out of Cloudflare Workers. Each involves tradeoffs around control, effort, and cost.

Cloudflare Analytics Engine

Cloudflare’s native solution for custom analytics. It’s built into the Workers platform, supports unlimited cardinality (unlike Prometheus-style systems), and is included on the Workers Paid plan with 10 million writes per month free. You write data points directly from your Worker using an AnalyticsEngine binding.

The constraints matter: you’re limited to 25 data points per Worker invocation, 20 numeric fields per data point, a single “index” field for partitioning, and a maximum retention of 3 months. There are no JOINs in the SQL API. Teams needing richer custom metrics, longer retention, or more flexible querying will outgrow it.

OpenTelemetry Wrappers

OpenTelemetry is the industry standard for telemetry, and there are lightweight wrappers built specifically for Workers (since the standard Node.js OTel SDK doesn’t work here). These wrappers typically weigh around 200 lines, carry zero runtime dependencies, and export metrics and traces over OTLP/HTTP with delta temporality.

The upside: compatibility with the broader OTel ecosystem. The downside: more configuration, more concepts to understand, and overkill if all you need are counters and histograms.

Cloudflare Native Observability (Workers Logs and Traces)

As of 2025, Cloudflare Workers can export traces and logs over OTLP to any endpoint without installing an SDK. The runtime records spans automatically. This is zero-code observability, great for getting baseline visibility without changing your application. The limitation: you can’t add custom business metrics (like “orders placed” or “feature flag evaluations”) through this channel. It’s platform telemetry, not application telemetry.

Lightweight JavaScript Metrics Clients

This is the approach that gives you the most control with the least infrastructure. A small JavaScript client records counters and histograms during request handling, buffers them in memory, and flushes to an API-first metrics service inside waitUntil(). No agents, no collectors, no TSDB to manage.

Trying to decide? Compare Distlang plan features to see how an API-first approach fits different team sizes.

Tail Workers

A Tail Worker is a secondary Worker that receives log data from a primary Worker. You configure it as a “tail consumer” in your wrangler.toml, and Cloudflare sends structured log events to it after each invocation of the primary Worker. Tail Workers are useful for custom log processing, forwarding to external systems, or building alerting pipelines without modifying the primary Worker’s code. They don’t replace metrics instrumentation, but they complement it.

Common Pitfalls Quick Reference

These are the mistakes that show up repeatedly in GitHub issues, community forums, and production incident reports when teams try to instrument Cloudflare Workers with serverless metrics using a JavaScript client.

Flushing without waitUntil(): If you call flush() but don’t wrap it in ctx.waitUntil(), the isolate can terminate before the HTTP request completes. Data is silently lost. This is the number one cause of “my metrics are missing” reports.

Using Node.js OTel SDKs: Installing @opentelemetry/sdk-trace-node or @opentelemetry/auto-instrumentations-node in a Worker will produce runtime errors. These packages depend on Node.js APIs that don’t exist in the V8 isolate environment, even with compatibility flags enabled.

Unbounded label values: Using request IDs, full URLs, or user IDs as metric labels causes cardinality to grow linearly with traffic. Your metrics backend slows down, your bill increases, and your dashboards become unusable.

Unhandled flush rejections: As the Sentry bug demonstrated, a rejected Promise inside waitUntil() can mark the entire invocation as failed. Always add .catch() to your flush call.

Relying solely on built-in analytics: Cloudflare’s dashboard shows request counts, error rates, and CPU time. But it can’t tell you business-specific things like conversion rates, feature usage, or queue processing times. Custom instrumentation fills that gap.

Assuming gauges work like they do on servers: Without a persistent process, a gauge in Workers is just a snapshot. If you need to track “current connections” or “queue depth,” you need a different architecture (like a Durable Object or external state store).

For an expanded treatment of each pitfall with solutions, see common pitfalls when instrumenting serverless handlers.

Putting It All Together

The complete pattern for instrumenting a Cloudflare Worker with serverless metrics using a JavaScript client looks like this:

  1. Choose your metric types. Counters for events, histograms for distributions. Skip gauges.
  2. Design your schema. Define metric sets with bounded, low-cardinality labels.
  3. Initialize a client per request. Pass your API token from environment variables.
  4. Record metrics during request handling. Increment counters, observe latencies.
  5. Flush inside waitUntil(). Wrap the flush in .catch() to prevent invocation failures.
  6. Verify on your dashboard. Confirm data arrives and charts render correctly.

Steps 1 through 6 can be completed in under an hour with a lightweight JS client and an API-first metrics service.

Ready to start? The end-to-end example walks through the full setup from application code to a live dashboard.

FAQ

Can I use Prometheus to monitor Cloudflare Workers?

Not directly. Prometheus uses a pull-based model where it scrapes metrics from an HTTP endpoint on your server. Workers don’t have persistent servers to scrape. You need a push-based approach where the Worker sends metrics to a remote endpoint. If you want Prometheus-compatible data, some metrics APIs can accept push-based writes in Prometheus format, but the architecture is fundamentally different.

How much CPU time does metrics instrumentation add to each request?

A lightweight JavaScript metrics client typically adds less than 1ms of CPU time per request. The actual flush (an HTTP POST to your metrics API) is I/O, so it counts against wall time, not CPU time. Since the flush happens inside waitUntil() after the response, it doesn’t affect user-facing latency at all.

What happens if the metrics API is down when my Worker tries to flush?

The flush HTTP call will fail, and if you’ve wrapped it in .catch() (which you should), the error is logged and the Worker invocation completes normally. The metric data points from that request are lost. This is an acceptable tradeoff for most applications: a few missing data points during an API outage are far less damaging than a failed user request. For critical metrics, consider a retry-once strategy within the 30-second waitUntil() window.

Should I use Cloudflare Analytics Engine or a JavaScript metrics client?

It depends on your needs. Analytics Engine is native, requires no external dependencies, and handles unlimited cardinality well. But it limits you to 25 data points per invocation, offers no JOINs, and retains data for a maximum of 3 months. A JavaScript metrics client gives you more control over what you measure, how you label it, and where the data goes. For custom business metrics and longer retention, an external metrics API is the better choice.

Is OpenTelemetry too heavy for Cloudflare Workers?

The standard Node.js OTel SDK is, yes. It won’t even run in the Workers runtime. But lightweight OTel-compatible wrappers built specifically for Workers exist and work well. They’re around 200 lines of code with zero dependencies. The question is whether you need OTel ecosystem compatibility. If you’re just sending counters and histograms to one backend, a simpler JavaScript metrics client requires less configuration.

How do I avoid losing metrics data in short-lived Workers?

Three rules: always flush inside ctx.waitUntil(), always wrap the flush in .catch(), and prefer per-request client instantiation over global singletons. If you’re using a framework like Hono or SvelteKit, make sure you’re accessing the correct execution context for waitUntil(). The framework-specific access patterns in this guide are a good reference.

What labels should I put on my Worker metrics?

Start with HTTP method, status code bucket (2xx/3xx/4xx/5xx), and route pattern. Add the Cloudflare colo (data center) if you care about geographic distribution. Never use request IDs, user IDs, or unbounded strings. The cardinality multiplication rule means every new unique label value creates a new time series, and costs scale accordingly.

Can I instrument Workers without writing any code?

Yes, partially. Cloudflare’s native observability features (Workers Logs and Traces) export platform-level telemetry without code changes. But this only covers what the runtime itself can measure: request timing, errors, and subrequests. For custom application metrics like “items added to cart” or “API calls to third-party service X,” you need code-level instrumentation with a JavaScript client.