0%
Concurrency and Async Programming: Threads, Locks, Event Loops, and Backpressure
Foundations
Synchronization
Asynchronous I/O
Producer Consumer and Backpressure
Producer consumer is the most common structure in concurrent software. One set of threads produces work, another consumes it, and a queue between them decouples their speeds. This section explains why the pattern is so widespread, what the queue buys, how pipelines chain stages together, and the first question every design must answer: what happens when the producer is faster than the consumer.
Decoupling through a queue
Producers and consumers rarely run at the same speed. A web server accepts requests in bursts, while a database writes at a steady rate. A log library receives records from hundreds of threads, while one thread writes them to disk. A video pipeline decodes frames faster than it can encode them on some scenes and slower on others. Connecting such components directly forces the faster one to wait for the slower one on every item, so each runs only as fast as the slowest at every moment. A queue between them lets each run at its own pace for a while: the producer appends items and moves on, the consumer takes items when it is ready, and the queue absorbs the difference. The producer does not need to know how many consumers exist or how they work, and consumers can be added, restarted or replaced without changing the producer.
This decoupling is why the pattern appears at every scale. Inside a process, it is a channel or a blocking queue between threads. Between processes on one machine, it is a pipe or a shared memory ring. Between services, it is a message broker such as Kafka, RabbitMQ or Amazon SQS. The same reasoning about rates, buffer sizes and what happens when the buffer fills applies at every level, and lessons learned at one scale transfer directly to the others.
The blocking queue
The simplest correct implementation of a bounded queue between threads is a buffer protected by a mutex with two condition variables, not full and not empty, as built in the condition variables lesson. Put waits on not full while the buffer is full, appends, and signals not empty. Take waits on not empty while the buffer is empty, removes, and signals not full. Every platform provides this ready made. Java has ArrayBlockingQueue, a bounded array with one lock, LinkedBlockingQueue, with separate locks for the two ends and an optional bound, and SynchronousQueue, which has no capacity and hands each item directly from a producer to a consumer. Python has queue.Queue for threads and asyncio.Queue for coroutines, both with an optional maxsize. Go has buffered channels. C++ has no standard blocking queue, but most codebases use one from a library or a short wrapper around std::deque and std::condition_variable.
Blocking queues also usually offer non blocking and timed variants. Java offer returns false immediately when full, and offer with a timeout waits for at most that long; poll does the same for take. These variants are what make it possible to implement policies other than waiting forever, such as dropping, rejecting or degrading, discussed later in this lesson.
Pipelines of stages
Complex processing is often expressed as a pipeline of stages connected by queues. A log ingestion pipeline might read raw lines, parse them, enrich them with metadata, batch them and write them to storage, each as a stage with its own threads. A video service might fetch, decode, transform, encode and upload. Each stage can be scaled independently by giving it more workers, and each queue between stages absorbs short variations in speed. The throughput of the whole pipeline is limited by its slowest stage, the bottleneck, and adding workers anywhere else does nothing except fill the queue in front of the bottleneck faster.
When the producer is faster
Every producer consumer design must answer one question: what happens when items arrive faster than they are consumed for longer than the queue can absorb? Over a long enough period, the average arrival rate must not exceed the average service rate, or the queue grows without bound. A queue only smooths out bursts; it does not create capacity. When arrivals exceed capacity, there are only three things a system can do. It can slow the producer down, which is backpressure. It can drop or reject some of the work, which is load shedding. Or it can buffer without limit, which delays the failure until memory runs out and makes every item late in the meantime. The rest of this lesson is about choosing deliberately among the first two, because the third is a choice too, just a bad one made by default.
Measuring a queue
A queue that is never observed hides problems until they become outages. Three measurements tell most of the story. The queue length, sampled regularly, shows whether the queue is usually near empty, which is healthy, or persistently growing, which means the consumer cannot keep up. The time items spend in the queue, measured from enqueue to dequeue, shows how much latency the queue adds, and is often more meaningful than length, because a queue of ten slow items can be worse than a queue of a thousand fast ones. And the rates of enqueue, dequeue and rejection show whether the system is in balance. A dashboard with these three for each queue in a pipeline points straight at the bottleneck during an incident.
Choosing the number of consumers
Once a queue sits between two stages, the number of consumers becomes a tuning knob. For CPU bound consumers, the useful number is close to the number of cores available to that stage, since more threads only add context switches. For consumers that wait on I/O, such as a database or a remote API, more consumers keep more requests in flight, and Little law, covered later in this lesson, gives the number needed: the target rate multiplied by the latency of each call. Beyond that point, adding consumers moves the bottleneck into the dependency, which then slows down for everyone. A good practice is to make the consumer count configurable, measure queue wait and consumer utilization under realistic load, and increase the count only while throughput rises and the dependency latency stays flat.
Single producer and multiple producer queues
The number of producers and consumers also shapes the queue implementation. A queue with one producer and one consumer can be built without locks, using a ring buffer with separate head and tail counters, as described in the lock free lesson, and is the fastest possible handoff between two threads. Multiple producers with one consumer is the common shape of logging libraries and actor mailboxes, and also has efficient lock free designs. Multiple producers and multiple consumers is the general case, usually built with a lock or with more complex lock free algorithms. Choosing the most restrictive shape that fits the design gives the best performance, but it also creates an invariant that future code must respect: a second producer added to a single producer queue causes subtle corruption rather than a clear error, so such queues should be wrapped and documented.
Queues hide failures
A queue that absorbs a slow consumer also delays the moment anyone notices the consumer is slow. Without a queue, a stalled database shows up immediately as failing requests; with a large queue, requests are accepted and seem fine for minutes, then all fail together when the queue fills or their deadlines expire. This is one reason to prefer small queues in request paths and to alert on queue wait time rather than on errors alone. Large durable queues still belong in asynchronous workflows, where delay is acceptable, but even there, consumer lag should be a first class alert.
Put a queue between producers and consumers to decouple their speeds and let each side scale independently. Throughput is set by the slowest stage. When arrivals exceed capacity for longer than the queue absorbs, the only choices are backpressure, shedding or unbounded growth, so choose one deliberately and measure queue length, wait time and rates.