The pattern
In every serverless handler, callflush() as the last operation before returning — after all LLM calls are complete, after your response is ready, before you return.
- TypeScript
- Python
Initialize the SDK once at module level, not inside the handler function. Module-level initialization persists across warm invocations of the same container, so you avoid the overhead of re-initializing on every request.
AWS Lambda
- Set a Lambda timeout of at least
init timeout + max LLM latency + 2 secondsto give the flush time to complete - The SDK flush is a single HTTP request — it typically completes in under 500ms
- On cold starts, the SDK initializes at module load time. This adds ~10ms and happens only once per container lifecycle
Vercel Functions (App Router)
- Set
maxDurationin yourvercel.jsonor route config to account for flush time - Vercel Edge Runtime does not support
AsyncLocalStorage— use the Node.js runtime (export const runtime = "nodejs") for full trace context propagation - For streaming responses, flush after the stream is complete — the SDK captures TTFT and full token counts at stream close
Vercel Functions — streaming responses
When streaming, the flush must happen after the stream fully closes:Netlify Functions
Google Cloud Run
Cloud Run containers can be reused across requests, making it safe to initialize at module level and flush per-request.- Node.js (Express)
- Python (Flask)
- Python (FastAPI)
- Cloud Run sends
SIGTERMbefore scaling down. Callflush()per-request — don’t rely on shutdown hooks alone. - Initialize at module level so the SDK persists across warm requests on the same instance.
Reducing flush latency
If the flush adds too much latency to your handler response, consider these options: Reduce batch size so the flush completes faster (fewer events per HTTP request):waitUntil (Vercel / Cloudflare Workers only):

