In short
A URL shortener stores a mapping from a short key to a long URL and answers each visit to the short link with an HTTP redirect. The design questions are how to generate keys that are short, unique and not trivially guessable, how to serve a read-heavy redirect path from a cache in front of a key-value lookup, whether to send a cacheable 301 or an uncached 302 (which decides whether you see every click), and how to keep analytics, abuse checks and expiry off the critical path of the redirect.
Key points
- Redirects outnumber new links by a wide margin, so design the read path first: one key lookup, served from a cache, with nothing else in the way.
- Counter plus base62 gives the shortest collision-free keys but sequential ones; hashing needs collision handling; random keys need a unique index and a retry; pre-allocated ID blocks remove per-write coordination.
- RFC 9110 makes 301 and 308 heuristically cacheable and 302 and 307 not, so a 302 with explicit no-store is the choice when every click should reach your server.
- Emit click events to a queue from the redirect handler and aggregate them elsewhere. The redirect must not wait for analytics.
- Check destinations against threat lists at creation and again later, rate limit creation and scanning, and refuse dangerous schemes and redirect loops.
- Decide what an expired code returns, whether codes are ever reused, and how custom aliases share the key space with generated ones.
Requirements
A URL shortener is the classic warm-up system design problem because the core is tiny and everything around it is not. The core: given a long URL, return a short one; given the short one, send the visitor to the long one. Write the requirements down before choosing anything.
- Create a short link for a long URL, optionally with a custom alias ("/spring-sale") and an expiry time.
- Redirect a visit to the short link to the long URL, with low latency everywhere visitors are.
- Keys are short, use only URL-safe characters, and are never handed out twice.
- Count clicks per link, with breakdowns such as time, country, referrer and device, for the link's owner.
- Let owners list, edit, disable and delete their links; let operators block abusive ones.
- Resist abuse: phishing and malware destinations, mass creation by bots, and scanning of the key space.
Non-functional requirements decide the architecture. Redirects must be fast and highly available, because a broken short link in a printed flyer or a sent message cannot be fixed by the sender. Creation can be a little slower and can tolerate brief unavailability. Analytics can lag by seconds or minutes. A link, once created, must keep pointing where it pointed: durability matters more than anything else in the store.
Back-of-envelope sizing
Pick round assumptions, write them down, and let the arithmetic tell you what is hard. These are illustrative, not measurements of any real service:
| Quantity | Assumption or result | Arithmetic |
|---|---|---|
| New links | 100 million per month | Given |
| Write rate | About 40 per second on average | 100,000,000 / (30 x 86,400 s) = 38.6 |
| Read to write ratio | 100 to 1 | Given; links are created once and clicked many times |
| Redirect rate | About 3,900 per second on average, several times that at peaks | 38.6 x 100 = 3,858 |
| Links kept | 6 billion | 100 million x 12 months x 5 years of retention |
| Row size | About 500 bytes | Key, long URL (most are far under 2,048 characters), owner, timestamps, flags |
| Link storage | About 3 TB before indexes and replicas | 6,000,000,000 x 500 bytes |
| Key space at 6 characters | 56.8 billion keys | 62 to the power 6 |
| Key space at 7 characters | 3.52 trillion keys | 62 to the power 7 |
| Hot set in cache | About 10 GB for the 20 million most-clicked links | 20,000,000 x 500 bytes |
Three conclusions follow. Writes are trivial for any database. Reads are the load, and they are almost perfectly cacheable because a link rarely changes, so most redirects should never reach the database. And storage grows without bound unless links expire, which is why retention is a requirement rather than an afterthought. Six characters would cover the six billion links with room to spare; seven gives enough headroom that random keys rarely collide, as the next section shows.
API and data model
The API is small: POST /links with the long URL and optional alias and expiry, returning the code; GET /{code} returning the redirect; and owner endpoints to list, update, disable and read stats. The access pattern on the hot path is a single lookup by key, which suits a key-value store or a relational table with the code as primary key equally well.
The schema below is PostgreSQL. It ran on a local PostgreSQL 14, and the comments show the real output. Expiry defaults to infinity, so every row has a value and the check is a plain comparison; the IS TRUE in the URL check also rejects a row with no URL at all, which a bare CHECK would let through.
CREATE TABLE links (
code text PRIMARY KEY, -- base62 key or custom alias
long_url text CHECK ((length(long_url) BETWEEN 1 AND 2048) IS TRUE),
owner_id bigint DEFAULT 0, -- 0 for anonymous links
is_custom boolean DEFAULT false,
status text DEFAULT 'active' CHECK (status IN ('active', 'blocked')),
created_at timestamptz DEFAULT now(),
expires_at timestamptz DEFAULT 'infinity', -- never, unless set
CHECK (code ~ '^[0-9A-Za-z_-]{4,32}$')
);
CREATE INDEX links_expires_at ON links (expires_at);
CREATE INDEX links_owner ON links (owner_id, created_at DESC);
INSERT INTO links (code, long_url) VALUES ('8SUD2', 'https://example.com/a/very/long/path?utm_source=x');
INSERT INTO links (code, long_url, is_custom, expires_at)
VALUES ('spring-sale', 'https://example.com/sale', true, now() - interval '1 hour');
-- The redirect lookup: one primary-key probe
SELECT code, long_url,
CASE WHEN status = 'blocked' THEN 'blocked'
WHEN expires_at <= now() THEN 'expired'
ELSE 'ok' END AS state
FROM links WHERE code IN ('8SUD2', 'spring-sale') ORDER BY code;
-- 8SUD2 | https://example.com/a/very/long/path?utm_source=x | ok
-- spring-sale | https://example.com/sale | expired
-- A taken custom alias inserts nothing; the API answers 409 Conflict
INSERT INTO links (code, long_url, is_custom) VALUES ('spring-sale', 'https://example.org', true)
ON CONFLICT (code) DO NOTHING RETURNING code;
-- (0 rows)In the same session, inserting a row without a URL and a row whose code contains a space both failed their check constraints. Validate the long URL in the application as well: parse it, require http or https, and cap its length, so a bad request gets a clear error rather than a constraint name.
Generating short keys
A key is a number written in a compact alphabet. Base62 uses the ten digits and the 26 letters in both cases, all safe in a URL path without escaping, so each character carries a little under six bits. The question is where the number comes from.
| Approach | How it works | Strengths | Weaknesses |
|---|---|---|---|
| Counter plus base62 | A database sequence or counter service hands out the next integer; encode it in base62 | Shortest possible keys; no collisions; trivial to decode back to the row ID | Sequential keys are enumerable and leak volume; one counter is a central dependency |
| Hash of the long URL | Hash the URL (for example SHA-256), base62-encode, keep the first 7 characters | No coordination; the same URL can map to the same key | Truncation makes collisions likely at scale, so every insert needs a conflict check and a fallback such as rehashing with a salt; one key per URL clashes with per-owner links and stats |
| Pre-allocated ID blocks | Each app server claims a block of IDs (say 10,000) from a central table, then encodes from memory | One coordination round trip per block, not per link; no collisions | Blocks of a crashed server are lost (harmless); keys within a block are sequential unless scrambled |
| Random keys | Draw 7 or 8 random base62 characters from a secure random source; insert, and retry on conflict | No coordination; keys do not reveal order or volume | Needs a unique index and a retry loop; collision chance grows with the number of links |
| Time-ordered IDs | Snowflake-style 64-bit IDs or UUIDv7, encoded in base62 | Unique without coordination; sortable by creation time | Too long for a short link: 11 characters for 64 bits, 22 for a 128-bit UUID; they also reveal creation time |
A common combination is pre-allocated blocks plus a reversible scramble: the counter guarantees uniqueness without retries, the block removes the per-write round trip, and the scramble hides the sequence. The block claim is one short transaction:
CREATE TABLE id_blocks (name text PRIMARY KEY, next_start bigint);
INSERT INTO id_blocks VALUES ('links', 1);
-- An app server claims a block of 10,000 ids in one short transaction,
-- then hands them out from memory: encode(scramble(id)) for each new link
UPDATE id_blocks SET next_start = next_start + 10000
WHERE name = 'links'
RETURNING next_start - 10000 AS block_start, next_start - 1 AS block_end;
-- 1 | 10000 (first claim)
-- 10001 | 20000 (second claim, by another server)PostgreSQL sequences have the same property built in: with CACHE above 1, each session reserves a range of values in memory, and the documentation says values are then only guaranteed to be distinct, not sequential across sessions, and that unused reserved values are lost when a session ends. That is fine for keys.
The encoder, the decoder and the scramble are a few lines. Multiplying by a constant that shares no factor with 62 to the power 7 is a bijection on the 7-character key space, so every ID maps to exactly one key and back. It hides the sequence from a casual glance; it is not security, because two consecutive keys reveal the multiplier to anyone who looks. The last loop uses the birthday approximation to show how quickly random 7-character keys start to collide.
const ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const BASE = 62n;
function encode(n: bigint): string {
if (n < 0n) throw new Error('negative id');
if (n === 0n) return ALPHABET[0];
let out = '';
while (n > 0n) {
out = ALPHABET[Number(n % BASE)] + out;
n /= BASE;
}
return out;
}
function decode(s: string): bigint {
let n = 0n;
for (const ch of s) {
const d = ALPHABET.indexOf(ch);
if (d === -1) throw new Error('bad character: ' + ch);
n = n * BASE + BigInt(d);
}
return n;
}
// Hide the counter: a bijection on [0, 62^7) so neighbours do not look alike
const SPACE = BASE ** 7n; // 3,521,614,606,208 keys of 7 characters
const MULT = 2_176_477_521_739n; // odd and not a multiple of 31, so coprime to 62^7
function modInverse(a: bigint, m: bigint): bigint {
let [oldR, r, oldS, s] = [a, m, 1n, 0n];
while (r !== 0n) {
const q = oldR / r;
[oldR, r] = [r, oldR - q * r];
[oldS, s] = [s, oldS - q * s];
}
return ((oldS % m) + m) % m;
}
const INV = modInverse(MULT, SPACE);
const scramble = (id: bigint) => (id * MULT) % SPACE;
const unscramble = (x: bigint) => (x * INV) % SPACE;
for (const id of [0n, 61n, 62n, 125_000_000n, SPACE - 1n]) {
const code = encode(id);
console.log(id.toString().padStart(13), code.padStart(7), decode(code) === id);
}
for (const id of [1000n, 1001n, 1002n]) {
const key = encode(scramble(id)).padStart(7, '0');
console.log(id.toString(), key, unscramble(decode(key)) === id);
}
// Chance that random 7-character keys have collided at least once after k links
for (const k of [1e5, 1e6, 1e7]) {
const p = 1 - Math.exp(-(k * (k - 1)) / (2 * Number(SPACE)));
console.log(k.toExponential(0), p.toFixed(4));
}
// 0 0 true
// 61 z true
// 62 10 true
// 125000000 8SUD2 true
// 3521614606207 zzzzzzz true
// 1000 26eSS0e true
// 1001 eQNGKLj true
// 1002 Gk64Cgo true
// 1e+5 0.0014
// 1e+6 0.1324
// 1e+7 1.0000The output comments are real, from Node 22 with type stripping. Two readings of the collision numbers matter. The chance that at least one pair of random keys collides is already about 13 percent at a million links and a near certainty at ten million. The chance that a given insert collides is far smaller: the number of existing links divided by 3.52 trillion, under three in a million at ten million links. So random keys are fine, but only with a unique index and a retry, never with an assumption that collisions do not happen.
Whichever scheme you choose, treat keys as public. RFC 9562, which defines UUIDs, says implementations should not assume UUIDs are hard to guess and must not use them as security capabilities; the same goes for short codes. A short link to a private document is a public link to that document. If links must be private, require authentication at the destination.
The redirect path: 301, 302, 307 or 308
The redirect handler parses the code, looks it up, checks that the link is active and not expired, emits a click event without waiting, and returns a redirect with the long URL in the Location header. RFC 9110 defines four redirect codes that matter here:
| Code | Meaning in RFC 9110 | Method on redirect | Caching by default |
|---|---|---|---|
| 301 Moved Permanently | The resource has a new permanent URI | A user agent may change POST to GET, for historical reasons | Heuristically cacheable |
| 302 Found | The resource is temporarily under a different URI | A user agent may change POST to GET | Not heuristically cacheable; cached only with explicit freshness |
| 307 Temporary Redirect | Temporary, like 302 | The user agent must not change the method | Not heuristically cacheable |
| 308 Permanent Redirect | Permanent, like 301 | The method must not change | Heuristically cacheable |
"Heuristically cacheable" is the important phrase. RFC 9110 lists 301 and 308 among the status codes a cache may reuse with a heuristic expiration time when the response carries no explicit cache controls, and says all codes not listed are not heuristically cacheable. RFC 9111 adds that a cache must not use heuristics when an explicit expiration time is present. In practice, a 301 without cache headers lets a browser or a shared cache store the redirect, so a repeat visit can go straight to the destination without asking the shortener.
- If the product promises click analytics, or links can be edited, disabled or expire, answer with 302 (or 307) and
Cache-Control: private, no-store. Every visit then reaches the shortener, at the price of serving every visit. - If links are immutable and analytics are not needed, a 301 (or 308) with an explicit
Cache-Control: max-age=...lets caches absorb repeat visits. Set the lifetime explicitly rather than leaving it to heuristics, and assume a cached permanent redirect cannot be recalled. - For a short link, the method rarely matters: visitors arrive with GET. The 307 and 308 variants matter only if clients might POST to the short URL.
The uncached temporary redirect is also what makes moderation work: blocking a phishing link only helps if visitors keep asking the shortener where to go. Whatever you choose, keep the handler free of slow work. Every millisecond in it is added to every click.
Caching hot links
Clicks tend to concentrate on a small share of links, the ones just shared widely, and a link rarely changes once created. That makes a cache in front of the store very effective, and the general patterns are in caching strategies. For a shortener, the specific choices are these:
- Cache-aside in an in-memory store, keyed by code, holding the long URL, status and expiry. A miss reads the database and fills the cache with a time to live.
- Cache misses too. A scanner probing random codes would otherwise send every probe to the database. Store "not found" entries with a short time to live.
- Keep a small in-process cache in each redirect server for the very hottest codes, with a lifetime of seconds, so one viral link does not send every request to a single cache node.
- Invalidate on change. When a link is edited, disabled or blocked, delete its cache entry in the same code path that commits the change, and keep time-to-live values short enough that a missed delete heals quickly.
- Check expiry at read time, against the cached expiry, rather than relying on the cache entry to expire at the right moment.
A CDN can serve redirects at the edge as well. With a 302, that means sending a shared-cache lifetime such as s-maxage while keeping browsers uncached, and getting click counts from the CDN's logs instead of your own servers; with a block or an edit, it means a purge. Both are workable, and both move part of your correctness into the CDN's configuration, so decide deliberately.
Database choice and sharding
The access pattern is a key-value lookup, a write rate any database handles, and a data set that grows into terabytes. Two families fit. A relational database such as PostgreSQL gives you unique constraints, transactions for custom aliases and owner data in one place; a primary with read replicas behind the cache carries a long way. A distributed key-value or wide-column store gives you horizontal scale and multi-region replication natively, with fewer guarantees around uniqueness that you then build yourself.
When one node is no longer enough, shard by the code. Consistent hashing and sharding explains the mechanics; the shortener-specific points are:
- Hash the code to pick a shard, rather than using key ranges. Counter-based keys are sequential, and range sharding would put all new, hot links on the last shard.
- The redirect touches exactly one shard. Keep it that way: nothing on the hot path should need a cross-shard query.
- Uniqueness is per shard, which is enough when the code decides the shard: two inserts of the same code always land on the same shard and its unique index.
- Owner queries ("all my links") cut across shards. Keep a separate table keyed by owner, written alongside each link, rather than scattering a query to every shard.
- Replicate across regions for reads. A link is written once and read everywhere, so asynchronous replication is acceptable if a freshly created link is read from the region that created it for its first seconds.
Click analytics off the hot path
Writing a row per click into the links database from the redirect handler couples the hottest path to the heaviest write load. Instead, the handler emits an event (code, time, coarse location, referrer, user agent) to a local buffer or a log such as a message queue, and returns the redirect immediately. Consumers read the stream, enrich and aggregate it, and write rollups the dashboards read.
-- Raw click events arrive from the queue, never from the redirect handler
CREATE TABLE click_events (
code text,
clicked_at timestamptz,
country text,
referrer text,
device text
);
-- Per-day rollups that the dashboard reads
CREATE TABLE click_daily (
code text,
day date,
clicks bigint DEFAULT 0,
PRIMARY KEY (code, day)
);
-- A rollup step: fold a batch of events into per-day counts
INSERT INTO click_events VALUES ('8SUD2', now(), 'NL', 'direct', 'mobile'),
('8SUD2', now(), 'US', 'direct', 'desktop');
INSERT INTO click_daily (code, day, clicks)
SELECT code, clicked_at::date, count(*) FROM click_events GROUP BY 1, 2
ON CONFLICT (code, day) DO UPDATE SET clicks = click_daily.clicks + EXCLUDED.clicks;
SELECT code, clicks FROM click_daily;
-- 8SUD2 | 2That ran in the same PostgreSQL 14 session as the schema above; at scale, the events would live in a log or a columnar store rather than a table in the links database. Points that decide whether the numbers mean anything:
- Delivery is at least once, so give each event an ID and make the rollup idempotent, or accept small overcounts knowingly.
- Losing a few events in a crash is usually acceptable; slowing every redirect to avoid that is not. Decide which you prefer and write it down.
- Many clicks are not people: link-preview fetchers in chat and social apps, security scanners and crawlers. Classify by user agent and behavior, and report human and automated clicks separately.
- Store as little personal data as the reports need. Coarsen IP addresses to a country or region at ingestion, and set a retention period for raw events.
Abuse: malicious links and rate limiting
A shortener hides a destination behind a neutral-looking domain, which is exactly what phishing and malware campaigns want. If a short domain becomes known for bad links, mail filters and browsers can start treating every link on it as suspect, the good ones included.
- Check every destination at creation against threat lists. Google's Safe Browsing APIs check URLs against lists of phishing, malware and unwanted-software sites, and are limited to non-commercial use; Google points commercial uses to its Web Risk API, which offers a lookup API and an update API that keeps hashed lists locally for privacy and speed.
- Check again later. A destination that was clean at creation can turn bad, so re-check active links on a schedule and on every abuse report, and block in the store and the cache together.
- Refuse dangerous inputs: schemes other than
httpandhttps(nojavascript:ordata:), links to your own short domain or to other shorteners, which build redirect chains and loops, and destinations on private network addresses if your service fetches them for previews. - Show an interstitial warning page instead of redirecting when a link is suspicious but not confirmed bad.
Rate limiting covers the rest; see rate limiter system design. Limit link creation per account and per IP address, with tighter limits for anonymous users. Limit "not found" responses per client as well, which slows anyone scanning the key space for private links. RFC 6585 defines 429 Too Many Requests for this, with an optional Retry-After header, and says a 429 response must not be stored by a cache.
Expiry and custom aliases
Expiry needs three decisions. First, what an expired code returns. RFC 9110 describes 410 Gone for a resource that is intentionally unavailable and likely to stay that way, mentioning limited-time promotions as a typical case, and 404 when the server does not know whether the condition is permanent. Note that 410 is heuristically cacheable too, so send explicit cache headers if the owner may extend the link. Second, when rows are removed: a background job deleting expired rows in small batches, using the index on expires_at, keeps storage bounded without touching the redirect path. Third, whether codes are reused. A printed code pointing at someone else's page years later is a real risk, so never reuse codes, or quarantine them for a long time; with a 7-character key space there is no shortage to justify reuse.
Custom aliases share the namespace with generated keys, and that needs rules:
- Reserve words that are routes or could mislead:
api,admin,login,help, your own brand terms. - Decide case handling. Base62 keys are case-sensitive, but people retype aliases from posters and conversations. One option is to fold aliases to lower case and check uniqueness on the folded form.
- Keep generated keys and aliases from colliding. Either give them disjoint shapes (generated keys exactly 7 characters, aliases required to be longer or to contain a hyphen), or rely on the unique index and retry generation on conflict.
- Claim an alias with an insert that fails on conflict and return 409 Conflict, as in the schema example, rather than checking first and inserting second, which races.
- Watch for look-alike aliases that imitate brands or other users' links, and include aliases in abuse review.
Put together, the system is a cached key-value lookup with a redirect in front, a key generator beside it, and everything else, analytics, scanning, cleanup, attached by queues and background jobs so that the one thing that must always work, the redirect, does as little as possible.
If you are building a link service, or any product with a hot read path like this one, see our web app development service: the code lives in your GitHub from day one, AI-assisted work is reviewed by an engineer, and the founders are on the calls.
Sources
Checked when this post was written.
- RFC 9110: HTTP Semantics (IETF, 2022)
- RFC 9111: HTTP Caching (IETF, 2022)
- RFC 6585: Additional HTTP Status Codes (IETF, 2012)
- RFC 9562: Universally Unique IDentifiers (UUIDs) (IETF, 2024)
- PostgreSQL documentation: CREATE SEQUENCE
- Google for Developers: Safe Browsing
- Google Cloud documentation: Overview of Web Risk