BackgroundDispatcher
The BackgroundDispatcher class batches outbound transmissions for efficient processing. It's ideal for logging and analytics calls to external services where you don't need 1:1 transmission with incoming requests. The dispatcher groups entries and invokes your callback with batches at regular intervals.
Beta Feature
This component is in Beta - please use with care and provide feedback to the team if you encounter any issues.
Constructor
ts
Creates a new background dispatcher instance.
dispatchFunction
- Async function called with batched entriesoptions.msDelay
- Milliseconds between dispatch calls (required, non-zero)T
- The type of entries being batched
Methods
enqueue
Adds an entry to the batch queue for later dispatch.
ts
Example
ts
The dispatcher invokes the dispatch function with batched records at most every 'n' milliseconds (as configured) when items are enqueued. If no items are enqueued, the function won't be invoked.
:::tip There are no automatic retries for failed dispatch functions. Implement retry logic in your dispatch function if needed. :::
Best Practices
Module-Level Initialization
Initialize the dispatcher at the module level so it can be shared across multiple requests:
ts
Choosing the Right Delay
The longer the delay, the larger your batches will get and the less frequently you'll send batched information. However, on a busy server this could build up a lot of memory and potentially cause an OOM (out-of-memory) situation.
The shorter the delay, the more frequently you'll send smaller batches. We typically recommend 10ms for very high traffic gateways and 100ms for lower traffic gateways.