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_dailywith 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
disabledflag 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