Design a Compact Link Redirect Service
System DesignModel answerLast updated
Build a distributed system that maps long URLs to short alphanumeric codes and serves fast redirects at scale.
Design a Compact Link Redirect Service
You need to architect a service that converts lengthy URLs into short alphanumeric codes and redirects users back to the original destination when they visit the shortened link.
Functional Requirements
- Create short link: Accept a long URL and return a compact alias (for example,
aB3xK9m). - Redirect: When a user visits the short link, send them to the original URL.
- Custom codes: Allow users to request a specific alias if it's available.
- Optional: Support link expiration and per-user link management.
Non-Functional Requirements
- Scale: The service creates roughly 100 million new links each month.
- Performance: Redirects must be fast—ideally under 50 ms at the 99th percentile.
- Availability: The redirect path should remain available even during partial outages.
- Compactness: Aliases should be as short as practical while avoiding collisions over a 10-year horizon.
What to Cover
- Capacity estimation: Calculate read/write rates, storage needs, and alias length.
- API contracts: Define the endpoints and their request/response format.
- Data storage: Choose a database technology and schema that fits the access pattern.
- Alias generation: Explain how you produce unique codes and handle collisions or custom requests.
- Scaling and caching: Describe how to serve high redirect traffic and distribute data across nodes.
Hints
Hint 1
Calculate the collision space for Base62 encoding with different lengths to justify your alias size.
Hint 2
Consider whether identical long URLs submitted by different users should map to the same short code or separate ones.
Hint 3
Think about the difference between a 301 permanent redirect and a 302 temporary redirect for analytics and caching.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
1. Capacity Estimation and Design Constraints
Begin by translating requirements into concrete numbers so you can size components appropriately.
Write load: 100 million links per month averages to roughly 40 writes/second. Peak traffic might hit 10× that, or 400 writes/second.
Read load: Link services are read-dominated. A conservative 100:1 read-to-write ratio yields 4,000 redirects/second average and 40,000/second at peak.
Storage: Over ten years, 100M/month accumulates to 12 billion records. Assume each record stores a long URL (averaging 100 bytes), the alias (7 bytes), metadata (user ID, timestamps, flags)—call it 500 bytes total. That's roughly 6 TB of raw data, which won't fit comfortably on one machine but is manageable for a sharded cluster.
Alias length: Using Base62 encoding ([a-zA-Z0-9]), seven characters gives 62^7 ≈ 3.5 trillion possible aliases, nearly 300× the ten-year requirement. Six characters (62^6 ≈ 57 billion) would be tighter but still sufficient; seven provides comfortable headroom and is the standard industry choice.
Redirect semantics: HTTP 301 (permanent) tells browsers to cache the mapping forever, reducing server load but breaking per-click analytics. HTTP 302 (temporary) forces every click through your service, preserving analytics. Choose 302 unless the user explicitly doesn't need click tracking.
Deduplication policy: Should two users shortening the same URL get the same alias? Recommend no—separate aliases let each user manage, expire, or delete their link independently and keeps analytics attribution clean.
2. API Design
POST /api/v1/shorten
Authorization: Bearer <token>
Content-Type: application/json
{
"long_url": "https://example.com/very/long/path?params=many",
"custom_alias": "sale2026", // optional
"expires_at": "2027-01-01T00:00:00Z" // optional
}
→ 201 Created
{
"short_url": "https://sho.rt/aB3xK9m",
"alias": "aB3xK9m",
"long_url": "https://example.com/very/long/path?params=many",
"created_at": "2026-11-03T14:22:00Z",
"expires_at": null
}
Errors:
400 Bad Request — malformed URL or alias
409 Conflict — custom alias already taken
429 Too Many Requests — rate limit exceeded
GET /{alias}
→ 302 Found
Location: https://example.com/very/long/path?params=many
Errors:
404 Not Found — alias does not exist
410 Gone — link expired or deleted
Optionally provide DELETE /api/v1/links/{alias} so users can remove their own links, returning 204 on success or 403 if the caller doesn't own the alias.
Validate incoming URLs: check scheme (http/https only), enforce a length cap (2 KB), and optionally check against a malware/spam blocklist before accepting.
3. Data Model and Storage Technology
The dominant access pattern is a point lookup by alias—no joins, no range scans on redirect. This naturally fits a key-value or wide-column NoSQL store like Cassandra or DynamoDB, both of which scale horizontally, replicate across availability zones, and deliver single-digit-millisecond reads.
links table (partition key: alias)
| Column | Type |
|---|---|
| alias | string PK |
| long_url | string |
| user_id | string |
| created_at | timestamp |
| expires_at | timestamp (nullable) |
| is_deleted | boolean |
For user management, keep a small users table in a relational DB (Postgres) or the same NoSQL store, indexed by user_id, holding API keys, rate-limit quotas, and tier metadata. If you need "list all my links," add a secondary global index on (user_id, created_at) or maintain a separate user_links table.
4. Alias Generation and Collision Handling
Three common strategies exist; compare them explicitly:
Option A: Hash the long URL, truncate to 7 Base62 characters.
Pro: deterministic and stateless.
Con: truncated hashes collide; identical URLs always produce the same alias (breaking per-user links); every write needs a read-check-retry loop on collision, adding latency.
Option B: Generate a random 7-character Base62 string.
Pro: simple and stateless.
Con: with 12B used out of 3.5T, birthday-paradox collision probability per insert is about 0.3 %. Use a conditional insert (INSERT IF NOT EXISTS in Cassandra, attribute_not_exists in DynamoDB) and retry with a new random string on conflict. Expect one or two retries per thousand writes.
Option C (recommended): Distributed counter with Base62 encoding.
Every ID is unique by construction, so zero collisions and no read-before-write overhead. Challenge: generating a global counter without a single point of contention.
Solution: Range-based allocation. A coordination service (ZooKeeper, etcd, or a single RDBMS row updated atomically) hands each application server a block of, say, 1 million IDs. The server encodes IDs from its in-memory range and only requests a new block when exhausted. A crashed server wastes at most one block, negligible given the 3.5 trillion space.
Sequential ID leakage: Raw counters are guessable and enumerable. Fix this by passing the counter through a reversible bijection before Base62 encoding—for example, a lightweight Feistel cipher or multiplication by a large odd constant modulo the space size. Uniqueness is preserved, but the output appears random.
Custom aliases: Validate that the requested alias matches your charset and length rules, and block reserved words (api, admin, www). Then attempt an atomic conditional insert. If two users race for the same custom alias, the database guarantees exactly one succeeds; the loser receives 409 Conflict. Never use check-then-insert—race conditions will produce duplicates.
To prevent custom aliases from colliding with generated ones, either enforce a different length/pattern for custom codes or rely on the conditional-insert protection for generated IDs and skip to the next counter value on conflict.
5. High-Level Architecture
User → GeoDNS → CDN/Edge → Layer-7 Load Balancer
↓
┌─────────────────────────────────────┐
│ Redirect Service (stateless fleet) │
└─────────────────────────────────────┘
↓ ↓
Redis cluster (LRU cache) Cassandra/DynamoDB (sharded, RF=3)
Write path:
User → Load Balancer → Write Service → ID allocator (ZK/etcd)
└→ Database
Async: Redirect Service → Kafka → Analytics consumers → OLAP warehouse
Separate the write service from the redirect service so each can scale independently. Redirects are latency-critical; writes can tolerate slightly higher latency.
6. Scalability and Distribution
Sharding: Partition the links table by alias using consistent hashing (native in Cassandra and DynamoDB). Every redirect is a single-partition point read. Base62-encoded, scrambled IDs distribute evenly with no hot ranges. Do not shard by user_id or created_at—redirects only know the alias.
Replication: Use replication factor 3 across availability zones. For redirects, read at consistency level LOCAL_ONE or ONE to minimize latency. For writes (especially custom-alias conditional inserts), use QUORUM to ensure correctness.
Horizontal scaling: Both the redirect and write services are stateless and sit behind autoscaling load balancers. Deploy across multiple regions and use GeoDNS to route users to the nearest cluster, cutting latency and improving availability.
7. Caching Strategy
Redis cluster (cache-aside pattern): On every redirect request, check Redis first. On cache miss, read from the database, populate Redis with a TTL (e.g., 24 hours), and return the result. Use LRU eviction so the hottest links stay in memory. Link traffic follows a power law—roughly 20 % of aliases account for 80 % of clicks. Caching that working set (tens of GB) fits easily in a modest Redis cluster and absorbs the majority of redirect load.
Negative caching: Cache "not found" responses for a short TTL (e.g., 60 seconds) to prevent attackers or bots from hammering the database with random aliases.
Invalidation: Alias mappings are immutable. On delete or expiration, remove the corresponding cache key. Short TTLs bound any staleness window.
Edge caching and CDN: For viral links, cache the 302 response at the CDN edge for a brief period (e.g., 30–60 seconds). This absorbs massive spikes but slightly delays analytics. Optionally, maintain a small in-process LRU on each redirect server to handle extreme hot-key bursts on a single Redis shard.
8. Trade-Offs and Design Decisions
- Counter-based IDs eliminate collisions but require a coordination service for range allocation. Random IDs avoid coordination but incur conditional-write retries.
- 302 vs. 301: A 302 redirect preserves click-level analytics at the cost of higher traffic; a 301 reduces load but blinds you to repeat visits.
- Eventual consistency on reads is acceptable—new links are typically accessed by their creator within seconds, and the cache can cover that window. Strong consistency on custom-alias writes prevents duplicates.
- NoSQL offers easy horizontal scaling and high throughput but limited query flexibility compared to SQL. Since this workload is pure key-value lookup, NoSQL is the natural fit.
- Sequential vs. random aliases: Sequential IDs (with scrambling) guarantee uniqueness and avoid retries; random IDs are simpler but require collision handling.
Common Mistakes to Avoid
- Using MD5/SHA hashing without handling collisions properly, or assuming truncated hashes never collide.
- Sharding by
user_idinstead ofalias, which forces cross-shard lookups on every redirect. - Forgetting to invalidate the cache on delete or expire, leading to stale 302s.
- Choosing 301 redirects without understanding the analytics trade-off.
- Overlooking GeoDNS and multi-region deployment, which significantly reduce latency for a global user base.