Build a link shortener with unique codes and fast redirect
System DesignModel answerLast updated
Design a service that converts long URLs into compact codes and serves redirects at high throughput with low latency.
You are tasked with building a service that accepts full-length URLs and returns compact, shortened versions. When someone visits a shortened link, they should be redirected to the original destination instantly.
The traffic profile, feature requirements, and data retention rules are unspecified. Begin by asking for these details or clearly state your assumptions with concrete figures that inform your design choices.
Questions to Resolve
- What is the daily volume of new links created, and what is the peak redirect rate per second?
- Should users be able to specify their own custom short codes? Do links have an expiration policy, and can owners modify or remove them after creation?
- If a user submits the same URL multiple times, should they always get back the same short code?
- Are there constraints on code length, character sets, or unpredictability requirements?
- Is there a need for tracking visitor metrics, and if so, what is the acceptable delay for this data?
- Should redirect functionality remain operational even when link creation services are unavailable?
Part 1 — Interface Design and Code Assignment
Describe the API surface and the mechanism for assigning short codes such that no two distinct URLs ever receive the same code.
Expected Coverage
- Endpoints for creation and redirection, including edge cases and support for user-defined codes
- Code length calculation based on anticipated link volume and the character alphabet
- A strategy that prevents collisions in a distributed environment, and fallback behavior if conflicts arise
- Whether codes can be predicted from their sequence, and the security implications
Part 2 — Optimizing the Redirect Flow
Ensure redirects are served quickly and reliably at the expected query volume.
Expected Coverage
- The complete request flow from incoming request to final redirect, including all caching layers
- Selection of HTTP redirect status code and its impact on browser caching and analytics accuracy
- Handling of nonexistent, expired, or removed codes, including negative result caching
- Performance and uptime objectives
Part 3 — Data Persistence and Growth Management
Select the storage technology and schema, and describe how the system handles growth and maintains reliability as the link count increases.
Expected Coverage
- Schema design and database selection rationale
- Sharding strategy, redundancy, and multi-region deployment
- Management of expired links, deletions, and the pipeline for click event processing
- Countermeasures for abuse: detecting harmful destinations and rate-limiting creation requests
Hints
Hint 1
Start with capacity planning—how many links will you store, and what throughput must you support?
Hint 2
Think about whether codes are generated in advance or at request time, and how distributed servers avoid conflicts.
Hint 3
Consider where caching happens and what redirect status code best balances performance with analytics needs.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
1. Requirements and Capacity Planning
Begin by establishing the system's scale. A reasonable baseline:
- Write load: 100 million new links per month (~40 new links/sec average, ~200/sec peak)
- Read load: 10 billion redirects per month (~4,000 redirects/sec average, ~20,000/sec peak)
- Read-to-write ratio: 100:1 (redirect-heavy workload)
- Storage horizon: Keep links for 5 years unless deleted
- Total links: ~6 billion over the lifetime
Code length: Using base62 (a-z, A-Z, 0-9), a 7-character code provides 62^7 ≈ 3.5 trillion possibilities, far exceeding our 6 billion target with room for sparse allocation. Codes like x3kR9pQ are compact and URL-safe.
Storage: Each mapping requires ~500 bytes (short code, long URL, metadata). Total: 6B × 500B ≈ 3TB. Achievable with modern databases.
2. API Design
Create Link
POST /api/links
Body: { "url": "https://example.com/very/long/path", "custom_code": "promo24" }
Response: { "short_url": "https://short.ly/promo24", "expires_at": "2026-01-15T00:00:00Z" }
Redirect
GET /:code
Response: 301 or 302 redirect to original URL
Return 404 for unknown codes, 410 for expired links.
3. Short Code Generation Strategy
Approach: Use a distributed counter with server ID encoding to guarantee uniqueness without coordination.
- Assign each application server a unique ID (0–1023, requiring 10 bits).
- Maintain a per-server counter (42 bits allows 4 trillion increments per server).
- Combine timestamp (12 bits for month-level granularity) + server ID + counter = 64-bit integer.
- Encode this integer in base62 to produce a 7-character code.
Why this works:
- No two servers share an ID, so their counters never collide.
- No database round-trip needed for code generation.
- Codes are effectively random to users but deterministic to the system.
Trade-offs:
- Codes are sequential and potentially guessable (mitigation: add a random salt or shuffling step if needed).
- Requires server ID assignment at startup (use a coordination service like ZooKeeper or pre-allocate ranges).
Collision handling: If a user requests a custom code already in use, return a 409 Conflict error. For auto-generated codes, collisions are impossible by design.
Idempotency: If the same URL is submitted twice, generate a new code unless the client explicitly requests the previous one (requires indexing by URL hash, which adds complexity; typically not done).
4. Redirect Path and Caching
Flow:
- Request arrives:
GET /x3kR9pQ - Check CDN edge cache (Cloudflare, Fastly): if hit, return cached redirect (99%+ of traffic stops here).
- If miss, query application cache (Redis cluster).
- If still miss, read from database (Cassandra or DynamoDB).
- Store result in Redis and CDN, then return redirect.
Redirect status code:
- Use 301 Moved Permanently for codes that never change (most cases). Browsers and CDNs cache aggressively, reducing backend load.
- Use 302 Found if you need real-time analytics for every click (disables caching, increases load significantly).
For most shorteners, 301 is preferred; analytics are collected via asynchronous logging of cache hits.
Negative caching: Cache 404 responses for unknown codes to prevent repeated database lookups during brute-force scanning or typos. TTL: 5 minutes.
Performance targets:
- p99 latency: <50ms (CDN hit: <10ms, cache hit: <20ms, database hit: <100ms)
- Availability: 99.9% (redirects must survive database outages via cache)
5. Storage and Data Model
Database choice: Cassandra or DynamoDB (NoSQL, wide-column store).
Why:
- Extremely high write throughput for link creation.
- Predictable low-latency reads by primary key (short code).
- Built-in replication and multi-region support.
- Horizontal scaling by adding nodes.
Schema:
Table: links
- short_code (partition key, string)
- long_url (string)
- created_at (timestamp)
- expires_at (timestamp, nullable)
- owner_id (string, nullable)
- click_count (counter, eventually consistent)
Partitioning: The short code is the partition key. With 6 billion links distributed across 1024 partitions, each partition holds ~6 million rows—well within limits. Cassandra's consistent hashing ensures even distribution.
Replication: Use replication factor 3 across multiple availability zones. Reads use LOCAL_QUORUM for low latency.
Multi-region: Deploy clusters in US, EU, and Asia. Use geo-DNS to route creation requests to the nearest region; redirect traffic is served by the CDN regardless of origin.
6. Expiry and Deletion
Expiry: Store expires_at timestamp. Run a daily batch job (Spark or Airflow) to scan for expired links and mark them as deleted (or move to a cold archive). Alternatively, check expiry lazily at read time and return 410 Gone.
Deletion: When a user deletes a link, update the row to set a deleted_at timestamp. Purge the entry from Redis and CDN caches immediately (via cache invalidation API). Keep the row in the database for audit purposes.
7. Analytics Pipeline
Click tracking:
- Log every redirect to a Kafka topic (short_code, timestamp, IP, user-agent, referer).
- Consume logs with Flink or Spark Streaming to compute aggregates (clicks per link, geographic distribution, top referrers).
- Store aggregates in a separate OLAP database (ClickHouse, BigQuery) or time-series store.
- Update
click_countin the main database asynchronously (eventual consistency is acceptable).
Real-time vs. batch: Real-time analytics add cost and complexity. For most use cases, updates every 5–15 minutes are sufficient.
8. Abuse and Rate Limiting
Malicious URLs:
- Integrate with a URL reputation service (Google Safe Browsing API) at creation time.
- Reject links to known phishing, malware, or illegal content.
- Allow users to report abusive links; flagged codes return a warning page instead of redirecting.
Rate limiting:
- Limit unauthenticated users to 10 link creations per IP per hour.
- Authenticated users get higher quotas (1,000/hour).
- Use a token bucket algorithm implemented in Redis (increment a counter with TTL).
Bot detection: Monitor for automated link scraping or brute-force code guessing. Block IPs with abnormal request patterns.
Common Mistakes
- Generating codes by hashing the URL: This makes codes deterministic (same URL = same code), which sounds appealing but creates problems. If user A creates a link and user B later creates the same URL, should B get A's link (privacy leak) or a new code (defeats the purpose)? Sequential generation with collision detection is cleaner.
- Using a single database for both writes and reads: At 20k redirects/sec, a traditional SQL database will saturate. Caching is mandatory, not optional.
- Ignoring CDN: Redirects are the bottleneck. A CDN absorbs 99% of traffic and makes regional latency irrelevant.
- Overbuilding analytics: Real-time per-click tracking is expensive and rarely needed. Batch processing suffices.
- Not planning for abuse: URL shorteners are heavily targeted by spammers. Reputation checks and rate limits are essential from day one.
Summary
A well-designed URL shortener prioritizes read performance (via aggressive caching), collision-free generation (via distributed counters), and horizontal scalability (via NoSQL partitioning). The architecture separates hot-path redirects (CDN + cache + simple key-value lookup) from cold-path operations (analytics, expiry, abuse detection). Concrete capacity estimates drive every choice: code length, cache size, database selection, and infrastructure cost.