Skip to content

Feature Request: Add option to flush with pending promises #2659

@ordehi

Description

@ordehi

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:

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:

  1. Call promiseQueue.join() to wait for pending async work
  2. Then flush the queue as normal
  3. 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

Additional context

Thank you for your feature request – we love each and every one!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions