System Design: URL Shortener (Walnut Link: Random Codes, Fast Redirects, Click Counts, Three Regions)
We design a service that turns a long web address into a short one. A visitor who opens the short link is sent on to the long address.
Our service is called Walnut Link, and its short links look like wl.nut/kH7q2Xa. Both names are made up.
As in an interview, every number here is our own planning assumption, and the design is our own.
Facts about real products, such as a database's license terms, are as of November 2026. All times are Eastern Time, in 2026, unless a line says otherwise.
How to read this post. It takes about 70 minutes in full, so it is built to be read in parts:
- Section 1 sets up the problem: one week of real use, the words, every kind of request and the numbers.
- Section 4 is the design, built in 6 stages, the way a candidate draws it. Stage 7 is the full picture to remember.
- Section 5 goes deep into each hard part. The first two deep dives compare the two ways to make short codes, and say which one wins at much larger scale.
- Sections 6 to 8 are the trade-offs, the bottlenecks and failures, and the interview follow-ups.
- For a quick revision, use the interview playbook for this design. Its Cheat Sheet and Learn cards take about 20 minutes, and the whole playbook about 40.
1. Requirements
1.1 What we are building
Walnut Link does three jobs:
- Make short links. A person or a program sends a long address and gets back a short code, such as kH7q2Xa. The code must be unique, and it must keep pointing to the same address for as long as the link lives.
- Send visitors on, fast. A click on wl.nut/kH7q2Xa must reach the long address fast. Our servers may add only a few milliseconds, even when one link goes viral.
- Count the clicks. Each link's owner sees how many people clicked, when, and from which countries and devices.
Harbor Coffee is a made-up coffee chain in Seattle, and one of our customers. Here is one week in November, and how each part ends:
- Mon 13:05. Jenna, Harbor's marketing manager, asks for a short link to the holiday menu. It will be printed on 2 million cups, so it must never change. Her network drops, and her tool asks twice. She still gets one code: kH7q2Xa.
- Mon 13:07. Jenna also asks for the alias wl.nut/holiday-menu, for posters.
- Tue 09:00. Tom's bike shop and Hannah's running store both ask for the alias black-friday, 40 ms apart. Tom gets it. Hannah is told "taken" at once, and uses black-friday-boston.
- Wed 10:15. Ben, a lawyer in Chicago, makes a private link to a client's file. It ends after 7 days.
- Wed 11:02. Someone links to a fake Harbor gift card page. We block it at 11:14, after about 1,100 clicks.
- Thu 03:10. A scanner guesses 2 million codes an hour, looking for links like Ben's. It finds only about 4,000 public pages, and never finds Ben's.
- Thu 12:00. A TV chef posts wl.nut/holiday-menu. Clicks peak at 40,000 a second, with no slowdown. At 12:40, Jenna's dashboard shows 1.9 million clicks, about 40 seconds behind.
- Fri 06:40. Our US East region goes down, and Sam, our on-call engineer, is paged. Clicks keep working from US West, about 1 second slower for 30 seconds. About 3,000 new links fail and are sent again. About 50 links made in its last second wait until it returns at 09:10.
The hard part: every code must be unique across three regions, and must never change. And there are 100 clicks for every new link, so clicks must be fast, and every one must be counted.
1.2 Words we use
Words used in only one place are explained there. Each word below is used all through the post.
Links and codes.
| Word | Meaning here |
|---|---|
| Long URL | The full web address a short link points to, such as Harbor's holiday menu page |
| Short code | The part after wl.nut/, such as kH7q2Xa. Seven characters for a normal link |
| Base62 | The 62 characters we use in codes: 0 to 9, a to z and A to Z. They are all safe in a web address |
| Custom alias | A code the customer chooses, such as holiday-menu. It always has a hyphen |
| Private link | A link with a 10-character code, much harder to guess. For links that carry a secret |
| Expiry | The time a link stops working. After it, the code answers "gone" and is never given out again |
| Redirect | Our answer to a click: "go to this long URL instead" |
| 302 | The kind of redirect we send. It tells the browser to ask us again next time |
| Click | One visit to a short link, counted once |
| Bot click | A visit from a program, such as a chat app fetching a link preview. Counted apart from people |
Machines and data.
| Word | Meaning here |
|---|---|
| Region | One of our three groups of data centers: US East in Virginia, US West in Oregon, EU in Frankfurt |
| Origin | Our own servers, as the CDN sees them |
| CDN | A content delivery network: an outside company with servers in hundreds of cities. It answers repeat clicks near the visitor |
| Cache | A fast copy of data kept close to where it is read. It can be thrown away and rebuilt |
| Cache hit | A read answered by a cache. A cache miss goes on to the next layer |
| Pod | One running copy of a service. We run many identical pods, and any pod can take any request |
| Shard | One part of a store that is split over several machines. Each key lives in one shard |
| Conditional insert | A database write that adds a row only if no row has that key yet. It tells the writer whether it won |
| Code slice | The part of all codes one region may make. A code's first character says which region made it |
| p99 | The time that 99 of every 100 requests meet. p95 is the same for 95 of 100 |
IDs in this post. Every ID below is made up.
| ID | What it names | Example from the story |
|---|---|---|
| kH7q2Xa | A short code | Jenna's cup link, made in US West |
| holiday-menu | A custom alias | Harbor's link for posters, the one the TV chef posts |
| black-friday | A custom alias | Tom's alias, won 40 ms before Hannah's request |
| c4Rt9wLm2Q | A private code, 10 characters | Ben's file share link, made in US East |
| Gp4Lx9T | A short code | The fake gift card link, made in EU |
| acct_2207 | An account ID | Harbor Coffee |
| acct_5518, acct_3390 | Account IDs | Tom's bike shop; Hannah's running store |
| acct_8841 | An account ID | Ben's law firm |
| acct_9054 | An account ID | The account behind the fake gift card link |
| req_7f3a91 | A request ID, made once by the client | Jenna's Monday request, sent twice |
| b_552301 | A log batch ID | One batch of click lines from the CDN |
| pg_1182 | A purge ID | The job that clears Gp4Lx9T from every cache |
1.3 Every kind of request and change
Walnut Link handles more than the story shows. This table lists every kind.
| Kind | What it is | How big or how often | Part that handles it | Outside company that takes part |
|---|---|---|---|---|
| Make a link | A long URL in, a random 7-character code out | 10 million a day | Link API | none |
| Make an alias | The customer names the code, such as holiday-menu | about 2% of new links | Link API, Links store | none |
| Make a private link | A 10-character code, often with an expiry | about 3% of new links | Link API | none |
| Bulk create | Up to 1,000 links in one call, such as a mail campaign | about 20% of new links | Link API | none |
| Click, answered by the CDN | The CDN already holds the redirect | 25% of clicks | CDN | The CDN company |
| Click, answered by us | The CDN asks us | 75% of clicks | Redirect service, Link cache, Links store | The CDN company |
| Click on an unknown code | A typo, or a scanner's guess | about 2% of clicks on a normal day | Redirect service | The CDN company |
| Click on an ended link | Expired, deleted or blocked | under 1% of clicks | Redirect service | The CDN company |
| Bot click | A chat app or search engine fetching the page | about 6% of clicks | Log receiver marks it | The bot's owner |
| Read click counts | A dashboard or report | about 2 million reads a day | Link API, Click store | none |
| Delete a link | The owner ends it early | about 50,000 a day | Link API, Purge worker | The CDN company |
| Block a link | A link to a scam or malware | about 2,000 a day | Safety scanner, Trust console, Purge worker | A threat list provider |
| Abuse report | A visitor or a company reports a link | about 5,000 a day | Trust console | none |
| Guessing attack | Many random codes tried from many addresses | a few a week | CDN bot rules, Redirect service | The CDN company |
| Region failure | One region stops answering | a few times a year | CDN, DNS, Links store | The CDN and DNS companies |
1.4 Functional requirements
- Make a short link. Return a random 7-character code for a long URL. A repeated request with the same request ID gets the same code.
- Follow a link. Send a visitor to the long URL with a 302 redirect.
- Custom aliases. Let a customer choose a code, such as holiday-menu. One alias belongs to one account, worldwide.
- Private links. Make a 10-character code on request, for links that carry a secret.
- Expiry. End a link at a chosen time, or never. An ended code is never given out again.
- Delete and block. Let the owner delete a link, and let our trust team block one. Both stop the link everywhere within a minute.
- Click counts. Show clicks by hour, country, device and referring site. Bot clicks are counted apart.
- Bulk create. Make up to 1,000 links in one call.
- Accounts and limits. Creates need an API key, and each key has a rate limit.
- Safety checks. Check each long URL when it is made, and again when its link gets busy.
Out of scope: changing where an existing link points, since a printed code must keep its meaning. Also out of scope: drawing QR code images, which the customer's own tool does, and billing.
1.5 Non-functional requirements
- Fast redirects. Our servers answer a click in under 5 ms at p99 on a cache hit, and under 15 ms on a miss. Network time to the visitor comes on top.
- Redirects stay up. Clicks work 99.99% of each month, about 4 minutes of failure at most.
- Creates. A new link comes back in under 300 ms at p99, and an alias in under 500 ms. Creates work 99.9% of each month.
- Durable links. A code is returned only after its row is on 2 of the 3 copies in its region.
- One code, one address. No two links ever share a code, and an ended code is never reused.
- Fresh counts. A click shows on the dashboard within 1 minute at p95.
- Fast takedown. A deleted or blocked link stops redirecting everywhere within 60 seconds.
- Scale. We build for 100,000 clicks a second and 1,000 creates a second.
- Privacy. No visitor's IP address is stored. We keep a salted hash, which counts unique visitors. Without the secret salt, it cannot be turned back into the address.
1.6 The numbers
These are rough sums, the kind a candidate does at a whiteboard in a few minutes. Every number is our own assumption. Design capacity is what we build for: the busiest hour, plus room for bulk campaigns and viral links.
| Number | How we get it | Result | What it decides |
|---|---|---|---|
| Creates | 10 million new links a day ÷ 86,400 seconds ≈ 116 a second. The busiest hour is about 3 times that: 116 × 3 ≈ 350. Bulk campaigns come on top, so we plan for 1,000 | 116 a second on average; 1,000 at design capacity | At 1,000 creates a second, each new link can afford a 2 ms conditional insert |
| Clicks | 1 billion clicks a day ÷ 86,400 ≈ 11,600 a second. The busiest hour is about 3 times that: 11,600 × 3 ≈ 35,000. Viral links come on top, so we plan for 100,000 | 11,600 a second on average; 100,000 at design capacity | 100 clicks arrive for each new link, so clicks shape the design. Clicks get their own service, with caches in front of the database |
| Codes | 10 million × 365 = 3.65 billion links a year; after about 3 years, about 10 billion. Codes of 7 characters: 62⁷ ≈ 3.5 trillion | 10 billion links use about 1 in 352 of the codes | 7 characters are enough, and a random code is free 351 times in 352 |
| Clashes | Each region makes codes from its own slice: 20 first characters × 62⁶ ≈ 1.14 trillion. US East makes 45% of links, so its slice holds 4.5 billion | 1 random pick in 250 is taken, at 10 billion links | Each region makes codes alone, with no counter to share. A clash costs one retry |
| Link data | A row is about 350 bytes: the code, a 200-byte long URL, owner, times and flags, and the database's own overhead. 10 billion × 350 bytes = 3.5 TB a copy, × 3 copies × 3 regions | about 31.5 TB | Too big for one server, and needed in three regions. So a key-value store spreads the keys over many machines. Storage, not traffic, sizes it |
| Database reads | The CDN answers 25% of clicks, so 75,000 a second reach us. Our two caches answer 60,000 of those, as stage 2 shows | 15,000 reads a second, about 5,000 per region. 85% of clicks come from a cache | The machines that 31.5 TB of storage needs can take 15,000 reads a second. A click answered from a cache takes under 5 ms |
| Cache size | The hottest 150 million links per region × 250 bytes × 1.6 for the cache's own overhead | about 60 GB per region | 60 GB fits in memory, on 6 cache shards of 10 GB |
| Clicks written | 100,000 clicks × 300 bytes ≈ 30 MB a second at peak. 1 billion × 300 bytes = 300 GB a day raw, about 30 GB compressed. Kept 13 months | up to 100,000 lines a second; about 12 TB a copy | Clicks are the biggest write load, 100 times the creates. So counting goes through a log, and a click never waits for it |
What these numbers tell us: 100 clicks arrive for each new link, so how a click is answered decides the design. The database's size is set by its 31.5 TB of storage, not by its 15,000 reads a second. And a click never waits for counting.
2. APIs
The Public API is our HTTPS API for customers' programs, such as Jenna's print tool. The Walnut Link app is our web app, built on the same API.
Jenna's request on Monday at 13:05:
POST /v1/links
Authorization: Bearer <Harbor's API key>
Idempotency-Key: req_7f3a91
{ "long_url": "https://www.harborcoffee.example/menu/holiday-2026?src=cup",
"private": false,
"expires_at": null }
201 Created
{ "code": "kH7q2Xa",
"short_url": "https://wl.nut/kH7q2Xa",
"created_at": "2026-11-16T18:05:02Z",
"expires_at": null }The click on Thursday, as the CDN sends it to us and as we answer:
GET /kH7q2Xa
Host: wl.nut
302 Found
Location: https://www.harborcoffee.example/menu/holiday-2026?src=cup
Cache-Control: max-age=0, s-maxage=60| Field | Why it is there |
|---|---|
| API key | It names the account, acct_2207. The account always comes from the key, never from the request body |
| Idempotency-Key | A request ID that the client makes once and sends again on every retry. A retry within 24 hours gets the first answer, so Jenna's second request returns kH7q2Xa again |
| long_url | The address to send visitors to. It must start with http or https, and be at most 2,048 characters |
| private | true asks for a 10-character code |
| expires_at | When the link ends, or null for never |
| alias | Not used here. With "alias": "holiday-menu" the customer chooses the code |
| 302 Found | The browser must ask us again next time, so each click is counted and an ended link stops |
| max-age=0 | The browser keeps no copy |
| s-maxage=60 | A shared cache, such as the CDN, may keep the answer for 60 seconds |
The other calls:
| Call | What it does |
|---|---|
| POST /v1/links/bulk | Up to 1,000 links in one call, each with its own result |
| GET /v1/links/{code} | One link's details: where it points, its owner and its expiry |
| GET /v1/links | The account's links, newest first, one page at a time |
| DELETE /v1/links/{code} | Ends a link now. Owners only |
| GET /v1/links/{code}/stats | Clicks by hour, country, device and referring site, with bots apart |
| POST /v1/reports | Anyone may report a link as a scam |
A code that does not exist gets 404 Not Found. A code that has ended gets 410 Gone, with a short page that says so. A blocked link gets a warning page and no redirect.
3. Data model
Where data lives, and why.
| Store | Kind | What it holds, and its key | Written by, and read by | Why this kind |
|---|---|---|---|---|
| Links store | A wide-column database such as ScyllaDB, with 3 copies in each of our 3 regions | Every link, keyed by code. Also each account's list of links, the request IDs of the last 24 hours, and pending purges | Written by the Link API, the Safety scanner and the Purge worker. Read by the Redirect service, the Link API and the Purge worker | Reads and writes by one key, fast, at 10 billion rows. Conditional inserts for unique codes |
| Link cache | A key-value store such as Valkey, in memory, one cluster per region | Hot links, keyed by code. Also rate-limit counters, recent unknown codes and written batch IDs | Written by the Redirect service, the Link API and the Log receiver; cleared by the Purge worker. Read by the same three services | Answers most clicks in under a millisecond |
| Click log | A durable ordered log such as Kafka, one cluster per region | Click lines from the CDN, kept 3 days. No key | Written by the Log receiver. Read by the Click store | A slow reader catches up later, with nothing lost |
| Click store | A column database for counting, such as ClickHouse. One copy in US East and one in US West | One row per click, and counts per link and hour | Written from the Click log. Read by the Link API for dashboards, and by the Safety scanner | Sums over billions of rows in under a second |
The links table. One row per code, in the Links store.
CREATE TABLE links (
code text PRIMARY KEY, -- kH7q2Xa, c4Rt9wLm2Q or holiday-menu
long_url text, -- written with a time to live when the link expires
account_id text,
kind text, -- random, private or alias
created_at timestamp,
expires_at timestamp, -- null for never
status text -- live, deleted or blocked
);| code | long_url | account_id | kind | expires_at | status | What it means |
|---|---|---|---|---|---|---|
| kH7q2Xa | harborcoffee.example/menu/holiday-2026?src=cup | acct_2207 | random | null | live | Jenna's cup link, made in US West |
| holiday-menu | harborcoffee.example/menu/holiday-2026 | acct_2207 | alias | null | live | The alias the TV chef posts |
| c4Rt9wLm2Q | files.example/s/9f2b…, a long secret token | acct_8841 | private | 2026-11-25 16:15 UTC | live | Ben's private link, made in US East |
| Gp4Lx9T | harbor-giftcard.example/claim | acct_9054 | random | null | blocked | The fake gift card link, blocked at 11:14 on Wednesday |
A code is kept forever. When a link expires, its long URL is removed, but its row stays with its code and its dates. About 60 bytes are left for each ended link. The row is what stops the code from being given out again: the check refuses that code forever.
The database removes the long URL by itself. The Link API writes the long URL with a time to live, the number of seconds until it expires. The rest of the row has none.
The other tables in the Links store.
| Table | Key | What one row holds | Who writes it, and who reads it |
|---|---|---|---|
| create_requests | account ID and request ID | The code made for that request. The row ends after 24 hours | Written by the Link API, put-if-absent. Read by the Link API on a retry |
| links_by_account | account ID, then time made, newest first | One code | Written by the Link API. Read for the account's list of links |
| purges | purge ID | One code, and the caches still to clear | Written by the Link API and the Safety scanner. Read by the Purge worker |
Put-if-absent is another name for a conditional insert on a key. The create_requests row for req_7f3a91 is why Jenna's retry gets kH7q2Xa again, not a second link.
The Link cache. Each region's Link cache holds five kinds of key:
| Key | Value | Lives for |
|---|---|---|
| link:kH7q2Xa | The long URL, the expiry and the status | 1 hour, or until a purge removes it |
| miss:Zq81bWe | "no such code", for a code that does not exist | 60 seconds |
| rate:acct_2207:minute | Creates by this account in this minute | 2 minutes |
| unknown:{IP hash}:minute | Unknown codes asked for by one IP address in this minute | 2 minutes |
| batch:b_552301 | "written", for a batch of click lines already in the Click log | 1 hour |
The clicks table. One row per click, in the Click store:
| Field | Example | Used for |
|---|---|---|
| code | holiday-menu | Which link |
| time | 2026-11-19 12:03:41 | Counts by hour |
| country, device | US, phone | The dashboard's breakdowns |
| referrer site | the social app's domain | Where clicks came from |
| is_bot | false | Bot clicks apart |
| visitor hash | a salted hash of the IP address | Unique visitors, without storing the address |
| CDN request ID | an ID the CDN gives each request | Finding a line sent twice |
A second table holds counts per link and hour, kept up to date as clicks arrive. Dashboards read it, not the raw rows.
The life of a link. A link is live until it expires, its owner deletes it, or our trust team blocks it. Then its code answers 410 Gone or a warning page, and the row stays.
What we never store. No visitor's IP address is stored, only its salted hash. The salt is a secret held only by the Log receivers, and it changes every month.
We never store the page behind a long URL. And we never store an API key, only its hash.
4. Architecture
We build the design the way a candidate draws it on a whiteboard: one problem at a time. Each stage starts with a problem from the story and adds only the boxes that solve it. The full picture comes last, as a summary.
How to read the figures:
- Boxes from earlier stages are gray. A new box is in color, and the color says its kind:
- blue for our services, jobs and code inside a program;
- green for stores and logs;
- teal, with a dashed line, for an outside company or a customer's own system.
- Under each box name, one line says its job. Each figure's key shows the colors and the shapes it uses.
- The shape says what kind of part it is:
- a rounded box is our service, and a sharp box inside it is code or data inside that program;
- a box with a small clock is a background job;
- a cylinder is a store, and a horizontal pipe is a log;
- a dashed teal box is another company, and a box with a browser bar or a phone shape is an app or a device.
- Arrows point the way data moves. A call and its answer get two numbers.
- Numbers are steps someone waits on. Each stage numbers its own steps from 1, in time order.
- Letters are background work that nobody waits on. Each letter is one path, and its arrows are numbered in order, such as C1 to C7. Each letter appears once in the post.
- A gray arrow with no tag is another call, named in the step list.
- Elsewhere a step is named with its stage: "stage 2, step 5". Each technology named is one common example, not the only choice.
4.1 Stage 1: making a short link
The problem. On Monday at 13:05, Jenna's print tool asks for a short link to Harbor's holiday menu. The code goes on 2 million cups, so it must be unique and must never change. Her network drops while the answer is on its way, and the tool sends the same request again.
What we need:
- a 7-character code that no other link has, now or later;
- a row that says where the code points, kept safely;
- one code for one request, even when the request arrives twice.
So we start with the simplest design that works: pick a random code, and write it only if no row has it yet.
The steps.
- 1. Harbor's print tool → Link API, 13:05:02. POST /v1/links with request ID req_7f3a91 and Harbor's API key. The Link API reads the account, acct_2207, from the key.
- 2. Link API → Links store. It claims the request ID in the create_requests table, put-if-absent on acct_2207 and req_7f3a91. The row says "in progress".
- 3. Links store → Link API. The claim succeeds, so this is a new request.
- 4. Link API → Links store. The Code maker picks 7 random Base62 characters: kH7q2Xa. The Link API writes the link row with a conditional insert: add it only if no row has this code.
- 5. Links store → Link API. "Applied": no row had kH7q2Xa, so the code now belongs to Harbor. If a row had it, the Code maker would pick again, as the deep dive on codes explains.
- 6. Link API → Links store. It writes kH7q2Xa onto the request row, and adds the code to Harbor's list in links_by_account. These are plain writes.
- 7. Link API → Harbor's print tool. 201 Created with wl.nut/kH7q2Xa, about 25 ms after step 1.
Jenna's retry, one second later. The print tool sends req_7f3a91 again. Step 2's claim fails this time, because the row exists.
The Link API reads kH7q2Xa from that row and returns the same code. No second link is made.
If the first request had died between steps 3 and 6, the row would still say "in progress". A retry that finds such a row waits 200 ms and reads it again. A row left in progress for over 5 seconds belongs to a dead request, so the retry takes it over and makes the code itself.
This version has three problems:
- Every click reads the database. Up to 100,000 clicks a second would all reach the Links store. Stage 2 adds caches.
- Some customers want to choose the code, or end the link. Stage 3 adds custom aliases, private links and expiry.
- One region is one failure away from an outage. Stage 5 spreads the design over three regions.
The first boxes.
| Box | What it is, and the problem it solves | In, and out | Tech, and why not the obvious other |
|---|---|---|---|
| Harbor's print tool | A customer's own program, which calls our Public API. The problem it solves for Harbor: a code for each print job, made without a person | In: a long URL. Out: POST /v1/links; the short link | Any program that speaks HTTPS. Our API is the same one our own web app uses |
| Link API | Our service, as many identical pods that keep no data of their own. Any pod takes any request. The problem it solves: one place makes, lists and ends links, with the account's rules | In: create, delete and stats calls. Out: short links; rows for the Links store | Pods on Kubernetes, at least 3 per region. One big server would be a single point of failure |
| Code maker, inside the Link API | Code that picks random characters from a secure random source. The problem it solves: a code that cannot be guessed from the one before | In: the length, 7 or 10. Out: a random code | Random, with a conditional insert. A counter is the other choice, and the deep dives compare the two |
| Links store | A wide-column database such as ScyllaDB, keyed by code, with 3 copies in each region. The problem it solves: 10 billion rows, each read and written by one key, fast | In: link rows, request rows, conditional inserts. Out: one row by code; "applied" or "not applied" | ScyllaDB, because it reads one key in about a millisecond and has conditional inserts. A single Postgres server cannot hold 31.5 TB, and the deep dive on regions compares the other databases |
4.2 Stage 2: following a link, fast
The problem. On Thursday at 08:10, Mia Turner scans the QR code on her Harbor cup in Columbus, Ohio. Her phone opens wl.nut/kH7q2Xa.
By noon, one link alone will take 40,000 clicks a second. We build for 100,000 a second in all.
What we need:
- an answer to most clicks without reading the database;
- an answer near the visitor, for clicks that repeat;
- a 302 redirect, so every click comes back to us and is counted.
The steps.
- 1. Mia's phone → CDN, 08:10:00. GET /kH7q2Xa reaches the CDN's server in Columbus.
- 2. CDN → Redirect service. That CDN server has no copy of the redirect yet, so it asks our origin.
- 3. Redirect service → Link cache. The Memory cache inside this pod has no entry either. So the Redirect service asks the Link cache for link:kH7q2Xa.
- 4. Link cache → Redirect service. A miss. This cup link was last clicked over an hour ago.
- 5. Redirect service → Links store. It reads the row for kH7q2Xa from one copy, the nearest. A row changes only when its link ends or is blocked, so the nearest copy is good enough.
- 6. Links store → Redirect service. The row: the long URL, live, no expiry. The Redirect service puts it into the Link cache for 1 hour, shown as a gray arrow, and into its Memory cache for 10 seconds.
- 7. Redirect service → CDN. 302 Found, with the long URL and Cache-Control: max-age=0, s-maxage=60. This took 3 ms of our time.
- 8. CDN → Mia's phone. The CDN passes the 302 on, and keeps a copy for 60 seconds.
- 9. Mia's phone → Harbor's website. Her phone opens the holiday menu page.
The next click. At 08:10:30 another person scans a cup in Columbus. The CDN server there still holds the copy, so it answers at once: steps 1 and 8 only.
A click from Denver reaches another CDN server, and that one asks us. Our Link cache now has the row, so steps 5 and 6 are skipped.
Four levels. Each level catches what the one before missed. At our design capacity of 100,000 clicks a second:
| Level | How long it keeps a link | Share it answers | Clicks a second | Our time |
|---|---|---|---|---|
| CDN | 60 seconds | 25% of all clicks | 25,000 | none |
| Memory cache, in each pod | 10 seconds | 20% of the 75,000 that reach us | 15,000 | a few microseconds |
| Link cache | 1 hour | 75% of the other 60,000 | 45,000 | under 1 ms |
| Links store | for good | the rest | 15,000 | 1 to 4 ms |
So 85% of clicks are answered from a cache. The other 15% read the database, about 5,000 a second in each region.
Each share follows from how long its level keeps a link:
- The CDN, 25%. A CDN server answers only a click that repeats in its own city within 60 seconds. Busy links do that, and the many quiet links do not.
- The Memory caches, 20%. A pod answers only a link it served in the last 10 seconds. That catches the few hundred hottest links of the moment.
- The Link cache, 75% of the rest. Each region's Link cache holds about 150 million links clicked in the last hour. They take most of the remaining clicks.
- The Links store, 15%. Links last clicked over an hour ago, such as Mia's cup link at 08:10.
These shares hold only while a few links take most clicks, as they do today. The deep dive on caches says what happens when they do not, and how the Memory cache handles one viral link.
The new boxes.
| Box | What it is, and the problem it solves | In, and out | Tech, and why not the obvious other |
|---|---|---|---|
| Mia's phone | A visitor's phone or browser. The problem it solves for Mia: it follows the redirect to the page she wants | In: a scanned code or a tapped link. Out: GET /kH7q2Xa; then the long URL | Any browser. A 302 works in every one |
| CDN | An outside company with servers in hundreds of cities, in front of all our redirects. The problem it solves for us: repeat clicks are answered near the visitor, and never reach us | In: every click. Out: a cached 302, or a request to our origin | A CDN such as Cloudflare or CloudFront. Our own servers in hundreds of cities would cost far more |
| Redirect service | Our service, as many identical pods with no data of their own. The problem it solves: it turns a code into a redirect in a few milliseconds | In: GET /{code} from the CDN. Out: a 302, a 404 or a 410 | A small, fast program, kept apart from the Link API. A slow create can then never slow a click |
| Memory cache, inside each Redirect service pod | The hottest links, in the pod's own memory, each kept 10 seconds. The problem it solves: a viral link is answered without any network call | In: rows read by this pod. Out: a row in microseconds | A small map inside the program. A shared cache would send every viral click to one cache shard |
| Link cache | A key-value store such as Valkey, in memory, 60 GB per region in 6 shards. Each shard has a copy on a second machine. The problem it solves: with the Memory caches, 80% of the clicks that reach us never touch the database | In: rows to keep for 1 hour. Out: a row by code, in under a millisecond | Valkey, because a lookup by key in memory is what it does. The Links store alone would need far more nodes for 75,000 reads a second |
| Harbor's website | An outside company's website, here Harbor's. The problem it solves for Mia: it is the page the link points to | In: Mia's visit. Out: the holiday menu | Not ours. We never fetch or store the page itself |
4.3 Stage 3: aliases, private links and expiry
The problem. At 13:07 on Monday, Jenna wants a link that people can read and type: wl.nut/holiday-menu. On Wednesday, Ben wants the opposite. His link carries a secret, so it must be hard to guess, and it must stop working after 7 days.
What we need:
- a code chosen by the customer, unique worldwide, that can never clash with a random code;
- longer codes for links that carry a secret;
- an end time, after which the code answers "gone" and is never handed out again.
The steps.
- 1. Jenna's Walnut Link app → Link API, 13:07:10. POST /v1/links with "alias": "holiday-menu" and the same holiday menu page. Before any write, the Alias rules inside the Link API check the name:
- it is turned to lowercase, so Holiday-Menu and holiday-menu are the same alias;
- it has 3 to 30 letters, digits and hyphens, with at least one hyphen;
- it is not a reserved word, such as api, login or help;
- it does not look like a sign-in page, such as a name that ends in -login.
- 2. Link API → Links store. A conditional insert of the row for holiday-menu, kind alias.
- 3. Links store → Link API. "Applied": no one had this alias.
- 4. Link API → Jenna's Walnut Link app. 201 Created with wl.nut/holiday-menu.
Why the hyphen. Random codes never contain a hyphen. So an alias and a random code can never be the same string, and the two never fight over one row.
Ben's private link, on Wednesday at 10:15 in Chicago. His request has "private": true and an end time 7 days later. The steps are those of stage 1.
The Code maker picks 10 characters instead of 7, and the link gets c4Rt9wLm2Q. The deep dive on guessing shows why 10 characters keep a scanner out.
The end time. The Link API writes Ben's long URL with a time to live of 604,800 seconds, which is 7 days. The rest of the row has none.
- On Wednesday 25 November at 10:15 in Chicago, the database drops the long URL by itself.
- The next click on c4Rt9wLm2Q finds a row with no long URL. The Redirect service answers 410 Gone.
- The row stays, so no new link can take that code.
This stage adds no new store. Its new box is a set of rules in the Link API, and its new idea is a column with a time to live.
The new boxes.
| Box | What it is, and the problem it solves | In, and out | Tech, and why not the obvious other |
|---|---|---|---|
| Jenna's Walnut Link app | Our web app, in the browser, built on the Public API. The problem it solves for Jenna: she makes, lists and ends links by hand, and sees their clicks | In: Jenna's choices. Out: Public API calls; the results | A web app, so nothing is installed. It uses the same API as customers' programs, so both behave the same |
| Alias rules, inside the Link API | Code that checks a chosen name before it is written. The problem it solves: an alias must be readable, must not take one of our own paths, and must never equal a random code | In: the name asked for. Out: the name in lowercase, or a 400 error that says why | Rules in code, checked on every alias. A check at the database alone could not refuse "login" |
4.4 Stage 4: counting clicks
The problem. On Thursday at 12:40, Jenna opens her dashboard to see how the TV chef's post is doing. About 40,000 clicks a second hit wl.nut/holiday-menu at the peak. The CDN answers 25% of all clicks without asking us, so our own servers never see those clicks.
What we need:
- every click counted once, including those the CDN answers alone;
- counting that never slows a click, even when the counting side is down;
- bot visits apart from people, and no stored IP addresses;
- a dashboard that shows clicks within a minute.
So we count from the CDN's own log of every request, not from our Redirect services. Every click passes the CDN, whether it is answered there or sent on to us. So its log holds every click.
The click lines. The CDN logs every request it gets. Each line holds the code, the time and the country. It also holds the IP address and the user agent, which names the browser or app.
The CDN pushes these lines to us in batches of about 1,000, a few times a second.
- C1. CDN → Log receiver, Thu 12:39:20. Batch b_552301 arrives with about 1,000 lines. If our answer does not come back, the CDN sends the same batch again later.
- C2. Log receiver → Link cache. Has batch b_552301 been written before?
- C3. Link cache → Log receiver. No.
- C4. Log receiver → Click log. It cleans each line and writes it to the Click log:
- the IP address becomes a salted hash, and the address itself is dropped;
- the user agent becomes a device kind, such as phone, and a bot flag. Chat apps that fetch link previews are marked as bots;
- lines go to any of the log's 32 parts, called partitions. We give no key, the value that would pin all lines of one link to one part. So one viral link spreads over all 32.
- C5. Click log → Log receiver. The log confirms the lines are stored on 3 machines.
- C6. Log receiver → Link cache. It marks b_552301 as written, for 1 hour.
- C7. Log receiver → CDN. 200 OK. A repeat of b_552301 now gets OK at once, with nothing written twice.
- C8. Click log → Click store. The Click store reads new lines every few seconds, in large batches. Each batch adds rows to the clicks table and updates the counts per link and hour.
A line reaches the counts about 30 seconds after the click, at p95.
Jenna's dashboard.
- 1. Jenna's Walnut Link app → Link API, 12:40:05. GET /v1/links/holiday-menu/stats.
- 2. Link API → Click store. A sum over the counts per hour for holiday-menu, by country and device.
- 3. Click store → Link API. The counts, in about 200 ms.
- 4. Link API → Jenna's Walnut Link app. 1.9 million clicks since noon, 6% of them bots. The newest minute is about 40 seconds behind.
The Redirect service sends nothing to the counting side. So a Click log or Click store outage can delay counts, but it cannot slow or fail a click.
The new boxes.
| Box | What it is, and the problem it solves | In, and out | Tech, and why not the obvious other |
|---|---|---|---|
| Log receiver | Our service, as many identical pods. The problem it solves: click lines from the CDN are cleaned once, written once and never hold up a click | In: batches of log lines from the CDN. Out: cleaned lines to the Click log; OK to the CDN | A small program. Writing raw CDN lines straight to the Click store would store IP addresses and count repeat batches twice |
| Click log | A durable ordered log such as Kafka, one cluster per region, with 32 partitions. Each line is kept on 3 machines for 3 days. The problem it solves: a slow or failed Click store catches up later, with nothing lost | In: cleaned click lines, up to 30 MB a second. Out: lines in order, to any reader | Kafka, because readers keep their own place in the log. A queue that deletes each message once read could not replay a day |
| Click store | A column database for counting, such as ClickHouse. One copy in US East and one in US West. The problem it solves: sums over billions of clicks in under a second | In: batches of click lines. Out: counts by link, hour, country, device and referring site | ClickHouse, because it reads only the columns a sum needs. The Links store cannot sum billions of rows |
4.5 Stage 5: three regions
The problem. Our visitors live in the US and in Europe, and a region can fail, as US East does on Friday. So the design runs in three regions: US East in Virginia, US West in Oregon and EU in Frankfurt. Each region has the whole design and a full copy of every link.
Monday shows the first catch. Jenna's cup link is made in US West at 13:05:02.
One second later, Kyle Brooks opens it from Jenna's email, at Harbor's design agency in New York. His click reaches US East, which may not have the new row yet.
What we need:
- each region makes codes alone, with no call to another region, and no two regions ever make the same code;
- a click works in any region, even on a link made a second ago somewhere else;
- an alias is unique worldwide, even when two regions are asked for it at the same moment.
Code slices. Each region may only make codes that start with one of its own 20 characters:
| Region | First characters | Codes in its slice | Example |
|---|---|---|---|
| US East | 0 to 9, a to j | 20 × 62⁶, about 1.14 trillion | c4Rt9wLm2Q, Ben's private link |
| US West | k to z, A to D | about 1.14 trillion | kH7q2Xa, Jenna's cup link |
| EU | E to X | about 1.14 trillion | Gp4Lx9T, the fake gift card link |
| Spare | Y, Z | kept for later |
So a region's conditional insert only needs to check the copies in its own region. No other region can ever write a code in its slice. And from a code's first character, any region can tell which region made it: the code's home region.
The steps.
- 1. Kyle's laptop → CDN, 13:05:03. GET /kH7q2Xa.
- 2. CDN → Redirect service in US East. The CDN sends each click it cannot answer to the nearest healthy region. For New York, that is US East.
- 3. Redirect service → Links store, US East copy. The Link cache misses, as the gray arrow shows. So the Redirect service reads the row from the US East copy.
- 4. Links store, US East copy → Redirect service. No row. The row is still on its way from US West.
- 5. Redirect service → Links store, US West copy. The code starts with k, so US West made it. A missing row in US East may just be late. The Redirect service reads the row in US West. It asks 2 of the 3 copies there, so one copy that is behind cannot wrongly say there is no row.
- 6. Links store, US West copy → Redirect service. The row arrives 70 ms later, the time of one round trip across the country.
- 7. Redirect service → CDN. 302 Found, as in stage 2.
- 8. CDN → Kyle's laptop. The 302. Kyle's click took about 80 ms longer than usual, and nothing failed.
The copies between regions.
- M1. Links store, US West copy → US East copy. Each new row is copied to the other regions in the background. It usually arrives within 200 ms. Today it took 1.4 seconds, because a large bulk import was running.
- M2. Links store, US West copy → EU copy. The same row, copied to Frankfurt.
A code that truly does not exist costs one extra read in its home region. Then the answer "no such code" is kept as miss:{code} in the Link cache for 60 seconds. So a typo repeated many times reads US West only once a minute.
Creates. An API call finds the nearest region through DNS. A DNS provider answers api.wl.nut with the address of the nearest healthy region.
Jenna's print tool in Seattle reaches US West, so her code starts with a US West character. The create writes to 2 of the 3 copies in US West, then returns. The other regions get the row a moment later, by M1 and M2.
Aliases are different. An alias such as black-friday has no home region, since any region may be asked for it. So its conditional insert must check every region, not just one.
This takes about 200 ms, the time of three round trips between regions. Aliases are 2% of new links, so few creates pay it. The deep dive on aliases follows Tom's and Hannah's race on Tuesday.
Clicks from every region. Each region has its own Log receiver and Click log. The CDN sends each batch of lines to its nearest region.
The Click store's US East copy reads all three Click logs, and the US West copy reads the same lines. So the dashboard works from either copy.
The new boxes.
| Box | What it is, and the problem it solves | In, and out | Tech, and why not the obvious other |
|---|---|---|---|
| Kyle's laptop | A visitor's browser. The problem it solves for Kyle: it follows the link in Jenna's email | In: a click. Out: GET /kH7q2Xa | Any browser |
| Links store, US East copy | Three copies of every link in Virginia, each on a different node. The problem it solves: clicks in the east read nearby, and US East's own codes are written here first | In: US East's new rows; rows copied from the other regions. Out: rows by code | The same ScyllaDB cluster. It spans all three regions, with 3 copies in each |
| Links store, US West copy | The same, in Oregon | In: US West's new rows, such as kH7q2Xa; copies from the others. Out: rows by code, also to other regions that ask for a new row | The same cluster |
| Links store, EU copy | The same, in Frankfurt. European links and clicks stay fast | In: EU's new rows; copies from the others. Out: rows by code | The same cluster |
| DNS | An outside company that answers api.wl.nut with the nearest healthy region. Drawn in the full picture. The problem it solves for us: API calls reach a working region without a list of servers | In: a name lookup. Out: the address of a region | A DNS provider with health checks. One fixed address would point to a dead region during a failure |
4.6 Stage 6: scams and guessing
The problem. On Wednesday at 11:02, an account makes the short link Gp4Lx9T in EU. It points to a fake Harbor Coffee gift card page that asks for card numbers.
The page is 20 minutes old, so no threat list knows it yet, and our check on create passes it. Emails carry the link to thousands of people.
On Thursday at 03:10, a scanner tries 2 million random codes an hour from 4,000 addresses. It is looking for links like Ben's, whose long URL holds a secret.
What we need:
- a second check of a new link once it gets busy, when a threat list may know more;
- a block that stops the link everywhere within a minute, in every cache;
- a person who reviews each block and can close the account behind it;
- codes too long to guess for links that carry a secret, and limits on anyone who guesses.
The block, on Wednesday.
- T1. Safety scanner → Click store, 11:14:00. Once a minute, it asks for busy new links. A busy new link was made in the last hour and has over 1,000 clicks.
- T2. Click store → Safety scanner. Gp4Lx9T was made at 11:02 and now has 1,012 clicks.
- T3. Safety scanner → Threat list provider. Is harbor-giftcard.example on a threat list now? At 11:02 it was not, when the Link API checked it on create.
- T4. Threat list provider → Safety scanner. Yes: listed as phishing since 11:09.
- T5. Safety scanner → Links store, 11:14:20. It sets the row's status to blocked, and adds purge pg_1182 to the purges table. The row change reaches every region within about a second.
The purge. A blocked row is not enough. Copies of the old redirect sit in the CDN and in every Link cache.
- P1. Links store → Purge worker. The Purge worker reads pending purges every 2 seconds, and finds pg_1182.
- P2. Purge worker → Link cache, in each region. It deletes link:Gp4Lx9T in all three regions.
- P3. Purge worker → CDN. It asks the CDN to drop its copies of /Gp4Lx9T on every CDN server. This takes a few seconds.
- P4. Purge worker → Links store, 11:14:40. pg_1182 is done. If a call had failed, the purge would stay pending and be tried again 2 seconds later.
The Memory caches are not purged, because their copies end within 10 seconds anyway. So by 11:14:50 every click on Gp4Lx9T gets a warning page.
In all, about 1,100 people opened the fake page before the block. An owner's delete takes the same path, with status deleted.
Even with no purge at all, the old answer could live at most 1 hour in a Link cache. The CDN keeps a copy for at most 60 seconds. A purge makes the stop come sooner.
Nora's review. Nora Kim is on our trust and safety team, in Atlanta.
- 1. Trust console → Link API, 11:40. Nora opens the list of today's automatic blocks.
- 2. Link API → Trust console. Gp4Lx9T, with the threat list's answer and its click count.
- 3. Trust console → Link API. She confirms the block and suspends account acct_9054.
- 4. Link API → Trust console. Done. The account's 37 other links are blocked in the Links store, as the gray arrow shows, each with its own purge.
The scanner, on Thursday. No new box stops it. Three limits slow it down, and longer codes make it useless against private links:
- Each Redirect service counts unknown codes per IP address in the Link cache. An address with over 30 unknown codes in a minute is blocked at the CDN for an hour.
- Every unknown code is kept as miss:{code} for 60 seconds, so repeated guesses never reach the database.
- We watch the share of clicks on unknown codes. It is about 2% on a normal day. At 03:12 it rose to 31%, and Sam was paged.
This scanner spread its guesses over 4,000 addresses, about 8 a minute each. That stays under the per-address limit.
So at 03:40 the CDN's bot rules started a browser challenge for those addresses. Real browsers pass it, and scripts fail. The scan stopped at 03:52.
It had found about 4,000 public links, pages anyone with the link could already open. It could not find Ben's private link, as the deep dive on guessing shows.
The new boxes.
| Box | What it is, and the problem it solves | In, and out | Tech, and why not the obvious other |
|---|---|---|---|
| Safety scanner | Our background job, run once a minute. The problem it solves: a scam page that was unknown at create time is caught when its link gets busy | In: busy new links from the Click store; answers from the threat list. Out: blocks and purges in the Links store | A job that checks only busy new links, about 30,000 a day. Checking all 10 billion links again every day would cost far more and find little |
| Threat list provider | An outside company that keeps lists of known scam and malware sites, such as Google Safe Browsing. The problem it solves for us: a check against sites reported across the whole web | In: a site name. Out: listed or not, and why | A rented service. Our own list would know only what our users report |
| Purge worker | Our background job. The problem it solves: a blocked or deleted link stops everywhere within a minute, not when the caches happen to expire | In: pending purges. Out: deletes in every Link cache; purges at the CDN | A job with a table of pending purges, so a failed call is tried again. A purge sent once from the Link API would be lost if that pod died |
| Nora's Trust console | Our web app for the trust and safety team. The problem it solves for Nora: she reviews blocks and reports, and closes bad accounts | In: Nora's choices. Out: reviews, suspensions | An internal web app on the same Link API, so every action is checked and logged |
4.7 Stage 7: the full picture
This is the design to draw at the end of an interview. Its arrows walk the life of Jenna's cup link, from Monday's create to Thursday's click.
The walk. These step numbers belong to this figure only.
| Steps | What happens | Explained in |
|---|---|---|
| 1 to 4 | Jenna's print tool makes kH7q2Xa in US West: claim the request, conditional insert, answer | Stage 1 |
| 5, 6 | Mia's click reaches the CDN, which sends it to the nearest region | Stages 2 and 5 |
| 7, 8 | The Redirect service finds the row in the Link cache | Stage 2 |
| 9 to 11 | The 302 goes back through the CDN, and Mia's phone opens Harbor's page | Stage 2 |
Also in the design.
| Kind | Boxes | Explained in |
|---|---|---|
| Inside programs | Code maker, Alias rules, Memory cache | Stages 1, 3 and 2 |
| Counting | Log receiver, Click log, Click store | Stage 4 |
| Regions | Links store copies in US East, US West and EU; DNS | Stage 5 |
| Safety | Safety scanner, Threat list provider, Purge worker | Stage 6 |
| Apps | Jenna's Walnut Link app, Nora's Trust console | Stages 3 and 6 |
The story in time order.
- Mon 13:05: Jenna's cup link and its retry, stage 1, steps 1 to 7.
- Mon 13:05:03: Kyle's click on a row still on its way, stage 5, steps 1 to 8.
- Mon 13:07: the holiday-menu alias, stage 3, steps 1 to 4.
- Tue 09:00: Tom's and Hannah's race for black-friday, the deep dive on aliases.
- Wed 10:15 in Chicago: Ben's private link, stage 3.
- Wed 11:14: the fake gift card link blocked and purged, stage 6, T1 to T5 and P1 to P4.
- Thu 03:10: the scanner, stage 6.
- Thu 08:10: Mia's scan, stage 2, steps 1 to 9.
- Thu 12:00: the TV chef's post, the deep dive on caches.
- Thu 12:40: Jenna's dashboard, stage 4, C1 to C8 and steps 1 to 4.
- Fri 06:40: US East fails, the failures section.
- Wed 25 Nov, 10:15 in Chicago: Ben's link ends, stage 3.
Which parts hold state.
- No data of their own: the Link API, the Redirect service and the Log receiver. Any pod can die, and another takes its requests.
- Caches that can be rebuilt: the Memory caches, the Link cache and the CDN's copies. Losing one costs speed, not data.
- Logs read in order: the Click log. The Click store keeps its own place in it.
- The data that must never be lost: the Links store holds every link, and the Click store holds every counted click. Both have copies in more than one region.
5. Deep dives
5.1 Short codes: random, with a conditional insert
The problem. On Monday at 13:05, the Code maker in US West must pick a code for Jenna's cup link. The Links store already holds about 10 billion links, and the new code must be one no link has used. The pick must be fast, and it must not need a call to any other region.
The idea. Pick the code at random from so many possible codes that clashes are rare. Then let the database decide in one step: write the row only if the code is free. On the rare clash, pick again.
Why one step. If we check first and write second, two creates can both see "kH7q2Xa is free" and both write it.
So the database does both at once: it saves the row only if the code is free. Otherwise it says no. This is the conditional insert.
An example. Each character has 62 choices, so the length sets how many codes there are:
| Length | Codes | 10 billion links would use | What we use it for |
|---|---|---|---|
| 6 | 62⁶, about 56.8 billion | about 1 in 6 | Too few: 1 random pick in 6 would be taken, and the codes run out within years |
| 7 | 62⁷, about 3.5 trillion | about 1 in 352 | Our choice for normal links |
| 8 | 62⁸, about 218 trillion | about 1 in 21,800 | Kept for later, when a slice fills |
| 10 | 62¹⁰, about 840 quadrillion | about 1 in 84 million | Private links |
| 22 | A UUID, a random 128-bit ID, written in Base62 | almost none | Unique, but three times longer than our codes. Too long for a short link |
Region slices. Each region owns its own set of first letters, as Figure 8 below shows. So two regions can never make the same code, and they never need to ask each other.
US East makes 45% of all links, so at 10 billion links its slice holds 4.5 billion codes. That is 4.5 billion used out of 1.14 trillion, about 1 in 250. So:
- the average create makes 1.004 tries;
- two clashes in a row happen about once in 63,000 creates;
- the Link API gives up after 5 clashes in a row, which would happen about once in a trillion creates.
How it works inside.
Figure 8. The first character names the region that made the code. The other six are random.
The Code maker picks the first character from its region's slice, and the rest from all 62. Python's secrets module uses the operating system's secure random source, so no one can predict the next code from the last one:
import secrets
B62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
SLICE = {"us-east": B62[0:20], "us-west": B62[20:40], "eu": B62[40:60]}
def make_code(region, length=7):
first = secrets.choice(SLICE[region])
rest = "".join(secrets.choice(B62) for _ in range(length - 1))
return first + rest
print(make_code("us-west")) # a code such as kH7q2XaThe Link API then writes the row with a conditional insert:
INSERT INTO links (code, long_url, account_id, kind, created_at, status)
VALUES ('kH7q2Xa', 'https://www.harborcoffee.example/menu/holiday-2026?src=cup',
'acct_2207', 'random', '2026-11-16 18:05:02+0000', 'live')
IF NOT EXISTS;
-- run with serial consistency LOCAL_SERIAL: the vote uses only this region's 3 copiesInside the database, a conditional insert is a short vote among the 3 copies in the region. The vote follows Paxos, a standard way for copies to agree, so only one writer can win.
In ScyllaDB it takes 3 round trips between the copies, about 2 ms in one region. It is about 4 times the work of a plain write.
We make up to 1,000 links a second. Each check costs about 4 plain writes, so that is like 4,000 writes a second for the whole Links store. That is light.
A vote slows down only when many writers want the same row, and random codes almost never do. So twice the creates needs twice the nodes, with no extra slowdown.
When to add a character. We move a region to 8-character codes when it has used 2% of its slice. That is about 22.7 billion of its 1.14 trillion codes. At US East's 4.5 million new links a day, that is about 14 years away.
Old 7-character codes keep working, because the Redirect service reads any length.
Why not a hash of the long URL. A hash gives the same code for the same URL. That sounds useful, but two customers who shorten the same page need separate links, with separate owners and counts.
And 7 characters of a hash clash too: past about 2 million links, a clash is more likely than not. So a hash still needs the conditional insert, and gives nothing in return.
The trap. A weak random source, such as one seeded with the time. Its codes can be predicted.
5.2 Counter blocks: the other way, and how it breaks
The problem. Most interviewers ask: "why not use a counter, so codes can never clash?" A counter is the most common answer to this question. So a candidate must know how it works, and exactly where it fails.
The idea. A counter store hands each server a block of numbers, for example the next 10,000. The server counts through its block in memory, with no call per create. A shuffle with a secret key turns each number into a code that looks random, so the next code cannot be guessed from the last.
An example. Pod 7 of the Link API asks the counter store for a block. The store moves its value from 50,000 up to 60,000 in one write. Its answer gives pod 7 the numbers 50,001 to 60,000.
For each new link, pod 7 takes the next number, shuffles it and writes the row with a plain insert. At 1,000 creates a second over all pods, the counter store gets one write about every 10 seconds.
How the shuffle works. The shuffle is a small cipher: a scramble that only the secret key can undo. It is reversible, so two different numbers always give two different codes. One common build is a Feistel network:
- Write the number in 42 bits. 42 bits is the smallest size that holds 62⁷, about 3.5 trillion.
- Split the 42 bits into two halves of 21 bits, left and right.
- Mix a keyed hash of the right half into the left half. Then swap the halves.
- Repeat. Each repeat is called a round.
Two rounds are not enough. With two rounds, a change in one half of the input shows up in the output in a fixed pattern. So a watcher can learn the order of codes.
Four rounds remove such patterns. A tested standard for this job is FF1, from NIST, the US standards body. FF1 is a cipher whose output has the same format as its input.
62⁷ is not a power of two. So a result of 62⁷ or more is shuffled again until it fits. Last, the result is written in Base62 as a 7-character code.
The shuffle, for one number. Pod 7 takes the first number in its block: 50,001. In 42 bits, its left half is 0 and its right half is 50,001.
After four rounds, both halves depend on every bit of the number and on the key. The result is about 2.9 trillion, below 62⁷, so no second shuffle is needed. In Base62 it is PjaMscI.
The next number, 50,002, gives a code with no visible link to PjaMscI.
Where it breaks. This table is the heart of the comparison:
| What happens | What it causes | What the design must add |
|---|---|---|
| A server crashes in the middle of its block | Its unused numbers are lost: a gap | Nothing. A gap does no harm |
| A block runs out | The server waits for a new block | Ask for the next block at 80% used, and keep one spare block |
| The counter store is slow or down | Servers live on their spare block, then creates fail | A counter store that runs on 3 machines, and spare blocks large enough to cover a failover |
| Two servers ask for a block at the same moment | Both could get 50,001 to 60,000 | A compare-and-set update: move the value only if it still says 50,000 |
| The counter goes backwards: a restore from an old backup, or a failover to a copy that was behind | The same numbers are handed out again. The same codes are made, and a plain insert overwrites the old links | Check every insert. After a restore, move the counter far ahead |
| The shuffle key leaks | Codes reveal their order, and so how many links exist and when each was made | A new key with new codes. Old codes cannot be changed |
| A second region is added | Two regions would count the same numbers | A region number inside every counter value |
The dangerous row is the one in bold. Nothing fails loudly. Weeks of links can be overwritten, and each printed cup or old email would send people to a stranger's page.
Figure 9. A counter that goes backwards hands out old codes again. Only a conditional insert on each link notices.
What happens on a clash. Both designs check each new code. If the code is already used, the database says no. Nothing is overwritten.
With random codes, this happens about 1 time in 250. We pick a new random code and try again.
With a counter, the pod skips that number and takes the next one from its block.
Why the counter must jump ahead. Say the counter is at 50,600,000. Then it is restored from a backup that says 50,000,000.
The next 600,000 numbers are already used. Skipping them one by one would take hours.
So after a restore, we move the counter far ahead, for example by 100 million. A day of creates is at most 86.4 million, so this is enough. We have 3.5 trillion codes, so skipping 100 million costs nothing.
Why random codes win. A counter still needs the same check as random codes. It also needs a counter store and a secret key. Random codes need neither.
Which one wins at larger scale. Both handle far more than our load. The table compares them as creates grow, with each rate held all year:
| Creates a second | Links a year | Code length needed | Link data a year, 9 copies | Better choice |
|---|---|---|---|---|
| 1,000, our design capacity | 31.5 billion | 7 characters | about 100 TB | Random: no counter store, and no silent overwrite |
| 100,000 | 3.15 trillion | 8, since 7 fill in about a year | about 10 PB | Random: the many machines needed for storage handle the extra checks easily |
| 1,000,000, links that end within a day | 31.5 trillion, few kept | 8 or 9 | small, since rows end fast | Counter blocks: only here does the cheaper plain insert matter |
Two things stand out:
- We run out of 7-character codes before the extra cost of the check matters. So both designs move to 8 characters at about the same time.
- At that size, we need hundreds of machines just to store the data. They handle the extra checks easily.
The trap. Saying a counter can never clash. That is true only while the counter never goes backwards. Counter stores do go backwards, after restores and failovers.
5.3 Guessing, scams and private links
The problem. On Thursday at 03:10, a scanner tries 2 million random codes an hour. Walnut Link holds about 10 billion links in 3.5 trillion codes, so 1 random guess in 352 opens a real link. At 2 million guesses an hour, that is about 5,700 links an hour.
The idea. A 7-character code keeps links short, but it is not a password. A link that carries a secret needs a much longer code. And limits make guessing slow and loud.
An example. Ben's private link has 10 characters, so there are 62¹⁰ codes, about 840 quadrillion. Walnut Link holds about 300 million private links. So one guess finds a private link about 1 time in 2.8 billion.
At 2 million guesses an hour, the scanner would need about 58 days of nonstop guessing to find one. Our alert fires within minutes.
How it works inside.
- Per-address limits. An IP address with over 30 unknown codes in a minute is blocked at the CDN for an hour. The Redirect service counts unknown codes in the Link cache.
- Unknown codes are cached. Each one is kept as miss:{code} for 60 seconds, so a repeated guess never reaches the Links store. If a new link later gets that code, the Link API deletes the miss key in its region. Other regions drop theirs within 60 seconds.
- An alert on the share of unknown codes. It is about 2% on a normal day. A scanner pushes it far higher, as on Thursday, when it reached 31%.
- A browser challenge. The CDN's bot rules can ask addresses for a browser check. Scripts fail it.
- No way to list links. No API lists links that belong to another account.
Scams. A short link hides where it goes, so scammers like them. Three checks run on every create:
- The long URL must start with http or https.
- Its site is checked with the Threat list provider. This takes about 50 ms.
- A long URL that points to another short-link service is refused, and so is one that points back to wl.nut. A chain of short links hides the final page from every check.
A new scam page is often unknown at create time, as the fake gift card page was. So the Safety scanner checks again when a new link gets busy, and the Purge worker clears every cache.
The trap. Treating a 7-character random code as a secret. It is safe from guessing only while few links exist.
At 10 billion links, a scanner finds thousands an hour. So links that carry a secret need a long code and an end time.
5.4 Redirects and caches: 301 or 302, and the viral link
The problem. On Thursday at 12:00, the TV chef posts wl.nut/holiday-menu. Three minutes later, 40,000 clicks a second arrive for this one code. If each one reached our servers, the cache shard that holds holiday-menu would take all 40,000 reads a second.
The idea. Answer repeat clicks as near the visitor as possible. The CDN answers most of them, and the Memory cache in each pod answers the rest. Only a few reads a second reach the Link cache.
An example. About 600 CDN servers see clicks for holiday-menu. Each one asks us at most once every 60 seconds, so about 10 requests a second reach our Redirect services.
Each pod keeps the row in its Memory cache for 10 seconds. So each pod reads holiday-menu from the Link cache at most once every 10 seconds, however many people click. Meanwhile 40,000 people a second click.
Figure 10. Four levels: three caches and the database. The Links store sees 15 of every 100 clicks.
301 or 302. Both send the visitor on. They differ in what the browser remembers:
| 301 Moved Permanently | 302 Found, our choice | |
|---|---|---|
| What the browser does next time | Goes straight to the long URL, without asking us | Asks us again |
| Clicks after the first | Not counted. We never see them | Counted |
| An expired, deleted or blocked link | Keeps working in that browser for as long as it keeps its copy | Stops at once |
| Load on us | Lower | The CDN carries most of it |
So we send 302, with Cache-Control: max-age=0, s-maxage=60. The browser keeps no copy. The CDN may keep one for 60 seconds, and our purges remove it sooner.
The cache header trap. The header "private, max-age=60" looks similar. But it forbids every shared cache, the CDN included. The CDN would then pass every click on to us.
The word private means "only the browser may keep this".
When the Link cache misses a hot link. Say the Link cache shard that holds holiday-menu restarts. Every pod would miss at once, and thousands of requests could read the Links store for one row.
So each pod lets one read go per code, and the other requests for that code wait for its answer. At most 60 reads reach the Links store, one per pod.
The risk in the numbers. Normally 75,000 clicks a second reach our servers. Our caches answer 80% of them, so 15,000 reach the Links store.
The caches work well because a few links get most clicks. Say a customer mails 100 million links at once, each getting a few clicks. Now the cache helps much less.
If the caches answered only 30%, 52,500 reads a second would reach the Links store. It is built for 30,000. So we page the on-call engineer when the caches answer less than 65%.
The trap. Choosing 301 because it is faster. It is, but it hands control of the link to every browser that has seen it. A blocked scam link would keep working for its past visitors.
5.5 Custom aliases
The problem. On Tuesday at 09:00:00.000, Tom asks for black-friday through US West. At 09:00:00.040, Hannah asks for the same alias through US East. An alias has no home region, so each region could think the name is free and give it away.
The idea. One vote across all three regions decides each alias. The first request to win the vote gets the row. The second sees that row and is told "taken" at once.
An example. Both requests run a conditional insert that checks all three regions, not just their own. Then the vote must win a majority of all 9 copies, at least 5. That needs copies in at least two regions.
Figure 11. The vote needs 5 of the 9 copies, so two regions can never both win. Tom's vote finished first.
- Tom's vote reaches 5 copies first, and writes the row for acct_5518 at about 09:00:00.190.
- Hannah's vote reads the same copies, sees Tom's row, and is not applied.
- Tom gets 201 Created after about 200 ms. Hannah gets 409 Conflict, with black-friday-boston offered instead.
How it works inside.
- The alias is turned to lowercase first, so Black-Friday and black-friday are one alias.
- The vote takes about 3 round trips between regions, about 200 ms. Aliases are 2% of creates, so this cost is small.
- With one region down, 6 of the 9 copies remain, more than the 5 a vote needs. So aliases can still be made.
- An ended alias stays with its account. The same account may use it again later. No other account can take it, so an old poster never sends people to a stranger.
Why not one leader region for all aliases. A leader region would keep each vote inside one region, at about 5 ms. But when the leader is down, no alias can be made anywhere. The vote across regions keeps working with any one region down.
The trap. Checking the alias only in the region that got the request. Tom and Hannah would both win, each in their own region.
When the copies met, the database would keep whichever row was written last: Hannah's. Tom's emails would then send his customers to a running store.
5.6 Expiry and deletion: a code is never reused
The problem. Ben's link ends on 25 November at 10:15 in Chicago. If its code could later be given to a new link, Ben's old emails would open a stranger's page. The same holds for 2 million printed cups.
The idea. End the link, but keep its code. The row stays in the Links store with its code and dates, and only the long URL goes.
An example. An ended row keeps about 60 bytes. Say 3 billion of our 10 billion links end:
- 3 billion × 60 bytes = 180 GB a copy;
- 180 GB × 9 copies = about 1.6 TB, about 5% of the 31.5 TB.
How it works inside.
- Expiry. The Link API writes the long URL with a time to live, as in stage 3. The database drops it at that time, with no cleanup job.
- The answer. A row with no long URL gets 410 Gone. So does a row past its expires_at time, even if the database has not dropped the URL yet.
- The caches. A cached row carries its expires_at time. The Redirect service checks the time on every click, so an expired link stops at its exact second, with no purge.
- The CDN. Close to an end time, the CDN keeps the 302 for fewer seconds. It keeps it for 60 seconds or for the seconds left, whichever is less. So the CDN never serves a link past its end.
- Deletion. An owner's delete sets the status to deleted and keeps the row. It also adds a purge, as stage 6 shows.
The trap. Letting the database delete the whole row at its end time. The next conditional insert for that code would then succeed, and the old code would point somewhere new.
A second trap is a nightly job that scans all 10 billion rows for expired links. The time to live does that work as rows age.
5.7 Counting clicks
The problem. On Thursday at 12:03, holiday-menu takes 40,000 clicks a second. The CDN answers most of them alone. Jenna wants every one counted within a minute, with bots apart.
The idea. Count from the CDN's log, which sees every click. Then:
- spread the clicks evenly over the log's 32 parts;
- drop repeat batches;
- mark bots, and keep no IP addresses.
The Click log is split into 32 parts, called partitions, spread over its machines. Each click line goes to one part. A key, such as the code, would send every line for one link to the same part.
An example. One code sends 40,000 lines a second. Each of the Click log's 32 partitions takes about 1,250 of them.
If lines were keyed by code, all 40,000 would go to one partition. That one partition would carry about 12 MB a second, while the other 31 sat idle.
How it works inside.
- No key. Kafka spreads lines with no key over all partitions. Counting needs no order between clicks, so no key is needed.
- Repeat batches. The CDN sends a batch again if our answer is lost. The Log receiver marks each written batch ID in the Link cache, so a repeat is answered OK with nothing written. If a Log receiver dies after writing but before marking, one batch of about 1,000 clicks is counted twice. That is rare, and we accept it.
- Bots. A list of known bot user agents, kept in the Log receiver, marks chat apps, search engines and link checkers. About 6% of clicks are bots. Dashboards show people by default.
- Unique visitors. The salted hash of the IP address counts unique visitors. The salt changes each month, so a hash cannot follow a person for long.
- No extra stream processor. ClickHouse reads Kafka itself and updates the counts per hour as lines arrive. A separate stream processor such as Flink is needed only for work across many clicks. One example is spotting a visitor hash with 500 clicks a minute.
Why not count in the Redirect service. It never sees the 25% of clicks the CDN answers alone. It would also put counting work on the click path. Then a slow Click log could slow every click.
The trap. One counter per link in a database, raised on every click. Holiday-menu's one row would then take 40,000 updates a second.
5.8 Three regions, and why ScyllaDB
The problem. On Friday at 06:40, US East's network fails. Visitors and programs must move to the other regions, and links made anywhere must open everywhere.
On Monday, Kyle clicked a link one second after it was made, before the copy reached his region. Stage 5 showed how he still got it.
The idea. Every region holds a full copy of every link. A create writes in its own region and returns. Copies to the other regions follow in the background, and a read that finds no row asks the code's home region.
An example. Each part of the design uses its own level of agreement between copies:
| Action | Copies that must answer | Time | Why |
|---|---|---|---|
| Make a random code | A vote among the 3 copies in the region | about 2 ms | The code slice means no other region can make this code |
| Write the link row | 2 of the 3 copies in the region | about 2 ms | One copy can die without losing the link |
| Read for a click | 1 copy, the nearest | under 1 ms | A row changes only when its link ends or is blocked |
| Read a late row: one not copied here yet | 2 of the 3 copies in the home region | about 70 ms | Only for a missing row |
| Make an alias | A vote among 5 of all 9 copies | about 200 ms | An alias has no home region |
A block or a delete changes a row's status. A copy may miss that change for about a second, and the purge then clears every cache.
Why the code slices. Without them, US West and EU could both pick kH7q2Xa within the second before their copies meet. Each local vote would approve its own row. Later, one row would silently replace the other.
Why ScyllaDB. The Links store needs fast reads by one key, conditional inserts, copies in three regions and a time to live per column. Four common choices:
| Database | Fit for us | The catch |
|---|---|---|
| ScyllaDB, our choice | Fast reads and conditional inserts. A vote takes 3 round trips. Copies across regions are built in | Free use stops at 50 vCPUs and 10 TB in all. Our 31.5 TB is already far past 10 TB, so we pay for a license or for ScyllaDB Cloud |
| Apache Cassandra | The same data model and query language. Fully open source, with no license fee | A vote takes 4 round trips. More nodes for the same load, and pauses while its Java memory is cleaned |
| DynamoDB global tables | Run by AWS, with no servers to manage. Conditional writes and a time to live are built in | By default, a conditional write checks only its own region's copy, so code slices are still needed. A strong mode across regions makes every write slower |
| Postgres | Simple and well known. Good for one region and under a few TB | One server takes all writes. 31.5 TB in three regions would need sharding by hand |
Why ScyllaDB is fast: one shard per CPU core. ScyllaDB splits each node's data by CPU core. Each of a node's 16 cores owns its own slice of the keys, with its own memory and its own disk queue:
- A read for kH7q2Xa goes straight to the one core that owns that key.
- Cores never share data, so they never wait on each other for a lock.
- ScyllaDB is written in C++, so there are no pauses to clean up memory.
So one 16-core node works like 16 small servers side by side. A read by key stays near 1 ms even when the node is busy.
Cassandra's threads share data and need locks, and its Java memory cleanup can pause requests for a moment. So Cassandra needs more nodes for the same load.
A team that will not pay for a license should pick Cassandra. The design stays the same, with more nodes. A team that wants no database servers at all should pick DynamoDB, and keep the code slices.
The trap. Making every create wait for copies in all three regions. Each create would take about 100 ms more. And creates would stop whenever any region was down.
6. Trade-offs
Stage 1: random codes.
- The problem: 10 billion unique codes, made in three regions, with no call between regions.
- We chose random codes with a conditional insert. We did not choose counter blocks with a shuffle.
- The cost: a vote of about 2 ms on each create, and a retry about once in 250 creates at 10 billion links.
- The other choice wins for about a million short-lived links a second, where the plain insert's lower cost matters.
Stage 1: a request ID on every create.
- The problem: Jenna's print tool sent the same request twice.
- We chose a put-if-absent claim on the request ID, kept 24 hours. We did not choose to trust clients not to retry.
- The cost: one more vote per create, about 2 ms.
- The other choice wins never for a paid API. Duplicate links confuse customers and their counts.
Stage 2: 302 with a 60-second CDN copy.
- The problem: every click must be counted, and a blocked link must stop.
- We chose 302 with s-maxage=60. We did not choose 301.
- The cost: every click from a browser reaches the CDN, and 75% reach us: 75,000 a second at design capacity.
- The other choice wins for a link that never changes and needs no counts, such as a company's own fixed redirects.
Stage 2: a 10-second Memory cache.
- The problem: one viral link could send 40,000 reads a second to one Link cache shard.
- We chose a Memory cache in each pod, with rows kept 10 seconds. We did not choose to read the Link cache for every click.
- The cost: a delete or block can take up to 10 seconds longer to reach a pod.
- The other choice wins when links change often and must stop within a second.
Stage 3: a hyphen in every alias.
- The problem: an alias must never equal a random code.
- We chose to require a hyphen, which random codes never have. We did not choose a separate path such as wl.nut/a/holiday-menu.
- The cost: an alias such as "summersale" is refused, and "summer-sale" is offered instead.
- The other choice wins when customers insist on any word at all.
Stage 3: ended codes are kept forever.
- The problem: a reused code would send old emails and printed cups to a stranger.
- We chose to keep each ended row, about 60 bytes. We did not choose to reuse codes.
- The cost: about 1.6 TB over all copies for 3 billion ended links.
- The other choice wins never for public links.
Stage 4: counting from the CDN's log.
- The problem: the CDN answers 25% of clicks, and our servers never see them.
- We chose the CDN's log as the only source of clicks. We did not choose to send clicks from the Redirect service.
- The cost: counts arrive about 30 seconds after the click, and we depend on the CDN's log feed.
- The other choice wins with no CDN in front of the redirects.
Stage 5: code slices.
- The problem: two regions must never make the same code.
- We chose a slice of first characters per region. We did not choose a vote across regions for every code.
- The cost: 2 of the 62 first characters are kept spare, and a fourth region needs a new slice.
- The other choice wins with only one region.
Stage 5: an alias vote across regions.
- The problem: two regions can be asked for the same alias at once.
- We chose a vote among 5 of all 9 copies. We did not choose one leader region for aliases.
- The cost: about 200 ms for each alias create, against about 5 ms in a leader region.
- The other choice wins when alias creates must be fast and losing them during a region failure is fine.
Stage 5: copies follow in the background.
- The problem: a create must be fast, and must work with one region down.
- We chose to write in one region and copy after. We did not choose to wait for every region.
- The cost: a click within about a second of a create may need a read from the code's home region, about 70 ms more. Links made in a failed region's last second wait for it to return.
- The other choice wins when every link must be readable everywhere the instant it exists.
Stage 6: checking busy new links again.
- The problem: a scam page may be unknown when its link is made.
- We chose to check links again once they pass 1,000 clicks in their first hour. We did not choose to check all links every day.
- The cost: a scam link can work until it gets busy. The fake gift card link reached about 1,100 people.
- The other choice wins for a small service with few links.
Options we did not pick.
| Option | Why not |
|---|---|
| A hash of the long URL | Merges different customers' links, and 7 characters of a hash clash after about 2 million links |
| A UUID as the code | 22 characters, three times longer than our codes |
| Codes from a counter with no shuffle | Anyone can walk the codes one by one and read every link |
| Postgres for the links | One server takes all writes, and 31.5 TB in three regions needs sharding by hand |
| A database counter per link for clicks | One row would take 40,000 updates a second for a viral link |
| A stream processor for clicks | ClickHouse reads Kafka itself, and counting needs no state across clicks |
The summary.
| Stage | We chose | Instead of | What we got | What we gave up |
|---|---|---|---|---|
| 1 | Random codes, conditional insert | Counter blocks and a shuffle | No counter store, no silent overwrite | A 2 ms vote per create |
| 1 | A request ID claim | No claim | One link per request | One more vote |
| 2 | 302, 60 seconds at the CDN | 301 | Counts, and links that can stop | More traffic to the CDN and to us |
| 2 | A 10-second Memory cache | The Link cache for every click | A viral link costs us almost nothing | Up to 10 seconds more for a block |
| 3 | A hyphen in every alias | A separate alias path | One table, no clash with random codes | Some names refused |
| 3 | Keep every ended code | Reuse | Old links never point somewhere new | About 1.6 TB |
| 4 | Count from the CDN's log | Count in the Redirect service | Every click, nothing on the click path | About 30 seconds of delay |
| 5 | Code slices | A vote across regions per code | Creates in one region, about 2 ms | 2 spare first characters |
| 5 | An alias vote across regions | A leader region | Aliases during a region failure | About 200 ms per alias |
| 5 | Copies in the background | Waiting for every region | Fast creates, with one region down | Home-region reads for new rows, and a failed region's last second waits |
| 6 | Check busy new links again | Check every link daily | Low cost | A scam works until it gets busy |
7. Bottlenecks and failures
What runs out first.
Most parts keep no data of their own, so we add more of them as load grows. The parts that hold data are the real limits:
- The Links store's disk (stages 1 and 2). 31.5 TB, growing by about 11 TB over all copies each year. Its read load, 15,000 a second, is small. So disk, not traffic, decides when we add database machines: about every 6 months.
- The Link cache's memory (stage 2). About 60 GB per region. Memory, not reads, sets its size.
- The Click log and the Click store (stage 4). Up to 100,000 lines, about 30 MB, a second. They take them in batches, so a click never waits on them.
The biggest costs are the CDN and the database with its license.
Hot spots and busy days.
- A viral link. One code takes 40,000 clicks a second. The CDN and the Memory caches absorb it, as the deep dive on caches shows. We see about 10 requests a second for it.
- Mail campaigns on Monday mornings. Bulk creates of 1,000 links a call arrive together. Each API key has a limit, by default 6,000 creates a minute, so one customer cannot fill the Link API.
- A new link's first second. A link clicked before its row reaches the nearest region needs a read from its home region. A big launch, with a link mailed to millions at once, sees this for about a second.
- A guessing attack. Unknown codes jump from 2% of clicks to 30% or more. Caching unknown codes and the CDN's limits keep these guesses away from the Links store.
- Black Friday and the holidays. Clicks reach about 3 times a normal busy hour. Design capacity is about 3 times the busy hour, so we add Redirect service pods in early November.
At 10 times the load. One million clicks a second and 10,000 creates a second.
- The CDN carries most of it. 750,000 a second reach us, so we run 10 times the Redirect service pods.
- The Links store gets 150,000 reads a second, still small for the nodes its disk needs.
- New links reach 100 million a day. US East's slice would pass 2% full in about 1.4 years, so we move to 8-character codes early.
- The slowest part to add is Links store nodes. Each new node must copy its share of the data, which takes hours. So we add nodes long before disks fill.
When parts fail. Three promises hold in every failure below:
- A link that was returned to its creator is on at least 2 copies.
- No two links ever share a code.
- A click is never slowed by the counting side.
| Stage | Part that fails | What people see | How it keeps working | How it recovers |
|---|---|---|---|---|
| 1 | One Link API pod | Its few creates in flight fail | Clients retry with the same request ID, and another pod answers | Kubernetes starts a new pod within a minute |
| 1 | One Links store node | Nothing | 2 of the 3 copies in the region still answer every read and vote | The node is replaced, and its data copied from the others. Up to 6 hours, with an engineer |
| 2 | The CDN, in one city | Slower clicks in that city | The CDN sends those visitors to its next city | The CDN company fixes it |
| 2 | One Link cache shard | Up to 10 seconds of slower clicks | Its copy takes over. Meanwhile, its keys are read from the Links store | The failed machine rejoins as a copy |
| 4 | The Click log in one region | Counts from that region stop | The CDN keeps sending lines to the other regions' Log receivers | Lines already in that log are read when it returns |
| 4 | The Click store in US East | Nothing | Dashboards read the US West copy | The copy catches up from the Click logs, which keep 3 days |
| 5 | A whole region | About 30 seconds of slower clicks, and about a minute of failed creates there | The CDN and DNS move traffic to the other two regions | Copies catch up when it returns. An engineer decides when to move traffic back |
| 6 | The Purge worker | A block takes up to 60 seconds, not about 30 | Every CDN copy ends within 60 seconds anyway, and the second pod takes over | Pending purges stay in the table and run when it returns |
| 6 | The Threat list provider | New links skip the check for a while | Creates go on. The Safety scanner checks them again when the provider returns | The provider recovers |
Timeline: US East fails, Friday. The load at 06:40:
- About 20,000 clicks a second arrive worldwide. US East takes 45%, about 9,000.
- The CDN answers 25% of those, so about 6,750 a second reach US East's origin.
- About 100 creates a second arrive worldwide, about 50 of them in US East.
| Time | What happens |
|---|---|
| 06:40:00 | US East's network fails |
| 06:40:00 to 06:40:30 | The CDN's calls to US East time out after 1 second. The CDN then sends each click to US West. Each click takes about 1 second longer |
| 06:40:30 | After 3 failed health checks, 10 seconds apart, the CDN marks US East down. Clicks go straight to US West and EU |
| 06:40:00 to 06:41:00 | Creates sent to US East fail. DNS stops naming US East after 30 seconds, and old DNS answers last about 30 seconds more |
| 06:41:00 | All traffic is in US West and EU. Their Redirect services were sized to carry the full load |
| 06:41 to 09:10 | About 50 links made in US East's last second never reached the other regions. A click on one asks US East, gets no answer, and gets 503 "try again soon", not 404 |
| 09:10 | US East's network returns. Its copies catch up with the rows they missed |
| 09:25 | Sam moves traffic back to US East, a little at a time |
The sums:
- About 6,750 clicks a second × 30 seconds ≈ 200,000 clicks took about 1 second longer. Almost none failed.
- About 50 creates a second × 60 seconds ≈ 3,000 creates failed, and clients sent them again.
- About 50 links could not be opened for 2.5 hours.
A retry that lands in US West makes a new code if the first try's row stayed in US East. The client gets the new code. The old code is never returned to anyone.
Timeline: one Link cache shard fails. At design capacity, US East's origin takes about 33,750 clicks a second. Its Link cache gets 27,000 of them, about 4,500 on each of its 6 shards. It answers 75% of what it gets.
| Time | What happens |
|---|---|
| 0 s | Shard 3 of US East's Link cache dies |
| 0 to 10 s | Shard 3's hits now go to the Links store: 75% of 4,500, about 3,400 more reads a second. US East's Links store goes from about 6,750 to about 10,100 reads a second, under the 30,000 it is sized for |
| 10 s | Shard 3's copy becomes the main shard. It already holds the same keys |
| later | A new machine joins as the copy |
The sum: about 34,000 extra reads over 10 seconds, each about 1 ms slower. No click fails.
Timeline: the Click store in US East fails for 2 hours.
| Time | What happens |
|---|---|
| 0 | US East's copy of the Click store stops |
| 0 to 2 h | Dashboards read the US West copy, which keeps reading all three Click logs. Jenna sees no change |
| 2 h | The US East copy returns, and reads the Click logs from where it stopped. It catches up in about 20 minutes |
No click is lost, because the Click logs keep 3 days of lines.
What we watch.
- The share of clicks answered by the CDN, the Memory caches and the Link cache. We page the on-call engineer when the caches answer below 65%.
- p99 redirect time at our servers, on hits and on misses.
- The share of clicks on unknown codes, and blocks at the CDN.
- Clashes per create, and each slice's share used.
- Reads sent to a home region for new rows, and the delay of copies between regions.
- The delay from click to dashboard, and the Click log's unread lines.
- Pending purges, and the age of the oldest.
8. Interview Follow-ups
"Why not use a counter, so codes can never clash?" A counter repeats codes when it goes backwards, after a restore or a failover. So it needs the same check as random codes, plus a counter store, a secret key and a jump ahead after each restore.
"Why 7 characters?" Seven characters give about 3.5 trillion codes, and 10 billion links use about 1 in 352 of them. Six characters give only 56.8 billion, so 1 random pick in 6 would already be taken. Eight characters are kept for when a region has used 2% of its codes.
"301 or 302?" 302, because a browser asks again each time, so every click is counted and a blocked link stops. The CDN keeps each 302 for 60 seconds, so most of the load never reaches us.
"One link gets 40,000 clicks a second. What breaks?" Nothing. About 600 CDN servers each ask us once a minute, so about 10 requests a second reach us. Each of our Redirect servers answers those from its own Memory cache, kept 10 seconds.
"Two people ask for the same alias at once, in two regions. Who wins?" The first to win a vote among 5 of the database's 9 copies, 3 in each region. The other request sees the row and gets 409 Conflict at once.
"A link expires. Can its code be reused?" No. Only the long URL is dropped, and the row with its code stays, so the check refuses that code forever.
"How do you count clicks the CDN answers?" We count from the CDN's log of every request, not from our servers. Lines are spread evenly over the Click log's 32 parts, not grouped by code, and repeat batches are dropped by batch ID.
"A region goes down. What do users see?" About 30 seconds of slower clicks and about a minute of failed creates in that region. Links made in its last second wait until it returns.