Distributed systems
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 a 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.
Math
Waiting callers grow with job time
At 100 requests a second and 2 s per job, 200 callers wait at once.
Little's law says the count in the system L is the arrival rate \lambda times the time each one stays, W.
L = \lambda WSubstitute the arrival rate and the job time.
L = 100\,\text{s}^{-1} \times 2\,\text{s}The units cancel, so L is a plain count.
L = 200
Code
A queue with two slots
The queue holds jobs until a worker is free. A full queue refuses new jobs, and that refusal is backpressure.
Trade-offs
What the queue costs
You trade an immediate answer for throughput. You must also handle jobs that fail after you have returned.
| Anti-pattern | What fails | Fix |
|---|---|---|
| An unbounded queue | It hides overload until memory runs out. | Bound it and push back. |
| Side effects with no key | A retried job charges the card twice. | Send an idempotency key. |
Notes and sources
- Little, J. D. C. "A Proof for the Queuing Formula L = λW." Operations Research, 1961.