How to Flush Metrics Reliably From Short-Lived Serverless
Flushing metrics reliably from a short-lived serverless handler means forcing any buffered metric data to be sent before the runtime can freeze, terminate, or reuse the invocation context. In practice, that means the flush operation must be awaited, scheduled with a lifecycle primitive such as ctx.waitUntil() or after(), or handed off to a durable system such as a queue.
A naked, unawaited flush() Promise is not reliable. Cloudflare’s documentation explicitly warns that a Promise not awaited, returned, or passed to ctx.waitUntil() is a “floating promise” that can cause dropped results and swallowed errors.
The rest of this guide explains why metrics disappear, what the safe patterns look like on each major platform, and where the reliability boundary actually sits.
If you want to jump straight into instrumenting serverless functions with counters and histograms, the Distlang Metrics quickstart covers setup in minutes.
Why Metrics Disappear in Short-Lived Handlers
The core problem is a lifecycle mismatch. A long-running Node.js server keeps its process alive across thousands of requests. The metrics SDK can buffer data, batch it, and send it on a comfortable interval. Nothing urgent about the timing.
Serverless handlers do not work this way. Each invocation is scoped to a single request (or a small batch of events). When the handler returns a response, the runtime is free to freeze the execution environment, terminate it, or recycle it for a different request. Any buffered metric data that has not been sent yet is at risk.
The sequence looks like this:
- Handler receives request and records a metric.
- SDK stores the metric in an in-memory buffer.
- Handler returns a response.
- Runtime freezes or exits.
- Buffered metric never reaches the backend.
Langfuse describes the identical issue for tracing: background clients can fail to send events because serverless functions are short-lived and may exit before background work finishes. AWS states it even more directly: once a Lambda function sends its response, the runtime environment freezes and the function cannot run additional code.
Missing data is not the only symptom. Vercel’s knowledge base explains that when an async task is left unawaited, the function can freeze the execution context before the task finishes. If the same warm environment is reused later, the orphaned task can complete during a different request, making logs appear mixed under the wrong request. Practitioners on Reddit report hitting this exact problem when trying to run slow processes after a Vercel API endpoint returns. The replies consistently recommended either a queue or waitUntil().
For a deeper look at how buffering works in this context, see buffer and flush metrics in serverless edge code.
The Unsafe Pattern: Fire-and-Forget Flush
Here is the pattern that causes missing metrics:
export default async function handler(request: Request) {
metrics.increment("request.count")
// Bad: this Promise is not awaited or attached to the runtime lifecycle.
metrics.flush()
return new Response("ok")
}
This looks fast. It is fast. It is also unreliable.
The flush() call starts an HTTP request to send buffered data, but it returns a Promise. That Promise is floating. The runtime was never told about it. On Cloudflare Workers, the isolate can terminate and cancel the in-flight request. On Lambda, the environment freezes. On Vercel, the execution context can be recycled.
Developers on r/Backend have asked whether fire-and-forget Promises behave differently in long-running Express servers versus serverless environments like Lambda and Vercel. The answer is yes, dramatically. In Express, the process stays alive. In serverless, the runtime controls the lifecycle, and it has no reason to wait for a Promise nobody told it about.
The fix is straightforward: make the flush part of the handler lifecycle. The specific mechanism depends on the platform.
The Safe Patterns
Pattern 1: Await the Flush Before Returning
This is the simplest approach and works everywhere. It is the right default when no post-response lifecycle primitive is available.
export async function handler(request: Request) {
const start = Date.now()
try {
const response = await doWork(request)
metrics.histogram("request.duration_ms", Date.now() - start)
metrics.counter("request.success", 1)
return response
} catch (err) {
metrics.counter("request.error", 1)
throw err
} finally {
await metrics.flush()
}
}
The finally block is important. It runs whether the request succeeded or threw an error, so both success and error metrics get flushed.
The trade-off is latency. The response does not return until the flush completes. For a fast flush to a nearby endpoint, this might add 5 to 50 milliseconds. For a slow or distant collector, it could be noticeable. AWS Lambda troubleshooting docs recommend making sure background processes complete before code exits, and awaiting the flush is the most direct way to follow that guidance.
Use this pattern on AWS Lambda, in any runtime without waitUntil(), or anywhere the flush is fast enough that the latency cost is acceptable.
Pattern 2: Cloudflare Workers with ctx.waitUntil()
Cloudflare Workers provide ctx.waitUntil() to extend the lifetime of an invocation beyond the response. This is the standard way to flush metrics reliably from short-lived serverless handlers on Cloudflare.
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
const start = Date.now()
const response = await handleRequest(request)
metrics.counter("http.requests", 1, {
route: "/api/example",
status: String(response.status),
})
metrics.histogram("http.request.duration_ms", Date.now() - start, {
route: "/api/example",
})
ctx.waitUntil(
metrics.flush().catch((err) => {
console.error("metrics flush failed", err)
})
)
return response
},
}
The response returns immediately. The flush happens in the background, and Cloudflare keeps the isolate alive long enough for the Promise to settle, up to 30 seconds after the response is sent or the client disconnects.
Two things to watch:
First, do not destructure ctx.waitUntil. Cloudflare’s best practices warn that const { waitUntil } = ctx loses the method’s this binding and throws “Illegal invocation.” Always call it as ctx.waitUntil(...).
Second, always attach .catch() to the flush Promise before passing it to waitUntil(). An unhandled rejection inside waitUntil() can surface as a confusing runtime error.
For more on this pattern, see ctx.waitUntil patterns for reliable worker tasks.
Practitioners on r/Cloudflare confirm this is the standard approach for background work in Workers. One thread also noted that returning the response does not kill work passed to ctx.waitUntil(), countering a common misconception.
Pattern 3: Vercel / Next.js with after()
For Next.js 15.1 and above running on Vercel, the recommended way to flush metrics after the response is after():
import { after } from "next/server"
export async function GET(request: Request) {
const start = Date.now()
const response = await handleRequest(request)
metrics.counter("http.requests", 1, {
route: "/api/example",
status: String(response.status),
})
metrics.histogram("http.request.duration_ms", Date.now() - start, {
route: "/api/example",
})
after(async () => {
try {
await metrics.flush()
} catch (err) {
console.error("metrics flush failed", err)
}
})
return response
}
Next.js docs describe after() as scheduling work after a response or prerender finishes, useful for side effects like logging and analytics. Under the hood in serverless contexts, it uses a waitUntil(promise) primitive.
Vercel’s leadership has publicly framed waitUntil and after as first-class “after-response compute,” not a hack or workaround. Developers unsure whether waitUntil() is “proper” can stop worrying: it is the provider’s supported mechanism for this exact use case.
For a focused walkthrough of this pattern, see using after() for metrics flush in Vercel edge functions.
Pattern 4: Vercel Non-Next.js or Older Next.js with waitUntil()
If you are not on Next.js 15.1+, use waitUntil() from @vercel/functions:
import { waitUntil } from "@vercel/functions"
export default {
async fetch(request: Request) {
const response = await handleRequest(request)
metrics.counter("http.requests", 1)
waitUntil(
metrics.flush().catch((err) => {
console.error("metrics flush failed", err)
})
)
return response
},
}
Vercel documents that Promises passed to waitUntil() share the function timeout and are cancelled if the function times out. This is the same constraint that applies to after().
Pattern 5: AWS Lambda with Deadline Headroom
Lambda does not have a universal waitUntil() equivalent for standard handlers. The safe default is to await the flush before returning, with a timeout based on how much execution time remains:
export const handler = async (event, context) => {
const start = Date.now()
try {
const result = await handleEvent(event)
metrics.counter("lambda.invocations", 1, {
function: context.functionName,
outcome: "success",
})
return result
} catch (err) {
metrics.counter("lambda.invocations", 1, {
function: context.functionName,
outcome: "error",
})
throw err
} finally {
const remainingMs = context.getRemainingTimeInMillis()
const timeoutMs = Math.max(0, Math.min(1000, remainingMs - 250))
if (timeoutMs > 0) {
await metrics.flush({ timeoutMs })
}
}
}
The context.getRemainingTimeInMillis() call lets you leave headroom so the flush does not cause a Lambda timeout. The 250ms buffer is a conservative margin; adjust based on your flush speed and Lambda timeout configuration.
Practitioners on r/aws warn against using callbackWaitsForEmptyEventLoop = false as a flush strategy. It is a Node.js Lambda event-loop behavior knob, not a lifecycle hook. AWS troubleshooting docs show how async callbacks from one invocation can resume in a future invocation after the environment freezes and thaws, leading to misattributed or orphaned work.
For post-response work on Lambda, AWS documents four options: asynchronous invocation, response streaming, Lambda extensions, and custom runtimes. Asynchronous invocation is the simplest if you need Lambda-managed retries. Extensions can send telemetry without blocking the response but add cold-start overhead, which practitioners on Hacker News have debated at length.
To explore client-side flush configuration in detail, see how to configure buffering and flush behavior in the JavaScript client.
The Flush Reliability Ladder
The word “reliably” does real work in this topic. Not all flush strategies offer the same guarantees. Here is a practical framework for choosing the right level.
| Level | Pattern | Blocks Response? | Reliability | Best For |
|---|---|---|---|---|
| 0 | Naked fire-and-forget: metrics.flush() |
No | Unreliable. Work can be dropped or misattributed. | Never use deliberately. |
| 1 | await metrics.flush() before return |
Yes | Good, if network succeeds before timeout. | Lambda, any runtime without lifecycle hooks. |
| 2 | ctx.waitUntil(metrics.flush()) |
No | Good within provider timeout (30s on Cloudflare). | Cloudflare Workers operational metrics. |
| 3 | after(async () => metrics.flush()) |
No | Good within max duration. | Next.js 15.1+ on Vercel. |
| 4 | Durable handoff: SQS, EventBridge, async invocation | No | Higher. Retries and dead-letter queues possible. | Billing, audit logs, compliance events. |
| 5 | Telemetry extension or sidecar | No | Strong for mature workloads. Operationally heavier. | Large teams with centralized telemetry. |
For typical operational metrics (request counts, latency histograms, error rates), levels 1 through 3 are the right choice. For business-critical events that must survive network failures, level 4 or above is the appropriate answer.
Inngest’s analysis of waitUntil() makes this point clearly: it provides a completion opportunity but does not ensure success and is not designed for durable background jobs.
If you are building your first metrics pipeline for a serverless project, the Distlang JavaScript client supports buffering and flush out of the box, designed around these patterns.
Provider Comparison Matrix
| Platform | Best Flush Pattern | Post-Response Primitive | Timeout Limit |
|---|---|---|---|
| Cloudflare Workers | ctx.waitUntil(metrics.flush()) |
ctx.waitUntil() |
30 seconds after response, shared across all calls |
| Vercel / Next.js 15.1+ | after(async () => metrics.flush()) |
after() (uses waitUntil internally) |
Platform default or configured max duration |
| Vercel non-Next.js | waitUntil(metrics.flush()) |
waitUntil() from @vercel/functions |
Shares function timeout |
| AWS Lambda | await metrics.flush() before return |
None for standard handlers | 1 to 900 seconds configurable; default is 3 seconds |
| OpenTelemetry SDKs | forceFlush() / shutdown() |
SDK-level, not platform-level | Should complete or abort within configured timeout |
The OpenTelemetry Metrics SDK spec explicitly calls out FaaS (Function as a Service) suspension as a case where ForceFlush is necessary. Some SDKs call it flush, OpenTelemetry calls it forceFlush, others expose shutdown. The name varies; the lifecycle requirement is always the same.
Hacker News discussions about OpenTelemetry in short-lived processes confirm this. Practitioners report that OTel works fine from short CLI invocations and serverless functions, but only when the SDK is cleanly shut down or force-flushed before the process exits. Skip that step and telemetry silently vanishes.
What “Reliable” Does and Does Not Mean
Precision matters here. Claiming waitUntil() “guarantees delivery” would be wrong.
Reliable flushing does mean:
- The runtime has been told about the flush work.
- The flush Promise is awaited or registered with a lifecycle primitive.
- The code catches errors and respects timeouts.
Reliable flushing does not mean:
- Guaranteed delivery through network failure.
- Automatic retries unless a queue or async invocation provides them.
- Permission to run long background jobs inside
waitUntil().
Both Cloudflare and Vercel document hard timeout boundaries for post-response work. If the downstream metrics endpoint is unreachable, the flush will fail regardless of the lifecycle hook. For events that absolutely cannot be lost, a durable queue is the right tool.
If metrics are going missing even with the right flush pattern, the debugging missing metrics guide covers common ingestion failure modes.
When to Use a Queue Instead of Flushing from the Handler
| Data Type | Example | Recommended Pattern |
|---|---|---|
| Operational metric | Request count, latency histogram, error rate | waitUntil() / after() / short await flush() |
| Debug telemetry | Trace span, structured log | Lifecycle hook or exporter flush |
| Business-critical event | Purchase completed, invoice generated, audit record | Durable queue or database write |
| Long-running work | Email with retries, webhook fanout | Queue or workflow system |
| Oversized payload | Huge metric batch, slow collector | Reduce batch size or queue |
The dividing line is simple: if losing the data means a business consequence (wrong invoice, missing audit trail, compliance violation), do not rely solely on a lifecycle hook. Queue the event. If losing an occasional latency data point is tolerable, waitUntil() or after() is a good trade-off between reliability and response speed.
For common mistakes when setting up serverless instrumentation, see pitfalls when instrumenting serverless handlers.
Metric Design Still Matters
A reliable flush path cannot save a bad metric design. If the payload is enormous or the labels are unbounded, the flush may exceed the platform’s deadline even when the lifecycle is correct.
OpenTelemetry explains that metric cardinality (the number of unique attribute combinations per metric) determines how much memory the SDK uses. High-cardinality attributes like raw user IDs, session tokens, or full URL paths cause unbounded memory growth. The default OpenTelemetry cardinality limit is 2,000 attribute combinations per metric stream.
Practical rules:
- Use route templates (
/api/users/:id) instead of raw paths (/api/users/12345). - Avoid user IDs, request IDs, or timestamps as metric labels.
- Prefer histograms for latency distributions over emitting one event per request.
- Keep flush payloads small enough to complete within the platform’s deadline.
A smaller, well-designed metric batch flushes faster and fits comfortably within tight serverless time limits. For a complete guide to label design, see low-cardinality label strategies.
Reliable Metrics Flush Checklist
Use this as a quick reference when instrumenting serverless handlers:
- Do not leave
flush()as a floating Promise. - If the response depends on the metric work,
awaitit. - If the work is non-critical and the platform supports it, use
ctx.waitUntil(),waitUntil(), orafter(). - Attach
.catch()to background flush Promises so failures are visible in logs. - Keep the flush bounded with a timeout.
- Leave deadline headroom in AWS Lambda using
context.getRemainingTimeInMillis(). - Use a queue for must-not-lose events.
- Keep metric labels low-cardinality.
- Flush once near the end of the handler, not after every increment.
- Test by injecting a slow or failing metrics endpoint and verifying the handler still returns correctly.
- Enable a no-floating-promises lint rule. Cloudflare specifically recommends linting for floating Promises in Workers projects.
FAQ
Should metrics flushing block the response?
Usually no, if the platform gives you a post-response primitive. Use ctx.waitUntil() on Cloudflare Workers or after() on Vercel so the response returns quickly while the flush completes in the invocation lifecycle. If no lifecycle primitive is available (like standard AWS Lambda handlers), a short awaited flush before returning is the safest option.
Is waitUntil() reliable enough for metrics?
For normal operational metrics, yes, as long as the flush is short, errors are caught, and losing an occasional data point is acceptable. For billing records, audit logs, payment events, or anything that must survive network failure, no. Use a durable queue because waitUntil() has timeout limits and does not provide retries.
If I call flush(), isn’t that enough?
No. Calling flush() starts work. It does not tell the serverless runtime to keep the invocation alive. The returned Promise must be awaited or registered with a lifecycle primitive. Without that, the runtime can freeze or terminate the isolate before the flush HTTP request completes.
Can I rely on the next warm invocation to finish old telemetry work?
No. That is exactly the behavior that causes misattributed data. Vercel documents that orphaned async work can complete during a later request and appear under the wrong request context. AWS documents that callbacks from one invocation can resume in a future invocation after the Lambda environment thaws. Both outcomes corrupt your data.
Is after() the same as waitUntil()?
Conceptually, yes, for the serverless lifecycle problem. Both schedule work after the response. In Next.js on Vercel, after() uses a waitUntil(promise) primitive under the hood. Vercel recommends after() as the preferred API for Next.js 15.1 and above.
What is the AWS Lambda equivalent of waitUntil()?
There is no direct universal equivalent for standard Lambda handlers. AWS documents that the runtime freezes after the response, and the supported ways to continue post-response work include asynchronous invocation, response streaming, Lambda extensions, and custom runtimes. For simple metric flushing, awaiting the flush before returning is the practical default.
Does Cloudflare Workers Analytics Engine need waitUntil()?
No. Cloudflare’s built-in Analytics Engine writeDataPoint() returns immediately and the Workers runtime handles the write in the background. This is a platform-specific optimization that does not apply to external metrics APIs or third-party SDKs, which still require waitUntil() for reliable delivery.
Should I flush every metric immediately?
Usually no. Immediate flush maximizes freshness but adds network overhead and defeats batching. In short-lived handlers, the practical pattern is to record metrics during the request and flush once at the end, either via a lifecycle hook or a short awaited flush. One flush per invocation, not one flush per counter increment.
Flushing metrics reliably from short-lived serverless handlers is a lifecycle contract, not just a method call. Pick the right pattern for your platform, catch errors, respect timeouts, and save queues for the events you cannot afford to lose.
If you are looking for a metrics service built around these serverless flush patterns, with a lightweight JavaScript client, counters, histograms, and an auto-generated dashboard, Distlang Metrics is designed for exactly this workflow.