Work Queues
A work queue lets producers hand off jobs and keep going. Workers take the jobs at their own pace, so a slow job never blocks the caller.
Map · the whole pipeline
Producer, queue, workers, result store
- The producer enqueues a job and returns at once.
- Each idle worker takes the next job. The queue holds the rest.
- A worker writes the result. Other services read it from the store.
The idea in five steps
- One lineA queue separates who asks for work from who does it.Read →
- WhyA caller that waits for slow work stalls whenever the work is slow.Read →
- MechanismWorkers pull jobs, and the queue buffers bursts.Read →
- Trade-offYou gain throughput and lose an immediate answer.Read →
- PrincipleIt is a bounded buffer between two clocks, like a Go channel.Read →
A slow job blocks its caller
If each caller waits for a 2-second job, 100 requests a second keep 200 callers waiting.
Each waiting caller holds a thread and a connection. So the load you can serve falls as the jobs get slower. Little's law gives the count: L = \lambda W, jobs in flight equal the arrival rate times the wait.
Arrivals stay at 100 a second, and the job time doubles to 4 s. How many callers wait at once?
A buffer between two clocks
The producer runs on its clock, and the workers run on theirs. The queue absorbs the difference.
Producers enqueue 120 jobs a second. Two workers finish 50 a second each. What happens to the queue?
Work queue
Producers enqueue, and a fixed pool of workers dequeues. A full queue pushes back on producers.
Counterpart
jobs := make(chan Job, 100) // the queue
for w := 0; w < 2; w++ {
go func() { for j := range jobs { run(j) } }()
}
jobs <- j // blocks when the buffer is fullIn the Go version, what happens when all 100 buffer slots are full?
What the queue costs
You trade an immediate answer for throughput. You must also handle jobs that fail after you have returned.
Anti-patterns
- An unbounded queue. It hides overload until memory runs out. Bound it and push back.
- Side effects without an idempotency key. A retried job charges the card twice.
A worker crashes after it charges a card but before it acknowledges the job. What prevents a second charge on retry?
Notes and sources
- Little, J. D. C. "A Proof for the Queuing Formula L = λW." Operations Research, 1961.
- The Go Programming Language Specification, "Channel types".
- Kleppmann, M. Designing Data-Intensive Applications. O'Reilly, 2017.