Part 1 of 2 · Fair Scheduling Across Queues with Deficit-Weighted Round Robin (DWRR)
Fair Scheduling Across Queues: Taking Turns
What fair means when several queues share one consumer, and how to check that an implementation agrees.
An MPEG transport stream is a sequence of 188-byte packets.1 Each packet contains data or metadata. The data can be video, audio, captions, or even application data. The metadata can tell us things like which packets belong to which programs. In order to play a program, we need to find all the packets associated with the program and deliver them out to a device like a receiver. Taking a stream apart is mostly bookkeeping.
Putting streams back together is more challenging. We need to take each of the individual streams and combine them back together, interleaved, carefully timed, packed tight to make good use of bandwidth. We have to recreate metadata to define the programs and timing.
We have a project to do just this: disassemble and then reassemble the programs into different transport streams containing different sets of programs. We can have one or more streams coming in, and one or more streams going out. The tricky part is remixing those streams.
In order to reassemble the outgoing streams, we take the incoming packets and match them up to programs. Then, a part of the program that starts putting outgoing streams together can pick packets from programs it needs for each stream.
Outgoing streams have to interleave their programs. Without that, we could have long stretches of packets for one program, and no packets for any other. A device that wants to play any of the other programs won’t have anything to play. So an important part of our task is choosing what packets to send next. We need to take turns.
Whose turn is it?
The question isn’t specific to video. It shows up whenever several producers share one consumer: tenants sharing a job runner, users sharing a rate-limited API, requests sharing a model server. The answers that come to mind first each fail in their own way.
First in, first out serves work in the order it arrived. When one producer sends a burst, everything else waits behind it.
Strict priority serves the most important queue whenever it has work. A busy high-priority queue can keep the others waiting indefinitely.
Round robin takes turns: one item from each queue that has something waiting, then around again.
Round robin seems fair. Every program gets the same number of packets, and since MPEG-TS packets are all the same size, each gets an equal share of the bandwidth.
But programs don’t need equal shares. One program might need four times as much bandwidth as another. Their needs can change over time, too. And the outgoing stream has to make room for metadata describing its programs while keeping everything properly timed.
Weighted round robin gets us closer. We can give one program four turns for every turn another program gets. But a fixed pattern of turns isn’t ideal when some queues temporarily run empty, others have plenty of data waiting, and the shares we want don’t divide neatly into whole packets.
What if, instead of just counting turns, we kept track of how much each program was entitled to send? Each time around, we could add to its allowance. Sending a packet would use some of that allowance. If there wasn’t enough left for another packet, we could save the remainder for the next round.
That’s deficit weighted round robin, or DWRR. Each queue earns credit according to its weight, spends that credit as it sends data, and carries unused credit forward while it has work waiting. Empty queues step aside so the others can continue.
It doesn’t solve every timing problem in a transport stream. But it gives us a straightforward way to decide which program gets the next opportunity to send.
Turns measured in work
Deficit round robin keeps the turns and changes what a turn means.2 Each queue gets a running total of how much work we want from it, called its deficit. When a queue’s turn begins, it increments that deficit by its quantum. It then serves items from the front of its queue for as long as its deficit covers the next item’s cost, subtracting the cost of each item as it goes. When the next item is more than the deficit, its turn ends.
Consider two queues with quanta of 250 and 500 bytes. Every work item costs 75 bytes. In the first round, the first queue sends three packets and carries 25 bytes of deficit forward. The second sends six packets and carries 50 bytes forward. In the next round, the first program sends three again, while the second sends seven. Each queue lowers its deficit based on the weight of work it sent. As long as both have packets waiting, the second program gets twice the bandwidth of the first over time.
Different quanta give us different shares of the bandwidth. Carrying deficit forward lets us honor those shares without rounding away the difference on every turn. That’s deficit weighted round robin, or DWRR.
Costs don’t have to be bytes. They can be tokens, estimated work time, or simply 1 per item, which gives us a packet-counting scheduler again. In my muxer, I use a cost function based on a deadline—the decoding timestamp, or DTS—and the number of packets waiting. DTS says when encoded data needs to be decoded; it isn’t itself a clock. The scheduler never needs to know what the costs mean. It only needs them to be measured in the same unit as the quanta.
The missing rules
Deficit weighted round robin is a simple algorithm, but that description leaves some important decisions unresolved. An implementation that someone else can depend on needs answers to questions like these:
If a queue’s weight changes in the middle of its turn, does the change apply now or at its next turn? What happens to the deficit it already has?
In this library, changing the weight preserves saved credit and any turn in progress. The new weight applies at the next grant. A caller asking for one item doesn’t end the turn, either: the next retrieval continues with the remaining credit, without another grant.
What happens when no queue can afford its next item this round?
If work is waiting, we proceed to later rounds until something can be served. The implementation can skip whole rounds that would serve nothing. If there’s no work at all, retrieval returns an empty result; it doesn’t wait for future arrivals.
Does an empty queue accumulate a deficit?
No. Emptying a queue resets its credit to zero. Carry-over belongs to a queue with work waiting, not an idle queue saving up a burst for later. This is separate from a late application catching up on scheduled output: the application decides what to send when it wakes, and the scheduler decides which queued item gets the next turn.
Each question has a reasonable answer, and several have more than one. Two implementations can answer them differently, both correctly describe themselves as deficit round robin, and still disagree about which item goes next.
How do we know?
A scheduler worth using has optimizations that make it harder to read than the paragraph. With numeric constants for the quanta of every busy queue, the Go implementation skips empty queues using a bitmap. When a whole round can’t afford anything, it calculates how many rounds to skip rather than spinning through them. Callable quanta are evaluated at every new grant and disable round skipping for the batch. It keeps exact credit in 64-bit integers and relies on an argument about how large that credit can grow. Each optimization is a place where the code could quietly stop meaning what the paragraph says.
Reading the code carefully helps, but I don’t want correctness to depend on how carefully someone read it. So the test suite includes a second scheduler written to be obviously right rather than fast. It visits every queue in order, one at a time, never skips anything, and is short enough to check by reading. The tests give both schedulers the same long, random sequences of operations, including weight changes and removals in the middle of a turn, and require them to agree at every step. A fuzzer generates additional sequences.
This only matters if the tests can fail. If the check that decides whether a queue can afford its next item is changed from < to <=, the differential test reports a counterexample: the sequence of operations that exposes the difference.
The reference model has a limit. An earlier rule reset credit whenever a weight changed. Repeatedly changing a waiting queue’s weight could erase its savings before it could afford an expensive head item, starving it while other queues kept working. The weight-change bug shows the limit. At the time, the reference followed the same reset-on-change rule as the implementation. The two agreed perfectly. The reference model could show that the code did what we said; it took a different question, whether a queue could go unserved, to show that we’d said the wrong thing.
The same answers in other languages
I want this scheduler in more than one language. Each port may choose different optimizations, but its observable answers must match within the shared specification.
That suggests a different arrangement from writing tests separately for each language. A shared draft specification, executable model, conformance corpus, replay tools, and protocol checker now exist. The replay tools drive each implementation through a small program in that language that reads operations and writes results, and compare those results with the corpus at every step.
The Go implementation is also checked against its own reference. Go, Elixir, and Python implementations are now released. Their APIs and extensions differ: the shared contract covers fixed quanta, not every language-specific feature. The series index links the implementations. A live harness that generates and fuzzes new sequences and shrinks failures is still planned. It will save each failure as a short sequence that still fails, so a bug found through one implementation becomes a test case for all of them. The ports have to deal with problems that only appear across languages. Credit that fits exactly in a Go uint64 doesn’t fit in a JavaScript number. And each language has its own idea of who should wait for work and how.
Fairness still means taking turns. Saying what a turn is takes more work than it first appears, and a slow, obvious reference keeps the fast version faithful to what we wrote down. Whether what we wrote down is fair is a different question, and we have to ask it on purpose.