Build a Link Compression Service
System DesignModel answerLast updated
Design a scalable service that converts long URLs into compact aliases and redirects users back to the original destinations.
Problem
Design a service that compresses URLs into shorter versions and handles redirection. Users submit lengthy URLs and receive compact aliases that redirect to the original destination when visited.
Core Functions
Your service must support:
- Compression: Accept a long URL and return a short, unique identifier
- Resolution: When someone visits the short link, redirect them to the original URL
- Custom identifiers: Let users choose their own alias (if available)
- Optional analytics: Track how many times each link is accessed
Scale Constraints
Your design should handle:
- Write volume: 100 million new URLs created daily
- Read volume: 1 billion redirections per day
- Latency target: Redirections complete in under 100ms
- Reliability: No data loss; links remain accessible indefinitely (or until expiration)
- Availability: Service stays operational under heavy traffic
What to Cover
Provide a complete design including:
- REST API specification with endpoints and payloads
- Data storage strategy (technology choice and schema)
- System architecture showing all major components
- Short code generation approach with collision handling
- Performance optimizations for read-heavy workload
- Discussion of key trade-offs and design decisions
Hints
Hint 1
Calculate the minimum identifier length needed to avoid exhausting the namespace within 5 years
Hint 2
The read-to-write ratio is roughly 10:1 - design for the common case
Hint 3
Consider how to guarantee uniqueness without checking the database on every write
Hint 4
Think about what happens when a link goes viral and gets millions of hits in minutes
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
1. Requirements Clarification and Capacity Planning
First, confirm assumptions:
- Are URLs mutable after creation? No, treat as immutable
- Do links expire? Support optional TTL
- Are real-time analytics needed? No, asynchronous processing is acceptable
Traffic estimates:
- Writes: 100M/day ≈ 1,200/sec average, ~5,000/sec peak
- Reads: 1B/day ≈ 11,600/sec average, ~50,000/sec peak
- Read:write ratio is 10:1; reads exhibit power-law distribution (few links get most traffic)
Storage over 5 years:
- 100M × 365 × 5 ≈ 183 billion URLs
- At ~500 bytes per entry (URL, metadata, timestamps): ~90 TB raw, ~270 TB with replication
- Requires horizontal partitioning
Identifier length:
- Base62 encoding (a-z, A-Z, 0-9): 62 possible characters
- 6 characters: 62^6 ≈ 56.8B combinations (exhausted in ~1.5 years)
- 7 characters: 62^7 ≈ 3.5 trillion (sufficient for 19× growth)
2. API Design
POST /api/v1/links
Request: {
"url": "https://example.com/very/long/path",
"custom_code": "my-link", // optional
"ttl_seconds": 86400 // optional
}
Response 201: {
"short_url": "https://sho.rt/aB3xY9z",
"code": "aB3xY9z",
"expires_at": "2024-01-15T00:00:00Z"
}
Errors: 409 (custom code taken), 400 (invalid URL)
GET /{code}
Response: 302 redirect with Location header
Errors: 404 (not found), 410 (expired)
GET /api/v1/links/{code}/analytics
Response: { "clicks": 15234, "created_at": "..." }
DELETE /api/v1/links/{code}
(Requires authentication)
Redirect status code choice: Use 302 (temporary redirect) rather than 301 (permanent). Browsers and CDNs cache 301 responses aggressively, making click tracking impossible. With 302, every access hits our service, enabling analytics.
3. Data Model
links table:
code STRING (partition key)
original_url STRING
user_id STRING
created_ts TIMESTAMP
expires_ts TIMESTAMP (nullable)
custom BOOLEAN
Storage technology: NoSQL key-value store (DynamoDB, Cassandra, or similar)
Rationale:
- Access pattern is simple key lookup by code - no joins or complex queries
- Natural horizontal scaling via hash partitioning on
code - Built-in replication and durability guarantees
- Native TTL support for automatic expiration
- Handles 90+ TB with consistent performance
For uniqueness guarantees, use conditional writes (e.g., DynamoDB's attribute_not_exists or Cassandra lightweight transactions) only when inserting custom aliases.
Maintain user accounts and API keys in a separate relational database - this data is low-volume and benefits from relational structure.
4. Architecture Overview
Users → CDN/Edge Locations → Load Balancer
|
+---------------------+---------------------+
| |
Write Service Read Service (stateless)
| |
+-------+-------+ +--------+--------+
| | | | |
ID Generator URL Validator Redis NoSQL Event Bus
| Cache Store (analytics)
+---> NoSQL Store ----populate cache---→ ↑
Component responsibilities:
- Write Service: Validates URLs, generates codes, writes to database, populates cache
- Read Service: Checks cache first, falls back to database, emits analytics events
- ID Generator: Leases ranges from coordination service, generates codes in-memory
- Redis Cache: Stores hot links (cache-aside pattern)
- Event Bus: Asynchronous analytics ingestion (Kafka/Kinesis)
Multi-region deployment:
- Read replicas in each region with local cache
- Write services allocated non-overlapping ID ranges per region (prevents global coordination)
5. Code Generation Strategy
Recommended approach: Range-based counter with base62 encoding
Architecture:
- Coordination service (ZooKeeper/etcd) assigns ranges like [1M-2M] to each write server
- Write servers convert sequential IDs to base62 locally - no per-request coordination
- Zero collision probability within the generation path
Implementation:
def generate_code(counter_value):
# Apply bijective function to avoid sequential patterns
shuffled = (counter_value * SECRET_PRIME) % (62**7)
return base62_encode(shuffled)
The multiplication by a coprime prime shuffles sequential IDs into pseudo-random codes, preventing enumeration attacks.
Handling custom aliases:
- Use conditional write operation (put-if-absent semantics)
- If conflict occurs, return 409 to user
- Rare collision between custom and generated codes: generator simply increments and retries
- Alternative: restrict custom aliases to different length (e.g., 5-6 chars) to separate namespace
Why not hash-based generation?
- Hashing the URL creates collisions due to truncation
- Every write requires database check-and-retry loop
- Harder to deduplicate per-user without complex indexing
6. Read Path Optimization
Target: 90th percentile under 100ms end-to-end.
Caching strategy:
- Redis cluster with cache-aside pattern, partitioned by code
- Cache size: ~20M hot URLs × 500B ≈ 10GB (easily fits in memory)
- Expected hit rate: 85-95% due to power-law distribution
- Write-through on creation ensures immediate read-after-write consistency
- LRU eviction policy with TTL matching link expiration
Handling viral links:
- In-process LRU cache on each read server (protects against Redis hot-key problem)
- CDN edge caching with short TTL (60-120 seconds)
- These layers absorb traffic spikes from popular links
Negative caching:
- Cache 404 responses for 60 seconds
- Prevents database hammering from random code scanning
Database reads:
- Use eventually consistent reads (lower latency, higher throughput)
- Quorum reads unnecessary since links are immutable
7. Key Trade-offs
Consistency vs. Availability:
- Custom aliases require strong consistency (conditional write)
- Generated codes can tolerate eventual consistency
- During network partition, custom alias creation may fail while resolution continues
Storage vs. Compute:
- Longer codes (8+ chars) never exhaust namespace but create uglier URLs
- 7 characters balances aesthetics with practical capacity
Analytics fidelity:
- Synchronous analytics on redirect path adds latency
- Asynchronous via event stream accepts ~1% data loss under extreme load but maintains sub-10ms service latency
- Implement at-least-once delivery with deduplication in stream processor
Global uniqueness:
- Range-based generation per region means codes reveal creation region
- Alternative: central ID generator with higher latency
- Trade-off favors regional autonomy for write availability
Common Mistakes to Avoid
- Using 301 redirects: Breaks analytics due to browser caching
- Sequential IDs without shuffling: Allows enumeration of all links
- Hash collisions on write path: Creates unpredictable latency
- Single-region ID generation: Becomes bottleneck and single point of failure
- No cache warming on write: Creates race condition where newly created links aren't immediately resolvable
- Ignoring hot-key problem: Viral links can overwhelm a single cache shard