System Design
URL Shortener
Design a read-heavy service that creates durable short links and resolves them with low latency.
"Design a URL shortener. Given a long URL, return a short one. Given the short one, redirect to the long URL."
A URL shortener saves a destination under a short code. When someone opens the link, the service looks up the code and sends their browser to the saved destination. People may keep using the link long after it was created.
Try the Guided Practice
Draw your design on a whiteboard, get AI feedback at each step, and finish with a debrief.

Requirements
Clarifying Questions
| Question | Answer |
|---|---|
| How short is an auto-generated code? | Exactly 7 base62 characters, using digits, lowercase letters, and uppercase letters. |
| Can users choose a code? | Yes. Custom aliases are supported. |
| Can a destination change later? | No. Mappings are immutable in this version. |
| Do we track analytics? | Yes. Count redirects and retain basic request metadata. |
Functional Requirements
- Create a short link for a destination URL
- Resolve a short code and redirect to its destination
- Allow a user to request a custom alias
- Record best-effort redirect analytics
- User accounts and link-management dashboards
- Link expiration, deletion, and destination editing
Non-Functional Requirements
P99 is the latency that 99% of requests finish at or below. Measure the time to the redirect response at our edge. The destination site's own response time is beyond that boundary.
- TrafficAssume ~100K redirects/s and ~1K creates/s at peak
- Redirect latencyP99 under 30 ms at the service edge
- AvailabilityKeep serving known destinations during a partial outage. Report a temporary failure when a lookup cannot finish.
- ConsistencyOnce a code has a destination, no concurrent create may replace it.
- DurabilityPreserve acknowledged mappings through a single database node failure.
Core Entities + API
Entities
The caller knows the short code. The shortener uses it as the lookup key for the destination.
UrlMapping short_code (primary key), destination_url
CreateRequest idempotency_key (primary key), request_fingerprint, short_code
ClickEvent event_id, short_code, occurred_atA CreateRequest records the result of one create. Its fingerprint is a hash of the destination and requested alias. If a key comes back with those same inputs, we can return the saved code. A click is its own record, so two visits to the same link carry different event IDs.
API
API Design follows the create request through its validation, retry behavior, and response.
Two endpoints cover the user-facing behavior.
POST /v1/links { destinationUrl, customAlias? } -> 201 { shortCode, shortUrl }
Idempotency-Key: <client retry key>
GET /:shortCode -> 302 Found
Location: destinationUrl
Cache-Control: no-storeThe client generates an idempotency key once and reuses it when retrying that create. The service stores it with the resulting code in the same transaction. A matching retry receives the original result. Reusing the key with different inputs returns 409 Conflict. The same status applies when a different create has already claimed the requested alias.
The browser follows the URL in Location. We send Cache-Control: no-store so a later visit reaches the shortener and can be counted. Send the same directive on errors. For example, someone can try an alias before it has been claimed, and a cached 404 Not Found would hide the link once it exists. Use 404 when the code is confirmed missing and 503 Service Unavailable when a required lookup or write cannot finish. HTTP caching standard
High-Level Design
Shorten and redirect, end to end
A club organizer shortens the event page and receives /0000021. The organizer needs that response to mean the link is safely saved. A visitor scanning the poster later needs one fast lookup. Any API instance can handle either request because the records live outside the instance.
-
The API commits the create. Check for a saved result under the retry key first. For a new request, allocate a code or try to claim the alias. Write the mapping and retry record in one PostgreSQL transaction. Fill Redis after the commit if it is reachable. If the cache write fails, the first visitor reads Postgres.
-
The API resolves the code. It asks Redis for the destination associated with
0000021. A cache hit gives us the destination immediately. On a miss, the API asks the Postgres primary, the database node that accepts writes, for the mapping. If it finds one, it fills Redis so any API instance can serve the next visit. -
The API replies to the visitor. The baseline tries a direct click write with a short timeout and then sends the
302. Timeout or failure drops the event. The write still spends part of our redirect latency budget on every click that waits for it.
Suppose a network partition cuts one group of API instances off from Postgres while some connections still work. If that group can still read Redis, it can redirect the immutable links already cached there. A cold code returns 503 when the primary cannot be reached. API instances that can reach the current primary still create and resolve links, so long as it can meet its commit requirement.
Choose a synchronous standby, a backup database that must confirm a durable copy before the primary can report success. During failover, fence the old primary so it cannot take writes, and choose a standby that has the acknowledged commits. Creation may be unavailable during that handoff. Cold redirects still depend on reaching the database. PostgreSQL synchronous replication
Deep Dives
Measure the traffic Redis cannot absorb
The cache-aside flow handles repeat visits well. A time to live (TTL) eventually expires a mapping in Redis, freeing room for other links. With 100,000 requests/s for existing codes and a 99% hit rate, about 1,000 redirects/s need Postgres.
100,000 redirects/s x 1% misses = 1,000 Postgres lookups/sNow add 20,000 requests/s for different invalid codes. Storing missing results can help when clients repeat a typo. Here each new typo still asks Postgres. The database sees more than twenty times its normal redirect load even though none of those requests resolve.
Share the first lookup for a popular link
When the Redis entry for the poster link expires, several visitors may see a miss before the first database read finishes. At 20,000 visits/s for that link and a five-millisecond read, about 100 requests can arrive in that gap. Adding Redis shards spreads different codes across machines. Requests for this one code still go to its owner.
On each API instance, let the first miss for a code start the database read. Other requests for that code can wait for the same result. This is request coalescing. With 20 API instances, that first wave now sends at most one simultaneous read per instance for the code. Give the lookup a short deadline and bound its waiters. If it times out, those visitors get a temporary failure and a later request can try again. Caching challenges and strategies
Coalescing helps when many requests ask for the same code. If every request asks for a different missing code, we need a cheaper way to answer those misses.
A Bloom filter rejects definite misses
A Bloom filter stores enough information about the set of existing codes to answer "definitely absent" or "maybe present." It needs to include all codes we have created. On a Redis miss, try the filter before reading Postgres. A possible match still needs an exact lookup. Bloom filter guarantees
At a 1% false-positive rate, one billion codes use roughly 1.2 GB before overhead. For a representative burst of distinct misses, about 200 requests/s still reach Postgres because the filter occasionally reports a possible match for an absent code.
20,000 invalid lookups/s x 1% false positives = 200 Postgres lookups/s
1 billion codes x 9.6 bits/code / 8 bits/byte = 1.2 GBOnly a complete filter may answer no
Imagine an API instance issued a fresh code and another instance still has yesterday's filter. A negative from that copy is unsafe. Use one current filter owner per database shard. Send misses through a shard router that accepts a negative only while the shard marks its filter active and the reply carries the current ownership epoch, an increasing number that identifies the owner.
While the filter is active, route creates through the owner and add the candidate code to the filter before committing the mapping. If a create fails after adding its code, the filter can report one extra possible match. The database lookup still gives the right result. If the owner cannot update the filter, switch that shard to bypass mode before accepting more creates.
On restart or failover, the router bypasses the filter. The old owner might still reach Postgres and receive creates, so the database also needs to check who may write. In the transaction that inserts the mapping, take a shared lock (FOR SHARE) on the shard's ownership row. Check that creates are enabled and the writer's epoch matches the row. Keep that lock through commit. Other creates can hold the same shared lock. PostgreSQL row locks · Fencing tokens
Build the replacement from a database snapshot while the shard remains in bypass mode and authorized creates continue. Replay committed changes from the snapshot's position so the filter can catch up before the handoff.
When only the last changes remain, take an exclusive lock (FOR UPDATE) on the ownership row. That waits for earlier creates to commit or abort. Update the row to pause creates and advance the epoch. An old owner that tries to write after the pause sees the new epoch and is rejected.
Replay through the transaction that paused creates. Once the filter includes those mappings, enable negative replies and resume creates under the new epoch. Each new code enters the filter before its mapping commits.
Look up the code in Postgres if the filter request times out or the router cannot confirm that the reply came from the current active filter. A code that gets a false positive can also keep getting one on repeated visits. Bound the number of concurrent database lookups and return 503 when they cannot finish.
Know when storage needs a new partition
Assume 100 million new mappings per month and 500 bytes per stored row with its index entry. This calculation covers mapping rows on one copy of the database. Budget separately for the retry records, replicas, and backups.
100M mappings/month x 500 bytes/mapping = 50 GB/month
50 GB/month x 12 months/year = 600 GB/yearWatch database read latency and bytes stored. Add Redis shards by a hash of short_code when the cache runs short of memory. If we later partition Postgres by code, each redirect still addresses one shard. A create becomes harder: the chosen code and the retry key can hash to different shards. We would need to preserve their atomic commit across that boundary. Keep both records in one database as long as it can meet the read and write targets.
Hash the destination URL and shorten the digest to seven base62 characters. Two different URLs can produce the same code.
Even if those candidates were uniformly distributed, the chance of at least one collision would reach about 50% after 2.2 million draws. Each new draw can match any earlier one. An insert must check the unique constraint and retry with a different candidate on a collision.
If the product allows longer links, use more characters and keep the unique constraint as protection. At 12 random base62 characters, the same 50% collision probability takes about 67 billion draws. The seven-character limit rules out that tradeoff here.
Allocate a unique integer and encode it in base62. As with decimal, the place to the left can hold another multiple of the base. ID 125 is two groups of 62 plus one, so it becomes 21 and pads to 0000021. The largest encodable ID is 62^7 - 1. Reject allocations beyond that bound before handing any codes out.
Counter IDs do not collide with other counter IDs. A custom alias can match a generated code. Both use the same unique index, so the generated create takes the next ID if it loses the claim.
The codes are public and predictable. A short link provides a shortcut to a destination, so the destination must enforce its own access checks. If we need short codes to be hard to guess, revisit the length and allocation policy.
UPDATE counters
SET next_id = next_id + 1
WHERE name = 'url_counter'
AND next_id < :namespace_size
RETURNING next_id - 1 AS allocated_id;The counter starts at zero, and namespace_size is 62^7. Postgres locks the row during each update. The exact throughput depends on hardware and transaction work, but every create still queues behind the same lock.
An API instance reserves a block with one atomic update. next_id stores the first unreserved ID:
UPDATE counters
SET next_id = next_id + :range_size
WHERE name = 'url_counter'
AND next_id <= :namespace_size - :range_size
RETURNING next_id - :range_size AS range_start;Suppose A commits a reservation for 1000-1099. B's update now starts at 1100, even if A has only used 30 IDs. Each instance increments its own in-memory cursor, then asks Postgres for another range when that range is spent.
Only draw from a range after the reservation has committed. If the reservation response is lost, reserve again. A committed reservation can leave a gap. If the reservation rolled back, its IDs stayed free. When the counter row exists but the update returns no row, fewer than range_size IDs remain. Reserve a smaller range if possible, or report that the namespace is exhausted.
Crash gaps are a sizing tradeoff
When A restarts, it reserves a new range and leaves its 70 unused IDs behind. Replaying an old in-memory cursor risks allocating an ID that already made it to the database. Gaps are harmless to lookups and consume a bounded part of the namespace per crash.
At 1,000 generated links/s, ranges of 100 reduce the steady-state reservation load to about ten database updates per second. Startup can produce a burst of reservations because every instance needs its first range. Pick the range size against both costs.
1,000 IDs/s / 100 IDs/reservation = 10 reservations/slaunch with different destinations. The winner's connection drops after commit, before it sees 201. What should each caller see when it tries again?Use the database uniqueness boundary
Postgres claims an alias with the same unique constraint used by generated codes:
INSERT INTO url_mappings (short_code, destination_url, custom)
VALUES ('launch', 'https://example.com/product', true)
ON CONFLICT (short_code) DO NOTHING
RETURNING short_code;A returned row means the request won the claim. Save its retry record in the same transaction before committing. The other insert can wait for that transaction to finish. Once the winner commits, the losing insert returns no row. If the first transaction rolls back, the second can claim the alias instead. PostgreSQL INSERT
A retry returns its own result
After a conflicting insert, look up the original retry key in a fresh statement. Under Postgres's default Read Committed isolation, ON CONFLICT DO NOTHING can detect a conflicting row that the insert's snapshot could not see. The next read can see the winning transaction once it has committed. PostgreSQL Read Committed
If the key and fingerprint match a saved create, return the stored short URL. A distinct request that lost the alias gets 409 Conflict. A separate uniqueness constraint on the retry key handles simultaneous replays even when they each picked a different generated code. Roll back the losing mapping transaction before loading the winner's result.
Keep the result for a stated retry window, such as 24 hours. Expiring that record ends the replay guarantee. The permanent short-code mapping remains available.
The redirect has one quick operation left
Give each API instance a small in-memory queue and a background publisher. Once the API has resolved the mapping, it tries to enqueue the click. The attempt returns immediately even if the queue is full. The browser receives the same 302 either way.
event = ClickEvent(new_event_id(), short_code, now())
if not analytics_buffer.try_enqueue(event):
metrics.increment("analytics_events_dropped")
return redirect(302, destination_url, headers={"Cache-Control": "no-store"})Know which failures lose clicks
The publisher sends events to a durable stream such as Kafka. That process may wait or retry while the request handler keeps serving. If each of 20 API instances sees about 5,000 redirects/s, a buffer of 1,000 events per instance fills in about 200 ms after the publisher stalls. The queue absorbs short bursts. Clicks start dropping during a longer outage.
100,000 events/s / 20 instances = 5,000 events/s/instance
1,000 events/instance / 5,000 events/s/instance = 0.2 sA crashed API instance can lose clicks that never reached the stream. An acknowledged stream write can also be delivered more than once to the consumer. The publisher reuses the event ID on a retry. The analytics store inserts by that ID, and the consumer acknowledges the stream record after the insert commits.
Watch the local drop count and compare how quickly events enter and leave the durable stream. If the product requires every click to be kept, the redirect would need to wait for a durable write. If we later cache redirects at a CDN, the edge would also need a way to record its own cache hits.
The complete design
On writes, the durable boundary is the Postgres commit. A create reserves an ID or claims an alias, adds the code if the filter is active, and saves the mapping and retry record before returning a short link.
On reads, a cache hit skips the filter and Postgres. A miss checks a complete filter when available, then looks up any possible match or uncertain result in Postgres. Every successful lookup attempts a local analytics enqueue before returning the redirect.
Done reading? Mark it so it sticks in your dashboard.