· software-engineers Editorial · Career  · 5 min read

Swe Interview System Design Url Shortener

Design a URL shortener end to end: encoding schemes, database choice, caching, and scale math for 2026 system design interviews.

Why URL Shorteners Remain the Canonical First System Design Question

Designing a URL shortener (a TinyURL/Bitly clone) persists as the most common opening system design question in 2026 interview loops because it’s approachable enough to complete in 45 minutes while touching nearly every core system design concept: unique ID generation, database schema and indexing, caching, read/write ratio skew, and horizontal scaling. Interviewers use it as a calibration question, and how far a candidate goes beyond the basic happy path (custom aliases, expiration, analytics, abuse prevention) is what differentiates a mid-level pass from a senior/staff pass.

Core Requirements Clarification

Before designing anything, strong candidates clarify: expected scale (reads vs writes, typically 100:1 read-heavy since a link is created once and clicked many times), whether custom aliases are supported, whether links expire, whether click analytics are required, and latency expectations for redirects (sub-100ms is standard since a redirect blocks page load). Skipping this step is one of the most common reasons otherwise technically strong candidates lose points early.

Encoding the Short URL: Three Approaches

1. Base62 encoding of an auto-incrementing ID. Convert a monotonically increasing integer ID (from a database sequence or a distributed ID generator) into a base62 string (a-z, A-Z, 0-9). A 7-character base62 string supports 62^7 (~3.5 trillion) unique codes, comfortably covering most systems’ lifetime volume. The challenge is generating unique IDs at scale without a single point of contention; solutions include a dedicated ID-generation service (like Twitter’s Snowflake, combining timestamp, machine ID, and sequence number) or pre-allocating ID ranges to each application server.

2. Hashing the long URL (MD5/SHA256, truncated). Hash the input URL and take the first N characters. This is simpler but requires collision handling (checking if the generated code already maps to a different URL and re-hashing with a salt), which adds complexity that pure counter-based approaches avoid.

3. Random string generation with a uniqueness check. Generate a random base62 string and check for collision against the database before committing, retrying on collision. At high scale this incurs unnecessary read-before-write latency and is generally considered inferior to counter-based Base62 for a well-architected system.

Database and Caching Design

The core data model is a simple key-value mapping (short_code -> long_url, plus metadata like creation_time, expiration, owner). This access pattern (point lookups by primary key) fits well-index relational databases (Postgres with an indexed short_code column) at moderate scale, or a key-value store (DynamoDB, Cassandra) at very large scale where horizontal partitioning by short_code hash simplifies sharding.

Given the read-heavy access pattern, a caching layer (Redis or Memcached) sitting in front of the database is essential: cache the short_code -> long_url mapping with a TTL, and since popular links follow a Zipfian distribution (a small fraction of links receive the vast majority of clicks), even a modest cache hit ratio (80-90%) dramatically reduces database load. Interviewers specifically look for candidates who mention cache invalidation strategy when a link’s destination is updated or when it expires.

Handling Scale: Numbers Interviewers Expect

A back-of-envelope calculation strong candidates walk through: at 100 million new URLs per month and a 100:1 read:write ratio, that’s roughly 40 writes/second and 4,000 reads/second sustained, with peak traffic several multiples higher. Storage for 6 billion URLs over 5 years at ~500 bytes per record (URL + metadata) is roughly 3TB, well within a single well-indexed database’s capacity if sharded, making this a “cache and index correctly” problem rather than a “need exotic storage” problem, a nuance senior candidates should state explicitly rather than over-engineering the solution.

Comparison Table: Short Code Generation Strategies

StrategyUniqueness GuaranteeCollision Handling NeededPredictabilityScaling Bottleneck
Base62(auto-increment ID)Yes, inherentNoSequential, guessableCentral ID generator
Base62(distributed Snowflake ID)Yes, inherentNoSemi-random, less guessableNone significant
Hash truncation (MD5/SHA)NoYes, retry with saltNon-sequentialExtra DB read per collision
Random string + DB checkNoYes, retry loopNon-sequentialRead-before-write latency

Extending the Design for Senior-Level Depth

Beyond the happy path, strong answers address: custom alias support (separate uniqueness check against a reserved namespace), rate limiting shortening requests per user/IP (ties directly to gateway rate-limiting patterns), analytics ingestion (asynchronous, via a message queue rather than synchronous writes on the hot redirect path, since blocking a user’s redirect on analytics writes would violate latency requirements), and abuse prevention (scanning submitted URLs against a malware/phishing blocklist before shortening).

The 0-to-1 SWE Interview Playbook (https://www.amazon.com/dp/B0H256Z1MF?tag=sirjohnnymai-20) walks through this exact question end to end with the follow-up probes interviewers actually ask after the initial design, which is where most of the differentiating signal in a real loop occurs.

FAQ

Q: Should the redirect be a 301 or 302 HTTP status? A: 302 (temporary redirect) is generally preferred in production because it prevents browsers from caching the redirect permanently, which would break analytics tracking and make it impossible to update or expire a link later; interviewers view naming this trade-off as a strong signal.

Q: How long should a short code be? A: Long enough to avoid running out of combinations for the expected lifetime volume, but no longer; 7 base62 characters (~3.5 trillion combinations) comfortably covers most real-world scales for years, and candidates should show the math rather than picking a number arbitrarily.

Q: Do I need a distributed database from the start for this design? A: No, and claiming you do is often a red flag; a single well-indexed relational database with a cache in front handles the vast majority of realistic scale requirements, and sharding should be introduced only when back-of-envelope math shows it’s actually necessary.

Back to Blog

Related Posts

View All Posts »