In a short-link service where application servers take batches from a pre-generated pool of unused codes, what failure modes must the design handle?
answer
- uniqueness settled at generation
- a crashed server's leftover batch
- atomic move from unused to issued
- low-watermark prefetch
- aliases and the shared namespace
basics
~20 sA server crash loses its leftover codes, which are written off, never reissued; a non-atomic claim can give two servers the same codes; a slow key service or empty pool stalls creates, so servers prefetch and the pool refills ahead.
solid answer
~50 sThe pool removes the per-request check because codes are made distinct at generation and each goes to exactly one server, so the design has to protect those two properties. When a server dies holding part of a batch, I write those codes off: I cannot tell which it assigned just before dying, and reissuing one risks a duplicate, while losing a thousand codes against 3.52 trillion costs nothing. The claim must be one atomic move from unused to issued, or two servers can get the same codes. Servers prefetch the next batch at a low watermark so a slow key service never stalls a create, the key service and its store are replicated, and the pool refills ahead with an alarm on days of supply. I keep a conditional insert on the link write as a tripwire.
code
pseudocode · 27 lines// Illustrative pool hand-out; names are invented and thread safety is omitted.
// Key service: one atomic step moves n codes from "unused" to "issued".
function claimBatch(serverId, n):
atomically:
codes = takeAny(unusedCodes, n)
add(issuedCodes, codes, owner = serverId, issuedAt = now())
remove(unusedCodes, codes)
return codes
// Application server: serve codes from memory, refill before the batch runs dry.
batch = keyService.claimBatch(serverId, 1000)
nextBatch = null
function nextCode():
if batch.remaining() < 200 and nextBatch == null:
nextBatch = keyService.claimBatchAsync(serverId, 1000)
if batch.isEmpty():
batch = await(nextBatch)
nextBatch = null
return batch.take()
function createLink(longUrl):
code = nextCode()
if insertIfAbsent(links, key = code, value = { longUrl, createdAt: now() }) == ALREADY_EXISTS:
alarm("pool handed out an issued code: " + code) // tripwire, should never fire
return createLink(longUrl)
return codego deeper
Recall that a pool of pre-made codes lets a server assign a short code without checking whether it is taken, because the pool already guarantees it is free.
Explain why uniqueness at generation plus one-server-per-code hand-out removes the per-request check, and why the claim must be a single atomic move.
Write off a crashed server's leftover batch rather than reclaim it, prefetch at a low watermark, replicate the key service, and keep a conditional insert as a tripwire.
Decide whether a pool's extra service and its store earn their keep over random codes with a conditional insert at this create rate.
## What a pre-generated pool is A **pre-generated pool** (often called a **key generation service**) moves the work of finding a free short code from the request path to an offline job. A generator fills a store with random seven-character base62 codes, discarding any code already in the unused set or already issued, so every code in the pool is distinct when it is made. Application servers then **claim batches** of codes, for example a thousand at a time, and assign them to new links from memory. **Why it removes the per-request check:** uniqueness was established once, at generation, and each code is handed to exactly one server, so a create needs no uniqueness lookup, no hashing and no retry loop. Designs often still write the link with a conditional insert as a **tripwire**: it costs almost nothing in the single write and catches a broken hand-out loudly instead of silently overwriting a link. The trade is a new component with its own failure modes, and those are what the design must answer. ## Failure modes and the design answer to each | failure | what happens | design answer | |---|---|---| | **An application server dies** holding part of a batch | its unassigned codes are never used | treat them as spent; do not reclaim | | **Two servers receive the same codes** | two links share a code; one silently overwrites the other | claim atomically: one step moves codes from unused to issued | | **The key service is down or slow** | servers run out of codes and creates fail | prefetch at a low watermark; replicate the key service and its store | | **The pool runs dry** | creates fail even though the keyspace is nearly empty | refill ahead of demand; alarm on days of supply left | | **A custom alias takes a code still in the pool** | the pool later hands out a code that is already a link | remove claimed aliases from the pool, or give aliases their own namespace | ## Why lost codes are not reclaimed When a server crashes, the issued-but-unassigned part of its batch looks recoverable. It is not safely recoverable: the server may have assigned a code and written the link a moment before it died, and the key service cannot tell which codes made it out. Reissuing them risks exactly the duplicate the pool exists to prevent. The waste is tiny: a thousand codes per crash against a keyspace of 62^7, about **3.52 trillion**. Losing codes is cheap; reusing one is a correctness bug. ## Sizing and operating the pool 1. **Batch size against hand-out rate.** The scenario's 100 million links a month is about 40 creates a second on average (derived). Spread over, say, 20 servers, a batch of 1,000 lasts between eight and nine minutes at average load and less at peak. Larger batches mean fewer key-service calls and more codes lost per crash. 2. **Prefetch before empty.** Request the next batch when, say, a fifth of the current one remains, so a slow key service never stalls a create; a server that holds one spare batch rides out a short outage. 3. **Keep the key service boring.** Its only job is an atomic move from unused to issued. Replicate its store; it is the source of truth for what has been handed out, and losing it means not knowing which codes are taken. 4. **Refill ahead.** The generator keeps weeks of supply in the unused set and raises an alarm on days left, not on empty. 5. **Split by region if needed.** Each region's key service can own a disjoint slice of the keyspace, such as codes starting with certain characters, so regions never coordinate per batch. ## How the pool compares with the other schemes - **Against random codes with a conditional insert:** same codes and same unguessability, but the uniqueness work happens once, offline, and the request path is a hand-out from memory. - **Against a base62 counter:** both avoid a per-request collision check, but pool codes are random and not enumerable. Handing out **ranges of a counter** instead of concrete codes is the general distributed-identifier pattern, and it keeps the counter's sequential codes. - **Against hash-and-truncate:** the pool loses determinism, so the same long URL gets a new code unless reuse is handled separately.
- How do custom aliases interact with a pre-generated pool?If aliases and generated codes share one namespace, an alias such as a seven-character word can match a code still sitting in the unused set. Either remove a claimed alias from the pool in the same step, or give aliases a separate namespace or character rule that generated codes can never match. Otherwise the pool later hands out a code that is already a link.
- What should the key service's store hold, and why does it need to survive?It holds the unused codes and which codes were issued to whom. If it is lost, the service no longer knows which codes are taken; rebuilding from the links table misses codes that were issued but not yet assigned. Replicate it like any source of truth, and keep its operation to an atomic move so it stays simple to run.
A cloakroom with pre-printed ticket rolls: each attendant takes a strip, so no two coats ever share a number without anyone checking, and when an attendant goes home with half a strip, those numbers are simply never used.
- When a server crashes, return its unused codes to the pool after a timeout.
- Reading free codes and then marking them issued in a second step is safe enough.
- Codes from the pool are sequential, so a server can compute the next free one.
- With a pool, the link write can never collide, so a tripwire check is wasted work.
- Fetch a new batch only when the current one is empty, to avoid wasting codes.