download

How does backpressure stop a fast producer from OOM-killing a service?

Systems~12 minReviewed 2 Dec 2026Free · No sign-in

Question

A log collector reads 5,000 events per second (2 KiB each) from a TCP socket and pushes them into an unbounded in-memory queue (mpsc::channel). The disk writer drains 1,000 events per second. The container has a 512 MiB RAM limit.

  1. How fast does the queue grow, and roughly how long until it hits 512 MiB?
  2. How does a bounded channel (sync_channel) apply backpressure, and how does TCP pass that slowdown upstream?
  3. What should you do when blocking the producer is not acceptable?
Show hints (3)
  1. "QUEUE GROWTH RATE"

    Subtract the drain rate from the arrival rate, then multiply by 2 KiB per event. Divide 512 MiB (524,288 KiB) by that rate.

  2. "TRACE UPSTREAM SIGNAL"

    When the bounded queue blocks the reader thread, who stops calling read() on the socket, and what happens to the kernel receive buffer?

  3. "WHEN BLOCKING HURTS"

    If upstream cannot pause (live telemetry or UI), use a non-blocking send and choose an explicit overload policy.

Show checked explanation

The queue grows by 4,000 events per second (8,000 KiB/s, about 7.8 MiB/s), hitting 512 MiB in roughly 66 seconds. Replacing the unbounded queue with a bounded channel (sync_channel) caps memory and blocks the reader thread, letting the TCP receive buffer fill so TCP advertises a zero receive window upstream. If you cannot block, shed load with try_send.

"SOLUTION · RUST"
use std::sync::mpsc::{sync_channel, TrySendError};
use std::thread;

fn main() {
    let (tx, rx) = sync_channel(2);
    tx.send(1).unwrap();
    tx.send(2).unwrap();
    let full = matches!(tx.try_send(3), Err(TrySendError::Full(3)));
    let reader = thread::spawn(move || {
        let mut sum = 0;
        for n in rx { sum += n; }
        sum
    });
    tx.send(3).unwrap();
    drop(tx);
    println!("blocked_at_cap={} sum={}", full, reader.join().unwrap());
}
"OUTPUT"
blocked_at_cap=true sum=6

Compiled and ran the Rust sync_channel bounded-capacity demo, unbounded contrast, and queue math assertions with rustc 1.94.1 and CPython 3.12.10 on Windows x64. Checked by an editor other than the author.

Walkthrough

Whenever input outpaces output, an unbounded queue turns a slow downstream into a ticking OOM crash:

  • Surplus arrival rate: 5,000 - 1,000 = 4,000 events/sec.
  • Payload growth rate: 4,000 * 2 KiB = 8,000 KiB/s (about 7.8 MiB/s, before allocator overhead).
  • Time to 512 MiB (524,288 KiB): 524,288 / 8,000 = 65.536 seconds (about 66 seconds).

A bounded queue breaks that crash loop by giving memory a hard ceiling. Capping the channel at 1,024 events limits queued payload to 2 MiB. In the code above, sync_channel(2) holds two items, rejects a third try_send(3) with TrySendError::Full(3), and makes blocking send(3) wait until the consumer drains a slot.

How backpressure travels end-to-end:

stagewhat fills upsignal pushed upstream
App pipelineBounded channel (sync_channel)send() blocks the socket reader thread
OS kernelSocket receive bufferReader stops calling read(); buffer fills
TCP (RFC 9293)Peer receive window (rwnd)Receiver advertises rwnd = 0; sender pauses

Unix pipes work the same way (pipe(7)): once the kernel pipe buffer fills, write() blocks the producer until the reader drains bytes. In TCP, the sender periodically sends zero-window probes so transmission resumes as soon as space opens.

When blocking is unacceptable. Real-time audio, live metrics, or a shared ingress serving healthy tenants cannot pause. Call try_send and shed load explicitly: drop oldest or newest events, sample, spill to disk, or return HTTP 429 or 503 fast.

Common mistakes

  • Thinking a huge queue (like 10 million slots) solves sustained overload. A bigger buffer only absorbs short bursts; when input stays faster than output, it just delays OOM and spikes tail latency.
  • Catching Full by spawning a new thread or pushing to a fallback Vec. That silently recreates an unbounded queue and still OOM-kills the process.
  • Applying backpressure on one slow downstream without isolating tenants. Blocking a shared socket reader can stall healthy streams sharing that same connection (head-of-line blocking).
  • Forgetting to drop all sender clones (tx) when shutting down. The consumer's for n in rx loop blocks forever if even one unused Sender stays alive.

Follow-up questions

  • "How do you size a bounded queue in production?" Size it for expected short bursts and acceptable tail latency, not for sustained overload. Check both memory (capacity * max_item_bytes) and max wait time (capacity / consumer_rate), then measure with real burst traffic.
  • "What happens in TCP if the packet announcing the reopened receive window gets lost?" RFC 9293 requires zero-window probing. While the peer's advertised window is zero, the sender periodically sends a small probe segment. The receiver replies with its current window size, avoiding a permanent stall.
  • "Does UDP give you automatic network backpressure like TCP?" No. UDP has no receive window or flow control. When the receiver's socket buffer fills, the kernel silently drops incoming datagrams unless your application protocol adds its own credits or rate limits.

What a strong answer covers

Calculates the 66-second OOM window and caps RAM with a bounded channel. Traces backpressure through the socket buffer to TCP's zero receive window, and names load shedding when blocking does not fit.

Open in interactive practice deck →

Original OfferVibe question. std::sync::mpsc::sync_channel · RFC 9293: TCP · pipe(7).
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.