CodingNodes Space play · ←→ step · R restart

The problem

A URL shortener swaps a long, unwieldy link for a short one, and sends anyone who opens the short version on to the original page. The product is tiny; the system is not. At one hundred million new links a day it is a write-heavy ingest pipeline bolted onto a read-hot lookup service, and the lookup has a latency budget measured in single-digit milliseconds.

Almost every interesting decision hides inside one small string: the code. How long is it, which characters may appear, and where do those characters come from — hashed, counted, or pre-generated? That single string decides your collision handling, your ID infrastructure, whether links are guessable, and how the rows are indexed.

We will fix the numbers first, then dissect the code itself, walk the write and read paths, weigh 301 against 302, and finish by pushing one real link through the whole machine — minting the code 1yy3PLz and clicking it.

Requirements

Functional — what it must do

  • Shorten: a client POSTs a long URL and receives a unique 7-character code; shortening the same long URL again returns the code it already got, not a second row.
  • Redirect: a client GETs a code and the service answers with the mapped long URL as the <code>Location</code> of a 301 (or 302) response.
  • Codes are immutable — no updates, no deletes — so every row is written once and the read path is a pure lookup.
  • The code travels in the path of the short domain, for example <code>lnk.to/1yy3PLz</code>.

Non-functional — how well it must do it

  • A redirect is one lookup: about 1 ms when the code is in cache, and no worse than 50 ms at the 99th percentile when the store must be read.
  • Reads outnumber writes 10:1, so the cache absorbs the hot share of clicks and the database only sees the cold tail.
  • High availability on the read path above all: links are shared in public and must survive a store failure through replicas and failover.
  • Ten years of growth must not change the code length or force a migration of the URL space.

Scale — how much it must take

  • 1,160 new links per second, 11,600 redirects per second, 365 billion rows and 36.5 TB after ten years.

Assumptions — the numbers this design is sized for

A rate limit means nothing without a scale. These are the figures every later part relies on: how much traffic arrives, how much work the limiter has to do per second, and how much latency and memory it may spend doing it.

New links
1,160 / s
100 million links created per day, spread across 86,400 seconds. The write path is sized to this.
Redirects
11,600 / s
Ten clicks per new link — a 10:1 read/write ratio. Reads dominate, so reads get the cache.
Lifetime rows
365 billion
100 million a day sustained for ten years. The code length must outlast this count.
Storage, 10 yrs
36.5 TB
365 billion rows at roughly 100 bytes each — big, but ordinary for a sharded store.
Code
7 chars
62^7 is about 3.5 trillion codes against 365 billion needed — roughly 9.6× headroom.
Write latency
≤ 50 ms p99
Dedupe lookup, one counter increment, one encode, one insert — a handful of fast operations.
Read latency
~1 ms hit
A cache hit answers from RAM; a miss adds one DB read and still fits the 50 ms budget.
Cache lease
30 min
A code stays cached while clicks keep arriving; a code with no clicks for 30 minutes ages out.

Takeaways

Part 1

Two verbs, one resource

The whole product is two endpoints over one immutable resource. Fixing that contract first keeps every later decision honest.

  1. 1
    Create a link

    The write side is one call. The client POSTs the long URL — a checkout-support page trailing tracking parameters — and the service answers with a fresh code such as 1yy3PLz, ready to be handed out.

  2. 2
    Follow a link

    The read side is even smaller: a GET with the code in the path. The service looks the code up and replies with a redirect status and the long URL sitting in the Location header.

  3. 3
    Write once, read forever

    Scope agreed up front: codes are immutable. No updates and no deletes keeps every row write-once, which makes the read path a pure lookup and the storage math boring — exactly what you want at this scale.

Part 2

Anatomy of the code

The code is the design. Its alphabet, its length, and the arithmetic that produces it decide collisions, indexing and guessability in one stroke.

  1. 1
    62 symbols

    A code draws from 62 characters: the ten digits, 26 lowercase letters and 26 uppercase ones. Case matters — w, K and 3 are three different symbols of this alphabet.

  2. 2
    Pick the length

    The length must outlast the system: 100 million links a day for ten years is 365 billion rows. The first power of 62 that clears that bar is the seventh — about 3.5 trillion codes, roughly 9.6× the requirement.

  3. 3
    Encode: divide by 62

    Encoding turns a number into a code. Take 125,909 — a small teaching ID: divide by 62, keep each remainder, repeat until the quotient hits zero, then read the remainders bottom-up and map them to characters: w, K, N.

  4. 4
    Decode: sum the places

    Decoding walks the same places in reverse — and this reversibility is the whole trick. The code is the row's ID in costume: wKN carries 32×3,844 + 46×62 + 49 = 125,909 straight back, no extra index required.

  5. 5
    Seven characters at full scale

    Production IDs are far larger than the teaching example. The finale mints ID 88,452,061,273 — encoded by the same division it becomes exactly the seven-character code 1yy3PLz you will follow through the rest of this chapter.

Part 3

Where codes come from

Three ways to fill seven characters: hash the URL, count and encode, or lease pre-made keys. They differ in collisions, infrastructure and guessability.

  1. 1
    Option A — hash and slice

    The service-free route: run a standard digest such as MD5 over the long URL and keep the first seven characters of the output. No counter, no coordination between servers — but nothing guarantees the slice is unused.

  2. 2
    Two URLs, one code

    Slices collide: two different long URLs can yield the same seven characters. The fix-up loop appends a salt, re-hashes and re-checks the store until the code is free — an extra round trip paid on every collision, plus a lookup on every write.

  3. 3
    Option B — count, then encode

    The ID route: a generator hands out sequential IDs and the base62 encoder from the last section turns each one into a code. Inputs are unique, so collisions are impossible by construction — the price is an ID service living on the write path.

  4. 4
    Option C — pre-made keys

    A third route moves the work offline: a key service generates large batches of unused codes ahead of time and leases one per write. Inserts stay fast, but the pool must be refilled before it runs dry and leased keys can be lost on a crash.

  5. 5
    Head to head

    We ship option B: collision-free by construction, and the codes grow longer only as the table fills — with 3.5 trillion slots the counter has trillions of increments before the seventh character is even threatened.

Part 4

The write path

Creating a link is four hops: check for a duplicate, mint an ID, encode it, store the row — all inside the 50 ms budget.

  1. 1
    The long URL lands

    A POST arrives with the long URL. Before minting anything, the API asks the store one cheap question: have we shortened this exact string before?

  2. 2
    Seen before? return it

    Popular targets get shortened over and over. If the lookup hits, the stored code goes straight back — one row and one ID saved. A miss means the URL is genuinely new and the path continues.

  3. 3
    Mint an ID

    New URL, so the API pulls the next ID from the generator: 88,452,061,273. One atomic increment — safe no matter how many servers are shortening at the same moment.

  4. 4
    Encode and store

    The encoder folds the ID into 1yy3PLz, and one insert lands the row with its three columns: id, code, long URL. At 1,160 inserts a second this is a light, easily sharded load.

  5. 5
    Four hops, one row

    The full write, assembled: dedupe, mint, encode, insert. The response hands back lnk.to/1yy3PLz, and the row now waits for its first click — 365 billion of these rows will accumulate over ten years.

Part 5

The read path

Redirects outnumber creates 10:1, so the read path is the product: a click, a cache, a store, and a Location header.

  1. 1
    A click arrives

    Someone opens lnk.to/1yy3PLz. The GET flows through the load balancer to a stateless web server; any server can answer any code, so scaling the read path is just adding boxes.

  2. 2
    Cache hit — 1 ms

    The web server asks the cache first. Hot codes live in RAM, so the usual case ends right here: the long URL comes back in about a millisecond and the database is never touched.

  3. 3
    Cache miss — one DB read

    A cold code misses, so the server reads the row from the store, answers with its long URL, and back-fills the cache so every later click of this code becomes a hit.

  4. 4
    Answer: the redirect

    The web server replies 301 with Location set to the long URL. The browser delivers the visitor to the destination — the entire read path was one lookup plus one redirect.

Part 6

301 or 302

The status code decides who remembers the mapping — the browser, or you. That choice trades server load against a complete click stream.

  1. 1
    First click of a 301

    A 301 declares the move permanent. On the first click the shortener answers and the browser stores the mapping alongside the code; the visitor proceeds to the destination as usual.

  2. 2
    Tomorrow's click skips you

    The second click on the same 301 never reaches the shortener: the browser answers itself from cache and goes straight to the destination. Cheap to serve — but the service saw one click where two happened.

  3. 3
    302 — every click reports

    A 302 declares the move temporary: the browser must ask again next time. Every click flows through the shortener, where it can be counted, attributed and rate-checked before being sent on.

  4. 4
    Choose by the product

    301 buys quiet servers; 302 buys a complete click stream. A shortener whose business is analytics runs 302 and pays for the traffic — this is a product decision, not a default.

Part 7

Cache & the cold tail

The 10:1 ratio makes the cache the most cost-effective box in the design. Codes earn their RAM seat by being clicked; silence evicts them.

  1. 1
    Hot link, busy hour

    Watch one code's clicks land on a clock — each marker is a click on 1yy3PLz, stamped with its wall-clock time. Every click refreshes the code's 30-minute lease, so a link in steady use simply never leaves RAM.

  2. 2
    Clicks keep it warm

    Two more clicks at 10:22 and 10:31, and the lease window slides forward with them. Everything inside the pane is a cache hit — five clicks, zero database reads for this code.

  3. 3
    Silence expires the entry

    Clicks stop. Nothing lands for the next half hour, so at 11:01 — thirty minutes after the final click — the lease lapses, the entry is evicted, and the next click for this code pays one database read.

  4. 4
    Sized to the tail

    Now multiply by the fleet: 11,600 redirects a second arrive, the hot sliver of codes answers most of them from RAM, and the store only ever sees the cold tail — roughly once per lease, at a still-acceptable 50 ms.

★ Finale

End to end

Both halves of the design in one machine: a link is minted, encoded and stored, clicked, served from the store once, then from RAM forever after.

  1. 1
    The whole system

    Everything in one frame. Writes enter on the left and are minted, encoded and stored; clicks arrive through the same door and leave as redirects, with the cache sitting between the servers and the store.

  2. 2
    Write: mint, encode, insert

    A POST arrives with the long URL. The generator hands over ID 88,452,061,273, the encoder folds it into 1yy3PLz, and one insert lands the row. The API returns lnk.to/1yy3PLz — the write is a few fast hops inside the 50 ms budget.

  3. 3
    First click: miss, then store

    The first visitor opens the new link. The cache has never seen this code, so the servers read the row from the store, answer 301 with the long URL — and back-fill the cache on the way out.

  4. 4
    Second click: served from RAM

    The next click finds the code sitting in cache. About one millisecond later the same 301 is on its way back — the store is untouched, and at 11,600 reads a second that difference is the whole business case for the cache.

  5. 5
    Ten years out

    Fast-forward a decade: 365 billion rows and 36.5 TB in the store, while the seven-character space of 3.5 trillion codes is only a tenth spent. Nothing migrated, nothing renamed — the sizing held.

🌐 In the wild

In the wild

The same shape — two endpoints, a counter-fed code, a cache in front of a store — is how real shorteners run. Here is who runs which piece, per the chapter's reference list.

  1. 1
    The pattern in production

    This design is not interview furniture. Each box below is anchored to a named system from the source chapter's references — an illustrative mapping, not a claim about anyone's internals.

  2. 2
    The redirect, served for real

    tinyurl.com runs exactly this loop — GET the short path, answer 301 with the long URL in Location. The response capture in the source chapter even lists Cloudflare headers, so an edge layer stands in front of the redirect fleet before any origin is reached.

  3. 3
    The API, REST-style

    The two endpoints are textbook REST: POST creates the short-link resource, GET reads it, and the status line plus Location header carry the redirect. The chapter's first reference is simply a RESTful tutorial — the contract costs an afternoon to learn.

  4. 4
    The cheap membership test

    Hash-based codes need a 'was this string ever stored?' probe on every write. A Bloom filter — the chapter's second reference — answers 'definitely not stored' from a few bits in RAM, so most writes skip the database probe; only a maybe pays for the real check.

  5. 5
    Guards and siblings

    The chapter's own wrap-up names the neighbors: a rate limiter in front of POST to blunt abuse, a distributed unique-ID generator feeding the counter, and replication plus sharding as the store grows. Every box in our diagram has a chapter of its own.