The Problem#
A URL shortener turns a long web address into a short one, such as sho.rt/aZ3kP9q. Anyone who opens the short link is sent on to the original page. Services like Bitly, TinyURL and Twitter's t.co also let people pick custom names for links, make links expire, and see how many people clicked, from where and when.
The product looks trivial: a lookup table with a web server in front. It is a favourite interview question for exactly that reason. The basic version fits in ten minutes. That leaves the rest of the interview for the real engineering:
- Generating codes that are short, unique and hard to guess.
- Serving redirects at very high read rates with low latency.
- Counting clicks without slowing down redirects.
- Growing to tens of billions of links without a redesign.
This page builds the design the way you would in an interview. It starts from questions and numbers, adds components only when a requirement forces them, and then goes deep on the parts interviewers probe. It is the classic example of the read-heavy pattern described in Pattern: Scaling Reads.
Clarifying Questions#
A good interview starts by asking, not drawing. Each question below changes something concrete in the design. The "Why it matters" column says what.
| Question | Assumed answer | Why it matters |
|---|---|---|
| Is this a public service like Bitly, or an internal tool? | Public, with anonymous and logged-in users | Public means abuse (phishing, spam) and enumeration are real threats; an internal tool could skip most of that |
| How many new links per day, and how many clicks? | About 6.5M new links a day (about 200M a month), about 100 clicks per link on average | Fixes the read-to-write ratio near 100:1 and tells us the write path is small while the read path dominates |
| How long do links live by default? | Forever, unless the creator sets an expiry | Storage grows without bound, so we need a plan for tens of billions of rows over years |
Can users choose a custom alias such as sho.rt/spring-sale? | Yes, for logged-in users, first come first served | Custom aliases share the code namespace with generated codes, so collisions between the two must be impossible |
| Can a link's destination be edited after creation? | Yes, for paid users | Editing rules out long-lived browser caching of redirects and pushes us toward 302 or short cache lifetimes |
| Do we need click analytics, and how fresh? | Yes: counts by time, country, referrer and device, a minute or two behind real time | Analytics must be asynchronous, and the redirect type and caching must still let us observe clicks |
| How short must codes be? | As short as practical; 7 characters is acceptable | Determines the code space (62 to the power 7 is about 3.5 trillion) and the generation strategy |
| Should codes be guessable or sequential? | No; codes should not reveal how many links exist or let people walk through other users' links | Rules out raw sequential counters and pushes toward random-looking codes |
| Does the same long URL always get the same short code? | No, each request gets a new code (optionally deduplicated per user) | Pure hashing would force one code per URL; separate codes allow separate analytics and expiry |
Do we support branded custom domains (like nyti.ms)? | Yes, for business customers | The lookup key becomes domain plus code, and TLS certificates must be issued per customer domain |
| What latency do users tolerate on a redirect? | Server-side p99 under 50 ms; total under 100 ms in most regions | Rules out a database hit on every click from far away and justifies caching and edge serving |
| What availability target? | 99.99% for redirects, 99.9% for link creation | Broken redirects break other companies' campaigns and printed QR codes, so reads matter most; writes can degrade a little |
Two answers matter most:
- The read-to-write ratio. It decides where to spend complexity.
- Mutability of the destination. It decides how aggressively we can cache redirects outside our control, in browsers and shared caches.
Ask about both early, even if the interviewer only gives a vague answer.
Requirements#
Functional#
- Users should be able to submit a long URL and get back a short URL, optionally choosing a custom alias and an expiry time.
- Users should be able to open a short URL and be redirected quickly to the original long URL.
- Users should be able to manage their links: change or remove the destination, and stop a link working (expire or delete it).
- Users should be able to see click analytics for their links: totals and breakdowns by time, country, referrer and device.
Out of scope: account sign-up and billing, QR-code rendering (a client-side concern), link-in-bio pages, A/B destination rotation, and full fraud machine-learning (we only cover the hooks for abuse checks).
Non-Functional#
- Scale:
- About 200M new links a month and about 20B redirects a month.
- Over ten years, that is roughly 24B links.
- Individual links can go viral and take a large share of all traffic for hours.
- Latency:
- Redirect p50 under 10 ms server-side, p99 under 50 ms.
- Link creation p99 under 300 ms. It's less critical because a human waits once.
- Availability:
- 99.99% for redirects, which is about 4.4 minutes of downtime a month.
- 99.9% for creation and analytics.
- We choose availability over strict consistency on the read path. Serving a slightly stale destination for a few seconds after an edit is fine; failing the redirect is not (CAP Theorem and PACELC).
- Uniqueness and correctness:
- One short code must never map to two different destinations at the same time.
- A code, once issued, must never be reissued to someone else, even after the link expires. Old printed codes would otherwise point at a stranger's page.
- Durability: Losing a mapping breaks links forever, so mappings need replicated, backed-up storage with no data-loss window on acknowledged creates.
- Analytics freshness: Within about 1–2 minutes. Counts may be approximate for unique visitors but must be accurate for total clicks over a day.
- Security:
- Codes are not enumerable.
- Destinations are checked against malware and phishing lists.
- Creation is rate limited.
Which matter most and why:
- Redirect latency and availability come first. They are what every clicker experiences, and the business depends on links never breaking.
- Uniqueness is a hard correctness rule.
- Analytics and creation can be slower and less available without much harm, which lets us push them off the hot path.
Capacity Estimation#
We only estimate the numbers that change the design. A day is about 10^5 seconds (86,400), which keeps the arithmetic quick (Back-of-the-Envelope Estimation).
Writes (link creation).
- 200M links a month ÷ 30 days ≈ 6.7M a day.
- 6.7M ÷ 86,400 s ≈ 80 creates per second on average.
- With a peak factor of 5 for business hours and bulk API users, that is about 400 creates per second.
- Implication: a single well-tuned relational primary handles this easily. Writes are not the scaling problem. The interesting write-side questions are uniqueness and coordination of code generation, not throughput.
Reads (redirects).
- 20B redirects a month ÷ 30 ≈ 670M a day.
- 670M ÷ 86,400 ≈ 7,700 redirects per second on average.
- A normal peak of 5x gives about 40k per second.
- Viral spikes are the dangerous case. A link in a Super Bowl ad, a push notification to 50M phones or a celebrity tweet can add 100k–500k requests per second for a single code within a minute.
- Implication:
- A cache is mandatory, because 40k uncached database reads per second across shards is possible but wasteful, and a single hot key would overload one shard.
- A CDN or edge layer is the right place to absorb spikes on individual codes.
Storage for mappings.
- Per link:
- code (7–8 bytes);
- long URL (average about 100 bytes, but up to a 2 KB cap);
- owner ID (8);
- created and expiry times (16);
- domain ID (4);
- flags and status (a few bytes);
- index and replication overhead.
- Rounding up to 500 bytes per link is safe.
- 24B links × 500 bytes ≈ 12 TB of primary data over ten years.
- 3 replicas take that to about 36 TB.
- Implication:
- One machine could technically store 12 TB, but backups, index rebuilds, failover and vacuuming at that size are painful.
- We plan horizontal partitioning from the start: either a sharded relational database or a distributed key-value store (Partitioning and Sharding).
- At year one (2.4B links, about 1.2 TB), a single replicated primary is fine. Choose a shard key now so the move is mechanical later.
Cache size.
- Link popularity is extremely skewed: most links get almost all their clicks in the first days, and a small fraction get most of all clicks.
- Suppose the links clicked in the last 24 hours number about 100M. 100M × 500 bytes ≈ 50 GB.
- Implication: the entire daily working set fits in a modest Redis or Memcached cluster, for example 3–6 nodes with replicas. A hit rate above 95% is realistic, which cuts database reads to a few thousand per second even at peak.
Analytics events.
- Every redirect produces a click event of about 200–300 bytes: code, time, country, referrer, user agent class, a hashed visitor ID.
- 670M a day × 250 bytes ≈ 170 GB a day raw, about 5 TB a month.
- Implication:
- Events must flow through a log such as Kafka into a columnar analytics store and cheap object storage.
- Events must never go into the mapping database.
- Raw events can be kept for 30–90 days; rollups by hour and day are kept for years at a tiny fraction of the size (Data Lifecycle, Tiering and Retention).
Bandwidth.
- A redirect response is tiny: about 300–600 bytes of headers.
- At 40k per second that is under 25 MB/s across the fleet.
- Implication: bandwidth is irrelevant here, unlike in media systems. Requests per second and tail latency are what we size for.
Code space.
- 62^6 ≈ 56.8B and 62^7 ≈ 3.52 trillion.
- 24B links over ten years fit inside 6 characters, but only at about 42% utilization. That is too dense if we want random-looking codes, where a guess would hit a real link 42% of the time.
- With 7 characters, 24B links use under 0.7% of the space. A random guess finds a real link less than 1 time in 140.
- Implication: we choose 7 characters for generated codes, and keep 8 in reserve.
Core Entities#
- Link: the mapping at the heart of the system:
- short code (and custom domain, if any);
- long URL;
- owner;
- creation time;
- optional expiry;
- status (active, disabled, expired, blocked).
- User: the creator of links. Anonymous creation is allowed with tighter limits, so many links have no user.
- Domain: the short domain a link lives on, either our default domain or a customer's branded domain with its own TLS certificate.
- Click event: one redirect, with time, code, coarse location, referrer, device class and a privacy-preserving visitor ID. It is immutable and append-only.
- Click aggregate: pre-computed counts per link per time bucket (minute, hour, day) and per dimension (country, referrer, device). This is what dashboards read.
- Code range (internal): a block of numbers handed to a code generator so it can mint codes without coordinating on every request.
API Design#
All management endpoints use HTTPS with an API key or an OAuth bearer token. The redirect endpoint is public. Creation accepts an Idempotency-Key header, so a client retrying after a timeout gets the same link back instead of a duplicate (Idempotency and Safe Retries).
POST /v1/links Idempotency-Key: <uuid>
{ "long_url": "https://...", "custom_alias": "spring-sale"?, "domain": "sho.rt"?,
"expires_at": "2027-01-01T00:00:00Z"? }
-> 201 { "code": "aZ3kP9q", "short_url": "https://sho.rt/aZ3kP9q", "expires_at": ... }
-> 409 alias taken | 422 invalid or blocked URL | 429 rate limited
GET /{code} (public, on the short domain)
-> 302 Location: <long_url> (or 301 with short max-age, see deep dive)
-> 404 unknown code | 410 expired or disabled | 451 blocked for legal reasons
GET /v1/links/{code} -> 200 { code, long_url, created_at, expires_at, status }
PATCH /v1/links/{code} { "long_url"?: ..., "expires_at"?: ..., "status"?: "disabled" }
If-Match: <etag> -> 200 updated link | 412 version conflict
DELETE /v1/links/{code} -> 204 (link disabled forever, code never reused)
GET /v1/links?cursor=...&limit=50 -> 200 { items: [...], next_cursor } (caller's links)
GET /v1/links/{code}/stats?from=...&to=...&granularity=hour&group_by=country
-> 200 { total, series: [...], breakdown: [...] }
POST /v1/links:batch { "links": [ up to 1000 create requests ] }
-> 207 per-item results (bulk creation for marketing tools)
POST /v1/domains { "hostname": "go.acme.com" }
-> 202 { verification: DNS CNAME record to add, status: "pending" }A few notes:
- Separate hosts. The redirect path is just
/{code}on the short domain. Every extra path segment costs characters in every link ever printed. The management API lives on a separate host such asapi.sho.rt. That keeps redirect traffic and management traffic on different fleets with different scaling and security rules. - PATCH uses optimistic concurrency (
If-Matchwith an ETag), so two teammates editing the same campaign link don't silently overwrite each other. - DELETE never frees the code. A deleted link returns 410 Gone forever.
- Paginated lists use a cursor, not page numbers, because users with millions of links make offset pagination slow (API Design Best Practices).
High-Level Design#
We build the design one functional requirement at a time. Each step adds only what that requirement needs, which shows the interviewer why every box exists.
1) Users can submit a long URL and get a short URL#
The simplest thing that works. A client calls POST /v1/links. A Link Service (stateless application servers behind a load balancer) then:
-
Validates the URL.
- Syntax: it parses, the scheme is
httporhttps, the host is present, and the length is under 2,048 characters. - Policy: the destination is not our own short domain, which prevents redirect loops and chains used to hide phishing.
- Syntax: it parses, the scheme is
-
Canonicalizes it lightly:
- lower-case the scheme and host;
- remove default ports such as
:443; - keep the path and query exactly as given, because they are case-sensitive on many servers.
Canonicalization matters for optional deduplication and for matching against blocklists.
-
Gets a new short code from a code generator. For now treat this as a function that returns a fresh, never-used 7-character string. Deep dive 1 explains how it really works.
-
Writes the mapping
(domain, code) → long_url, owner, created_at, expires_at, statusto the Links database. The write uses a uniqueness constraint on(domain, code), so even a buggy generator can never overwrite an existing link. -
Returns
https://sho.rt/{code}.
Custom aliases. If the request carries an alias, the service:
- checks it against rules: allowed characters, 3–50 characters long, not a reserved word such as
api,loginoradmin, not offensive; - inserts it with a conditional write ("insert only if not exists").
If the insert fails, the alias is taken and the API returns 409. There is no "check then insert" race: the database's uniqueness check is the single source of truth.
At this stage the diagram is just client → load balancer → Link Service → Links database, plus a code generator. That is enough for requirement 1.
2) Users can open a short URL and be redirected#
The read path is the real product. A browser requests GET https://sho.rt/aZ3kP9q:
- DNS resolves
sho.rtto our edge or load balancer (DNS: The Domain Name System). - A Redirect Service (a separate stateless fleet, because its load is about 100 times the creation load) reads the code from the path.
- It looks up
(sho.rt, aZ3kP9q)in the Links database by primary key. An indexed point read costs about 1–5 ms. - It answers:
- If the link exists, is active and hasn't expired, it responds with an HTTP redirect: status
302 Foundand aLocation: <long_url>header. The browser follows it automatically. - Unknown codes get 404.
- Expired or disabled links get 410 Gone with a small human-readable page.
- If the link exists, is active and hasn't expired, it responds with an HTTP redirect: status
Why split creation and redirect into two services. They differ in nearly every way:
- load: about 80 versus 7,700 requests per second on average;
- latency budgets: 300 ms versus 50 ms at p99;
- dependencies: creation needs the code generator and abuse checks; redirect needs only a lookup;
- failure tolerance.
Separate fleets let us scale and deploy them independently. They also guarantee that a slow abuse-check dependency on the write path can never slow a redirect.
Adding a cache.
- The problem. At 40k redirects per second at peak, hitting the database for every click wastes capacity and adds latency. A single viral code would hammer one shard.
- The cache. We add a Redis or Memcached cluster in front of the database using cache-aside: look in the cache, and on a miss, read the database and populate the cache with a TTL (Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind).
- Why it works. Mappings are written once and rarely change, which is the best case for caching. The hit rate is typically above 95%, and a cache hit costs about 0.5–1 ms.
Adding an edge. For the hottest links, we can answer at a CDN close to the user, so most viral traffic never reaches our data centers. Deep dive 3 covers this layering.
3) Users can change, expire or delete their links#
Updates are rare but must be correct.
- Editing the destination or expiry goes through the Link Service, which checks ownership and the
If-Matchversion. It updates the database row, then invalidates the cache entry for that code: delete the key, don't overwrite it, to avoid races with concurrent cache fills (Cache Eviction and Invalidation). - Purging the CDN. If the edge caches the redirect, the service also issues a CDN purge for that URL, or relies on a short edge TTL.
Expiry needs no job on the hot path:
- Lazy check. The Redirect Service compares
expires_atto the current time on every lookup, which makes expiry exact even if the row still exists. - Bounded cache TTL. Cache TTLs are capped at the time remaining before expiry, so a cached entry can't outlive its link.
- Background cleanup. A sweeper, or the database's native TTL feature, later marks or archives expired rows for storage hygiene. Codes are never reissued.
Deletion marks the row disabled rather than removing it. The code must stay reserved forever, and a tombstone lets us return 410 instead of a misleading 404.
4) Users can see click analytics#
The naive approach. Increment a counter column on the link row for every redirect.
Why it fails. It turns a read-only, cacheable path into a write on every click: 7,700 writes per second on average, and 100k+ per second on one row for a viral link. That's the textbook hot-row problem (Pattern: Scaling Writes). It would also tie redirect latency to database write latency.
The design: decouple. The Redirect Service emits a click event after sending the redirect, asynchronously and fire-and-forget into a local buffer:
- Events flow into Kafka, partitioned by code. Kafka absorbs bursts and replays on failure (Apache Kafka in Practice).
- A stream processor (Flink, or Kafka Streams) does three things:
- enriches events (IP → country, user agent → device class, bot detection);
- aggregates per link per minute;
- writes the rollups to a columnar analytics store such as ClickHouse, Apache Druid or Apache Pinot.
- Raw events also land in object storage, as Parquet in S3, for reprocessing and long-term batch jobs (Batch vs Stream Processing).
- The Stats API reads the rollups. Dashboards are a minute or two behind real time, which meets the requirement.
Batch alternative. The primer-style design uses a periodic MapReduce over web server logs, emitting (month, url) → count. That works if analytics can be a day late. It's still how the batch layer recomputes accurate daily numbers.
Redirect type matters here. If we answered with a long-cached 301, repeat clicks from the same browser would never reach us and would go uncounted. The redirect type and the cache headers are an analytics decision as much as an HTTP one; see deep dive 2.
The full high-level design#
Read path (redirects and click capture):
Write path (creation, management and stats):
Dashboards reach the analytics store through a separate Stats API behind the same gateway.
What each component does:
- CDN and edge functions:
- terminate TLS close to users;
- serve cached redirects for hot codes;
- run cheap bot and abuse filters;
- absorb viral spikes.
- Load balancer: spreads cache misses across Redirect Service instances and removes unhealthy ones (Load Balancing).
- Redirect Service: a stateless read path with a two-level lookup (local memory, then Redis, then the database). It returns 301 or 302, 404 or 410, and emits click events without waiting for them.
- In-process LRU cache: a few hundred MB per instance holding the hottest codes. It removes even the Redis hop for viral links and spreads hot-key load across all instances.
- Redis or Memcached cluster: a shared cache of about 50 GB of daily working set, with replicas. It serves more than 95% of the lookups that pass the edge.
- Links database: the durable source of truth for mappings, partitioned by a hash of the code. It can be DynamoDB, Cassandra, or sharded PostgreSQL or MySQL.
- Local event buffer: a bounded in-memory queue in each redirect instance that batches events to Kafka, so a Kafka slowdown never blocks a redirect.
- Kafka: a durable, replayable log of click events that decouples redirects from analytics.
- Stream processor: enriches, filters bots, deduplicates and aggregates clicks into minute, hour and day rollups.
- Analytics store: a columnar database for fast slice-and-dice queries on rollups and recent raw events.
- Object storage: cheap long-term raw event archive for reprocessing and batch jobs.
- API gateway: authentication, per-key and per-IP rate limits, and request validation for management traffic (API Gateway and Backend-for-Frontend).
- Link Service: business logic for creating, editing and deleting links, with conditional writes and cache and CDN invalidation.
- Code generator: hands out unique, random-looking 7-character codes from preallocated numeric ranges without a network call per code.
- Range allocator: a small, strongly consistent store that leases disjoint number ranges to generator instances.
- URL safety check: checks destinations against malware and phishing lists, and flags suspicious patterns.
- Stats API: reads aggregates for dashboards and exports.
Key Flows#
Creating a short link#
- Rate limiting and authentication happen at the gateway before any work is done. Anonymous callers get much lower limits than API keys (Rate Limiting and Throttling).
- The idempotency lookup comes first. A client that timed out and retried with the same key gets the original link back, not a second one.
- The safety check runs before the code is issued. Known-bad destinations are refused with 422 instead of being cleaned up later. Slower, deeper checks run asynchronously afterwards (deep dive 9).
- The code comes from a range the generator already holds in memory, so creation does not wait on a coordinator.
- The insert is conditional on the code not existing. It is acknowledged only after it is durable on a quorum of replicas, because an acknowledged link that later vanishes breaks a link someone already printed.
Following a short link#
- Hot codes are answered at the edge. That is typically the bulk of a viral link's traffic. The click is recorded from edge logs or from an edge function that posts events in batches, so analytics still see it.
- On an edge miss, the local LRU and then Redis answer in about 1 ms. Only a small fraction of lookups reach the database, and each is a point read on the primary key.
- Expiry and status are checked on every lookup, even on cache hits. An entry cached a minute before its expiry still stops working on time.
- The click event is queued after the response is written. A slow Kafka can never add latency to a redirect. If the buffer is full, events are dropped and counted as dropped rather than blocking.
Data Model#
Which database for links, and why. The mapping workload has four properties:
- point reads by key, very read-heavy;
- a modest write rate;
- no joins on the hot path;
- growth to about 12 TB over years.
Two choices fit well (Choosing a Database: A Decision Guide):
-
A distributed key-value or wide-column store: DynamoDB, Cassandra or ScyllaDB.
- The partition key
(domain_id, code)gives single-digit-millisecond point reads at any size. - Conditional writes give insert-if-absent for aliases.
- Native TTL handles cleanup.
- Horizontal scaling is built in.
This is our default for the mapping table (Amazon DynamoDB in Practice, Apache Cassandra in Practice). On Cassandra, insert-if-absent needs a lightweight transaction (
IF NOT EXISTS, using Paxos). That's acceptable at 400 creates per second. - The partition key
-
PostgreSQL or MySQL, sharded by code hash.
- Excellent if the team already runs it, and a single primary covers the first few years.
- Add read replicas for misses and region failover, then shard with Vitess or Citus, or application-level shard maps, when size demands it (PostgreSQL in Practice).
- User-facing management queries, like "list my links sorted by date", are easier here.
Many real systems use both:
- a key-value store for the redirect path, keyed by code;
- a relational database for accounts, domains, billing and the "my links" listing.
The listing is kept in sync through change data capture (Change Data Capture and the Outbox Pattern).
Keys and indexes:
- Primary key
(domain_id, code). Every redirect is a point lookup on this key. A custom domain and the default domain can both have/salewithout conflict. - "Links by owner" is served by a separate table or global secondary index keyed by
(owner_user_id, created_at DESC), so a user can page through their links with a cursor. It is eventually consistent, which is fine for a dashboard. - Optional dedupe index:
- The index is
(owner_user_id, sha256(canonical_long_url)), for customers who want "same URL gives the same link". - It is a hash rather than the URL itself, because URLs can be 2 KB and index entries should be small.
- The index is
- The idempotency key table has a 24-hour TTL.
Partition or shard key.
- Use a hash of
(domain_id, code). Codes are random-looking, so even sequential issuance spreads uniformly. - Don't partition by owner. One enterprise customer with 500M links would create a giant shard, and the redirect path doesn't know the owner anyway.
- Don't range-partition by raw counter value. All new writes would land on the last shard, and new links are also the hottest for reads (Consistent Hashing).
Click data never lives in the mapping store:
- raw events go to Kafka, then object storage plus the columnar store;
- rollups are keyed by
(domain_id, code, bucket_start, dimension, value)and are sorted for time-range scans.
Deep Dives#
1) How do we generate short codes that are unique, short and not guessable?#
Three constraints pull against each other:
- Unique: never two links on one code.
- Short: few characters.
- Cheap to generate: no coordination per request.
A fourth, not guessable, appears as soon as the service is public. The options, from weakest to strongest:
Not even Basic: take a prefix of the long URL.
- How it works. Using the first N characters of the URL as the code is fast and needs no state.
- Why it fails. It fails uniqueness immediately. Every URL starting with
www.linkedin.com/in/would share one code. It isn't short for long hosts, and it leaks the destination. Mention it only to dismiss it.
Basic: random code, then check and retry.
- How it works.
- Draw 7 random characters from the 62-character alphabet
[0-9a-zA-Z], using a cryptographically secure random generator rather thanMath.random. - Insert with a uniqueness constraint.
- On a conflict, draw again.
- Draw 7 random characters from the 62-character alphabet
- Why base62. Base64 adds
+and/. The slash is a path separator, and+may be decoded as a space in query strings, so both cause escaping bugs in URLs. Base62 uses only letters and digits, which are safe anywhere in a URL. - Why it's better. It's simple and stateless, and codes are unpredictable.
- The collision math. With a code space S and n codes already used, the chance that a new random code collides is n ÷ S.
- For S = 62^7 ≈ 3.5 × 10^12 and n = 24 × 10^9 at ten years, that's about 0.7% per attempt.
- The expected number of attempts is 1 ÷ (1 − 0.007), about 1.007. That's cheap.
- The chance of needing more than 3 attempts is 0.007^3, about 3 × 10^-7.
- Where it fails.
- Every insert must check uniqueness against a 24B-row table. With a key-value store's conditional put that's still one round trip, so it's fine, but it's an extra hop when using caches or replicas.
- Collisions rise as the space fills. The rate stays low with 7 characters, but at 6 characters and 24B links, a 42% collision rate per attempt makes the scheme unusable.
- A common confusion: the birthday bound. This is the probability that any two of n random codes collide, and it reaches 50% at about 1.18 × √S, roughly 2.2M codes for S = 3.5T. That sounds alarming, but it doesn't matter here: we check every insert, so a collision costs one retry, never a wrong redirect. The birthday bound matters only when you can't check, such as with hash-only schemes that skip the database.
Basic variant: hash the URL.
- How it works. Compute SHA-256 (or MD5, as the primer suggests, on IP plus timestamp) of the canonical URL, base62-encode it, and keep the first 7 characters.
- Why it's attractive. It's deterministic: the same URL always gives the same code, which deduplicates for free. Truncated hash output is uniformly spread.
- Why it's weaker than it looks:
- Collisions. Truncation throws away most of the hash, so collisions happen at the same rate as random codes. The fix — check, then re-hash with a salt or counter appended — is exactly the random scheme plus extra steps.
- Unwanted determinism. Two users shortening the same URL get the same code, so they share analytics and expiry. Usually that's undesirable. Adding the user ID or a nonce to the input fixes it, but removes the dedupe benefit.
- Guessability. Anyone can compute the code for a known URL and check whether it was shortened, which leaks private links. Use a keyed hash (HMAC with a secret) if hashing at all.
Better: a global counter, base62-encoded.
- How it works. Keep one counter. Every new link takes the next value (1, 2, 3, ...) and encodes it in base62. 1,000,000,000 becomes
15ftgG, only 6 characters. A single Redis instance withINCRis a convenient counter. Redis executes commands one at a time, so two concurrent calls always get different values. - Why it wins over random.
- No collisions by construction, so no retries and no uniqueness lookups beyond the safety-net constraint.
- Codes are as short as possible for the number issued: 6 characters until about 56.8B links, then 7 up to about 3.5T.
- The code decodes back to the number, which some designs use as the database key.
- Why it fails as described:
- A single point of failure and a network hop per create. Every creation depends on one Redis.
- Predictable codes. Sequential codes reveal volume: a competitor can create a link at noon and another at midnight and subtract. Worse, anyone can walk
...gG,...gH,...gIand discover every link, including private documents shared "by obscure link". That's a real privacy failure. - Hot spots. Neighbouring codes are created at the same time. If anything partitions by code ranges, all new writes and reads hit the same partition.
Best: preallocated counter ranges plus a reversible permutation.
-
Ranges remove the per-request coordinator.
- Each generator instance (inside the Link Service process) leases a block of, say, 10,000 numbers from a small, strongly consistent allocator: an etcd key updated with compare-and-swap, a database row (
UPDATE ranges SET next = next + 10000 RETURNING next), or RedisINCRBY 10000. - It then mints codes from memory.
- At 400 creates per second across 20 instances, each instance asks for a new block about every 500 seconds, so the allocator sees about one request every 25 seconds. Its availability barely matters, as long as instances refill early, for example when a block is 80% used.
- This is the idea behind Flickr's "ticket servers" (described on the Flickr engineering blog in 2010): two MySQL servers with auto-increment offsets of 1 and 2, so they never issue the same number. It also appears in database sequence caching (Unique ID Generation).
- Each generator instance (inside the Link Service process) leases a block of, say, 10,000 numbers from a small, strongly consistent allocator: an etcd key updated with compare-and-swap, a database row (
-
A keyed permutation removes predictability.
- Before encoding, the number passes through a bijection on the range
[0, 62^7), a one-to-one shuffle keyed by a secret. Sequential inputs then come out scattered across the whole code space. - A small Feistel network does this well, with a "cycle walking" trick to stay inside a non-power-of-two range. Luby and Rackoff ("How to Construct Pseudorandom Permutations from Pseudorandom Functions", 1988) showed that a few Feistel rounds with a good round function give a pseudorandom permutation.
- Standardized format-preserving encryption (NIST SP 800-38G's FF1 mode, 2016) gives the same property with stronger guarantees.
- Because it's a bijection, uniqueness is preserved: distinct counters always give distinct codes, with no collision check needed.
- Before encoding, the number passes through a bijection on the range
-
What we lose. Gaps: blocks leased by instances that crash are never used. With 10,000-number blocks and a few crashes a day, we waste maybe 10^5 numbers a day out of 3.5 × 10^12. That's nothing. We only need uniqueness, not continuity.
-
The safety net. Keep the database uniqueness constraint anyway. It catches the bugs that will eventually happen:
- a misconfigured allocator handing out the same range twice;
- a restored backup with an old
nextvalue; - two regions given overlapping ranges.
When the constraint fires, log loudly and take the next number.
What about pre-generated keys? A Key Generation Service (KGS):
- generates random codes offline;
- stores them in a "free keys" table;
- hands batches to app servers, which move them to a "used keys" table.
It works and was popular in early designs. Compared with ranges plus a permutation, it costs storage for billions of unused keys and needs careful bookkeeping so no key is handed out twice: mark the batch as taken in the same transaction that hands it out. It also gives the same guarantees, so the permutation approach is usually simpler. KGS still makes sense when codes must satisfy rules a permutation can't guarantee, such as no profanity substrings and no confusable characters, because keys can be filtered when generated.
What about Snowflake-style IDs? 64-bit time-plus-machine-plus-sequence IDs (Twitter's Snowflake, 2010) need no coordination, but they encode to 11 base62 characters. That's too long for a shortener, which values every character more than coordination-free generation.
| Approach | Unique by construction | Length at 24B links | Coordination | Guessable | Verdict |
|---|---|---|---|---|---|
| URL prefix | No | Varies | None | Leaks URL | Unusable |
| Random + retry | No (retry on conflict) | 7 | None (DB check per insert) | No | Good and simple |
| Truncated hash | No (retry with salt) | 7 | None (DB check) | Yes, unless keyed | Only if dedupe is required |
| Global counter + base62 | Yes | 6 | Per request | Yes, sequential | Good for internal tools |
| Ranges + permutation + base62 | Yes | 7 (permuted over the full space) | One call per 10k codes | No | Best default |
| Pre-generated keys | Yes, if bookkept | 7 | Per batch | No | Fine; heavier |
Here is the core of the generator, a 4-round Feistel network over the 7-character space:
const ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const SPACE = 62n ** 7n; // 3,521,614,606,208 codes
const HALF_BITS = 21n; // 2^42 > SPACE, split into 2 x 21 bits
const MASK = (1n << HALF_BITS) - 1n;
function roundFn(x: bigint, key: bigint, round: number): bigint {
// Any keyed pseudorandom function works; HMAC truncated to 21 bits in production.
return (x * 0x5bd1e995n + key + BigInt(round) * 0x9e3779b9n) % (MASK + 1n);
}
function feistel(n: bigint, key: bigint): bigint {
let left = n >> HALF_BITS, right = n & MASK;
for (let r = 0; r < 4; r++) {
[left, right] = [right, left ^ roundFn(right, key, r)];
}
return (left << HALF_BITS) | right; // bijection on [0, 2^42)
}
export function permute(n: bigint, key: bigint): bigint {
let x = feistel(n, key);
while (x >= SPACE) x = feistel(x, key); // cycle-walk back into [0, 62^7)
return x;
}
export function toBase62(n: bigint, width = 7): string {
let s = "";
for (let i = 0; i < width; i++) { s = ALPHABET[Number(n % 62n)] + s; n /= 62n; }
return s;
}
// code = toBase62(permute(counterValue, SECRET_KEY))Notes on the snippet:
- Cycle-walking is cheap. The Feistel network is a permutation on 2^42 values, about 4.4 trillion. Our space is 3.5 trillion, about 80% of that, so cycle-walking needs about 1.25 iterations on average.
- Fixed width is deliberate. Every generated code is exactly 7 characters.
- Disjoint namespaces. Custom aliases may be any length from 3 to 50, but an alias made of exactly 7 characters, all from the base62 alphabet, is rejected. Generated codes and aliases then live in disjoint namespaces and can never collide (deep dive 5).
2) Should redirects be 301 or 302, and what cache headers should they carry?#
The redirect status code decides who is allowed to remember the mapping. That choice affects analytics, editability, latency and load. HTTP defines four redirect codes that matter here. RFC 9110 (2022) is the current specification of HTTP semantics, and 308 was first added by RFC 7538 (2015).
| Code | Meaning | Browser caching by default | Method on follow |
|---|---|---|---|
| 301 Moved Permanently | "This address has moved for good" | May be cached indefinitely; browsers cache it aggressively | May change POST to GET (historical behaviour) |
| 302 Found | "Temporarily elsewhere" | Not cached unless headers allow it | May change POST to GET |
| 307 Temporary Redirect | Like 302 | Not cached unless headers allow it | Method and body preserved |
| 308 Permanent Redirect | Like 301 | Cacheable like 301 | Method and body preserved |
Short-link clicks are almost always GET, so the method difference rarely matters. The real decision is about caching.
Basic: 301 with no cache headers.
- How it works. The browser remembers "
sho.rt/aZ3kP9q→ destination" and on the next click goes straight there without contacting us. - Why it's tempting:
- Fewer requests to our servers.
- A faster second click for that user.
- Search engines treat a 301 as a permanent move, so the destination gets credit for the link.
- Why it fails our requirements:
- Analytics go blind. Repeat clicks from the same browser never reach us, so counts are systematically low, by an unknown amount.
- Edits and expiry stop working. Browsers that cached the old target keep using it, possibly for months. A link disabled for phishing keeps sending previous visitors to the phishing page.
- No recall. You cannot reach into users' browsers to evict a cached 301.
Better: 302, not cacheable by browsers.
- How it works. Every click comes to us (or to our edge), so every click is counted, and edits, expiry and takedowns take effect immediately.
- Why it's better. Control and correct analytics, which are the core business of a commercial shortener.
- The trade-off. Every click costs a request to our infrastructure, plus an extra round trip for the user compared with a browser-cached 301. On a mobile network that round trip can be 50–150 ms if our servers are far away. The edge layer (deep dive 3) is what makes that affordable.
Best: choose per link, and separate browser caching from edge caching with explicit headers.
-
For editable or tracked links (the default), use
302(or307) with:Cache-Control: private, max-age=0for browsers. Separately, set an edge-only TTL (
s-maxage=60or a CDN-specific surrogate header) so our own CDN can serve the redirect for up to a minute. Clicks are still counted from edge logs or an edge function. An edit or takedown triggers a CDN purge, so the edge staleness is seconds in practice and 60 s in the worst case. -
For immutable links where the creator opted out of editing (for example, links printed on packaging), consider
301with a boundedCache-Control: private, max-age=3600or similar.- Browsers re-check at most hourly, so we still see each browser roughly once an hour.
- The bound limits the damage if the link later has to be taken down.
- It helps search engines and repeat visitors.
Always:
- Serve only HTTPS on the short domain. Put the domain on the HSTS preload list (HTTP Strict Transport Security tells browsers to always use HTTPS), so an
http://click doesn't cost an extra plain-HTTP-to-HTTPS redirect hop (HTTP, HTTP/2, HTTP/3 and HTTPS). - Avoid redirect chains. Shortener → tracking domain → final page adds a DNS lookup, TCP and TLS handshake, and round trip per hop: easily 100–300 ms each on mobile.
The design choice in one sentence: 302 is the right default because the service's value is control and measurement. Use bounded 301s only when the link is promised never to change.
3) How do we keep redirects fast at 40k per second with viral spikes?#
The target is a server-side p99 under 50 ms, with one link possibly taking hundreds of thousands of requests per second. Each option below adds a layer.
Basic: an index on the code.
- How it works. Make
(domain_id, code)the primary key.- B-tree (PostgreSQL or MySQL). A point lookup costs O(log n). With a fan-out of a few hundred keys per page, even 24B rows need only 4–5 levels, and the top levels stay in memory, so a lookup usually touches disk once or not at all.
- LSM store (Cassandra, DynamoDB). Bloom filters on each sorted file let a read skip files that can't contain the key (Storage Engines: B-Trees vs LSM Trees).
- Either way, a lookup costs about 1–5 ms.
- Why it's not enough.
- Volume. 40k reads per second at peak, plus spikes, spread across shards is feasible but wasteful.
- Hot keys. A viral code lives on one partition. Even with 3 replicas, 300k reads per second on one key exceeds what a shard can serve (DynamoDB, for example, limits a single partition to about 3,000 strongly consistent or 6,000 eventually consistent small reads per second, and one item can't be split across partitions).
- Distance. Users far from the database's region pay the cross-region round trip: 80–100 ms US–EU, 150–200 ms US–Asia.
Better: a shared in-memory cache (cache-aside).
- How it works.
- Redis or Memcached in front of the database, keyed
link:{domain}:{code}. - The value is
long_url | status | expires_at. - The TTL is something like 24 hours, capped at the remaining lifetime of the link.
- On a miss, read the database and set the cache.
- On an edit or delete, delete the key.
- Redis or Memcached in front of the database, keyed
- Why it wins.
- Fast. A hit costs about 0.5–1 ms.
- Fits easily. The 50 GB working set fits on a handful of nodes.
- Offloads the database. At a 95% hit rate, only 2,000 of the 40k peak reads per second reach the database.
- Low staleness risk. Mappings are written once and rarely change, so cache invalidation, usually the hard part of caching, is close to trivial.
- Where it still fails:
- Hot keys again. A viral code maps to one cache shard. A single Redis node handles about 100k simple operations per second, and the spike can exceed that. Replicas help only if clients spread reads across them.
- Cache stampede on cold keys. A freshly tweeted link has no cache entry. 10,000 simultaneous first clicks all miss and all hit the database at once (Cache Failure Modes: Stampedes, Hot Keys and Penetration).
- Penetration. Requests for codes that don't exist always miss the cache and always hit the database. Bots probing random codes, or a typo in a printed campaign, can generate a steady stream of these.
- Distance remains. A user in Sydney still crosses the Pacific to reach the origin.
Best: a tiered read path from the edge inward, with hot-key and miss protection.
- CDN edge cache.
- The short domain is fronted by a CDN with points of presence (PoPs) worldwide (Content Delivery Networks (CDN)). The edge caches redirect responses with
s-maxageof 30–300 seconds. - A viral link then becomes one origin request per PoP per TTL, instead of hundreds of thousands per second. With 300 PoPs and a 60 s TTL, that's about 5 origin requests per second, regardless of how viral the link is.
- Users get the redirect from a PoP typically 10–30 ms away instead of 100–200 ms.
- The short domain is fronted by a CDN with points of presence (PoPs) worldwide (Content Delivery Networks (CDN)). The edge caches redirect responses with
- Edge compute with an edge key-value store (optional, for the global long tail).
- Edge functions (Cloudflare Workers, Lambda@Edge, Fastly Compute) can look up codes in a globally replicated edge key-value store (Edge Computing and Edge Functions).
- That makes even first clicks fast worldwide, at the cost of replicating mappings to every edge region, eventual consistency (edge stores typically converge within seconds to a minute), and per-request compute cost.
- This is worth it when the user base is global and latency is a competitive feature.
- In-process LRU on each Redirect Service instance.
- A few hundred MB holding the hottest codes for 10–60 seconds.
- Hot keys are then served from memory on every instance, spreading load across the whole fleet instead of one Redis shard.
- Request coalescing ("single flight").
- When several requests on one instance miss on the same key, only one goes to Redis or the database; the rest wait for its result.
- Combined with the edge, this turns a 10,000-request stampede into a handful of origin reads.
- Negative caching.
- Cache "not found" results for unknown codes for a short time (30–60 s), so repeated misses don't reach the database.
- Rate limit 404s per IP or prefix at the edge, since a burst of unknown codes from one client is almost always a scanner.
- Optional Bloom filter of existing codes.
- A Bloom filter answers "definitely not present" or "maybe present" (Probabilistic Data Structures for Big Data). At a 1% false-positive rate it needs about 9.6 bits per element, so 24B codes take about 29 GB.
- That's too big for each instance, but fine when sharded across the cache tier (for example RedisBloom partitioned by code).
- It blocks almost all random-code probes before they reach the database. Because our codes are random-looking over a 3.5T space, more than 99% of guesses miss.
- Stale-while-revalidate.
- If the database is slow or down, serve the last known cached mapping, even past its soft TTL, while refreshing in the background.
- Mappings rarely change, so serving a slightly stale one is far better than a 5xx, as long as the entry wasn't explicitly invalidated by a takedown.
A latency budget for a cold first click from Europe to a US-hosted origin shows why the layers matter:
| Step | Origin only | With edge cache hit |
|---|---|---|
| DNS (often cached) | 0–30 ms | 0–30 ms |
| TCP + TLS 1.3 handshake | 1 RTT to the origin: 80–100 ms (plus TCP) | 1 RTT to the PoP: 10–30 ms |
| Request to response | 80–100 ms RTT + 2 ms processing | 10–30 ms RTT, under 1 ms at the edge |
| Total before the browser starts on the destination | about 200–250 ms | about 25–60 ms |
The server-side p99 we promised (under 50 ms) is easy at origin. The user-perceived win comes from serving at the edge.
4) How do we scale storage and the database to tens of billions of links?#
Writes are only about 400 per second at peak. The challenge is size (about 12 TB of primary data, growing forever), availability of the read path, and operational sanity: backups, failover, schema changes.
Basic: one relational database.
- How it works. One PostgreSQL or MySQL primary with the mapping table and a primary key on the code.
- Why it's fine at first. In year one, with 2.4B links (about 1.2 TB) and a few thousand cache-miss reads per second, one well-provisioned server handles it (Relational Databases and SQL). Interviewers like hearing that you don't shard prematurely.
- Why it fails later:
- A single point of failure for both creation and cache misses.
- Painful maintenance at 10 TB and beyond: a full backup or replica rebuild can take many hours, index rebuilds and vacuuming slow down, and one machine's disk becomes the ceiling.
- A single region: far-away users pay cross-region latency on every miss.
Better: replication for availability and read scaling.
- How it works.
- Add synchronous or semi-synchronous replicas in other availability zones for failover without losing acknowledged links.
- Add asynchronous read replicas, possibly in other regions, for cache misses (Database Replication).
- Take periodic snapshots plus continuous archiving of the write-ahead log, for point-in-time recovery from operator mistakes (Disaster Recovery and Backups).
- Why it wins.
- Surviving a zone failure is automatic.
- Read capacity scales with replicas.
- Replicas in other regions serve misses locally.
- The catch: replication lag. A redirect for a link created 50 ms ago in another region may hit a replica that hasn't received it yet and wrongly return 404. Three fixes:
- Read your writes on miss. On a replica miss, retry against the primary before returning 404. Misses are rare, so this costs little.
- Write-through on creation. Write the new mapping into the cache when creating it, so the first clicks hit the cache instead of a lagging replica.
- Short negative caching. Cache 404s for a few seconds only, so a lag-induced 404 heals quickly.
- Where it still falls short. Storage still lives on one primary's disk, and all writes go to one region.
Best: partition the mapping table by hash of the code, on a horizontally scalable store.
- Option A: a managed key-value or wide-column store (DynamoDB, Cassandra, ScyllaDB, Bigtable).
- The partition key
(domain_id, code)is hashed across nodes. - Each item is replicated 3 ways across zones, and capacity grows by adding nodes or by on-demand scaling.
- Conditional writes give us insert-if-absent.
- Global tables or multi-datacenter replication put a full copy in each region for local reads.
- The partition key
- Option B: sharded SQL.
- Keep PostgreSQL or MySQL, but split the table into, say, 64 or 256 logical shards by
hash(code) mod N. Map logical shards to a smaller number of physical clusters. - Tools such as Vitess (MySQL) or Citus (PostgreSQL) automate the routing.
- Logical shards let you move load later by relocating whole shards, never by re-hashing every row (Partitioning and Sharding).
- Keep PostgreSQL or MySQL, but split the table into, say, 64 or 256 logical shards by
- Why the code hash is the right shard key:
- Every redirect knows only the code, so each read goes to exactly one shard with no scatter-gather.
- Even spread. Generated codes come from a permutation, so they spread uniformly even though the underlying counter is sequential.
- No owner skew. A customer with 500M links spreads across all shards.
- "List my links" needs the owner instead. Serve it from a separate table keyed by owner, either maintained by the Link Service in the same logical operation (with an outbox for reliability) or derived through change data capture into a relational or search store. That index can be eventually consistent.
Growth arithmetic for the best option:
- Data: 12 TB primary, 36 TB with 3 replicas. A Cassandra node comfortably holds 1–2 TB of live data with room for compaction, so about 20–40 nodes per region.
- Reads: at 2,000 cache-miss reads per second, with each node handling thousands, the cluster is mostly idle on reads. The size is driven by storage, not load.
- Writes: 400 per second is trivial. Even a 100x bulk-import burst (40k per second for a large customer) fits once spread over 20+ nodes.
Keeping mappings forever, or not. Links are permanent by default, but most links are clicked only in their first weeks. Two complementary cost tactics:
- Tiering. Rows untouched for two or more years can move to a cheaper storage class or an "archive" table on dense, slower disks. A miss in the hot table falls back to the archive, so an old printed code still works, just a few milliseconds slower.
- Retention policy for anonymous links. Some services expire anonymous links after a period of inactivity, and say so in their terms. That's a product decision, not an engineering default; it is a promise to users. Google's goo.gl shortener stopped accepting new links in 2019 and later announced plans to stop redirecting old links, which drew strong pushback precisely because so many documents, papers and products depended on them. Short links are often printed in books, papers and on products. Breaking them is costly, and the decision should be made with eyes open.
5) How do custom aliases and branded domains work without collisions?#
The requirement. Users can choose sho.rt/spring-sale. Business customers can use their own domain (go.acme.com/sale). Generated codes and aliases must never collide, now or in the future.
Basic: check whether the alias exists, then insert.
- How it works.
SELECTthe alias; if absent,INSERT. - Why it fails. It's a race. Two users submitting
spring-saleat the same moment both see "absent" and both insert. Without a unique constraint, the second overwrites the first: a correctness bug that silently hijacks someone's campaign. It can also collide with a future generated code that happens to equalspringSif aliases and generated codes share a format.
Better: a uniqueness constraint and a conditional insert.
- How it works.
- Make
(domain_id, code)unique. - Insert the alias with "insert if not exists": a primary key on SQL,
attribute_not_existson DynamoDB,IF NOT EXISTSon Cassandra. - Exactly one of the racing requests wins; the other gets 409 and a suggestion such as
spring-sale-2.
- Make
- Why it wins. The database's atomic uniqueness check is the single arbiter, so there's no window for a race (Concurrency Control and Database Locking).
- What remains. Collisions with generated codes, plus policy problems: impersonation, offensive or reserved words.
Best: disjoint namespaces, normalization rules and policy checks.
- Disjoint formats.
- Generated codes are always exactly 7 base62 characters.
- Aliases must not match that exact pattern: they must be shorter, longer, or contain a hyphen or underscore.
- A generated code can then never equal an existing or future alias. This requires no lookup and no coordination, and holds forever.
- An alternative used by some systems is a prefix (
sho.rt/~aliasorsho.rt/c/alias), at the cost of a character and some aesthetics.
- Normalization and confusables.
- Decide on case sensitivity explicitly. Generated codes are case-sensitive, because base62 needs both cases. Aliases are usually stored case-insensitively, with the creator's casing preserved for display, so
Spring-Saleandspring-salecan't point to different places and confuse people. - Reject Unicode look-alikes or restrict aliases to ASCII. Internationalized aliases need punycode and confusable checks (Internationalization and Localization).
- Decide on case sensitivity explicitly. Generated codes are case-sensitive, because base62 needs both cases. Aliases are usually stored case-insensitively, with the creator's casing preserved for display, so
- A reserved list of system paths (
api,admin,login,help,static,robots.txt,favicon.ico) and brand names that are protected for trademark reasons. - Abuse rules:
- a profanity and slur filter;
- limits on alias creation per account;
- on the shared domain, aliases for paying users only, which reduces squatting on attractive words.
- Branded domains are a separate namespace. The key includes
domain_id, sogo.acme.com/saleandsho.rt/salecoexist. The customer namespace is private to the customer, so aliases there need no global competition.
What a branded domain needs operationally:
- Verification. The customer proves control of the domain by adding a DNS record (a TXT challenge, or a CNAME to
custom.sho.rt). - A TLS certificate, issued automatically through ACME (the protocol used by Let's Encrypt) at the CDN or load balancer, and renewed before expiry. Certificates for thousands of customer domains are managed by the edge provider's "custom hostnames" feature or by an in-house certificate service.
- Routing. The edge maps the
Hostheader todomain_id, so the lookup key becomes(domain_id, path). - Fallback pages. A root URL with no code (
go.acme.com/) or an unknown code redirects to a page the customer configures, rather than our default 404.
One more alias subtlety: changing an alias. Treat it as creating a new link and disabling the old one, never as renaming. Renaming frees the old alias, which someone else could then claim and receive the traffic from old printed materials. Keep the old alias reserved forever, pointing to the same destination or to a 410.
6) How do we handle expiry, deletion and takedowns correctly?#
Links can stop working for four reasons:
- the creator set an expiry;
- the creator deleted or disabled it;
- we blocked it for abuse;
- a legal order requires it.
Each must take effect quickly and survive every cache layer.
Basic: a nightly cleanup job that deletes expired rows.
- How it works. A cron job runs
DELETE FROM links WHERE expires_at < now(), as in the primer's design that scans for expired pastes. - Why it fails:
- Up to 24 hours late. A link set to expire at 09:00 keeps working until the job runs, and longer if it stays cached.
- Expensive. A huge delete on a big table causes lock contention, replication lag and bloat.
- It frees the code. Physically removing the row lets a future link reuse the code, so old QR codes would send people to a stranger's destination.
Better: lazy expiry on read, plus a background sweeper.
- How it works.
- Every lookup compares
expires_atwith the current time and returns 410 when it has passed, so expiry is exact to the second. - A background sweeper later flips the status to
expiredin small batches for reporting and archival. - Rows are never physically deleted while the code must stay reserved.
- Every lookup compares
- Why it wins. Correctness no longer depends on the job's schedule. The sweeper can be slow, throttled and restartable, and it never touches the hot path.
- What remains. Caches. A Redis entry with a 24-hour TTL, a CDN edge entry, or a browser-cached 301 may still hold the mapping after expiry or after a takedown.
Best: the lifecycle as explicit states, with every cache layer bounded by the state's lifetime.
The diagram shows the forward path only. Three transitions lead back to Active:
- Expired → Active: the owner extends the expiry.
- Disabled → Active: the owner re-enables the link within a grace period.
- Blocked → Active: an appeal is accepted.
Every transition into or out of Active invalidates the caches, just as editing the destination does.
The rules that make it correct:
-
Every cached copy stores
expires_atandstatus, not just the URL. Every layer re-checks expiry at read time. The edge function or Redirect Service can therefore stop serving an expiring link at the exact second, even from cache. -
TTLs are capped by the remaining lifetime. The Redis TTL is
min(24 h, expires_at − now). The CDNs-maxageismin(60 s, expires_at − now). -
Takedowns actively invalidate. Blocking a link for phishing does three things in order:
- updates the row;
- deletes the Redis key;
- issues a CDN purge for
https://sho.rt/{code}on every domain alias.
Purges on major CDNs usually take effect globally within seconds. The 60 s edge TTL bounds the worst case if a purge is lost.
-
No long-lived browser caching for links that might be taken down. This is the strongest argument against unbounded 301s.
-
Distinct responses:
- 404 means "never existed".
- 410 Gone means "existed, now expired or disabled".
- Blocked links show a warning page with status 200, or 451 Unavailable For Legal Reasons for legal blocks, not a redirect.
This helps support teams, crawlers and users.
-
Codes are never reused. Archiving moves the full row to cold storage but leaves a small tombstone
(domain_id, code, status=archived)in the hot table, so uniqueness checks still see it. -
Native TTL is for derived data only. DynamoDB's TTL or Cassandra's TTL can delete idempotency records and short-lived caches, never the reservation of a code.
The cost of keeping tombstones is small: 24B × about 40 bytes is about 1 TB, against a guarantee that a printed link can never be hijacked.
7) How do we count clicks and serve analytics without slowing redirects?#
The requirement. Totals and breakdowns (time, country, referrer, device), about 1–2 minutes fresh. Totals are accurate per day; unique-visitor counts may be approximate.
Basic: update a counter in the database on each click.
- How it works.
UPDATE links SET clicks = clicks + 1 WHERE code = ?inside the redirect handler. - Why it fails:
- It turns the read path into a write path. That's 7,700 writes per second on average, and for a viral link 100k+ per second on one row. Row locks serialize those increments, so throughput on that row collapses and redirect latency explodes.
- It couples redirect availability to database write availability.
- Breakdowns are impossible. A single counter can't hold "by country by hour".
Better: log the click, then aggregate in batch.
- How it works.
- The redirect handler writes an access log line, which costs almost nothing.
- Logs are shipped to object storage.
- A periodic batch job (MapReduce, or Spark today) aggregates
(code, hour, country, referrer) → countinto a warehouse such as BigQuery, Redshift or Snowflake (Data Pipelines, Warehouses and Lakes).
- Why it wins. The redirect path stays read-only. Batch processing is cheap, simple and easy to re-run when logic changes.
- Why it's not enough. Freshness is hours, not minutes, and customers watching a campaign launch want to see clicks within a minute or two.
Best: an event stream with real-time aggregation, plus batch recomputation (a lambda-style split).
- Emit.
- The Redirect Service, or the edge function for edge-served redirects, sends a click event to Kafka after responding, through a bounded in-process buffer.
- Batching of about 100 ms or 500 events per request keeps the overhead tiny.
- If the buffer overflows, it drops events and increments a "dropped" metric rather than blocking redirects.
- CDN logs cover edge hits: most CDNs can stream logs in near real time to a collector.
- Partition. Kafka topic
clicks, partitioned by code, so all events for a link go to one partition in order. At about 40k events per second at peak and about 250 bytes each, that's about 10 MB/s, comfortable for a small cluster (Apache Kafka in Practice). - Enrich and filter in a stream processor (Apache Flink and Stream Processing):
- Map IP to country and region with a GeoIP database, then drop the IP, which is privacy by design.
- Classify the user agent into a device class.
- Flag bots: known crawler user agents, link-preview fetchers from chat apps and social networks (which "click" every posted link), data-center IP ranges, and abnormal rates.
- Deduplicate retried or double-fired events using an event ID.
- Aggregate.
- Use one-minute tumbling windows per
(code, dimension, value), with event-time processing and a watermark of a minute or two, so late events land in the right bucket. - Write rollups to a columnar store (ClickHouse, Druid or Pinot), which answers "clicks by country for the last 7 days" in tens of milliseconds over billions of rows.
- Use one-minute tumbling windows per
- Handle hot partitions. One viral link concentrates its events in one Kafka partition and one processor task.
- Pre-aggregate in the producer: each Redirect Service instance sums clicks per code over 1 s before emitting, turning 300k events per second into a few hundred partial counts per second.
- Or salt the key for known-hot codes:
code#0..7combined downstream (Pattern: Scaling Writes).
- Unique visitors.
- Exact distinct counts per link per day would need to store every visitor ID.
- Instead, keep a HyperLogLog sketch per link per bucket. That's about 12 KB per sketch for about 0.8% standard error in Redis's implementation, and sketches can be merged across buckets for weekly or monthly uniques. The algorithm is from Flajolet, Fusy, Gandouet and Meunier ("HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm", 2007).
- The visitor ID itself is a salted hash of IP plus user agent, rotated daily, so it can't be used to track people across days.
- Correctness and recomputation.
- Raw events also land in object storage as Parquet.
- A nightly batch job recomputes the day's exact totals and replaces the streaming rollups for closed days. The fast path gives freshness; the batch path gives accuracy and the ability to fix bugs by re-running.
- The stream's checkpoints together with idempotent upserts into the store, keyed by
(code, bucket, dimension), give effectively-once aggregates for the fast path (Delivery Guarantees: At-Most, At-Least and Exactly-Once).
Storage for rollups. Suppose 670M clicks a day spread over about 50M distinct links clicked that day.
- At minute granularity for the last 48 hours, hour granularity for 90 days, and day granularity forever, with about 5 dimensions, the rollup tables are orders of magnitude smaller than raw events.
- Most links have a few clicks a day, so most minute buckets are empty and never stored.
- Hot links dominate the row count, but they are few.
Analytics are also an abuse sensor. A brand-new link receiving thousands of clicks a minute from email clients in many countries is a classic phishing-campaign signature. The stream processor can feed that signal to the safety system (deep dive 9).
8) How does code generation stay available and unique across instances and regions?#
Deep dive 1 chose counter ranges plus a permutation. This one covers who hands out the ranges and what happens when that component, or a whole region, fails.
Basic: one Redis instance, one INCR per create.
- How it works. Every Link Service instance calls
INCR global_counterfor each link. It's correct, because Redis runs commands one at a time, and fast (about 0.5–1 ms). - Why it fails.
- No Redis, no new links. Creation availability equals that single node's availability.
- Failover can duplicate numbers. Redis replication is asynchronous. If the primary acknowledged
INCRup to 1,000,500 but the replica only received up to 1,000,400 before failover, the new primary hands out 1,000,401–1,000,500 again. - Without a uniqueness constraint in the database, those duplicates would overwrite live links.
Better: batched ranges from a replicated allocator.
- How it works.
- Each instance leases a block (
INCRBY 10000orUPDATE ... RETURNING) and issues codes from memory. - The allocator is called about once every 25 seconds fleet-wide, so a brief outage of it is invisible, as long as each instance refills before its block runs out. Keep a second block in reserve and refill at 50–80% usage.
- Each instance leases a block (
- Why it wins.
- The allocator stops being in the hot path: a 5-minute allocator outage is absorbed by reserve blocks.
- Allocation load drops by four orders of magnitude.
- The remaining risk is still duplicates after an asynchronous failover of the allocator, now in units of whole blocks. And a single global allocator means cross-region calls for remote regions.
Best: a strongly consistent allocator, per-region disjoint ranges, and a database safety net.
- A consensus-backed allocator.
- Store the "next free block" in etcd or ZooKeeper (Raft or ZAB consensus; ZooKeeper and etcd), or in a database row on a synchronously replicated primary.
- Allocation is a compare-and-swap: read
next = 5,000,000, writenext = 5,010,000only if it is still 5,000,000. - A committed lease survives the failure of any minority of nodes, so a failover can never hand out a block twice (Consensus: Raft and Paxos).
- Per-region top-level ranges.
- Split the number space up front: region A owns numbers from 0 up to 10^12, region B owns numbers from 10^12 up to 2 × 10^12, and so on. 62^7 is about 3.5 × 10^12, so either reserve 8-character codes for more regions or use smaller regional slices.
- Each region runs its own allocator inside its slice, so creating a link in Singapore never waits on Virginia.
- Because the permutation is applied after range selection, codes from all regions still look uniformly random. Nobody can tell from a code which region minted it.
- Instance leases as an audit trail. Record
(block_start, instance_id, leased_at). During an incident you can prove which instance issued which code. - The safety net. The conditional insert on
(domain_id, code)stays, so a configuration mistake (two regions given the same slice, or a restored allocator snapshot) produces a failed insert and an alert, never a hijacked link. - Backup restores need a rule. After restoring the allocator from a backup, jump forward: set
nextto the maximum code seen in the links table, decoded, plus a generous margin. Never reuse the snapshot value.
What about custom aliases across regions? Aliases can't be pre-partitioned, because users choose them. Two users in different regions could request spring-sale simultaneously. Three options:
- Route alias creation to one "home" region for the shared domain, and use a strongly consistent conditional write there. Alias creation is rare and can tolerate an extra 100–200 ms.
- Use a globally consistent store for alias claims, such as Spanner, CockroachDB or DynamoDB with a single-region writer for this table.
- For branded domains, make the customer's home region authoritative for that domain's namespace.
Never use last-writer-wins multi-region replication for the alias table. LWW would silently let the later claim overwrite the earlier one (Multi-Region and Global Data).
9) How do we stop abuse: phishing, malware, spam and enumeration?#
A public shortener is an attractive tool for attackers. A short link hides the destination, borrows the shortener's reputation, and can be swapped after it passes a filter. If the shortener's domain ends up on blocklists, every legitimate customer's links stop working in email and chat. Abuse prevention is therefore a core availability concern, not an add-on (Security Fundamentals for System Design).
Basic: check the destination when the link is created.
- How it works. At creation, look up the URL in a threat-intelligence list (for example, Google's Safe Browsing API or a commercial feed) and refuse known-bad destinations.
- Why it's not enough:
- Bait and switch. Attackers create the link while the destination is clean and change the page later. Or they point at a clean redirector they control and change that.
- Bad URLs are rarely listed when first used. They usually get listed hours after a campaign starts.
- Editable links let the attacker change the destination after the check, unless every edit is checked too.
Better: check at creation, on every edit, and continuously re-scan, with rate limits and reputation.
- Check on every edit, exactly as on creation.
- Re-scan continuously.
- Re-check active links against updated feeds asynchronously: recent links often (for example hourly), old links daily.
- When a link becomes listed, move it to
Blockedand invalidate all caches (deep dive 6).
- Rate limits. Apply rate limits by API key, account, IP and /24 subnet, with much tighter limits for anonymous use: for example 10 links a minute per IP anonymous versus thousands per minute for verified API keys (Rate Limiting and Throttling).
- Reputation scoring of accounts and destinations based on account age, payment verification, past abuse, the destination domain's age, and whether it's a known URL-shortener or open redirector (a common evasion layer).
- Why it wins. It closes the bait-and-switch window to hours and makes mass abuse expensive.
- What remains. Zero-day phishing pages unknown to any list, and attacks that use our links in large email campaigns before anything is listed.
Best: layered defense, including click-time signals and user-facing warnings.
- Click-time checks at the edge. For links younger than a few days or from low-reputation accounts, the edge checks a fast local copy of the blocklist on each redirect, about 1 ms with a Bloom filter or hash set. Newly listed URLs are blocked within minutes without waiting for the re-scan.
- Behavioural detection from analytics. Feed the click stream into the abuse system (deep dive 7). It flags patterns such as:
- a new link from a new account getting thousands of clicks per minute from webmail referrers in many countries;
- many links from one account all pointing at freshly registered domains;
- links whose destination returns a login form imitating a known brand.
- Interstitial warnings. For suspicious but unconfirmed links, show a preview page instead of a 302: "This link goes to
example-login.top. Continue?" Adding+to a short link to see its stats and destination is a well-known feature of some shorteners, and it doubles as a safety preview. - Unenumerable codes (deep dive 1) and 404 rate limits stop scanners from harvesting private links. Treat "secret by obscure URL" links as public anyway: document that short links are not access control, and recommend real authentication for sensitive documents.
- Redirect-loop and chain protection. Refuse destinations on our own domains. Cap the number of known shorteners in a chain, since chains are used to hide phishing.
- Report-abuse endpoint and a takedown workflow with an SLA. Feed confirmed abuse back into the account reputation, which usually leads to suspending the whole account.
- Domain reputation hygiene.
- Consider separate short domains for anonymous links and for verified business links, so abuse on the anonymous domain can't get the business domain blocklisted.
- Twitter's t.co wraps every link posted on the platform, partly so it can check them against malware and spam lists and stop a bad link everywhere at once.
The cost of a check at creation (about 20–100 ms for an external API call) is acceptable within the 300 ms creation budget. The click-time check must be local and in memory to fit the redirect budget.
10) How do redirects stay at 99.99% availability, even through a regional outage?#
At 99.99%, redirects can be down about 4.4 minutes a month. Short links are embedded in other companies' emails, ads, printed packaging and QR codes, so an outage breaks things we don't control and can't re-send (Designing for High Availability).
Basic: one region with redundant components.
- How it works.
- Multiple Redirect Service instances across availability zones behind a load balancer.
- A replicated cache.
- A database with a synchronous standby in another zone.
- Why it's good. It survives instance and zone failures automatically.
- Why it fails 99.99%. A regional outage, a bad deploy pushed to the whole region, or a DNS or certificate mistake takes everything down. One multi-hour regional incident a year already uses more than the yearly budget of about 53 minutes.
Better: active-passive multi-region.
- How it works.
- A second region holds an asynchronous replica of the links database and a warm Redirect Service fleet.
- On failure, DNS or traffic management moves traffic to it.
- Why it's better. It survives losing a region.
- Why it's not best:
- Slow recovery. Failover takes minutes: detection, the decision, DNS TTLs and cold caches. A few of those per year can exceed 4.4 minutes a month.
- Untested standby. The passive region rarely serves real traffic, so it breaks in ways nobody notices until the day it's needed.
Best: active-active reads everywhere, single-writer creation, and graceful degradation.
- Every region serves redirects all the time.
- Each region has a full read copy of the mappings: a DynamoDB global table, a multi-datacenter Cassandra cluster with
LOCAL_ONEorLOCAL_QUORUMreads, or regional read replicas. - Each region also has its own cache tier.
- Anycast or latency-based DNS at the CDN sends users to the nearest healthy region, and the CDN fails over origins automatically on errors.
- Because all regions take real traffic every day, failover is just "drain one region"; nothing has to warm up.
- Each region has a full read copy of the mappings: a DynamoDB global table, a multi-datacenter Cassandra cluster with
- Creation can be multi-region too. Each region mints codes from its own range (deep dive 8). Aliases go to the home region. During a region outage, link creation in that region fails over to another region's Link Service.
- Degradation order, from first to last to lose:
- Analytics first. Kafka or the stream processor being down just means events buffer locally and then drop (counted). Redirects continue.
- Creation next. If the database's write path is impaired, creation returns 503 with
Retry-After. Redirects for existing links still work from caches and replicas. - Redirects last. If the regional database is unreachable, serve from Redis and the in-process caches. With a 95%+ hit rate and stale-while-revalidate, nearly all clicks still work. The edge keeps serving cached hot links even if every origin is down for a few minutes.
- Blast-radius control.
- Deploy region by region with canaries, so a bad release breaks at most one region, and the CDN steers traffic away from it (CI/CD and Deployment Strategies).
- Keep certificate renewals, DNS changes and CDN configuration under the same staged, reviewed process. Expired certificates and DNS mistakes are among the most common causes of total outages.
- Observability on the user-visible signal.
- Measure the redirect success rate and latency from synthetic probes in many countries, plus real traffic at the edge, per region and per domain.
- Alert on SLO burn rate, not on CPU (Observability: Logs, Metrics and Traces).
The consistency trade-off, stated plainly. In this design, a link created in region A may take tens to hundreds of milliseconds to reach region B's replica. A click arriving in B before then would miss. Four mitigations:
- Write-through. Write the new mapping into region A's cache and edge KV at creation.
- Fallback read. On a replica miss for a code whose embedded timestamp or range says "recent", fall back to a cross-region read of the home region before returning 404.
- Brief negative caching. Cache 404s for only a few seconds.
- Human pacing. In practice humans paste links seconds after creating them, so lag rarely bites. The fallback read covers bots and automated campaigns that click instantly.
This is PACELC in action (CAP Theorem and PACELC). During a partition we choose availability, serving cached and replicated mappings. Normally we choose latency (local reads) over strict consistency, with targeted fixes for the one anomaly that matters.
11) Should the same long URL always return the same short code?#
The question. If two requests shorten https://example.com/page, should they get the same code? The answer affects storage, analytics and privacy.
Basic: always create a new code.
- How it works. Every create mints a fresh code.
- Why it's the right default for most products.
- Each link gets its own expiry, its own edit rights and its own analytics. A marketer who creates separate links for an email campaign and a social campaign to the same page wants separate click counts.
- It's simple, and it has no privacy leak: nobody can tell that someone else shortened the same URL.
- The cost. Storage for duplicates. Popular pages may be shortened millions of times, at 500 bytes each. That's real but small next to the analytics data.
Better: deduplicate per owner.
- How it works. Keep an index
(owner_id, hash(canonical_url)) → code. When the same user shortens the same canonical URL again, with the same options, return their existing link. - Why it's better.
- It prevents clutter in a user's dashboard.
- It makes client retries without an idempotency key harmless.
- It never shares links between users, so there's no privacy leak.
- The subtleties:
- Option changes. If the second request has a different expiry or alias, it's not a duplicate; create a new link.
- Index size. Use a 128-bit or 256-bit hash of the canonical URL as the index key, not the 2 KB URL itself. It's then about 32 bytes per entry, and a hash collision is astronomically unlikely, so compare the stored URL on match anyway.
Best: deduplicate per owner, idempotency keys for retries, and careful canonicalization.
- Idempotency keys handle network retries exactly. The same
Idempotency-Keywithin 24 hours returns the same response, whether or not the URL matches existing links. This is separate from dedupe, which is a product feature. - Canonicalization must be conservative. It must never change where the URL points:
- Safe: lower-case the scheme and host; remove default ports; decode percent-encoded unreserved characters (
%7E→~); convert internationalized hostnames to punycode. - Unsafe: lower-casing the path, reordering query parameters, removing trailing slashes, or stripping parameters such as
utm_source. Each can change the response on some servers, or remove tracking the creator wants. - Apply only safe rules for dedupe. Apply more aggressive normalization only for blocklist matching, where a false match is better than a miss.
- Safe: lower-case the scheme and host; remove default ports; decode percent-encoded unreserved characters (
- Global dedupe (one code per URL across all users) is right only for special cases, such as a platform wrapping every posted link for safety scanning, where analytics per creator don't matter. It requires a global index on the URL hash, and it reveals that a URL was previously shortened.
12) How do we serve bulk creation and very large API customers?#
Some customers create links in bulk: e-commerce platforms generating a link per product, SMS marketers generating a unique link per recipient (millions per campaign), or publishers wrapping every outbound link. One customer can generate more creation traffic than all web users combined.
Basic: let them call POST /v1/links in a loop.
- How it works. Each link is a separate HTTPS request.
- Why it fails.
- Slow. 10M links at 50 ms each, with 20 parallel connections, takes about 7 hours.
- It competes with interactive traffic for the same capacity.
- Failures are hard to track. A failure halfway leaves the customer unsure which links exist.
Better: a synchronous batch endpoint.
- How it works.
POST /v1/links:batchwith up to 1,000 items returns per-item results (207 Multi-Status). The Link Service takes 1,000 codes from its local block and writes them in a multi-row or batch insert (DynamoDB'sBatchWriteItemtakes 25 items per call; SQL takes multi-rowINSERT). - Why it's better.
- Far fewer round trips: 10M links is 10,000 requests, minutes rather than hours.
- Per-item results let the client retry only the failures.
- Its limit. Very large jobs still hold connections open, and per-request time limits (often 30–60 s at gateways) cap the batch size.
Best: asynchronous bulk jobs with quotas and isolation.
- How it works.
- The customer uploads a file of URLs to a presigned object-storage URL, or posts a job description (Pattern: Handling Large Files and Blobs).
- The API returns
202 Acceptedwith a job ID. - Bulk workers read the file, create links in batches, and write an output file that maps input row to short URL.
- Progress is visible at
GET /v1/jobs/{id}, and completion triggers a webhook (Pattern: Managing Long-Running Tasks).
- Why it wins:
- Isolation. Bulk workers run on a separate pool with their own rate limits and a lower-priority write queue, so a 50M-link job can't starve interactive users.
- Resumability. Jobs checkpoint by row offset, and idempotency keys per row (
job_id:row) make restarts safe. - Code supply. Bulk workers lease larger blocks (for example 1M codes), reducing allocator traffic further.
- Safety checks are done per destination domain rather than per URL where possible. Millions of links to one known merchant domain need only one domain-reputation decision, plus a sampled deep scan.
- Quotas and pricing. Per-plan monthly link quotas, enforced in the job admission step, keep a single customer from growing the table by billions of rows unexpectedly. It's also how commercial shorteners price their service.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Viral link (one code at 100k–500k requests per second) | One cache shard and one DB partition overloaded; latency spikes for every code on that shard | CDN edge caching with s-maxage; in-process LRU on every instance; request coalescing; never let hot reads reach the database |
| Cold cache after deploy, failover or flush | Hit rate drops from 95% to near 0; database read load jumps 20x | Warm the cache from the top-N codes of the last hour before shifting traffic; stagger restarts; single-flight on misses; keep the edge cache, which survives origin restarts |
| Random-code scanning or typo floods (404s) | Cache penetration: every request misses cache and hits the database | Negative caching for 30–60 s; Bloom filter of existing codes; 404 rate limits per IP and prefix at the edge |
| Range allocator (etcd) unavailable | New blocks can't be leased; creation stops once local blocks run out | Reserve blocks per instance refilled at 50–80% use; 5+ minutes of buffer; consensus store across 3 zones |
| Allocator restored from an old backup or misconfigured regional ranges | Duplicate numbers, so codes collide with live links | Conditional insert on (domain_id, code) catches it; alert on any conflict; "jump forward" restore procedure |
| Replication lag between regions | Fresh link returns a false 404 in a remote region for a few hundred ms | Write-through to cache and edge at creation; cross-region fallback read for recent codes; very short negative-cache TTL |
| Kafka or stream processor down | Click events delayed or lost; dashboards stale | Bounded local buffers and drop-with-metrics so redirects never block; Kafka replication factor 3; replay from retained logs; nightly batch recompute from raw logs and CDN logs |
| Hot Kafka partition from a viral link | One consumer task lags; that link's stats fall behind | Pre-aggregate counts per code per second in producers; salt keys for hot codes; scale partitions |
| Phishing campaign using our links | Our domain gets blocklisted by mail providers and browsers; all customers' links break | Creation and edit scanning, continuous re-scans, click-time blocklist at the edge, behavioural detection, fast takedown and purge, separate domain for anonymous links |
| Expired or blocked link still served from cache | Takedowns ineffective; expired campaigns keep working | Store status and expires_at in every cached value and re-check them; TTL capped at remaining lifetime; explicit purge on block; no unbounded 301s |
| TLS certificate or DNS misconfiguration | Every redirect on a domain fails, a total outage | Automated ACME renewals with expiry alerts weeks ahead; staged DNS changes; synthetic probes per domain; multi-provider DNS |
| Database shard full or hot after years of growth | Write failures or slow misses on one shard | Logical shards (256+) mapped to physical clusters, so shards move without re-hashing; tier old links to cheaper storage; capacity alerts at 60–70% |
What Interviewers Expect#
Mid-level#
- A working end-to-end design:
- a create endpoint and a redirect endpoint;
- a database keyed by short code;
- an explanation of the click path from the browser through to the
Locationheader.
- At least one sound code-generation approach (random with a uniqueness check, or a counter with base62), the reason for base62, and how length relates to the number of links (62^7 is about 3.5 trillion).
- Recognizing the read-heavy workload, adding a cache with sensible TTLs, and knowing the difference between 301 and 302 at least in outline, with prompting allowed.
- Basic capacity math: reads per second from daily clicks, and storage from row size times link count.
Senior#
- Drive the design from the numbers. State the roughly 100:1 read-to-write ratio and peak versus average up front, and let them justify separating the redirect and creation services, a multi-level cache, and an edge layer.
- Compare code-generation options with their trade-offs:
- collision math for random codes;
- coordination for counters;
- predictability and enumeration;
- counter batching or ranges to remove the per-request coordinator.
- Choose 302 versus 301 deliberately, tied to analytics, editability and takedowns, with explicit
Cache-Controlchoices for browsers versus the edge. - Handle the hard parts of correctness:
- race-free custom aliases with conditional writes;
- expiry checked at read time with cache TTLs bounded by expiry;
- codes never reused;
- an asynchronous analytics pipeline that can't slow redirects.
Staff+#
- Treat availability as the product. Design active-active multi-region reads, a degradation order (analytics, then creation, then redirects), blast-radius-limited deploys, and certificate and DNS hygiene. Explain the PACELC trade-off for freshly created links and the targeted fix.
- Engineer the generator properly:
- per-region disjoint ranges from a consensus-backed allocator;
- a keyed permutation so codes are unenumerable but collision-free;
- a uniqueness constraint as the safety net;
- procedures for backup restores.
- Treat abuse as an availability risk:
- scanning at creation, on edit and continuously;
- click-time checks;
- behavioural signals from analytics;
- domain separation;
- takedown SLAs.
- Think about long-term economics and product evolution: tiering old links, link-permanence promises (the goo.gl lesson), bulk customers and quotas, branded domains with automated TLS, and privacy-preserving analytics such as dropping IPs and keeping HyperLogLog uniques.
Deep Dive: The mathematics of code spaces, guessability and alphabetsShow
The short-code alphabet and length look like details. They decide how many links you can issue, how guessable links are, and even how big printed QR codes become.
Code space by length (base62):
| Length | Codes | Comment |
|---|---|---|
| 5 | about 916 million | Too small for a public service; fine for an internal tool |
| 6 | about 56.8 billion | Enough for many years if sequential, but dense when randomized |
| 7 | about 3.52 trillion | The common choice for public shorteners |
| 8 | about 218 trillion | Headroom for very large scale or strong unguessability |
Exhaustion time. At 200M links a month, 7 characters last 3.52 × 10^12 ÷ 2.4 × 10^9 per year, which is about 1,470 years. Even at 100 times our scale, 7 characters last about 15 years. Running out of codes is not a real risk at 7 characters. Running out of unguessability is.
Guessability is about density, not secrecy.
- Density. If n links exist in a space of S codes, a random guess hits a real link with probability n ÷ S. At ten years we have 24B links in 3.52T codes, a density of about 0.68%.
- What a scanner gets. A scanner making 1,000 guesses a second would find about 7 valid links per second, or about 600,000 a day, without per-IP limits.
- Lessons:
- Short links are not access control. Any "secret" document shared only by short link will eventually be found by someone scanning. Researchers have demonstrated exactly this against real shorteners, finding links to private cloud documents and map directions.
- Rate limits on 404s matter as much as randomness. Limiting each IP to, say, 100 misses an hour reduces a scanner to about 0.7 finds an hour per IP. Determined attackers need large botnets.
- Use more length where sensitive links are expected. Moving to 8 characters for links to private resources lowers density by 62x, to about 0.011%. Some services offer longer "private" codes as an option.
Random-code collision cost, revisited. The expected number of database attempts per insert is 1 ÷ (1 − n/S). It's 1.007 at 0.68% density and still only 1.33 at 25%. Random generation with a uniqueness check only breaks down when the space is mostly full, so it's an honest option even at scale. The case for counters with a permutation is zero retries, no uniqueness lookup in the common path, and exact control over which region mints which codes, not that random fails.
Alphabet choices:
- Base62 (
0-9A-Za-z) gives the most codes per character among URL-safe alphanumerics. Its downside is look-alikes when a human reads or types a code:0/O,1/l/I. - Base58 removes
0,O,Iandl(popularized by Bitcoin addresses), trading about 2% of space per character for fewer transcription errors. It's useful when codes are printed and typed. - Crockford's Base32 is case-insensitive and avoids ambiguous letters. Every code can be read aloud or typed on a phone without the shift key, at the cost of length: 32^8 is about 1.1T, so you need 8 characters for the space 7 base62 characters give.
- Case-insensitive codes matter for QR codes. QR codes have an alphanumeric mode that encodes only digits, upper-case letters and a few symbols (space,
$ % * + - . / :) using fewer bits than byte mode. A short URL written entirely in upper case,HTTPS://SHO.RT/AZ3KP9Q, can be encoded in alphanumeric mode and gives a smaller, more scannable QR code. A case-sensitive base62 code forces byte mode. Shorteners whose links mainly end up printed sometimes use case-insensitive alphabets for exactly this reason.
Fixed versus variable length. A sequential counter in base62 grows from 1 character to 7 over time. Early links are 1–3 characters, very short but trivially guessable, and the namespace is shared with aliases. Fixed-width permuted codes avoid both problems, which is why we pad to exactly 7.
Checksums. Adding a check character, as credit card numbers do with the Luhn algorithm, lets the edge reject mistyped codes without a lookup. It costs one character, and it's useful for codes typed by hand from print. Most web shorteners skip it.
Deep Dive: Running a shortener at real-world scale: edge cases, cost and variantsShow
Edge cases that break naive implementations:
-
Dangerous schemes. Accept only
httpandhttpsdestinations. A shortener that redirects tojavascript:ordata:URLs becomes a cross-site-scripting tool, because some clients execute those when navigating. Also refuse destinations pointing at internal networks (localhost, private IP ranges, cloud metadata addresses). Otherwise link-preview fetchers and safety scanners on our own servers can be tricked into requesting internal resources (server-side request forgery). -
Open redirect reputation. By design, a shortener is an "open redirector", and attackers use open redirectors to make phishing links look trustworthy. Abuse controls (deep dive 9) are the price of offering the feature.
-
Link-preview bots. Chat apps, social networks and email security gateways fetch every link they see, to build previews or to scan. One message to a 10,000-member group can generate preview fetches that look like clicks.
- Detect them by user agent and IP range.
- Exclude them from analytics.
- Serve them a fast response: a redirect is fine, since the bot follows it to the destination page's metadata.
Some email security gateways also "pre-click" every link in incoming mail to scan the destination, which inflates click counts on email campaigns unless they are filtered.
-
Mobile deep links. Marketers often want a short link to open an app instead of the website. On iOS (Universal Links) and Android (App Links), the operating system decides whether a URL opens an app, based on the destination domain's association files. The shortener's redirect has to land on that destination domain for the app to open. Some shorteners host per-customer association files on branded short domains so the short link itself can open the app.
-
Query and fragment pass-through. Should
sho.rt/aZ3kP9q?ref=newsletterappendref=newsletterto the destination? Many shorteners do, for UTM tracking. Define and document a merge rule: keep destination parameters and append new ones. The fragment (#section) is never sent to the server, so browsers apply it to the redirect target automatically. -
Very long destination URLs. Some marketing URLs carry kilobytes of tracking parameters. Cap at about 2 KB (browsers and servers commonly accept around 8 KB, but caches and logs suffer). Store the URL compressed if the average grows.
-
Internationalized URLs. Destinations with non-ASCII host names are stored in punycode form for matching and safety checks, and in Unicode for display. Paths are percent-encoded.
Privacy and compliance:
- Click analytics are personal data in many jurisdictions when they include IP addresses or device identifiers.
- Drop IPs after GeoIP lookup.
- Use daily-rotating salted hashes for visitor counting.
- Keep raw events for a bounded window (30–90 days).
- Support deletion of a creator's data.
- When a user deletes their account, their links' destinations may need to keep working, because other people rely on them. Or they may need to stop, because the creator wants them gone. Make the choice explicit in the product and the terms.
Cost structure. With these assumptions, the main cost drivers are:
- Edge and request costs. CDN pricing is often per request plus per GB. Our responses are tiny, so the per-request part dominates. At about 20B redirects a month, the per-request price is worth negotiating, and serving from our own origins can be cheaper for the cold tail.
- Analytics storage and compute. About 5 TB a month of raw events, plus stream processing, exceeds the mapping store's cost. Retention windows and rollups are the biggest cost levers.
- The mapping store. About 36 TB replicated after ten years, growing linearly. Tiering old rows to cheaper storage helps.
- The redirect fleet, which is small: at about 10k requests per second per instance for a cache-hit-heavy handler, 40k per second at peak needs only a handful of instances per region, plus headroom.
A rule of thumb: in a shortener, analytics, not redirects, is the expensive part. That's why the analytics pipeline is aggressively aggregated, and why many shorteners charge for analytics retention.
Variant: Pastebin. Pastebin is the same problem with large values. Instead of a 100-byte URL, each key maps to text of up to, say, 10 MB. The primer's version assumes:
- Traffic: 10M pastes a month, about 1 KB average, so about 12.7 GB of new content a month and about 450 GB over three years; 100M reads a month (about 40 per second on average).
- Design changes:
- Content goes in object storage (S3) and the database stores only metadata and the object path, keeping the database small.
- Reads are served through a cache or CDN of the content itself.
- Expiry deletes the object as well as the row.
The code-generation, caching, expiry and analytics reasoning on this page carries over directly (Design a Pastebin).
Variant: an internal shortener. Many companies run go/ links (for example go/oncall) on internal DNS. Every code is a human-chosen alias, scale is tiny, and the design is a single replicated database plus SSO. The interesting problems are ownership of names and cleanup of stale links when teams change, not scale.
Real-world notes:
- Twitter's t.co wraps every link posted on the platform, to measure clicks and to check links against malicious-site lists. A link later found to be bad can be disabled everywhere it was posted at once.
- Bitly and similar commercial shorteners monetize branded domains, analytics and link management, which is why analytics freshness and retention feature so prominently in their products.
- Google's goo.gl stopped accepting new links in 2019. The long tail of old printed and published goo.gl links shows why a shortener's most important promise is longevity, not scale.
Deep Dive: Evolving the design from launch to ten yearsShow
Interviewers at senior levels and above often ask, "What would you build first?" A design that only works at its final size is a poor answer. Here is how this system should grow. Each stage is triggered by a measured need, not by anticipation.
Stage 0: launch, up to about 10M links.
- The setup:
- One region and one PostgreSQL primary with a synchronous standby.
- A single stateless service handling both creation and redirects, behind a load balancer.
- Random 7-character codes with a uniqueness check.
- 302 redirects.
- Click events written to a log and aggregated nightly.
- Why it's enough. Peak redirects are hundreds per second. The whole mapping table fits in the database's memory, so even uncached lookups are sub-millisecond. The team should spend its effort on the product and on abuse controls, which are needed from day one on a public domain.
- The decisions that are expensive to change later, so make them now:
- Code length and alphabet. Printed links live forever.
- Redirect semantics (302 with explicit headers). Browsers that cached a 301 can't be fixed later.
- Never reuse codes.
- The key shape
(domain_id, code), so branded domains don't require a migration. - A shard key decision, a hash of the code, even if there is only one shard today.
Stage 1: growth, about 100M–1B links and thousands of redirects per second.
- Triggers:
- Redirect peaks reach several thousand per second.
- The first viral links cause latency spikes.
- Customers ask for real-time stats.
- Changes:
- Split the redirect and creation services so they scale and deploy independently.
- Add a Redis cache tier for the mappings.
- Put the short domain behind a CDN with short edge TTLs.
- Move click events to Kafka and add streaming aggregation into a columnar store. Keep the nightly batch job as the accuracy backstop.
- Switch code generation to counter ranges plus a permutation if retries or the uniqueness lookup show up in creation latency. Otherwise random codes can stay.
- What not to do yet. Don't shard the database: about 500 GB fits comfortably on one primary with replicas, and sharding adds permanent operational cost.
Stage 2: scale, about 1B–10B links and tens of thousands of redirects per second.
- Triggers:
- The mapping table passes a few terabytes.
- Backup and restore times exceed the recovery-time objective.
- Users on other continents complain about latency.
- The 99.99% target is formalized as a customer contract.
- Changes:
- Move the mapping table to a horizontally scalable store: migrate to DynamoDB or Cassandra, or shard PostgreSQL into logical shards. The migration uses dual writes plus a backfill, then flips reads shard by shard with verification (Online Data Migrations and Schema Evolution).
- Add regions: read copies in each region, active-active redirects, latency-based routing, regional allocators with disjoint ranges, and a home region for aliases.
- Separate the "my links" listing into its own owner-keyed store, fed by change data capture.
- Mature abuse defenses: continuous re-scanning, click-time checks at the edge, and behavioural detection on the click stream.
Stage 3: maturity, about 10B+ links and years of history.
- Triggers: storage cost grows linearly forever, and most of it is links nobody clicks.
- Changes:
- Tier old mappings and keep tombstones.
- Archive raw click events to object storage and keep rollups only.
- Introduce bulk-job infrastructure for enterprise customers.
- Formalize SLOs, synthetic probes per domain, and staged rollouts across regions.
- The architecture is now the one in the high-level diagram, and each component has a clear reason to exist.
How to tell this story in an interview. State the final design's shape early, so the interviewer sees where you're heading. Then explain which parts you would build first and what metric would trigger each next step:
- cache hit rate;
- p99 redirect latency by region;
- table size against backup time;
- the error budget burn rate.
This shows judgement: the ability to avoid both under-engineering, where a shortener falls over on its first viral link, and over-engineering, where there's a multi-region sharded cluster for 10,000 links.
A note on migrations that never end. In shorteners the most painful changes are the ones that touch already issued links: changing code length, alphabet or case sensitivity, moving to a new short domain, or changing redirect semantics.
- Old links must keep working forever, so every such change means supporting the old format alongside the new, indefinitely.
- Moving to a new domain means the old domain must be renewed and served forever. Losing control of an old short domain would hand every link ever printed on it to whoever registers it next, a serious security risk.
- Treat domain registration as critical infrastructure:
- auto-renewal;
- registrar lock;
- multiple people with access;
- expiry alerts months ahead.
Key Takeaways#
- Start from the ratio. About 100 clicks per created link makes this a read-scaling problem: separate the redirect path from creation, and stack caches from the edge inward (Pattern: Scaling Reads, Content Delivery Networks (CDN)).
- Code generation is a uniqueness problem first and a secrecy problem second. Counter ranges from a consensus-backed allocator, passed through a keyed permutation and base62-encoded to a fixed 7 characters, give collision-free, unenumerable codes with almost no coordination. A uniqueness constraint in the database is the final safety net (Unique ID Generation).
- 302 by default, with explicit cache headers. Browsers must not remember editable or takedown-able links. Short edge TTLs plus purges give speed without losing control or analytics.
- Never put writes on the read path. Click counting goes through an asynchronous event log into stream aggregation and a columnar store, with batch recomputation for accuracy and HyperLogLog for uniques (Batch vs Stream Processing).
- Correctness lives in small rules:
- conditional inserts for aliases;
- disjoint alias and code formats;
- expiry checked at read time, with every TTL capped by it;
- codes never reused.
- Availability is the product. Active-active reads in every region, graceful degradation (analytics, then creation, then redirects), abuse prevention to protect the domain's reputation, and the promise that a printed link keeps working for years.