The shape
Many designs have one place that owns a shared count. It can be the token bucket behind a rate limit, the sequence that hands out ids, or the stock of seats for a concert. That place is the coordinator. The obvious design asks it on every operation, with one atomic call that checks the count and changes it. This is correct. It also puts a network round trip on every request, and it sends every one of those calls to one key on one machine.
The fix is to stop asking per operation. A process takes many units in one call, say 50 tokens or 10,000 ids, and keeps them in its own memory. It spends them one at a time without asking anyone, and takes more when they run low. Taking a block this way is leasing, and the process that has the block is the holder. While a holder has a block, nobody else can spend it. This lease grants a quantity, not ownership of a lock.
The coordinator hears from each holder once per block, and the system can be wrong by up to one block per holder. Calls fall by a factor of the block size. The error grows with the block size and with the number of holders. So pick the block from the error you can afford, and take whatever saving in calls that block gives you.
In a rate limiter, the question is whether every request has to call Redis. In an id service, it is whether every new row needs a round trip to one sequence. In a ticket system, it is whether every sale checks one global stock count. Gateways lease tokens, writers lease ranges of ids, and regions sell from their own pools of stock. They differ only in the cost of a unit left over in a holder's hands.
The mechanism
Three steps.
- Take a block in one atomic call. The coordinator changes the shared count and reports the result in the same operation, so two holders can never take the same units. For tokens, the call takes up to one block off the count, say 50, and returns how many it granted. That is fewer when the count is low. The rate limiter makes this one script call to Redis. For ids, one database statement,
UPDATE id_blocks SET next_id = next_id + 10000 WHERE name = 'links' RETURNING next_id, adds 10,000 to a counter row and returns the new value. If that value is 50,000, the holder owns 40,001 to 50,000. - Spend from memory. Each operation takes the next unit from the local block. There is no network call and no shared lock.
- Ask for more before the block runs out. Pick a low-water mark, a level at which the holder asks for more, so new units arrive before anyone needs them. For a budget, it asks only for the block size minus what it still holds, one request at a time. So it never holds more than one block. A Kafka proposal, KIP-730, suggests fetching the next block of producer ids early for the same reason.
The mark has to cover what the holder spends during one round trip, plus a margin. Each top-up moves a little less than a block, so calls run slightly above operations divided by the block. A holder that waits for an empty block makes the next request wait for the round trip.
If a top-up's reply is lost, the holder retries, and the retry must not take a second grant. So each request carries the holder's id and a refill number, and the coordinator answers a repeated number with the grant it already made.
A budget and a namespace
A budget is a quantity that gets used up, such as the tokens in a rate limit, read capacity on a table, or seats in a venue. A block comes off the shared count.
A namespace is a set of values that must never repeat, such as sequence numbers, row ids or producer ids. A block is a range kept for one holder.
The steps are the same for both. The two differ in the cost of the units a holder still has when it stops, and that cost decides how large a block can be.
For a budget, a leftover unit is allowance that nobody can use. If a holder crashes, its unspent tokens are gone: the grant already took them off the count, and the coordinator cannot tell how many were spent. The allowance comes back only as the bucket refills or the next time window starts.
A holder that is alive but quiet errs the other way. It can spend old tokens after the window that granted them, on top of the next window's allowance, until its lease expires. Either way, the error is at most one block per holder.
For a namespace, a leftover value is a gap. A holder that dies at 4,412 in the block 4,001 to 5,000 leaves 4,413 to 5,000 unissued for good. Its replacement takes the next free block, which starts at 5,001 if nobody leased in between. No value is handed out twice, so the values stay unique through every crash.
A holder that is only paused, or cut off by a partition, keeps handing out values from its old block after its replacement starts. The values stay distinct, but a sequence meant to have one owner now has two. That case needs the numbered ownership in fencing and epochs.
Two shared counts from the course, sized with the same two
lines. Calls to the coordinator are operations divided by
the block. The worst case is holders times the block.
A budget: the rate limiter's tokens
1M req/s, 200 gateways, at most 5% over the limit
calls, no leasing = 1,000,000/s
calls, block of 50 1,000,000 / 50 = 20,000/s
worst case 200 × 50 = 10,000 requests over
largest safe block 0.05 × limit / 200
limit 200,000/min 0.05 × 200,000 / 200 = 50
limit 4,000/min 0.05 × 4,000 / 200 = 1
below 4,000/min → under 1 token, no lease
A namespace: the URL shortener's counter
3,500 creations/s at peak
calls, block of 10,000 3,500 / 10,000 = 0.35/s
a crash wastes at most = 10,000 codes
share of the space 10,000 / 3.52T ≈ 0.0000003%
A leftover token is a request over the limit, or allowance a
customer cannot use. In the shortener, a leftover number is
a gap nobody sees. So the budget's block stays near what the
limit can absorb, and the shortener's block is 200 times
larger. Size each block from what its leftover costs, never
from one default.DynamoDB runs the budget version for table capacity, and its 2022 paper calls it global admission control. Each request router admits requests from a local token bucket and asks a central service for more tokens every few seconds. The tokens are time-limited, so a router runs out by spending them or by letting them expire. The central service keeps only short-lived state, and the paper says any of its servers can be restarted without affecting the service.
Databases run the namespace version. A PostgreSQL sequence with CACHE 10 hands each session 10 values at a time, and a session's unused values are lost when it ends. TiDB gives each server a batch of 30,000 auto-increment values by default, lost on a restart. A Kafka broker takes producer ids in blocks of 1,000 and keeps each block only in memory, so a restart loses the rest of it.
A namespace also gives up order. With a cache of 10, session A reserves 1 to 10 and returns 1. Session B reserves 11 to 20 and returns 11 before A returns 2. PostgreSQL's documentation gives this example, and says that with a cache above one, you can assume only that values are distinct. TiDB says the same of its default mode: values are unique, and increase only within one server.
If the block is large enough, it never runs out. Twitter's Snowflake gives each machine a configured 10-bit machine id, and puts it in every id that machine mints, so machines mint without coordinating.
The coordination has moved, not gone. Up to 1,024 machine ids must be handed out once, and the clock must be trusted. If it moves backwards, Snowflake stops minting until it passes the time of the last id.
How to tell you have this problem
Three signs say a design needs this, and two conditions rule it out.
Calls to the coordinator match your request rate. Count the calls that take from the shared count, per operation served. In Redis, INFO commandstats keeps a running calls total per command. Read the line for the lease command, which is cmdstat_evalsha if it is a script, not the total for all commands. Sample it twice and divide the rate by your request rate. A ratio near 1 means every operation pays a round trip.
The coordinator is sized for operations, not data. The rate limiter's counters fit on one node by memory and need 20 shards by throughput. If every rule can be leased, blocks of 50 turn 1 million requests a second into 20,000 calls, which one primary with a replica serves, so leasing removes the cluster.
One key carries one customer's whole load. A hot key hashes to one shard, and adding shards does not split it. A key at 200,000 requests a second with blocks of 50 makes 4,000 calls a second.
Two conditions rule leasing out. If the coordinator serves the rate with room to spare and the round trip fits the latency budget, leasing adds error for nothing. And if the decision cannot absorb one block per holder, no block is small enough. On 200 gateways with a 5 percent tolerance, that is any rate limit below about 4,000 a minute.
Traffic under those small limits still calls once per request and sets a floor. If it is 10 percent of the rate limiter's traffic, Redis handles about 118,000 calls a second rather than 20,000.
What it costs
The bound moves with the fleet. The worst case is holders times block, and the number of holders changes on its own. A limit of 200,000 a minute with a 5 percent tolerance allows 10,000 extra requests, and 200 gateways with blocks of 50 sit exactly on that bound. At 400 gateways the same block allows 20,000.
So the rate limiter pushes the instance count to every gateway, and each one works out its block from it. The count must include every instance that may still hold a block, draining ones too. A new instance starts at the smallest block until the count includes it.
If the fleet grows with traffic against a fixed limit, halving the block makes calls grow with the square of traffic. At 2 million requests a second, 400 gateways with blocks of 25 make 80,000 calls a second, against 20,000 at 1 million on 200.
Lost units cost the customer. A holder that crashes, or is stopped by a deploy, takes its unspent units with it, and the customer gets less than the limit until the bucket refills. Nothing is credited back, because crediting the whole grant would let a holder that was only paused spend it twice. A rolling deploy does this to every instance in turn, unless each one hands back its unspent tokens on a clean shutdown, as the rate limiter's gateways do.
With stock in regional pools, one region sells out while another still has stock, until the rebalancer moves some.
Gaps and lost order break readers that assume dense values. In the WhatsApp breakdown, a client that sees 4,412 and then 5,001 believes 588 messages are missing, and asks for them once per failover.
The URL shortener's range check rejects any code that decodes above its published high water mark, the highest counter value handed out. Copies of the mark can be seconds stale, so it carries a reserve larger than all the blocks writers can lease in that time. Without it, a brand-new link could get a 404.
A namespace coordinator must not forget. A budget coordinator can lose its state, as DynamoDB's is built to. If the rate limiter's Redis restarts empty, every key starts a fresh window, and the cost is a moment of extra allowance.
A namespace coordinator that loses its last value hands out a range again, and every id in it is a duplicate. So the new value must be written where a failover cannot lose it, such as a synchronously replicated database or a consensus store like ZooKeeper. The WhatsApp breakdown's owner process leases from a small durable counter for the same reason.
Where it shows up in the course
| article | the form it takes there |
|---|---|
| CAP and What It Actually Constrains | stock of 10,000 split into ten regional pools of 1,000, each sold with a local atomic operation, with a rebalancer moving stock every few minutes |
| Distributed Rate Limiter | gateways lease tokens 50 at a time, 1 million requests a second become 20,000 Redis calls, and the overshoot is 200 gateways times the block |
| Notification Service | send workers take blocks of tokens from one limiter per provider account, keeping it off the per-message path |
| URL Shortener | writers lease 10,000 counter values at a time, so the central sequence hears from them about once every 3 seconds, and the range check's bound carries a reserve larger than all the blocks leased while a copy of it is stale |
| WhatsApp and Chat Systems | an owner process leases sequence numbers 1,000 at a time from a small durable counter, and a crash leaves a gap that each client asks about once |
Getting it wrong
Choosing the block from the load you want to shed. "50, because it cuts calls 50 times" starts from the wrong number. Start from the error the decision can absorb and divide by the holders: 5 percent of a 200,000 a minute limit, over 200 gateways, is 50.
Sizing the block for today's fleet. Going from 200 to 400 holders doubles the bound, unless each one recomputes its block from a pushed count.
Topping up past one block. A holder that asks for a full block at the low-water mark can hold a block plus the mark. A retry with no refill number can take two blocks. Either breaks the bound of one block per holder.
Keeping an id counter where the tokens live. A Redis node set up for rate limits runs with persistence off, which is right for tokens. Even with persistence on, Redis replicates asynchronously, so a failover can lose an acknowledged increment and reissue a block.
Reading leased ids as dense or ordered. Every crash leaves a gap, and values from two holders interleave. Across holders, the only promise is that the values are distinct.
Sources
The production systems here are described from their own documents and papers. The course numbers are derived in the linked breakdowns.
- PostgreSQL documentation, CREATE SEQUENCE. The
CACHEoption, holes, and out-of-order values. - Elhemali et al., Amazon DynamoDB: A Scalable, Predictably Performant, and Fully Managed NoSQL Database Service, USENIX Annual Technical Conference 2022. Section 4.2, on global admission control.
- Apache Kafka, KIP-730: Producer ID generation in KRaft mode. Blocks of 1,000 producer ids, and fetching early.
- PingCAP, TiDB AUTO_INCREMENT. Batches of 30,000 per server, and the default mode's guarantees.
- Twitter, Snowflake. The id layout, machines that do not coordinate, and the clock check.
- Redis documentation, WAIT. Asynchronous replication, and writes lost in a failover.