Skip to content

Batcher

Batcher<K, E, V> = object

Defined in: Core/Batcher.ts:32

A microtask-coalescing request demultiplexer that batches concurrent single-key lookups into a single bulk query to eliminate N+1 query loops.

Unlike traditional cache-bound loaders, Batcher is stateless across execution turns: once a batch resolves and its callers settle, its pending queue clears. This allows Batcher instances to live safely as long-lived application singletons without memory leaks or cross-request stale state.

const userBatcher = Batcher.make({
  fetch: (ids: readonly string[]) =>
    pipe(
      db.users.findMany({ where: { id: { in: ids } } }),
      Task.Result.map(Arr.indexBy((u) => u.id)),
    ),
  maxBatchSize: 100,
});

// Resolves to a first-class tri-state outcome:
const outcome = await userBatcher.load("u_1");

K

E

V

readonly flush: () => Deferred<void>

Defined in: Core/Batcher.ts:65

Immediately flushes and settles all currently queued batches without waiting for the microtask tick or window timer to elapse.

Primarily used in unit tests or before transaction boundaries to guarantee deterministic batch execution.

Deferred<void>

Batcher.load to enqueue individual lookups.


readonly load: (key, signal?) => Deferred<Outcome<E, V, K>>

Defined in: Core/Batcher.ts:41

Immediately coalesces the given key into the active batch window and returns an eager Deferred resolving to a tri-state Batcher.Outcome<E, V, K>.

K

The key to look up.

AbortSignal

Optional AbortSignal to cancel this individual caller’s lookup.

Deferred<Outcome<E, V, K>>

Batcher.loadMany to coalesce multiple keys in a single call.


readonly loadMany: (keys, signal?) => Deferred<readonly Outcome<E, V, K>[]>

Defined in: Core/Batcher.ts:54

Immediately coalesces multiple keys into the batch window and returns their resolved outcomes in order.

Does not short-circuit: preserves discrete per-key outcomes (Ok, Missing, or Err) for each requested key.

readonly K[]

The collection of keys to look up.

AbortSignal

Optional AbortSignal to cancel this caller’s lookup batch.

Deferred<readonly Outcome<E, V, K>[]>

Batcher.load to look up an individual key.