Fan-Out / Fan-In Batch Processing and Backpressure Without Overloading Downstream APIs
Imagine dispatching a campaign to 50,000 opted-in customers. Spawning 50,000 child tasks simultaneously inside a single Promise.all blows worker RAM, exhausts database connection pools, and trips provider rate limits in under two seconds. Controlled chunked fan-out with backpressure turns massive batches into calm, predictable throughput.
Bounded Concurrency vs Unbounded Fan-Out
| Pattern | Memory Footprint | Failure Blast Radius | Recommended Max Batch Size |
|---|---|---|---|
Naive Promise.all(items) | O(N) unbounded | Catastrophic | Never for N > 50 |
| Chunked Paged Waves | O(pageSize) constant | Isolated to 1 chunk | 100 to 500 per wave |
| Worker Pool + Semaphore | O(concurrency) constant | Per-item retry + breaker | 5 to 25 concurrent per sender |
Keyset Pagination Over Offset Pagination
When iterating through 50,000 queued recipients across waves, never use OFFSET 40000 LIMIT 200 (which scans and discards 40,000 rows on every wave and skips rows if earlier items mutate). Use keyset pagination (WHERE id > $lastId ORDER BY id ASC LIMIT 200) for constant O(log N) index lookups.
export async function runWithConcurrencyLimit<T, R>(
items: readonly T[],
concurrency: number,
worker: (item: T) => Promise<R>
): Promise<R[]> {
const results = new Array<R>(items.length);
let cursor = 0;
async function consume(): Promise<void> {
while (cursor < items.length) {
const idx = cursor++;
results[idx] = await worker(items[idx]);
}
}
const slots = Array.from({ length: Math.min(concurrency, items.length) }, consume);
await Promise.all(slots);
return results;
}
Fair Scheduling Across Multi-Tenant Batches
If Tenant A enqueues 100,000 outbound messages and Tenant B enqueues 20 transactional order confirmations, a single FIFO queue starves Tenant B for an hour. Isolate interactive/transactional traffic onto a dedicated high-priority task queue separate from bulk batch traffic, and cap per-tenant active concurrency so one noisy neighbor never monopolizes shared worker capacity.
Next: deploy new workflow code while thousands of long-running workflows are mid-flight in Safe Workflow Versioning.