awesome-everything RU
↑ Back to the climb

Backend Architecture

Backpressure and bounded concurrency

Crux Async makes it easy to start more work than the system can finish, and the loop will not stop you. Backpressure lets a fast producer feel a slow consumer; bounded concurrency caps how many run at once. Without them, unbounded fan-out becomes OOM and overloaded downstreams.
Your altitude — climbing toward senior
ZeroJuniorMiddleSenior
You are at senior altitude — in orbit
◷ 16 min

A migration script reads a million user IDs and “for each, fetch the profile and upsert it.” Written the obvious async way — await Promise.all(ids.map(processUser)) — it launches a million concurrent operations in the same instant. The database opens connections until it refuses, memory climbs as a million pending promises and their closures pile up, and the process is OOM-killed before the first thousand finish. The code was correct. The concurrency was unbounded, and an event loop will happily start infinite work it can never finish.

The loop will not stop you

The event loop’s gift — start thousands of operations cheaply — is also a loaded gun. Nothing in Promise.all(items.map(fn)) limits how many fns are in flight; it starts all of them, immediately. For ten items that is fine. For a million it is a self-inflicted denial of service: every in-flight operation holds memory (buffers, closures, a pending promise), and every one hammers whatever it calls. Two distinct disciplines tame this: backpressure (let a slow consumer push back on a fast producer) and bounded concurrency (cap how many operations run at once). They solve the same disease — producing faster than you consume — at different layers.

Backpressure: the consumer pushes back

Backpressure is a feedback signal from a slow consumer to a fast producer: “stop sending, I’m full.” Node streams have it built in. When you writable.write(chunk) and the internal buffer exceeds the highWaterMark (default 16 KB for byte streams, 16 objects in object mode), write() returns false — your cue to stop writing until the stream emits a drain event signaling the buffer has emptied. Honor that signal and memory stays bounded; ignore it and Node keeps buffering every chunk in memory until the process OOMs.

The reason pipe() and pipeline() are the recommended way to connect streams is that they wire this handshake automatically — pausing the readable when the writable is full, resuming on drain — so a 50 GB file copies through a few hundred KB of live buffer instead of loading whole. Manual read/write loops that skip the false/drain dance are the classic source of streaming OOMs.

Why this works

Why is highWaterMark a threshold and not a hard cap? It is the line at which the stream starts saying “false” — backpressure is advisory, not enforced. A single write() of a 10 MB chunk still buffers all 10 MB even though the mark is 16 KB; the mark only governs when the stream signals fullness, not how much a given write may add. This matters because backpressure protects you only if you check the return value and wait for drain. Code that calls write() in a tight loop ignoring the boolean defeats the entire mechanism — the buffer grows without bound regardless of the high-water mark. The mark is a politeness signal between cooperating parties; it does nothing for code that does not listen.

Bounded concurrency: cap the fan-out

Streams handle the byte-pipeline case. The other case is N independent async tasks — fetch these 10,000 URLs, process these million rows — where the fix is a concurrency limit: run at most k at a time, and as each finishes, start the next. The migration above becomes safe by replacing Promise.all(ids.map(fn)) with a limiter (e.g. p-limit(20)) so only 20 operations are ever in flight, or by using a worker-pool/for await pattern that pulls from the list as capacity frees up.

The numbers make the case: a sequential for...of await loop and a bounded Promise.all can differ by orders of magnitude in wall time (one benchmark: ~30 s sequential vs ~340 ms concurrent), but unbounded concurrency does not beat bounded — past the point your downstream can absorb, extra in-flight work only adds queueing, memory, and failures. The sweet spot is the largest k the downstream tolerates, not infinity. That k is usually set by the downstream’s own limit: a connection pool of 20, an API rate limit, a disk’s IOPS.

Three regimes, one decision

Picture the spectrum. Sequential (await in a loop) is one-at-a-time: safe, slow, no pressure on anything. Unbounded (Promise.all over a huge list) is all-at-once: fast to start, catastrophic at scale. Bounded (limit k) is the production answer: fast enough, predictable memory, downstream-respecting. The senior reflex on seeing Promise.all(bigArray.map(...)) is immediate: what bounds this? If the array size is attacker- or data-controlled, unbounded Promise.all is a latent outage.

PatternIn flightSpeedRisk
Sequential for await1SlowestNone, but wastes idle capacity
Unbounded Promise.all(map)All NFast start, then collapseOOM, downstream overload
Bounded (limit k)At most kFast and stableTune k to downstream limit
Stream pipeline()~highWaterMarkSteadyMust not bypass backpressure
Quiz

`await Promise.all(millionIds.map(processUser))` OOM-kills the process. What actually went wrong?

Quiz

In a Node stream, `writable.write(chunk)` returns `false`. What does that signal and what should you do?

Quiz

What usually sets the right concurrency limit *k* for a bounded fan-out of async tasks?

Recall before you leave
  1. 01
    Why does Promise.all over a huge array cause an outage, and what is the fix?
  2. 02
    How does Node stream backpressure work, and why are pipe/pipeline preferred over manual loops?
  3. 03
    Compare sequential, unbounded, and bounded concurrency and explain how to choose k.
Recap

The same cheapness that lets an event loop start thousands of operations also lets it start work it can never finish, and it will not stop you — Promise.all over a million-item array launches a million operations at once and OOM-kills the process while hammering every downstream. Two disciplines match production speed to consumption speed. Backpressure is the consumer pushing back on the producer: a stream write returns false past the highWaterMark (16 KB or 16 objects), and you must wait for drain, which pipe and pipeline do automatically so enormous files flow through tiny live buffers; the high-water mark is only a signal threshold, so code that ignores the boolean defeats it entirely. Bounded concurrency caps independent tasks at k in flight, replacing the unbounded fan-out with a limiter or worker pool, where k is set by what the downstream can absorb — a pool of 20, an API rate limit, disk IOPS — because beyond that, more concurrency buys only queueing and failure. Sequential is safe but slow, unbounded is fast then catastrophic, bounded is the answer. With work shed off the loop and inflow throttled to capacity, the final lesson zooms out to the whole system under load: how queueing makes tail latency explode near saturation, and why one loop is one core.

Connected lessons
appears again in185
Continue the climb ↑Throughput under load: tail latency and saturation
shortcuts expand
search
K
prev piece
k
next piece
j
cycle tier
t
this menu
?
sources3
expand
  1. 01
  2. 02
  3. 03

Trademarks belong to their respective owners. Editorial reference only.