Ch.56: URL Shortener System Design: The Link That Wouldn't Die

Outline

Transcript

0:00 Imagine you're printing posters for a workshop. A URL shortener turns the long registration address into a little link people can type or scan. It stores where that short code points, then tells each visitor's browser where to go. A small name for a longer address. The workshop closes. You disable the link. One phone gets a closed page; another still opens registration. That looks like a bug. We'll design the shortener: create unique codes, serve a viral link quickly, and work out what disabling one can actually stop.

0:31 Because a green disabled flag isn't much comfort if people keep signing up. Let's follow that other phone's direction next. First, put those directions on the complete map. The owner changes a durable record; visitors cross redirect servers holding short-lived copies of it. Then the visitor follows the address out to the registration site. That last step leaves our service. Do we still control it? No. And the browser can remember an earlier direction. Keep that path outside our boundary; we'll return to this picture with both phones.

1:02 We're proposing our own backend, using the public HTTP standards for the browser's behavior. The source links are in the description. Good. Before picking a database, let's pin down the promise. Which requests must stop receiving directions, and how quickly? For that boundary, the functional requirements are code creation, resolution, and permanent owner disablement. Creation retries should return the same code. Click estimates are useful too. Keep destinations fixed in this design. Changing targets and scheduling expiry can wait.

1:31 For non-functional requirements, assume a hundred million records and 1,000 creations per second. With 100,000 redirects per second at peak. Our regional service should finish 95% within 50 milliseconds, excluding the destination's loading time. Here's the freshness promise: requests entering our service more than 5 seconds after a committed disable must not use an old active record. Already-started replies aren't recalled. That's narrower than making registration disappear. We need acknowledged records to survive our chosen failover too, rather than let a replacement server undo disablement.

2:05 First comes that durable name. Choose eight random letters or digits and store the long address beside them. We're naming an entry, not compressing the address. I used to picture a tiny reversible encoding. But arbitrary addresses don't all fit into eight characters. Different inputs eventually need the same little code. Exactly. With 62 possible characters, eight positions give about 218 trillion candidates. A huge space, still not a uniqueness guarantee. Yeah, take two creators whose requests pick the same empty slot.

2:35 Checking then inserting lets both race through. Who actually settles that race? The database's unique constraint. Admit the code atomically; if another mapping already owns it, generate a different candidate instead of replacing the first destination. Next, take a request whose success reply is lost after commit. The poster owner tries again, and a fresh random code creates a second link. Give that creation an account-scoped request token. Commit the mapping and the token's result together, in one transaction, before acknowledging success.

3:06 Then the repeated token finds the code already assigned. I'd also bind the token to the submitted address, so a changed request doesn't borrow that result. Yes. Same token and same request returns its committed result; different content is rejected. This needs real transactional constraints, not two hopeful writes to separate stores. Okay, creation pays for that coordination once. It's our smaller workload, not the public path everybody crosses when scanning the poster. With creation settled, the read path routes the code to a redirect server.

3:35 Its local cache holds the destination and active state between scans. If 20 servers each refresh one continuously hot code every 5 seconds, that's about four database reads per second after warmup. What stops simultaneous refreshes piling up? Let callers waiting for the same code share one refresh inside each process. Consider a server restarting: cold entries still cost reads. That calculation isn't the whole workload. And a refresh needs current authority, not whichever replica answers fastest.

4:05 An old follower could keep telling us the disabled code is active. Right. Use committed authoritative reads and a configured synchronous durability boundary. An uncertain replacement can't mint fresh permissions from an old copy. Next, consider the browser's copy. That browser path starts with an address called Location in our response. In the incident, the service sent it with a cacheable permanent redirect, code 301. And that direction is still fresh in one phone's browser cache. It can reuse it and go straight to registration, without asking our redirect server again.

4:36 Hold on. I was about to purge every server cache. That clears our copies, but this phone never gives those servers another request. Exactly. We can change the database, drain the caches, even restart the service. None of that forces a browser holding a usable response to check back. Oh, I see. A stale service answer and a visit bypassing us need different debugging. Which cache policy keeps future phones on the path we control? For that controlled path, send a temporary redirect, 302, with the explicit cache instruction no store.

5:11 Apply it at the edge too. I think people treat temporary as uncacheable. Is the response code alone enough to keep the browser coming back? No. Redirect meaning and cache policy are separate. The HTTP caching standard says no store forbids a conforming cache from saving that response for reuse. And no cache is a different instruction: a stored response needs validation before reuse. For this design, I'd pay for another service visit and choose no store. That helps future responses, not the old phone's saved instruction or direct destination access. Let's work through the limit on our own cache next.

5:48 Now limit the local mapping cache as well: 5 seconds from the start of its authoritative read, on an elapsed clock that counts pauses. Corrections mustn't restart it. Suppose a server's read begins at zero, returns active at one, and the owner disables it at two. When does that entry's allowance end? At five. Starting another 5 seconds when reading finishes would quietly extend the old answer. A result returning at six is already expired; discard it. Oh, right. My first thought was to start the timer on insertion.

6:19 A read just before disable can still use nearly the whole allowance afterward. That's our accepted staleness. Yep, check it when deciding each new request. A pushed invalidation can evict sooner instead of waiting for expiry, but missing that message cannot extend the allowance. Once that allowance ends, imagine a database outage. The poster gives us a hard choice: keep sending people to registration, or admit we can't verify this code. I'd return a retryable service-unavailable response. Using an expired active record would break our disable promise.

6:53 Calling it permanently gone would invent a different fact. A current lookup confirming no record can give 404. Known retirement may return 410. A timeout proves neither, and error responses get no store too. Same reasoning during failover: the replacement authority must retain the acknowledged disable. If recovery can't establish that, keep the uncertain path unavailable rather than reopening registration. That means some scans fail during an outage instead of receiving an unverified destination. Maintaining that bound costs availability when authority is unreachable.

7:23 Once a code is disabled, keep a small tombstone instead of offering it to the next creator. Think of a poster surviving after every cache expires. Otherwise an old poster could suddenly send people to somebody else's page. Keeping the old code unavailable preserves its meaning, even when its active mapping is gone. Google ran into the long life of embedded links when retiring its shortener. Its updated plan in August 2025 preserved actively used links. That was a change to the blanket shutdown plan, not evidence all their links stopped working.

7:57 Links were already inside documents, videos and posts; the references had outlived creation. Bitly also documents optional link expiration. We aren't copying either backend. For ours, the closing rule is permanent disablement with no code recycling. The redirect path also produces click events. Put them on a bounded asynchronous queue so reporting workers don't delay a browser waiting for its redirect. If the queue fills, do we sacrifice counts? I'd rather have a labelled estimate than turn an analytics outage into a broken poster. Yes. Drop or sample events under the declared policy.

8:32 These are observed requests, not a ledger of every human visit. Retries and bots already complicate that claim. True, and the phone reusing its stored instruction doesn't reach our counter. Faster navigation can make the dashboard less complete, even while registration sees a visitor. Useful counts, honest limits. Before trusting the disabled flag or latency chart, I'd test the failure paths rather than only measure successful redirects. First, in a design review, force a code collision and lose a creation reply.

9:02 Preserve the earlier mapping; recover the code assigned to that token. Then hold an active read until its allowance expires. Deliver it late, drop the invalidation, and partition the authority. None of those should mint a fresh active cache entry. Test failover after a successful disable too. A green replica health check doesn't prove the replacement retained that particular write. And try to allocate the retired code again. Finally, use two browser profiles: one with the older cached redirect, one making a fresh request.

9:33 The different results should match the paths we promised, rather than look like a mystery. Measure the regional request through its final service decision, including unavailable outcomes. That gives us latency and stale-serving age, rather than a reassuring cache-lookup time. Finally, return to that full architecture and create our printed link once. The transaction binds its destination and request token durably. A lost reply finds the same result. Visitors cross the edge to redirect workers. A hot code stays cheap through short-lived local copies, while current authority sets their allowance.

10:06 New responses tell browsers not to store the direction. Disable commits at that authority. Invalidation can hurry eviction, and the allowance limits missed messages. An uncertain expired copy produces unavailable, not another active instruction. The older phone goes from its browser cache directly to registration. Our disabled record never enters that journey, so its answer differs from the visitor checking with us. And the discarded code stays retired while click reporting runs beside navigation.

10:33 We stop our future directions, rather than pretend to recall an address already disclosed. That leaves the owner with a practical distinction. Disabling the short link stops future directions from our service under the freshness rule. It cannot undo telling someone the destination. If registration itself must close, the site hosting it needs to enforce that. A short code is convenient routing, not a remote control for the page at the other end. I'd ask that question before promising instant revocation.

11:02 Otherwise the fastest redirect in the world can be faithfully carrying out yesterday's instruction. And the useful interview answer follows the whole instruction: who creates it, who remembers it, and which component still has authority to stop issuing it. Thanks for listening to Learning Podcasts.