9 Common Pitfalls When Instrumenting Serverless Handlers
What “instrumenting serverless handlers” means
A serverless handler is a function that runs in response to an HTTP request, queue message, or scheduled event, then returns control to the runtime. Lambda functions, Vercel Functions, Next.js Route Handlers, and Cloudflare Workers all follow this pattern.
Instrumentation is the code you add to record what happened during a request: counters, histograms, logs, traces, analytics events, or custom spans. For a broader overview of these signal types, see this guide on telemetry in serverless apps.
The phrase “common pitfalls when instrumenting serverless handlers” refers to the recurring mistakes that cause telemetry to behave unreliably in short-lived runtimes. The failure usually is not in the metrics API itself. It happens because the handler returned before telemetry finished, the runtime killed a floating promise, the SDK buffered data without flushing, or the labels created too many distinct time series.
If you want lightweight, API-first metrics designed for exactly these runtimes, Distlang Metrics provides counters and histograms with explicit flush patterns for Cloudflare Workers and Vercel.
Why serverless instrumentation fails differently
On a traditional server, a background client has time to batch and send telemetry because the process keeps running between requests. In a serverless handler, the runtime may freeze, terminate, or recycle the execution context soon after the handler returns. That single difference is the root cause of most instrumentation pitfalls in serverless handlers.
Five properties make serverless runtimes hostile to naive telemetry code.
The runtime can cancel unfinished work. Cloudflare warns that an async call not awaited or passed to ctx.waitUntil() can be canceled when invocation ends, dropping logs or leaving writes unfinished. AWS Lambda has a related trap: the execution environment can freeze and later resume async callbacks from a previous invocation, creating confusing state.
Telemetry clients buffer data. Buffering reduces network overhead, and that is usually good. But a short-lived handler needs explicit flush semantics, or the buffer sits in memory when the runtime stops.
Cold starts make initialization visible. Heavy SDKs, auto-instrumentation layers, and collectors compete with application code for startup time and memory. This cost is invisible on a long-running server but measurable on every cold invocation.
Every label combination creates a new time series. Metrics backends store one series per unique label set. User IDs, raw URL paths, and request IDs as labels can produce thousands or millions of series. Prometheus recommends keeping cardinality below 10 for most metrics and investigating alternatives above 100.
Platform limits are part of the instrumentation design. Cloudflare Workers enforce a 128 MB memory limit and CPU time caps. Lambda has duration and concurrency limits. Your telemetry must fit within these budgets, not sit on top of them.
Quick reference: common pitfalls at a glance
Before going deeper, here is a summary table of the most common pitfalls when instrumenting serverless handlers, mapping each one to its symptom and fix.
| Pitfall | Symptom | Fix |
|---|---|---|
| Floating promises | Metrics or logs disappear in production | await critical work; use waitUntil() for non-critical work |
Treating waitUntil() as a job queue |
Jobs sometimes vanish, no retries | Use a durable queue for reliable work |
| Blocking on every telemetry call | P95 latency climbs after adding instrumentation | Batch metrics; flush once per request using post-response hooks |
| Forgetting to flush SDK buffers | Dashboard stays empty, especially at low traffic | Call flush() explicitly before exit or inside waitUntil() |
| Heavy auto-instrumentation | Cold starts increase noticeably | Disable unused instrumentations; measure overhead |
| High-cardinality labels | Metrics bill explodes; backend drops data | Use bounded labels; put user IDs in logs, not metric labels |
| Wrong metric type | Dashboards lie or alerts misfire | Counters for events, histograms for latency, gauges for snapshots |
| Missing platform metrics | You see app metrics but miss throttles and timeouts | Monitor platform metrics alongside custom metrics |
| Broken trace propagation | Traces stop at queues or async boundaries | Propagate trace context in message attributes |
| Global request state | Cross-request data leaks or wrong request IDs | Keep clients global; pass request context per invocation |
Pitfall 1: Fire-and-forget telemetry (floating promises)
A floating promise is an async operation that starts but is never awaited, returned, or registered with a lifecycle primitive like waitUntil(). This is the single most common instrumentation mistake in serverless handlers.
Cloudflare’s best practices documentation calls floating promises out explicitly, warning they cause dropped results, swallowed errors, and unfinished work. Vercel’s troubleshooting docs describe the same problem: if a function starts an async task but does not await it, the execution context may freeze before the task finishes.
Practitioners on Reddit confirm this is not theoretical. Multiple Next.js and Vercel discussions describe developers running work after returning a response, only to find it aborted or unreliable in production. A Cloudflare Workers thread describes a developer discovering that a fire-and-forget send was killed after the response returned, and another developer in the same thread explaining they kept a D1-backed queue for work that needed durability.
// Bad: this promise may be canceled after the response
export async function POST(request: Request) {
const result = await createCheckout(request);
metrics.increment("checkout.created");
metrics.flush(); // not awaited, not registered
return Response.json(result);
}
// Better: registered with Cloudflare's lifecycle
export default {
async fetch(request, env, ctx) {
const result = await handleRequest(request);
metrics.increment("request.completed", {
route: "/checkout",
status: "success",
});
ctx.waitUntil(
metrics.flush().catch((err) => console.error("flush failed", err))
);
return Response.json(result);
},
};
The symptom is always the same: “it works locally but drops events in production.” Local development environments do not aggressively terminate execution contexts the way production runtimes do. For a deeper walkthrough of these lifecycle patterns, see how waitUntil() affects metrics.
Pitfall 2: Treating waitUntil() or after() as a job queue
Once developers discover waitUntil() or Next.js after(), it is tempting to use them for everything: sending emails, processing webhooks, running database migrations, syncing external services. This is a mistake.
These primitives are lifecycle helpers, not durability systems. Cloudflare’s documentation states that ctx.waitUntil() can extend execution for up to 30 seconds after response or disconnect, and recommends Queues for work that needs reliable delivery and automatic retries. Inngest draws the same line: waitUntil() is suitable for non-critical operations like logging and analytics, but lacks built-in retries or failure handling.
A practical decision tree for categorizing work:
- Does the response depend on it? Await it.
- Is it telemetry or a non-critical side effect that finishes quickly? Use
waitUntil()orafter(). - Must it happen even if the function crashes? Enqueue it.
- Does it take longer than the handler’s lifecycle limit? Move it out of the handler entirely.
Most instrumentation pitfalls around serverless handlers happen when developers put durable work into a best-effort mechanism.
Pitfall 3: Blocking every response on telemetry export
The opposite mistake is equally harmful. Some developers await every metrics call, log export, and trace flush before returning a response. This adds network round-trip time to every request.
AWS recommends emitting Lambda custom metrics asynchronously using Embedded Metric Format instead of making synchronous CloudWatch API calls from inside function code, because EMF sends metrics through stdout and avoids blocking the handler. Vercel designed waitUntil() specifically so post-response telemetry does not block the user.
Practical rules for keeping latency under control:
- Do not make a network request per individual metric increment.
- Batch metrics in memory and flush once per handler invocation.
- Use post-response lifecycle primitives when occasional data loss is acceptable.
- Reserve synchronous awaiting for data that the response depends on.
Pitfall 4: Forgetting to flush buffered SDKs
Many telemetry clients buffer events to reduce network overhead. On a long-running server, a background interval timer sends the buffer every few seconds. In a serverless handler, that timer may never fire because the runtime freezes between invocations.
Langfuse identifies this directly: background tracing clients may not complete before serverless exit, so users should manually call flush() before the function exits or use waitUntil() to let the flush promise resolve after the response. The same principle applies to any buffered metrics, analytics, or logging client.
The fix pattern is consistent across platforms:
- Record metrics throughout the handler.
- Call
flush()once at the end. - Register the flush promise with the runtime lifecycle.
- Catch flush errors so a telemetry failure does not crash the response.
import { after } from "next/server";
export async function POST(request: Request) {
const result = await handleRequest(request);
metrics.increment("request.completed", {
route: "/checkout",
status: "success",
});
after(async () => {
try {
await metrics.flush();
} catch (err) {
console.error("metrics flush failed", err);
}
});
return Response.json(result);
}
Buffering is not the problem. Unflushed buffering is. For more on configuring this correctly, read about flush strategies for short-lived handlers.
Pitfall 5: Adding too much instrumentation to cold starts
Serverless instrumentation competes with application code for startup time, CPU, and memory. Auto-instrumentation frameworks, OpenTelemetry layers, and collector sidecars can add meaningful overhead to cold starts.
AWS’s observability best-practices guide says the ADOT Lambda Layer can require additional memory and have a notable impact on cold-start latency, recommending that teams enable only the instrumentations their application actually uses. Lambda also publishes a PostRuntimeExtensionsDuration metric that captures time spent running extension code after the function itself has completed.
Practitioners on Reddit report this as a real adoption blocker. One OpenTelemetry user said cold-start overhead concerns kept them from deploying ADOT broadly in production. Another described removing a collector layer and sending traces directly to the backend because the cold-start hit was “dramatic.” On LinkedIn, a practitioner working on OpenTelemetry Node.js Lambda layers described reducing cold-start overhead to roughly 90 to 99 ms through bundling, tree-shaking, V8 compile caching, and dependency removal.
The lesson: serious teams treat observability code as production code with a performance budget. Measure cold-start and warm-invocation latency before and after adding instrumentation. Disable auto-instrumentations you are not using. Prefer lightweight metrics clients for simple counters and histograms, and reserve tracing for high-value code paths where the overhead is justified.
Pitfall 6: High-cardinality metric labels
This is the instrumentation pitfall that costs money before it causes technical failures. Every unique combination of label values creates a distinct time series. Prometheus documentation recommends keeping cardinality below 10 for most metrics and investigating alternatives when a metric exceeds or could grow past 100 unique combinations. OpenTelemetry enforces a default cardinality limit of 2,000 attribute combinations per metric stream because uncapped cardinality causes unbounded memory growth.
Practitioners on Reddit describe high-cardinality labels as a classic production footgun. One Prometheus-focused thread discusses user IDs, full request paths, and attacker-controlled headers as ways to accidentally create hundreds of thousands of series and exhaust memory.
Here is what good and bad label design looks like in practice:
| Bad label | Why it is bad | Better approach |
|---|---|---|
user_id="abc123" |
Unbounded; one series per user | Put user ID in logs or traces, not metric labels |
path="/users/123/settings" |
Raw paths explode series count | route="/users/:id/settings" |
email="user@example.com" |
High-cardinality and sensitive | Use account tier or cohort instead |
request_id="req_xyz" |
Unique per request | Use trace or log correlation |
error_message="Stripe declined..." |
Unbounded and may contain PII | error_class="payment_declined" |
For a complete guide to structuring labels well, see label naming and cardinality strategies.
Pitfall 7: Using the wrong metric type
Picking the wrong metric type produces dashboards that lie. Counters, histograms, and gauges have different semantics, and confusing them leads to incorrect rate calculations, misleading averages, or alerts that never fire.
Counters only go up and reset to zero on restart. Gauges can go up and down. Raw counters are rarely useful without a rate calculation, and you should never take the rate of a gauge. In serverless environments, local in-memory counters reset frequently because functions restart often, so the backend must handle these resets properly.
Common serverless metric type choices:
http_requests_totalis a counter.http_request_duration_msis a histogram.queue_depthis a gauge.checkout_failures_totalis a counter.db_query_duration_msis a histogram.
One specific mistake to avoid: encoding status codes into metric names like http_500_total and http_200_total. Use one metric with a bounded status_class label ("2xx", "4xx", "5xx"). For implementation patterns in JavaScript, see how to instrument counters and histograms.
Pitfall 8: Losing trace context across async boundaries
HTTP request tracing works well within a single handler invocation. It breaks down when requests flow through queues, event buses, or async processing chains.
OpenTelemetry’s AWS Lambda semantic conventions describe how X-Ray active tracing propagates context through _X_AMZN_TRACE_ID and how misconfiguration of the xray-lambda propagator can break traces when exporting to systems other than X-Ray. Lambda event source mappings also process events at least once, so duplicate processing can occur and event-count metrics may count records more than once due to retries.
Practical guidance for preserving trace context:
- When publishing queue messages, include trace context in message attributes.
- Expect asynchronous processing to produce span links or batch processing spans, not always a simple parent-child tree.
- Make metric increments idempotent where retries can duplicate processing.
- Use deduplication keys for business events, not just telemetry events.
Pitfall 9: Putting request state in global scope
A globally scoped telemetry client is usually fine. A globally scoped request ID, user ID, trace context, or active span is not.
Cloudflare warns that Workers reuse isolates across requests, so module-level request-scoped variables can cause cross-request data leaks and stale state. AWS Lambda has a related risk: execution environments can be reused, and async callbacks from a previous invocation may resume in a later one, creating confusing logs and potential data leakage.
The rule for instrumenting serverless handlers safely:
// Fine: client is stateless and reusable across requests
const metrics = createMetricsClient({ token: process.env.METRICS_TOKEN });
// Bad: request state stored globally
let currentUserId: string | null = null;
let activeSpan: Span | null = null;
Pass request-scoped data through function arguments, async local storage, or the runtime’s context APIs. Never assign it to module-level variables that persist across invocations.
Platform-specific notes
Cloudflare Workers
Cloudflare Workers reuse V8 isolates and enforce strict resource limits. Key facts for instrumentation:
ctx.waitUntil()extends execution up to 30 seconds after the response or disconnect. Unfinished promises are canceled after that window.- Free plan Workers get 10 ms CPU time per HTTP request and 128 MB memory. Paid Workers default to 30 seconds of CPU time. Instrumentation, serialization, and heavy SDK initialization count toward this budget.
- Do not destructure
ctx.waitUntil()from the context object. Cloudflare documents that destructuring can lose thethisbinding and throw “Illegal invocation.” - Practitioners on Reddit report that CPU time limit errors can surface after adding heavier frameworks or changing packages. Treat instrumentation overhead as part of your CPU budget.
For a step-by-step setup, see the Cloudflare Workers metrics quickstart.
Vercel and Next.js
Vercel Functions and Next.js Route Handlers have their own lifecycle primitives:
- Vercel’s
waitUntil()works in both Node.js and Edge runtimes for post-response work like logging, analytics, and cache updates. - Next.js 15.1 made
after()stable for code that runs after a response finishes streaming. Vercel recommendsafter()over the@vercel/functionswaitUntil()for Next.js 15.1 and later. - Tasks handled by
waitUntil()orafter()remain bound by the function’s maximum execution timeout.
For Vercel-specific flush patterns, see the Vercel metrics quickstart or the guide on using after() for metrics.
AWS Lambda
Lambda has the most mature but also the most complex instrumentation ecosystem:
callbackWaitsForEmptyEventLoopcontrols whether callback-based Node.js handlers wait for the event loop to empty. Setting it tofalsecan leave outstanding async work to resume during the next invocation.- AWS recommends Embedded Metric Format for custom metrics instead of synchronous CloudWatch API calls. Lambda Powertools can aggregate up to 100 metrics in a single EMF object.
Durationexcludes cold-start time.PostRuntimeExtensionsDurationcaptures time extensions spend running after function code completes.- ADOT Lambda layers provide OpenTelemetry integration but can notably impact cold starts. Enable only the instrumentations your application actually uses.
The serverless instrumentation budget
Every common pitfall when instrumenting serverless handlers maps back to exceeding one of four budgets:
- Lifecycle budget. How long will the runtime keep your work alive after the response?
- Latency budget. How much time can telemetry add to the response path?
- Cold-start budget. How much initialization time can telemetry add?
- Cardinality budget. How many distinct label combinations should the metrics backend accept?
If you do not size these budgets before shipping, you will discover the limits in production through slow responses, missing data, or unexpected bills.
Serverless instrumentation checklist
Use this checklist before shipping instrumentation to production:
- [ ] Every async telemetry operation is awaited, flushed, or registered with a lifecycle hook (
waitUntil(),after()). - [ ] Post-response work is either non-critical or queued if it must be durable.
- [ ] Flush errors are caught so telemetry failures do not crash the response.
- [ ] Metric labels are bounded and do not include user IDs, raw paths, request IDs, or raw error messages.
- [ ] Route paths are normalized (e.g.,
/users/:id/settings, not/users/123/settings). - [ ] Cold-start and warm-invocation latency are measured before and after adding instrumentation.
- [ ] Platform metrics (throttles, timeouts, errors, duration) are monitored alongside custom metrics.
- [ ] Trace context is propagated across queues and async boundaries where needed.
- [ ] Request-scoped state is not stored in global variables.
- [ ] The correct metric type is used: counters for events, histograms for durations, gauges for snapshots.
- [ ] Payload sizes and batch sizes are capped within platform limits.
If you want to start sending metrics from short-lived JavaScript handlers without running agents or Prometheus, get started with Distlang Metrics in minutes.
FAQ
Why do my metrics appear locally but not in production?
The most likely cause is a floating promise. Local development environments rarely terminate execution contexts aggressively, so fire-and-forget telemetry usually completes. Production serverless runtimes freeze or stop the context after the response returns, canceling any unregistered async work. Register telemetry with waitUntil(), after(), or an explicit await.
Is waitUntil() reliable enough for metrics?
For operational telemetry like counters, histograms, and analytics events, yes. These primitives are designed for exactly this use case. They are not reliable enough for work that must happen or retry, like sending a payment confirmation email or writing an audit log to a compliance system. Use a durable queue for that.
How much cold-start overhead does OpenTelemetry add to Lambda?
It depends on the configuration. AWS notes that ADOT Lambda layers can have a notable impact on cold-start latency, especially with broad auto-instrumentation. Practitioners report cold-start additions ranging from under 100 ms (with optimized, tree-shaken layers) to several hundred milliseconds (with full auto-instrumentation and collector layers). Measure it in your environment and disable unused instrumentations.
What labels should I avoid on serverless metrics?
Avoid any label whose unique values are unbounded: user IDs, email addresses, full URL paths with dynamic segments, request IDs, session IDs, and raw error messages. These create a new time series for every unique value. Use normalized routes, error classes, HTTP method, and bounded status categories instead.
Should I await my metrics flush or use waitUntil()?
If the response depends on the telemetry being sent (rare), await it. For most instrumentation, use waitUntil() or after() to flush after the response. This keeps user-facing latency low while still giving the runtime time to send the data.
Do I need both platform metrics and custom metrics?
Yes. Platform metrics (Lambda duration, throttles, Cloudflare CPU time, Vercel timeout errors) tell you whether the runtime is healthy. Custom metrics (checkout counts, API error rates, cache hit ratios) tell you what the application was doing. If your custom metric says checkout.started but platform metrics show throttling, the platform metric is the root-cause clue.
Can high-cardinality labels crash my metrics backend?
They can. Each unique label combination is a separate time series stored in memory. Unbounded labels like user IDs or raw paths can create hundreds of thousands of series, exhausting RAM and increasing storage costs. OpenTelemetry SDKs enforce a default cap of 2,000 combinations per metric stream as a safety net, but hitting that cap means you are already losing data.
What is the simplest way to avoid these pitfalls?
Start with a small set of bounded metrics (three to five), use a lightweight client with explicit flush behavior, register the flush with your runtime’s lifecycle primitive, and measure the overhead. Add more metrics after you have confirmed the basics work in production.