-
Notifications
You must be signed in to change notification settings - Fork 213
Description
Is your feature request related to a problem?
When using captureException() in serverless environments like AWS Lambda with warm containers, there's no clean way to flush exception events without calling shutdown().
The issue: captureException() builds events asynchronously via addPendingPromise(), but flush() only flushes what's already queued, it doesn't wait for pending promises. shutdown() works because it calls promiseQueue.join() first, but this implies teardown semantics when you just want to ensure events are sent.
This affects any async operation tracked via addPendingPromise(), including:
captureException()(issuecaptureExceptiondoesn't get flushed, which breaks exception autocapture on fatal errors #2220)capture({ sendFeatureFlags: true })
Current workaround:
await posthog.shutdown()
posthog = new PostHog(apiKey, { flushAt: 1, flushInterval: 0 })This works but requires re-initialization when the container is kept warm for multiple requests.
Describe the solution you'd like
Add an option to flush() to wait for pending promises:
await posthog.flush({ waitForPending: true })Or add a dedicated method:
await posthog.flushWithPending()This would:
- Call
promiseQueue.join()to wait for pending async work - Then flush the queue as normal
- Keep the client alive for subsequent operations
Describe alternatives you've considered
Alternative 1: Access internal API (fragile)
// @ts-ignore
await posthog.promiseQueue?.join()
await posthog.flush()Alternative 2: Time-based delay (unreliable)
await new Promise(r => setTimeout(r, 100))
await posthog.flush()Alternative 3: Use shutdown() and re-initialize (current workaround)
None of these are as clean as having a proper API for flushing with pending promises.
Additional context
From: https://posthoghelp.zendesk.com/agent/tickets/43781
Related sub-libraries
- All of them
- posthog-js (web)
- posthog-js-lite (web lite)
- posthog-node
- posthog-react-native
- @posthog/react
- @posthog/ai
- @posthog/nextjs-config
- @posthog/nuxt
- @posthog/rollup-plugin
- @posthog/webpack-plugin