Skip to main content

Overview

EventBatcher buffers events in memory and flushes them automatically — either when the buffer fills up or after a configurable idle timeout. Use it instead of calling event() per-action in high-frequency contexts like API middleware, webhooks, or background jobs.

Create a batcher

Signature

BatcherOptions

number
Flush the buffer after this many milliseconds of inactivity. Default: 5000. The timer resets on every push(). Must be a positive finite number.
number
Flush immediately when the buffer reaches this size. Default: 100. Must be between 1 and 500.
(count: number) => void
Optional callback called after each successful flush. Receives the number of events flushed.
(err: unknown) => void
Optional callback called when a flush fails. Use this to log errors without crashing.

EventBatcher interface

push(event)

Adds an event to the buffer. Triggers an immediate flush if maxSize is reached.
Calling push() after destroy() throws a ChurnKitError with code VALIDATION_ERROR.

flush()

Immediately flushes all buffered events. Returns the number of events sent.

destroy()

Flushes remaining events, cancels the flush timer, and permanently closes the batcher. Call this on process shutdown or component unmount.

Examples

Express middleware

Next.js App Router middleware

With error handling

Serverless (flush at end of request)

In serverless environments where timers don’t persist, flush manually at the end of each handler: