Home›Design›Design a URL shortener
Course · Whole systemsLesson 30 of 330 read

Design a URL shortener

What does the database for a URL shortener actually look like?

Both paths, animated, with the schema and the numbers.

Press Play, or step with the arrows. Switch to Create a link for the write path.

A URL shortener is the first design in most system design courses. The diagram usually shows a box called database. This lesson opens that box: the table, the key, the code generation, and the one counter that will hurt you.

The table

Go deeper
CREATE TABLE links (
  code       text PRIMARY KEY,          -- base 62 of a sequence value
  url        text NOT NULL,
  owner_id   bigint,
  created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX ON links (owner_id, created_at);  -- "my links" page

Napkin math

Go deeper

Say a row averages 141 bytes on disk: a 7-character code, an 80-byte URL, an owner, a timestamp and the row overhead. That is 57 rows per 8 KB page, so a billion links take about 134 GiB (about 144 GB) of table, plus the two indexes. One PostgreSQL server holds that. What decides the design is read traffic, and the cache and replicas take that. Method in Database napkin math.

Three ways to make the code

Go deeper
ApproachGoodWatch out for
Sequence, then base 62Short, no collisions, one INSERTCodes are guessable and reveal volume; one counter, or ranges per server
Random 7 charactersNot guessable, no coordinationRare collisions: let the primary key reject them and retry
Hash of the URLThe same URL gets the same codeCollisions after truncating the hash; different users share links

When it grows

Go deeper
  • Reads: more cache, more replicas. A replica lag of a second only matters for a link created a second ago, so read your own new links from the primary.
  • Writes: a single primary takes thousands of inserts a second. Past that, shard by a hash of the code, with consistent hashing or fixed slots.
  • Expiry: delete expired links with a background job that deletes in small batches, instead of one big DELETE.
Connected

Where this shows up

The same mechanism, keys and ids, caches and memory, elsewhere on the site: in real incidents, in measurements, and in designs.

Check yourself · 3 questions

Check yourself

Pick an answer. You will see whether it is right, and why.

1. How many links do seven base 62 characters cover?

2. Why not count clicks with UPDATE links SET clicks = clicks + 1?

3. A link was created a second ago and the redirect says not found. Most likely cause?

Part 3 of 4 · Design · 24 pagesAll pages

Which database does my application need? What kind of application data goes in which database, and why, as design docs, plus the anti-patterns and the decisions behind them.