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.
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
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.
| Approach | Good | Watch out for |
|---|---|---|
| Sequence, then base 62 | Short, no collisions, one INSERT | Codes are guessable and reveal volume; one counter, or ranges per server |
| Random 7 characters | Not guessable, no coordination | Rare collisions: let the primary key reject them and retry |
| Hash of the URL | The same URL gets the same code | Collisions after truncating the hash; different users share links |
The same mechanism, keys and ids, caches and memory, elsewhere on the site: in real incidents, in measurements, and in designs.
Pick an answer. You will see whether it is right, and why.
1. How many links do seven base 62 characters cover?
62^7 = 3,521,614,606,208.
2. Why not count clicks with UPDATE links SET clicks = clicks + 1?
One hot row serializes all its writers. Append clicks and aggregate them.
3. A link was created a second ago and the redirect says not found. Most likely cause?
Asynchronous replicas lag. Read just-created links from the primary, or cache them on create.
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.