Design an Ultra-Low Latency Distributed Link Shortening Platform
System DesignModel answerLast updated
Architect a scalable, high-availability URL shortener capable of handling heavy read workloads, instant redirects, custom aliases, and automated TTL cleanup.
Problem Statement
Design a distributed URL shortener service (similar to Bitly or TinyURL) capable of processing high volume with a strong read-to-write skew.
Requirements
Functional
- URL Encoding: Convert a long target URL into a short, unique code (e.g.,
https://short.link/a7B9kX2). - Redirection: Resolve a short link to its original target URL with high responsiveness.
- Custom Vanity Links: Allow users to specify custom short aliases when available.
- Link Expiration: Support optional TTL (Time To Live) parameters after which links expire and cease to redirect.
Non-Functional
- Ultra-Low Latency: Redirect lookup latencies must maintain sub-100ms at $p_{99}$.
- High Availability: The read path must remain resilient even during single-node or regional failures.
- Capacity Target: Design for 100 million creation requests per month with a 100:1 read-to-write ratio.
Deliverables
Present an end-to-end system design addressing:
- Estimation & scale requirements
- RESTful API definitions
- Data model and storage architecture
- Collision-free short code generation strategy
- Caching layer and read/write optimization paths
- Trade-offs and failure scenarios
Hints
Hint 1
Calculate throughput requirements for reads vs. writes first to inform your storage and caching layer decisions.
Hint 2
Consider how pre-allocating integer ranges (or using a Key Generation Service) avoids database locks or collision retries during short code generation.
Hint 3
Evaluate HTTP 301 vs. HTTP 302/307 status codes carefully with respect to client-side caching and telemetry collection.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Scale Estimation & Requirements
Traffic Estimates
- Writes (New URLs): $100\text{ million} / 30\text{ days} \approx 3.33\text{ million/day} \approx 40\text{ writes/sec}$.
- Peak Writes (5x): $\approx 200\text{ writes/sec}$.
- Reads (Redirects): $100 \times \text{writes} = 4,000\text{ reads/sec}$.
- Peak Reads (5x): $\approx 20,000\text{ reads/sec}$.
Capacity & Storage Estimates
- Total Storage (5 Years):
- $100\text{ million/month} \times 12\text{ months} \times 5\text{ years} = 6\text{ billion records}$.
- Average record size: ~500 bytes (Code: 7 bytes, Long URL: 400 bytes, Metadata: ~93 bytes).
- $6\text{ billion} \times 500\text{ bytes} \approx 3\text{ TB}$.
- Memory Estimates (Cache):
- Following the Pareto Principle (80/20 rule), 20% of links account for 80% of read traffic.
- Daily Read Volume: $4,000\text{ reads/sec} \times 86,400\text{ sec} \approx 345\text{ million reads/day}$.
- Hot set memory needed: $0.20 \times (345\text{ million} \times 500\text{ bytes}) \approx 34.5\text{ GB}$.
2. API Interface Design
POST /api/v1/shorten
Content-Type: application/json
{
"long_url": "https://www.example.com/deep/nested/resource/path?id=123",
"custom_alias": "my-promo", // optional
"expires_in_seconds": 86400 // optional
}
Response: 201 Created
{
"short_url": "https://short.link/my-promo",
"code": "my-promo",
"created_at": 1700000000,
"expires_at": 1700086400
}
GET /{code}
Response: 302 Found
Location: https://www.example.com/deep/nested/resource/path?id=123
HTTP 301 vs HTTP 302/307:
- 301 Moved Permanently: Browsers cache the destination aggressively. Reduces service load, but prevents the backend from collecting click analytics or revoking/expiring links dynamically.
- 302 Found / 307 Temporary Redirect: Forces the browser to hit the redirect service every time, allowing accurate analytics collection and TTL enforcement. Choice: HTTP 302/307.
3. Storage Strategy & Schema Design
Because this application exhibits a key-value workload ($code \rightarrow long_url$) without complex relational joins, a NoSQL key-value store (e.g., DynamoDB or Apache Cassandra) is selected for horizontal scalability, linear write expansion, and native TTL capabilities.
Table Schema: short_urls
| Field | Type | Partition Key | Description |
|---|---|---|---|
code | String (ASCII) | PK | 7-character Base62 string or custom string |
long_url | String | Destination URL (up to 2048 chars) | |
user_id | String | Identifier of link creator (for rate limiting/management) | |
created_at | Integer | Epoch timestamp (seconds) | |
expires_at | Integer | Epoch timestamp (seconds), mapping to native TTL engine |
4. Short Code Generation Strategies
Generating unique 7-character strings from a Base62 set ([a-z, A-Z, 0-9], $62^7 \approx 3.5\text{ trillion}$ combinations) can be approached in three ways:
Approach A: Hashing (MD5/SHA256) + Truncation
- Hash
long_urland take the first 7 characters. - Drawback: Identical URLs produce collisions or require appended salt. Truncation increases collision probability, requiring DB collision-checks on every write.
Approach B: Random Code + Conditional Insert
- Generate random 7-character Base62 string. Insert using conditional check (
attribute_not_exists). - Drawback: As space utilization increases, collision rates rise, leading to exponential retry costs.
Approach C: Range-Based Distributed ID Generator + Base62 (Recommended)
Use a centralized coordination cluster (ZooKeeper or etcd) to allocate non-overlapping integer ranges (e.g., range of 1,000,000 IDs) to application server instances.
ZooKeeper -> Assigns [1,000,000 - 1,999,999] to Server A
Assigns [2,000,000 - 2,999,999] to Server B
- Server A generates local sequential integer IDs in memory without network calls.
- The integer is converted to Base62 string representation.
- To prevent sequence enumeration/guessing: Apply a deterministic variable-bit cipher or Feistel permutation over the integer space prior to Base62 encoding.
# Conceptual Base62 Encoding
BASE62_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def encode_base62(num: int, length: int = 7) -> str:
chars = []
while num > 0:
num, remainder = divmod(num, 62)
chars.append(BASE62_ALPHABET[remainder])
# Pad to fixed length
while len(chars) < length:
chars.append(BASE62_ALPHABET[0])
return "".join(reversed(chars))
Handling Custom Vanity Aliases
- User passes custom alias (e.g.,
"summer-sale"). - Write directly to the database with a conditional write (
attribute_not_exists(code)). - If code exists, return
409 Conflict. - Namespace collision between custom aliases and auto-generated Base62 keys is avoided by reserving specific prefix/suffix formats or validating custom aliases against a minimum length (e.g., custom aliases must contain non-Base62 characters like
-or be $>7$ characters).
5. System Architecture
+-------------------+
| GeoDNS / CDN |
+---------+---------+
|
v
+-------------------+
| API Gateway |
| (Rate Limiter) |
+---------+---------+
|
+---------------------+---------------------+
| Read Path | Write Path
v v
+-------------------+ +-------------------+
| Redirect Service | | Creation Service |
+---------+---------+ +---------+---------+
| | |
+------------+------------+ | v
| | | +--------------+
v v | | etcd/ZK |
+-----------------+ +-----------------+ | | (ID Ranges) |
| Redis Cluster | Cache | DynamoDB / | | +--------------+
| (LRU Cache) | Miss | Cassandra |<--------------------+
+-----------------+------>+-----------------+ |
| | |
| Event Stream | Async Log |
v v |
+-------------------------------------------+ |
| Kafka / Kinesis -> Analytics Engine |<--------------------+
+-------------------------------------------+
Read Path Optimization
- Request hits Redis cluster.
- Cache Hit: Check
expires_at. If valid, return302 FoundwithLocation: long_url. - Cache Miss: Read from primary KV Store.
- If record found and not expired: Write to Redis cache with TTL equal to $\min(\text{default_cache_ttl}, \text{expires_at} - \text{now})$. Return
302. - If code not found: Store a dummy payload in Redis with short TTL (e.g., 60 seconds) to mitigate Cache Penetration attacks.
- If record found and not expired: Write to Redis cache with TTL equal to $\min(\text{default_cache_ttl}, \text{expires_at} - \text{now})$. Return
- Asynchronously emit read event to Kafka for processing analytics (click count, geo, referrer).
6. Fault Tolerance, Edge Cases & Trade-offs
Edge Cases & Mitigations
- Expired Link Requests: Checked at the cache layer and database level. DynamoDB TTL handles background deletion asynchronously. The application explicitly checks
expires_at > current_timeto prevent returning stale data before the background sweeper removes the record. - Cache Stampede (Thundering Herd): If a viral link expires from cache, thousands of concurrent requests could hit the primary database. Use distributed locking (e.g., Redlock) or singleflight request coalescing on application nodes to ensure only one DB lookup occurs.
- Hot Partitioning: Popular short links hit the same Redis node. Scale Redis read replicas behind a load balancer and utilize local in-memory caches (L1 cache within the app server memory) with short TTLs (e.g., 5 seconds) for top viral links.
Key Trade-offs
- Consistency vs Availability (CAP): We prioritize Availability over Consistency for read operations (AP system). Eventual consistency across global database replicas is acceptable; a newly created link propagating across regions within a few hundred milliseconds does not impact end-user experience.
- Pre-allocated ID Ranges vs Real-time Key Generation: Range-based ID allocation introduces potential gaps in ID sequences if an app server crashes without using its entire range block. This trade-off is accepted, as the Base62 ID space ($3.5\text{ trillion}$) is large enough that minor range losses are negligible.