System DesignMedium• 8 min read• Updated 2026-11-24
Designing a URL Shortener: The Senior Engineer Approach
A URL shortener looks simple until the interviewer asks how you handle 100 million writes a month and 100 times that in reads. Hashing the long URL with MD5 and slicing off seven characters seems clever, but you will spend half the interview writing collision resolution code. Here is how I structure this problem when I interview candidates, from database sizing to cache eviction.
1. Sizing the Numbers: Traffic and Storage Math
Never start sketching boxes without napkin math. It anchors every decision you make later.
Assume 100 million new URLs created per month. That translates to roughly 38 writes per second average. Even with a 4x peak traffic multiplier, you are looking at around 150 writes per second. That is trivial for any modern relational database.
The read side is where things get interesting. URL shorteners are heavily read-skewed, typically with a 100 to 1 read-to-write ratio. That means 3,800 reads per second average and around 15,000 peak reads per second.
Over five years, 100 million writes per month yields 6 billion records. If each row takes about 500 bytes (long URL, short hash, user ID, creation timestamp, expiration date), you need 3 terabytes of storage. This easily fits on a single managed database volume, but we partition by hash key to spread read IOPS across replicas.
The Sizing Mistake
Candidates often scream Cassandra or DynamoDB before checking the write volume. 150 writes per second can run on a single PostgreSQL instance without breaking a sweat.
2. The Hashing Trap vs Unique Sequence Encoding
The most common rookie mistake is hashing the original URL with MD5 or SHA-256 and taking the first 7 characters. Do not do this.
MD5 produces a 128-bit hash. Even if you convert it to Base62 (which supports 62^7 = 3.5 trillion values), birthday paradox collision math guarantees that you will hit collisions after storing just a few million URLs. Once you collide, you have to query the database, detect the collision, append a salt, hash again, and retry. That turns one write into multiple sequential database lookups.
The clean approach is completely deterministic: assign every URL an incremental 64-bit unique integer ID, then convert that integer directly to a Base62 string. Base62 using characters [0-9, a-z, A-Z] represents up to 3.5 trillion URLs with only seven characters, with zero collision checks ever needed.
def id_to_base62(num: int) -> str:
chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
if num == 0:
return chars[0]
result = []
while num > 0:
result.append(chars[num % 62])
num //= 62
return "".join(reversed(result))
Live Technical Interview Practice
Practice this topic on the interactive AI whiteboard
Do not just read the solution. Test your architecture under realistic interview pressure with an AI interviewer probing bottlenecks in real time.
If we use integer IDs, how do we generate them across a distributed fleet of API workers without a single point of failure?
You have two solid choices. The first is a Twitter Snowflake-style ID generator. Each 64-bit ID contains a 41-bit timestamp, a 10-bit worker machine ID, and a 12-bit sequence counter. Every node generates time-ordered unique IDs independently in memory with zero coordination latency.
The second is a range allocation service like Flickr uses. A dedicated counter service dispenses ranges of 100,000 IDs to API workers. Worker 1 handles IDs 1 to 100,000 in memory. Worker 2 handles 100,001 to 200,000. If a worker crashes, you waste a few unused IDs, but you never duplicate.
4. HTTP 301 vs 302: An Interviewer Favorite
When the client requests a short link, should your service return HTTP 301 Moved Permanently or HTTP 302 Found?
This is a trick question interviewers use to check real-world engineering judgment.
HTTP 301 instructs the browser to cache the target URL forever. The next time the user clicks the link, the browser bypasses your service entirely and loads the destination page. This reduces server load to near zero, but destroys your click tracking and analytics.
HTTP 302 or 307 Temporary Redirect forces every click through your redirect service. You capture the referrer, IP address, and timestamp before returning the Location header. If analytics or link decommissioning matter, choose 302.
Whiteboard Tip
State this trade-off explicitly before the interviewer asks. Say: I will use HTTP 302 so we retain click analytics and can revoke malicious links in real time.
5. Caching Strategy and Cache Eviction
Remember the 80/20 rule: 20 percent of URLs generate 80 percent of redirection traffic. Top viral links on social media get hit thousands of times a second, while long-tail links sit dormant.
We place a Redis cluster between our load balancers and the database. With 100 million requests per day, caching the top 20 percent requires storing 20 million URLs. At 500 bytes each, that is just 10 gigabytes of RAM. A single Redis replica pair handles the entire working set comfortably.
Configure Redis with allkeys-lru (Least Recently Used) eviction policy. When memory fills, infrequently accessed links drop out automatically, keeping hot links warm.
Key Architecture Decisions & Trade-offs
Decision Area
Options Evaluated
Recommendation
Hash Truncation vs Base62 ID Conversion
MD5/SHA truncation vs Snowflake counter + Base62
Use Base62 conversion. Completely eliminates collision resolution logic and database check loops.
Redirect Status Code
HTTP 301 Permanent vs HTTP 302 Temporary
HTTP 302. Keeps request path observable for fraud detection, analytics, and instant link revocation.
Database Selection
PostgreSQL vs DynamoDB/Cassandra
PostgreSQL with B-Tree index on short_code. Total write volume is small, and ACID guarantees ensure reliable uniqueness.
Frequently Asked Interview Follow-ups
Why do we use Base62 instead of standard Base64?
Base64 includes plus (+) and forward slash (/) characters, which have special meanings in URLs and require URL encoding. Base62 uses only alphanumeric characters (0-9, a-z, A-Z), making every generated code clean in all web browsers without escaping.
How do you handle link expiration efficiently?
Use a two-tier strategy. First, check expiration lazily on access: if current_time > expires_at, delete the record and return HTTP 404. Second, run a low-priority background cron job during off-peak hours to sweep expired records in batches.
What happens if the Redis cache fails?
Redis operates as a look-aside cache. If a cache node drops, requests fall back to the PostgreSQL read replicas. Connection pools clamp database queries while Redis Sentinel promotes a warm replica within seconds.
Ready for the interview loop?
Test your design under real pressure
Simulate a full 45-minute technical session on SWEPrep. Diagram architecture on the canvas, justify your trade-offs, and receive instant rubric feedback.