Design a URL Shortener: Keys, Redirects, Caching and Analytics at 100M Links a Month


System Design Phase 15: Put It All Together
Applied Lesson 83 of 86 21 min read Updated Nov 30, 2026

A marketing team schedules a campaign: one short link, printed on 4 million flyers, posted by an account with 30 million followers, and sent in a push notification at 09:00. At 09:00:05 the redirect service goes from 4,000 requests per second to 90,000. Every one of those requests is for the same seven character key.

If the design is right, nothing interesting happens. The key is already in the CDN and in the in-memory cache, the database sees a few hundred requests per second, and the analytics pipeline lags by a minute and catches up. If the design is wrong, the shard that owns that key melts, the redirect times out, and 30 million people see an error page on the most expensive link the customer ever bought.

A URL shortener is the classic warm-up capstone because it looks trivial and is not. It forces you to reason about key spaces, collision probability, HTTP caching semantics, extreme read skew and an analytics side channel that is ten times bigger than the core data. This article walks the whole design using the system design framework, linking back to the concept articles where each idea is taught in depth.

1. Requirements

Functional

  • Create: given a long URL, return a short URL like sho.rt/aZ3k9Qx. Authenticated users own their links; anonymous creation is allowed with tighter limits.
  • Redirect: GET /aZ3k9Qx returns an HTTP redirect to the long URL.
  • Custom aliases: a user can request sho.rt/black-friday if it is free.
  • Expiry: links can have an expiry time. After it, the link returns 410 Gone.
  • Analytics: per link click counts over time, referrers, countries, device types, and approximate unique visitors.
  • Management: owners can disable or re-point their links; trust and safety can take down malicious ones.

Non-functional

  • Redirect latency: p99 under 50 ms at the server, much less from the edge. Redirect is in the critical path of a human clicking.
  • Availability: redirects at 99.99% (about 52 minutes of downtime a year). Creating links can tolerate 99.9%. Analytics can be minutes behind and must never slow a redirect.
  • Durability: a created link must never silently point somewhere else. Losing a mapping breaks printed flyers forever.
  • Scale: 100M new links a month, 100:1 read to write ratio, 5 years of retention.
  • Unguessability: keys should not be trivially enumerable, so private links are not scraped.

Out of scope

Link previews and QR code rendering (cheap static add-ons), billing, a full admin console, and A/B routing of one short link to several destinations. Mention them, then move on.

2. Estimation

Do the numbers before drawing boxes, using the method from back-of-envelope estimation. Try it in the calculator: 100M links a month is about 3.3M writes a day, so enter 3,300,000 daily users at 1 write each, a read ratio of 100 and an object size of 0.5 KB, then watch which number is actually large.

Back of the envelope estimator

Change DAU or object size and see which number becomes your real constraint.

Traffic

Storage

Bandwidth

Decimal units (1 KB = 1,000 bytes) and 86,400 seconds per day, the usual interview convention. Storage counts writes only and includes every replica; bandwidth counts payload only.

The takeaway is that the core system is small. 120 writes per second and 3 TB fit on one well provisioned Postgres primary with replicas. The real engineering is in three places: generating keys without coordination pain, absorbing skewed reads, and moving a high volume of click events off the hot path.

3. API

Follow the conventions from API design fundamentals: resource nouns, an idempotency key on create, and clear error codes.

POST /v1/links
Authorization: Bearer <token>
Idempotency-Key: 6f1c2b7e-...
Content-Type: application/json

{ "long_url": "https://example.com/spring-sale?utm_source=flyer",
  "custom_alias": "spring-sale",        // optional
  "expires_at": "2027-03-31T23:59:59Z"  // optional
}

201 Created
{ "key": "spring-sale", "short_url": "https://sho.rt/spring-sale",
  "expires_at": "2027-03-31T23:59:59Z" }

409 Conflict   -> alias already taken
422 Unprocessable -> URL failed validation or safety check
429 Too Many Requests -> rate limited, with Retry-After
GET /spring-sale
302 Found
Location: https://example.com/spring-sale?utm_source=flyer
Cache-Control: private, max-age=300

GET /v1/links/spring-sale/stats?from=2026-11-01&to=2026-11-30&granularity=day
200 OK  -> time series of clicks, top referrers, countries, unique visitors (approximate)

PATCH /v1/links/spring-sale   -> change destination, disable, change expiry
DELETE /v1/links/spring-sale  -> soft delete; key is never reissued

The Idempotency-Key matters more than it looks. A mobile client that retries a timed out create without it gets two different short links for one campaign. With it, the server stores the first response and replays it, as covered in idempotency.

4. Data model

The access pattern is almost entirely “get by key”. That points to a key-value shape, whether you store it in a sharded relational database or a wide column or document store. The trade-offs are covered in SQL vs NoSQL.

-- links: the hot table, sharded by short_key
CREATE TABLE links (
  short_key    VARCHAR(32) PRIMARY KEY,  -- 7 chars generated, up to 32 for aliases
  long_url     TEXT        NOT NULL,
  owner_id     BIGINT,                   -- null for anonymous
  created_at   TIMESTAMPTZ NOT NULL,
  expires_at   TIMESTAMPTZ,              -- null means never
  status       SMALLINT    NOT NULL      -- active, disabled, taken_down
);

-- owner_links: secondary access path for "my links" pages, sharded by owner_id
CREATE TABLE owner_links (
  owner_id   BIGINT,
  created_at TIMESTAMPTZ,
  short_key  VARCHAR(32),
  PRIMARY KEY (owner_id, created_at, short_key)
);

Two tables with two partition keys is deliberate denormalization. The redirect path never touches owner_links; the dashboard never scans links. Write both in one transaction when they live in the same database, or write links first and populate owner_links asynchronously from a change stream (see outbox and CDC) when they do not.

Click events live in a separate OLAP store, not in this database. Section 6 explains why.

5. High-level design

flowchart LR
U["Browser or app"] -->|"GET /key"| CDN["CDN / edge<br/>short TTL cache"]
CDN -->|"miss"| LB["Load balancer"]
LB --> R["Redirect service<br/>(stateless)"]
R -->|"1. lookup"| C["Cache cluster<br/>Redis or Valkey"]
R -->|"2. on miss"| DB["Links store<br/>sharded by key"]
R -.->|"click event, async"| K["Event log<br/>(Kafka)"]
W["Create API"] --> KG["Key allocator<br/>(ranges)"]
W --> DB
W --> S["URL safety check"]
K --> SP["Stream processor<br/>aggregate per minute"]
SP --> O["OLAP store"]
O --> A["Stats API"]
style R fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style DB fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style C fill:#E1F5EE,stroke:#0F6E56,color:#085041
style CDN fill:#E1F5EE,stroke:#0F6E56,color:#085041
style K fill:#F1EFE8,stroke:#888780,color:#444441
style O fill:#F1EFE8,stroke:#888780,color:#444441

The read path and the write path are separate services because they scale and fail differently. The redirect service is stateless and can run hundreds of replicas behind a load balancer. It does one lookup and emits one event. The create service is low QPS but does more work: validation, safety scanning, key allocation and a durable write.

The analytics path is a side channel. The redirect service hands a click event to a local buffer and returns the redirect without waiting. If the event log is slow or down, redirects still work and some analytics are delayed or, in the worst case, sampled.

6. Deep dives

6.1 Key generation

There are three serious options. The constraint they all serve is the same: every key must be unique, short, and generated without a global lock on every write.

Option A: hash and truncate. Compute a hash of the long URL (plus the owner ID, so two users shortening the same URL get separate links and separate analytics), base62 encode it, and take the first 7 characters. On insert, use a conditional write (INSERT ... ON CONFLICT DO NOTHING, or a put-if-absent condition in a key-value store). If it fails because a different URL already holds the key, append a salt and rehash.

The birthday math tells you how often that retry fires. With N = 3.5 trillion keys and n links already stored, the chance a new random key collides is n / N. At 6 billion links that is 0.17% per insert, so retries are rare. But the total number of collisions over the lifetime is about n squared over 2N: (6 x 10^9)^2 / (2 x 3.5 x 10^12) = about 5.1 million. Collision handling is not an edge case you can skip; it runs five million times.

Option B: counter plus base62, with a range allocator. Give each link a unique integer and base62 encode it. A single global counter would be a bottleneck and a single point of failure, so instead a small allocator service (backed by a strongly consistent store such as a database row updated in a transaction, or etcd) hands out ranges of, say, 100,000 integers. Each create server burns through its range locally with no coordination at all. Even if a single server took all 120 writes per second, a range would last about 14 minutes (100,000 / 120 = 833 s), so the allocator is touched a few times an hour per server. If a server crashes, the rest of its range is simply skipped, which wastes keys but never duplicates them.

This is the range or “hi/lo” scheme from distributed ID generation. Note why a Snowflake-style 64-bit ID does not fit here: 2^64 is about 1.8 x 10^19, which needs 11 base62 characters (62^10 is only 8.4 x 10^17). Short links want a dense counter, not a timestamp-plus-machine layout.

The weakness of a plain counter is that keys are sequential: aZ3k9Qx is followed by aZ3k9Qy, so anyone can walk the space and scrape private links. Fix it with a bijective scramble before encoding: multiply by a large constant that is coprime with 62^7 and take the result modulo 62^7, or run the integer through a small Feistel network. Both are one to one, so uniqueness is preserved, and consecutive IDs land far apart.

Option C: pre-generated key service. A background job generates random 7 character keys, removes duplicates, and stores them in an “unused keys” table. Create servers fetch batches of, say, 1,000 keys and mark them handed out. Uniqueness is guaranteed at generation time, so the write path never retries. The cost is another stateful service to run, and the hand-out step must be atomic so two servers never get the same batch. Keys in a crashed server’s batch are lost, which is acceptable.

Option Collisions Coordination Enumerable Operational cost
Hash and truncate Yes, handled by conditional insert None No Lowest
Counter + ranges Never Allocator, a few calls an hour Only without a scramble Low
Pre-generated keys Never at insert time Key service on every batch No Highest

A strong default is option B with a scramble: no retries, trivial coordination, and a clear story for how many keys remain. Custom aliases bypass the generator entirely and go straight to a conditional insert, which returns 409 if the alias exists. Reserve a namespace (for example, generated keys are exactly 7 characters and aliases must be at least 8, or contain a hyphen) so an alias can never steal a key the generator will later issue.

6.2 Redirect semantics: 301 vs 302

The status code is an architecture decision because it decides who caches the mapping, as described in HTTP semantics.

  • 301 Moved Permanently (and 308) are cacheable by default. Browsers keep them, often for a long time, even without a Cache-Control header. The second click from the same browser never reaches you. That saves load, but you lose those clicks from analytics, and you cannot reliably re-point, expire or take down the link for that user.
  • 302 Found (and 307) are only cached if you send explicit freshness headers. Every click reaches your infrastructure, so analytics are complete and changes take effect at once.

Use 302 with Cache-Control: private, max-age=300 or similar. That lets the CDN do the heavy lifting under your control: configure the edge to cache the redirect for a short time (for example 60 seconds) and to purge on change, and collect clicks from edge logs or an edge function instead of from origin. You get most of the load savings of 301 without giving the cache key to millions of browsers you cannot purge. Offer 301 as an opt-in for customers who care only about SEO link equity and never change destinations.

The difference between 302 and 307 is minor here: 307 guarantees the method is preserved, which matters for POST, not for a GET redirect.

6.3 Storage and sharding

At 3 TB and 120 writes per second, storage is a capacity and operability question, not a throughput one. Options that all work:

  • Sharded Postgres or MySQL: familiar, strong constraints for the conditional insert, good tooling. Shard by a hash of short_key across, say, 8 shards of under 500 GB each, following sharding and partitioning.
  • A managed key-value store such as DynamoDB, or Cassandra: partitioning and replication are built in, conditional writes exist (DynamoDB condition expressions; Cassandra lightweight transactions, which cost extra consensus round trips), and TTL deletion is native.

Shard by short_key, never by owner_id or created_at. Every redirect has the key and nothing else, so key-based routing gives one shard per lookup. Hash the key rather than range-partitioning it, because counter-based keys (even scrambled ones) and alias prefixes like black-friday-* can cluster. Consistent hashing or a fixed number of virtual partitions mapped to physical nodes keeps rebalancing cheap when you add capacity. Replicate each shard across three zones using the approaches in replication strategies.

Expiry is enforced on read, not by a deletion job. The redirect service checks expires_at on every lookup and returns 410 if it has passed. A background sweeper or the store’s native TTL reclaims space later. Expired and deleted keys are never reissued; a printed flyer that suddenly points to someone else’s page is a safety incident.

6.4 Caching the read path

The cache is where the 100:1 ratio pays off. Use cache-aside: the redirect service checks the cache, falls back to the shard on a miss, and populates the cache with a TTL of hours. Because mappings rarely change, invalidation is simple: on PATCH or takedown, delete the cache entry and purge the CDN path.

Hit rate is the number that sizes the database. At 11,600 peak redirects per second:

  • 90% hit rate: 1,160 reads per second reach the shards.
  • 99% hit rate: 116 reads per second reach the shards.

Click traffic on short links is extremely skewed (new links get most of their clicks in the first days, viral links dwarf everything), so an LRU cache of a few GB comfortably sits in the high 90s. Eviction policies explains why LRU fits recency-heavy traffic like this.

Two failure modes need explicit handling, both covered in cache stampedes and hot keys:

  • Hot key. The 90,000 requests per second for one campaign key all hash to one cache node. Put a small in-process cache (a few seconds TTL, a few thousand entries) inside each redirect server so the hottest keys never leave the process, and let the CDN take the first layer.
  • Stampede. When a hot entry expires, thousands of concurrent misses hit one shard. Use request coalescing (one in-flight fetch per key per server) and jittered TTLs.

Also cache negative results briefly (a few seconds) so bots probing random keys do not each cost a database read. Keep the negative TTL short, because a custom alias created a moment ago must start working immediately.

6.5 Edge redirects

The fastest redirect is the one that never leaves the user’s city. A CDN in front of the redirect service caches 302 responses under your short s-maxage, so a viral link is served from hundreds of edge locations and origin sees roughly one request per edge per TTL.

You can go further with edge compute and an edge key-value store (Cloudflare Workers with Workers KV is a common example): the edge function looks up the key in a globally replicated store and builds the redirect itself, logging the click to a regional collector. The trade-off is consistency. Edge stores are typically eventually consistent with propagation measured in seconds, so a takedown or a re-point is not instant everywhere. Keep an origin-side blocklist check for takedowns, or purge explicitly, and treat edge replication lag as part of the takedown SLA.

6.6 Analytics pipeline

Writing a counter row on every redirect would turn a read-mostly system into a write-heavy one: 11,600 increments a second, concentrated on the hottest keys, which is exactly where row lock contention hurts. Instead, treat clicks as an event stream.

flowchart LR
R["Redirect servers<br/>and edge logs"] -->|"batched, async"| K["Kafka topic clicks<br/>partitioned by key"]
K --> SP["Stream processor<br/>1 min tumbling windows"]
SP -->|"counts, HLL sketches"| O["OLAP store<br/>(ClickHouse, Druid, Pinot)"]
K --> L["Object storage<br/>raw events, Parquet"]
O --> API["Stats API"]
style K fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style O fill:#E1F5EE,stroke:#0F6E56,color:#085041
style L fill:#F1EFE8,stroke:#888780,color:#444441
  1. The redirect server enriches each click (timestamp, key, country from IP, referrer, user agent class) and appends it to an in-memory buffer, flushed in batches to a log such as Kafka. Kafka 4.x runs without ZooKeeper (KRaft only); the partitioning and retention model is in Kafka internals. If the buffer fills, drop or sample events rather than block the redirect.
  2. A stream processor aggregates per key per minute: click counts, counts by country and referrer, and a HyperLogLog sketch per key per window for unique visitors. HLL gives under 1% standard error in about 12 KB per sketch, and sketches merge across windows, which exact sets cannot do cheaply (see probabilistic data structures).
  3. Aggregates land in a columnar OLAP store, which is built for “sum clicks by day for this key over 30 days” scans. Why this is a different store from the links database is the subject of OLTP vs OLAP.
  4. Raw events also go to object storage as Parquet for reprocessing, fraud investigation and backfills.

Delivery is at least once (see delivery semantics). Give each event an ID and deduplicate in the processor, or accept a tiny overcount; click analytics rarely justify exactly-once machinery. Bot filtering (known crawlers, link-preview fetchers from chat apps, prefetchers) happens in the processor and is reported separately, because customers notice when preview bots inflate their numbers.

6.7 Abuse prevention and rate limiting

A public shortener is a gift to phishers: a trusted domain that hides the real destination. Abuse defence is a core requirement, not a feature.

  • On create: check the destination against a threat list such as the Google Safe Browsing API and your own blocklist, reject redirect loops to your own domain, and run slower reputation checks asynchronously. Flagged links get an interstitial warning page instead of a direct redirect.
  • Rate limits per API key, per user and per IP, with anonymous creation far stricter (for example 10 links an hour per IP). A token bucket lets legitimate bulk users burst while capping sustained abuse; try the burst button below to see the bucket drain and refill. The algorithms are compared in rate limiting algorithms, and enforcing them at the edge is covered in API gateway patterns.
  • On redirect: rate limit per IP on 404s to slow key enumeration, and keep a takedown blocklist that the redirect service checks on every request (a small in-memory set refreshed every few seconds), so takedowns do not depend on cache TTLs.

Token bucket rate limiter

Send a burst of 20: the bucket absorbs up to its capacity, then only the refill rate gets through.

Tokens now0
Accepted0
Rejected (429)0
Accepted, last 10 s0
Accepted Rejected Timeline shows the last 10 seconds, newest on the right.

Long run throughput can never exceed the refill rate. Capacity only decides how big a burst is forgiven.

7. Bottlenecks, failure scenarios and trade-offs

Cache cluster loss. If the cache disappears, 11,600 reads per second fall on shards sized for about 1,000. Size the shards to survive a full cache miss at average load, keep the in-process cache as a second layer, and shed load for unknown keys first, since redirecting known hot links is the business.

A shard primary fails. Redirects for keys on that shard can still be served from cache and from replicas (a slightly stale mapping is fine for redirects). Creates that hash to the shard fail until failover completes. With counter-based keys you can route new creates to healthy shards by drawing from a different range, so creates keep working at full availability.

Key allocator down. Servers keep issuing keys from their current range for minutes. Allocate the next range when the current one is 50% used, so a short allocator outage is invisible.

Analytics backlog. Kafka retains events for days, so a stuck processor means late dashboards, not lost data. Alert on consumer lag, not on redirect errors.

Multi-region reads. Users click from everywhere, so serve redirects from every region: each region has redirect servers, a cache, and a read replica of the links store (asynchronous replication, or a multi-region table). Writes go to one home region. The interesting failure is read-after-create: a user creates a link in Europe and a colleague clicks it in Asia 200 ms later, before replication arrives. Handle it by falling back to the home region on a local miss for keys younger than a few seconds (the scrambled counter or a creation timestamp hint tells you roughly how new a key is), and by not negatively caching that miss. The broader patterns, including when to go active-active, are in multi-region architecture, and the consistency trade is a textbook case of consistency models: redirects tolerate staleness, but not for a link that was just shown to its creator.

Decision You gain You pay When it flips
302 over 301 Complete analytics, instant re-point and takedown Every click hits your edge or origin Customer wants SEO-only permanent links
Counter + ranges over hashing No collision retries, predictable key usage An allocator service and a scramble step You want dedup of identical URLs for free
Async analytics over synchronous counters Redirect latency independent of analytics Minutes of lag, at-least-once duplicates Billing on clicks needs audited exact counts
Edge KV redirects over CDN caching Lowest latency, origin barely touched Seconds of propagation lag on changes Strict takedown SLAs or per-click auth

✅ Key takeaways

  • Seven base62 characters give 3.5 trillion keys; 6 billion links use 0.17% of the space, but random keys still collide about 5 million times over five years, so collision handling is mandatory if you hash.
  • A counter with range allocation plus a bijective scramble gives collision-free, unguessable keys with an allocator touched only a few times an hour.
  • Prefer 302 with short, explicit cache headers so you keep analytics and control; 301 hands the mapping to browser caches you cannot purge.
  • The read path is cache-aside with a 99% hit rate, an in-process layer for hot keys and a CDN in front; size the database to survive cache loss.
  • Click analytics is a stream into an OLAP store with HyperLogLog for unique visitors, never a synchronous counter on the redirect path.
  • Abuse prevention (safety checks, rate limits, a fast takedown path) and never reusing keys are core requirements for a public shortener.

🧠 Check your understanding

0 / 4
  1. 1You generate keys by taking 7 random base62 characters. After 6 billion links, about how often does a new insert collide with an existing key?

  2. 2Why do most shorteners default to 302 instead of 301 for redirects?

  3. 3A counter-based key scheme uses ranges of 100,000 IDs per server. A server crashes halfway through its range. What happens?

  4. 4Redirects run at 11,600 per second at peak. Which change most reduces load on the links database?

Interview questions

How would you let two users shorten the same long URL? Should they get the same key?

Usually not. Separate keys give separate owners, separate analytics, separate expiry and separate takedown. With hashing, include the owner ID in the hash input; with counters it happens naturally. Deduplicate only for anonymous creation if storage matters, and even then a malicious destination taken down for one user would affect everyone sharing the key, which is a good reason to avoid it.

A customer says their dashboard shows 20% more clicks than their own site analytics. What do you look at?

Bots and preview fetchers first: chat apps and social platforms fetch links to build previews, and browsers prefetch. Classify user agents and known crawler IP ranges in the stream processor and report them separately. Then duplicates from at-least-once delivery, which event IDs and deduplication fix. Finally, the definitions differ: you count redirects, their site counts page loads that finished, and users who bounce before the destination page renders show up only in yours.

How do you take down a phishing link within one minute everywhere?

Mark it in the database, publish the key to a takedown blocklist that every redirect server and edge function refreshes every few seconds and checks before the cache, delete the cache entry, and issue a CDN purge for the path. The blocklist check is what makes the SLA independent of cache TTLs and edge store propagation. Then serve a warning page with status 410 or a dedicated interstitial instead of the redirect.

What changes if you need exact, billable click counts?

Exactness moves into the pipeline, not the redirect path. Give every click a unique event ID at the edge, use a processor with transactional or idempotent writes to the OLAP store keyed by that ID, and reconcile daily against raw events in object storage. Define what counts as billable (bots excluded, repeat clicks within a window collapsed) in writing, because the hard part of billing is the definition, not the counter.

Where to go next

  • Distributed ID generation goes deeper on range allocation, Snowflake layouts and the trade between short and coordination-free IDs.
  • Cache stampedes and hot keys covers the viral-link failure mode in detail, including request coalescing and probabilistic early refresh.
  • Design a news feed is the next capstone and adds fan-out, ranking and a much harder write path.
  • CDN and edge caching explains surrogate keys, purge APIs and how to keep edge caches correct.

Finished this lesson?

Mark it complete to track your progress across the roadmap.