Video in progress
Design a URL shortener that runs in several regions: how is the short code generated and how do you make the redirect fast?
To generate codes without collisions I give each region its own ID range or Snowflake-style IDs and encode them in base62. The redirect path is read-only: a CDN/edge cache plus a KV store in the region, with writes going through asynchronous replication.
📖 Answer
First I pin down the ratio: reads outnumber writes 100-1000 times. So the architecture is built around the redirect, and creation is secondary.
Code generation. I consider three options:
- the first 7 characters of
hash(url): collisions happen, checking needs a global read, and that's awkward in multi-region; - a central counter: a synchronous call between regions, latency and a single point of failure;
- a range per region (for example, the high bits of the ID are the region number) or each instance takes a block of 10,000 at a time. No collisions, and regions don't wait for each other.
If we encode the ID in base62, 7 characters give ≈ 3.5 trillion combinations. Sequential IDs are guessable. If that's a problem (private links), you can scramble the ID with reversible encryption (for example, a Feistel cipher) and then encode it.
The redirect path.
- Edge/CDN: popular links are cached with a
301/302response. One catch: the browser remembers a301forever and click analytics disappear, so many services use302plus a shortCache-Control. - Inside the region: a
code → urlKV store (DynamoDB, Cassandra, or Redis + Postgres). The data is small: even billions of records are a few TB. - A newly created link may not have reached another region yet. If it isn't found, look at the region bit inside the code and ask the owning region. That closes the hole left by eventual consistency.
Analytics isn't written synchronously on the redirect path: click events go to Kafka, and from there to a store like ClickHouse.
Custom codes (they need a uniqueness check), expiring links (TTL), and scanning for malicious URLs: I mention these briefly at the end of the interview.
Sign up to mark studied questions and save your progress.