← Back to SQL, page 17

sql-0322 · Medium mid

Design the database for a URL shortener.

A links table with a short code as the primary key, the target URL, owner and created_at serves the redirect lookup by key. Generate codes from an id with base62 encoding or random strings checked by the unique key. Store click events separately, ideally aggregated per day, because redirects are read-heavy and click logging is write-heavy.

Full answer
text
links(code TEXT PRIMARY KEY, target_url TEXT NOT NULL, owner_id, created_at, expires_at)
clicks_daily(code, day, clicks, PRIMARY KEY (code, day))
  • The redirect is a primary key lookup; cache hot codes in memory.
  • Code generation: base62 of an auto-increment id is short and collision-free but guessable; random 7-character codes need a retry on unique violation.
  • Raw click events can go to a log or queue and be rolled up into clicks_daily with an upsert (ON CONFLICT DO UPDATE SET clicks = clicks + excluded.clicks).
  • Custom aliases share the same key space; reserve words such as 'admin'.
  • Abuse handling: a disabled flag and a check against blocked domains at creation.

The database is rarely the bottleneck for redirects if reads are cached; it is the source of truth for codes and owners.

Key points

  • Short code as primary key for fast redirects
  • Base62 ids or random codes with uniqueness retries
  • Separate, aggregated click storage
  • Cache hot codes

Common mistakes

  • Writing a row per click synchronously on the redirect path
  • Sequential codes where guessability matters

Follow-ups

  • How would you support link expiry?
  • How would you count unique visitors?

Tips

  • Separate the read path from analytics