flushPendingEvents resolves once every buffered event is either delivered or deliberately dropped (and reported through onError). It rejects only when a transient delivery failure leaves events buffered, so you can decide how to handle loss at shutdown:
Create the
Carbon instance and wrap your client once at module scope, not
per request — the buffer and its background delivery are shared across the
warm invocations that reuse the same instance.Flush after the response
Awaiting the flush before you return delays the response by however long delivery takes. On platforms that can keep the function alive past the response, schedule the flush as post-response work instead — the user gets their response immediately and events still drain before the runtime freezes.- Next.js
- Vercel Functions
- AWS Lambda
- Cloudflare Workers
Next.js
after runs a callback once the response has finished streaming, without blocking it:Why an explicit flush is needed
By default a buffered batch is sent when it reaches 50 events or after it has waited 5 seconds, whichever comes first. A serverless invocation usually handles a single request and returns in well under 5 seconds, so neither threshold is reached before the runtime freezes — the explicit flush is what forces delivery. You can tune these thresholds —bufferBatchSize, bufferMaxTimeMs, and the rest — but in a short-lived function flushing before exit is the reliable guarantee. See Configuration for the full set of buffering options and delivery semantics.
Long-running servers
Persistent processes — a Node server, a container — drain the buffer continuously as it fills, so no per-request flush is needed. CallflushPendingEvents only on graceful shutdown, so events captured just before exit are delivered: