Serverless Counters and Histograms for Edge Functions: 2026
What Are Serverless Counters and Histograms for Edge Functions?
A counter tracks how many times something happened. A histogram records the distribution of measured values, like request latency or payload size, by sorting observations into buckets. In edge functions, both metric types need a push-style ingestion path and an explicit flush step because the runtime may stop executing moments after the response is sent.
Prometheus defines a counter as a cumulative metric that only goes up (or resets to zero on restart) and recommends counters for things like requests served and errors. It defines histograms as observations counted into configurable buckets, commonly used for request durations or response sizes. Source: Prometheus metric types
That matters here because edge functions are not long-running servers. There is no persistent process where a metrics agent, background thread, or scrape endpoint can reliably live. Counters and histograms in this context must be recorded during the request and flushed after the response through platform lifecycle primitives.
Distlang Metrics is built for exactly this pattern: API-first counters and histograms from serverless JavaScript handlers, with no agents or sidecars required.
Why Counters and Histograms Work Differently at the Edge
Most metrics advice assumes a server that runs for hours, days, or weeks. A Prometheus exporter sits on port 9090. A Datadog agent runs as a sidecar. A background thread batches and ships telemetry every 10 seconds.
Edge functions break those assumptions.
Cloudflare Workers run in V8 isolates with a 128 MB memory limit and CPU time constraints that vary by plan. Source: Cloudflare Workers limits Vercel Functions running on the Edge Runtime use a minimal JavaScript environment with Web Standard APIs and only a subset of Node.js APIs. Both environments are short-lived. Your function starts, handles a request, returns a response, and the runtime may freeze or terminate.
This means serverless counters and histograms for edge functions face three constraints that traditional metrics do not:
- No persistent process. You cannot keep a metrics buffer alive across requests in the same way a Node.js server can.
- Stricter resource limits. CPU, memory, and bundle size budgets are tighter, so heavy observability SDKs are a problem.
- Platform metrics are not application metrics. Cloudflare and Vercel show you invocation counts, error rates, CPU time, and memory usage. They do not automatically know about your checkout attempts, auth decisions, or tenant-specific API latency.
Practitioners on Reddit confirm this gap. One thread about Cloudflare Worker limitations noted that Workers are strong for stateless edge logic and global low-latency reads, but observability feels thinner than CloudWatch, and teams often need to wire their own monitoring beyond the basics. Another Reddit discussion about Vercel observability raised concerns about retention limits and lack of schema control in built-in tools.
The bottom line: if you want application-level visibility into what your edge function is doing, you need to instrument counters and histograms yourself.
Counter
A counter is a metric that only increases or resets. Use it for events.
Prometheus explicitly warns not to use a counter for values that can decrease (like currently running processes). If the value can go down, it is a gauge, not a counter.
Good counter examples for edge functions:
edge_requests_total
edge_errors_total
cache_hits_total
origin_fetch_failures_total
auth_denied_total
rate_limited_requests_total
How to read a counter on a dashboard:
A raw counter value (say, 1,247,832 total requests) is less useful than its rate of change. In Prometheus-style thinking, you graph rate() over a time window to see requests per second or errors per minute. The number going up is expected. What matters is how fast it is going up, and whether that speed changes.
The rule: use a counter when the number should never go down. requests_total is a counter. active_requests (which decreases when a request finishes) is not.
For a deeper walkthrough of JavaScript instrumentation, see how to instrument counters.
Histogram
A histogram records observed values into buckets so you can understand a distribution. It does not store every individual measurement forever. Instead, it stores enough bucketed data to answer questions like “what was p95 latency over the last five minutes?”
Good histogram examples for edge functions:
edge_request_duration_ms
origin_fetch_duration_ms
auth_check_duration_ms
response_body_bytes
request_payload_bytes
Why histograms matter more than averages:
If 95 requests take 20 ms and 5 requests take 2 seconds, the average is roughly 119 ms. That looks fine. But 5% of your users are waiting 2 full seconds, and the average hides that completely. Histograms let the backend estimate percentiles like p50, p90, p95, and p99, exposing the tail latency that averages obscure. Source: Prometheus histograms and summaries
OpenTelemetry’s semantic conventions recommend http.server.request.duration as a histogram instrument with explicit bucket boundaries. Source: OpenTelemetry HTTP metrics
The rule: use a histogram when you care about distribution, not just “how many requests happened” but “how slow were the slowest requests?”
Counter vs Histogram vs Gauge in Serverless Metrics
Choosing the right metric type is one of the first decisions when instrumenting edge function counters and histograms. This table covers the main options.
| Metric type | Use when | Edge example | Common mistake |
|---|---|---|---|
| Counter | A value only increases | edge_requests_total |
Using it for active requests (which go down) |
| Histogram | You need a distribution | edge_request_duration_ms |
Only tracking average latency |
| Gauge | Current value can go up or down | queue depth, in-flight requests | Treating a sampled snapshot as an event count |
| Log/event | You need high-cardinality detail | request ID, user ID, raw path | Putting user IDs into metric labels |
| Trace/span | You need request flow | downstream API call chain | Trying to debug causality from metrics alone |
Counters and histograms handle the “what changed” and “how is performance distributed” questions. Logs and traces answer “why did this specific request fail.” For a broader look at how metrics, logs, events, and traces relate, see the guide on telemetry signals and OpenTelemetry.
Recording Is Easy; Flushing Is the Serverless Part
Recording a counter increment or histogram observation takes a line of code. The hard part with serverless counters and histograms for edge functions is making sure that data actually leaves the function before the runtime shuts down.
The pattern is: record synchronously, flush asynchronously after the response.
const start = Date.now();
try {
// handler logic
metrics.counter("edge_requests_total", 1, { route: "/api/search", method: "GET" });
return new Response("ok");
} catch (err) {
metrics.counter("edge_errors_total", 1, { route: "/api/search", status_class: "5xx" });
throw err;
} finally {
metrics.histogram("edge_request_duration_ms", Date.now() - start, { route: "/api/search" });
}
The flush happens through a platform lifecycle primitive.
Cloudflare Workers: ctx.waitUntil()
Cloudflare’s ctx.waitUntil() extends a Worker’s lifetime for non-blocking work after the response. For HTTP-triggered Workers, it can extend execution up to 30 seconds after the response is sent. Source: Cloudflare Workers context API
ctx.waitUntil(metrics.flush());
A practitioner on Reddit described exactly this approach: accumulating request-scoped data and emitting a data point in waitUntil() at the end of each invocation to track usage and costs. This is the standard pattern for edge metrics flushing on Cloudflare.
For a detailed walkthrough, see waitUntil semantics for Workers.
Vercel and Next.js: waitUntil() and after()
Vercel’s knowledge base warns that if a function starts async work and does not await it, the function can return and freeze before that work completes. Source: Vercel troubleshooting logs The fix is waitUntil() for Vercel Functions or after() for Next.js App Router handlers.
after(() => metrics.flush());
Next.js documents after() as a way to run tasks like logging and analytics after a response finishes. Source: Next.js after() API One LinkedIn post by a Vercel practitioner described waitUntil() as the right tool for non-critical operations like logging after sending a response.
For Vercel-specific patterns, see using after() for metrics flush.
An Important Caveat
waitUntil() and after() improve reliability and reduce user-facing latency. They are not infinite queues or guaranteed-delivery systems. Cloudflare imposes a post-response time limit, and Vercel says background tasks remain bound by the function’s maximum execution timeout. If the metric data is mission-critical billing information, consider a durable queue or write-ahead storage rather than relying solely on best-effort post-response flush.
For more on buffering and batching strategies, see flush strategies for edge functions.
Get started with the Distlang Metrics quickstart to see these flush patterns in working code for both Cloudflare and Vercel.
Label Rules for Edge Counters and Histograms
Labels (sometimes called tags or dimensions) let you slice metrics by route, method, status, or other attributes. They are powerful and dangerous. Every unique combination of label values creates a new time series, and Prometheus warns against high-cardinality label values such as user IDs, email addresses, or other unbounded sets. Source: Prometheus naming practices
Prometheus instrumentation best practices say that if a metric has cardinality over 100 (or could grow that large), teams should investigate reducing dimensions or moving the analysis to another system. Source: Prometheus instrumentation
Here is a practical table for edge function metrics:
| Goal | Good label | Bad label |
|---|---|---|
| Compare route performance | route="/api/users/:id" |
path="/api/users/123?debug=true" |
| Compare status classes | status_class="2xx" |
raw exception message |
| Compare tenants at small scale | plan="free" |
user_id="user_abc123" |
| Compare cache behavior | cache_status="hit" |
full cache key |
| Compare region | runtime="cloudflare_workers" |
raw data center + request ID |
The principle: use metrics labels for bounded dimensions. Use logs, traces, or analytics events for high-cardinality debugging fields like user IDs, session tokens, and full URLs.
For a deeper dive into label naming strategies, see label naming and cardinality.
On Reddit, a thread about a zero-dependency Cloudflare Workers observability SDK highlighted another related concern: every observability SDK the developer tried required nodejs_compat and added 50 to 100 KB of polyfills to the Worker bundle. Lightweight instrumentation with minimal dependencies matters at the edge, not just for performance but for staying within bundle size limits.
Native Platform Observability vs Custom Metrics
Cloudflare Workers metrics show request counts, subrequests, wall time, CPU time, memory usage, and invocation status. Vercel Observability shows invocation counts, error rates, and function performance broken down by route. These are useful for answering “is my function platform healthy?”
But neither platform automatically knows about your app-specific business events: checkout attempts, auth decisions, AI token usage, cache hits by pricing plan, or tenant-specific API latency. That is where custom counters and histograms for edge functions come in.
Here is how the options compare:
| Option | Best for | Weakness in edge functions |
|---|---|---|
| Native platform observability | Platform health, runtime usage, errors | Does not cover app-specific business events |
| API-first metrics service | Code-level counters and histograms, quick dashboards | Requires label discipline and flush setup |
| OpenTelemetry | Standardized signals, vendor portability | Edge runtime support varies; Cloudflare says Worker metrics export through OTel is not yet supported |
| Prometheus scrape model | Long-running services, Kubernetes | Edge handlers are ephemeral; Pushgateway has limitations |
| Logs and events | High-cardinality debugging detail | More expensive for simple aggregate charts |
Cloudflare positions its Workers Analytics Engine for custom analytics, usage-based billing, and per-customer health. That is a platform-specific option worth evaluating. But for developers building across Cloudflare and Vercel (or who want portability), an API-first metrics service that accepts push-style counters and histograms is often simpler.
The Prometheus Pushgateway Problem
Prometheus is excellent for long-running services. But its core model is scrape-based: a Prometheus server pulls metrics from your /metrics endpoint on a schedule. Edge functions are ephemeral, so there is no stable endpoint to scrape.
The Prometheus Pushgateway exists for jobs that cannot be scraped, but official documentation recommends it only in limited cases. It can become a single point of failure, it loses automatic instance health semantics, and it retains stale series unless they are manually deleted. Source: Prometheus pushing
For edge functions, push-style or API-first metrics ingestion is the more natural fit. Trying to adapt a pull-based model to ephemeral handlers creates friction that does not need to exist.
Practical Examples of Serverless Counters and Histograms
Example A: API Request Metrics
Counter: edge_requests_total{route="/api/search", method="GET", status_class="2xx"}
Counter: edge_errors_total{route="/api/search", status_class="5xx"}
Histogram: edge_request_duration_ms{route="/api/search", method="GET"}
On a dashboard, the counter becomes a “requests per minute” line chart. The error counter becomes an “error rate by route” chart. The histogram becomes a p50/p95/p99 latency chart that shows whether your slowest requests are getting worse.
Example B: Origin Fetch Metrics
Counter: origin_fetches_total{origin="primary", cache_status="miss"}
Counter: origin_fetch_failures_total{origin="primary"}
Histogram: origin_fetch_duration_ms{origin="primary"}
This helps isolate whether high p95 latency comes from your edge handler logic or from the upstream origin. If origin_fetch_duration_ms p95 is high but edge_request_duration_ms p95 is only slightly higher, the origin is the bottleneck.
Example C: Auth and Rate Limiting
Counter: auth_denied_total{reason="missing_token"}
Counter: rate_limited_requests_total{route="/api/search", plan="free"}
Histogram: auth_check_duration_ms{provider="jwt"}
Notice that reason is bounded (“missing_token,” “expired_token,” “invalid_signature”) and plan is bounded (“free,” “pro,” “enterprise”). No user IDs, no session tokens.
The Edge Metrics Lifecycle
Here is a framework for thinking about serverless counters and histograms for edge functions as a process, not just a concept.
1. Choose the signal. Is this a count, a distribution, a current value, a log, or a trace?
2. Name the metric. Include the unit where useful: request_duration_ms, payload_bytes, errors_total.
3. Constrain the labels. Normalize before recording. Use route="/api/users/:id", not route="/api/users/123".
4. Record inside the handler. Increment counters and observe histogram values while request context is available.
5. Buffer briefly. Keep the buffer small and request-local in edge/serverless functions.
6. Flush through a lifecycle primitive. Use ctx.waitUntil(), waitUntil(), or after() to send buffered metrics after the response.
This lifecycle is what separates edge metrics from traditional server metrics. Steps 5 and 6 simply do not exist when you have a persistent Node.js process.
Common Mistakes
1. Using counters for values that go down. If it decreases, it is a gauge. active_connections is not a counter.
2. Only tracking average latency. Averages hide tail latency. Histograms with percentile views expose the pain that averages smooth over.
3. Adding user IDs as labels. Each unique user ID creates a new time series. With thousands of users, you have thousands of series per metric. Use logs for user-level debugging.
4. Forgetting to flush. Unawaited async work can be frozen when the function returns. Always use the platform’s lifecycle primitive.
5. Treating waitUntil() as a durable queue. It helps, but it has time limits. For critical billing data, use a durable ingestion path.
6. Assuming native platform metrics cover everything. Platform metrics show function health. Application metrics show business behavior. Both are needed.
7. Copying Prometheus Pushgateway patterns without understanding the tradeoffs. It was designed for batch jobs, not for every ephemeral function invocation pushing metrics.
Hacker News discussions about Cloudflare Workers have shown a persistent desire for deeper visibility than basic logs and platform metrics. Counters and histograms are the first layer of that application visibility. They tell you what changed and where latency shifted. Traces and logs help explain why.
Getting Started
Serverless counters and histograms are simple in concept but easy to lose in short-lived handlers. The practical path is: define the metric set, record counters and histograms in the handler, flush with waitUntil() or after(), and check the dashboard.
Distlang Metrics is designed for this workflow. It provides API-first counters and histograms from serverless JavaScript handlers, with quickstarts for Cloudflare Workers and Vercel, a hosted dashboard per metric set, and a free plan to start with.
FAQ
What is a counter in serverless metrics?
A counter is a metric that only increases or resets to zero. In serverless metrics, counters track request totals, error totals, cache hits, signups, or rate-limit events. The key property is monotonicity: the value never goes down during normal operation.
What is a histogram in edge function metrics?
A histogram records observed values into buckets so you can understand a distribution. In edge functions, histograms commonly measure request latency, origin-fetch latency, auth-check duration, payload size, and response size. They let you compute percentiles like p95 and p99 rather than relying on averages.
Should I use a counter or histogram for latency?
Use a histogram. A counter tells you how many requests happened, but a histogram shows the distribution of request duration and supports percentile views. If you only track a counter for requests and an average for latency, you are missing the tail.
How do you send metrics from Cloudflare Workers?
Record counters and histograms during the request, then flush them via ctx.waitUntil() after the response. This extends the Worker’s execution for non-blocking work without adding latency to the response. The post-response window is up to 30 seconds for HTTP-triggered Workers.
How do you send metrics from Vercel or Next.js?
In Vercel Functions, use waitUntil() for non-critical async work after the response. In Next.js App Router, use after() to schedule post-response tasks like logging or analytics. Without these lifecycle hooks, unawaited async work can be frozen when the function returns.
Can Prometheus monitor edge functions?
It can be adapted, but classic Prometheus is scrape-first and not a natural fit for ephemeral edge functions. The Pushgateway exists for jobs that cannot be scraped, but Prometheus documentation recommends it only in limited cases because of stale-series retention, bottleneck risk, and loss of instance health semantics.
What labels should I avoid in edge function metrics?
Avoid unbounded labels: user IDs, email addresses, request IDs, raw IP addresses, full URLs with query strings, and session tokens. Each unique label combination creates a new time series, and cardinality above 100 per metric should trigger investigation.
What is the difference between platform metrics and application metrics?
Platform metrics (from Cloudflare or Vercel dashboards) show function-level health: invocations, errors, CPU time, memory. Application metrics (your own counters and histograms) show business-level behavior: checkout attempts, auth decisions, cache hit rates by plan, or downstream API latency. You need both for full visibility.