Design a Link Shortening Service: Codes, Storage, and Redirects
System DesignModel answerLast updated
Design a system that converts long URLs into short codes and redirects visitors at scale, covering code generation, storage choices, caching, and failure handling.
Build a Link Shortening Service
A product team wants to launch a link shortening service. Users paste in a long URL and get back a compact link — something like sho.rt/aB3kZ9. Anyone who visits that short link gets redirected to the original destination. Your job is to drive the design from first principles: clarify requirements, estimate load, pick a code-generation strategy, choose a data store, and describe how the redirect path holds up under heavy and skewed traffic.
No scale numbers are given upfront — that is intentional. State your own assumptions and carry them through your estimates.
Scope for this exercise
The following are in scope:
- Creating a short code for a given long URL
- Redirecting a visitor who hits a short code to the original URL
- Optional link expiration
Treat custom vanity codes and per-link click analytics as stretch topics to raise if time allows.
Constraints
- Every short code must map to exactly one long URL; no two different URLs may share a code.
- Redirect speed and availability outweigh the latency of creating a new link.
- Codes must not be trivially guessable or enumerable for a public service.
Clarifying Questions to consider
Before diving in, think about what you would ask the interviewer:
- What write and read volumes should the design target — links created per day and redirects per second?
- If the same long URL is submitted twice, should the service return the same code or generate a new one?
- Do links expire by default? Can creators delete or update them?
- Is sequential or predictable code assignment acceptable, or is enumeration resistance required?
- Is real-time click analytics required, or is an eventually consistent count acceptable?
Part 1 — Requirements, API, and capacity estimates
Pin down what the service must do and how it must perform. Define the two core endpoints. Then work through back-of-envelope estimates for write rate, read rate, storage needs, and the minimum code length required to avoid exhaustion.
Cover:
- Functional requirements and non-functional priorities (latency, availability, durability)
POST /linksandGET /{code}— request/response shapes and appropriate HTTP status codes- Estimated writes per second, reads per second, and total storage over a multi-year horizon
- Why your chosen redirect status code matters for browser caching and analytics accuracy
Part 2 — Generating short codes
Compare at least two code-generation approaches and argue for one. The scheme must stay collision-free when many application servers are creating links simultaneously.
Cover:
- At least two generation strategies (e.g., hashing, auto-increment counter, pre-allocated key ranges) with trade-offs
- How your chosen approach guarantees uniqueness across concurrent servers without a bottleneck
- Whether codes are guessable, and how to harden against enumeration if that is a requirement
- How you handle custom aliases and idempotent shortening of the same long URL
Part 3 — Storage, caching, and the redirect path
Pick a data store, justify it against the access pattern, and walk through both the write path (creating a link) and the read path (serving a redirect). Explain how the system stays fast and available under skewed traffic — where a small number of links receive the vast majority of hits — and what degrades gracefully when individual components fail.
Cover:
- Data model and store choice tied to the read-heavy, key-lookup access pattern
- Cache placement, eviction policy, and how expiration or deletion gets reflected in the cache
- Partitioning and replication strategy for scale and fault tolerance
- Failure scenarios: what happens when the cache is cold, the primary store is slow, or a node goes down
- Observability signals you would monitor on the redirect path
Hints
Hint 1
For code length, work backwards from your total projected links. A 7-character base-62 string gives over 3.5 trillion combinations — compute how many years that covers at your assumed write rate before committing to a length.
Hint 2
The redirect endpoint is a pure key-value lookup by code. That access pattern almost never needs a relational database. Think about what that implies for your store choice and your cache key design.
Hint 3
A 301 redirect tells browsers to cache the destination permanently, meaning future visits skip your servers entirely — great for load, bad for analytics and for serving deletions. A 302 keeps every request flowing through you. Pick deliberately and state the trade-off.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Part 1 — Requirements, API, and estimates
Functional requirements: create a short code for a long URL; redirect a visitor to the original URL; optionally expire links after a configurable TTL.
Non-functional priorities: redirect latency (P99 < 50 ms), high availability (99.99% uptime), eventual durability for newly created links, and enumeration resistance.
Assumptions: 100 million new links per month (~40 writes/second), 10 billion redirects per month (~3,900 reads/second peak ~2×, so ~8,000 rps). Read-to-write ratio is roughly 100:1.
Storage: a link record stores the code, long URL, owner ID, creation timestamp, and expiry. Roughly 500 bytes per row. 100 M links/month × 12 months × 5 years = 6 billion rows → ~3 TB raw before replication. Manageable for a single distributed key-value store.
Code length: base-62 alphabet (a–z, A–Z, 0–9). 62^7 ≈ 3.5 trillion combinations. At 100 M links/month that is ~2,900 years of namespace. 7 characters is safe.
API:
POST /links
Body: { "url": "https://...", "ttl_seconds": 86400 }
Response 201: { "code": "aB3kZ9f", "short_url": "https://sho.rt/aB3kZ9f", "expires_at": "..." }
GET /{code}
Response 302 Location: <original URL> (or 301 — see below)
Response 404 if code unknown or expired
Redirect status code trade-off: 301 Permanent lets browsers cache the destination forever, eliminating future load — but it breaks analytics (subsequent visits never reach you) and makes deleted or edited links invisible to returning visitors. 302 Found routes every visit through your infrastructure, which preserves analytics accuracy and allows you to serve deletions, at the cost of extra latency on cached routes. For a public service where links can expire or be removed, 302 is the right default.
Part 2 — Code generation
Option A — Hash the long URL. Take SHA-256 of the URL, base-62-encode it, and take the first 7 characters. Deterministic and idempotent for the same input. Problem: collisions are rare but possible (different long URLs can share a prefix), and detecting them requires a read before every write.
Option B — Global auto-increment counter. A single counter service hands out monotonically increasing integers; encode each in base-62. Simple and collision-free by construction, but the counter is a single point of failure and a bottleneck at high write rates. Codes are also sequential, making enumeration trivial.
Option C — Pre-allocated key ranges (recommended). A dedicated Key Generation Service (KGS) pre-generates random 7-character codes, stores them in a unused_keys table, and marks them used atomically on assignment. Each application server checks out a batch of, say, 1,000 keys on startup and refills when the local pool runs low. No coordination is needed per write — servers draw from their local batch. Uniqueness is guaranteed because the KGS marks a key used before handing it out. Codes are random and non-sequential, providing enumeration resistance without extra hashing.
Custom aliases: allow callers to supply their own code in the POST body. Attempt an insert; return 409 Conflict if the code already exists. Custom codes bypass the KGS pool.
Idempotency: if you want the same long URL to return the same code, maintain a reverse index (long_url → code). Check it on write; return the existing code if found. This adds a read per write but keeps the namespace smaller. Skip the reverse index if you prefer simplicity and are comfortable issuing a new code on each submission.
Part 3 — Storage, caching, and the redirect path
Data store: the redirect path is a pure point lookup by code. No joins, no range scans. A relational database adds unnecessary overhead. A distributed key-value store — DynamoDB, Cassandra, or Redis Cluster with persistence — suits this pattern. Partition by code (already high cardinality, so hot-partition risk is low) and replicate across three availability zones for durability and read scaling.
Data model (single table):
| Field | Type | Notes |
|---|---|---|
| code (PK) | string | 7-char base-62 |
| long_url | string | original destination |
| created_at | timestamp | |
| expires_at | timestamp / null | null = no expiry |
| owner_id | string / null | for deletion rights |
Write path: application server draws a code from its local KGS batch → writes the record to the primary store → returns the short URL. P99 write latency can be ~10 ms; no strict SLA needed.
Read path: GET /{code} hits an in-process or sidecar cache first (Redis or Memcached). On a miss, it reads from the primary store, caches the result with a TTL equal to the link's remaining lifetime (or a fixed 24 h for non-expiring links), and issues the 302. Cache hit rate for a skewed workload (top 10% of links drive 90% of traffic) should easily exceed 95%, keeping median redirect latency under 5 ms.
Cache invalidation: when a link is deleted or its expiry is updated, write a tombstone to the cache with a short TTL (e.g., 60 s) rather than attempting eager invalidation across a distributed cache cluster. Serving a stale redirect for up to 60 s after deletion is an acceptable trade-off for most use cases; tighten the TTL if stronger consistency is required.
Partitioning and replication: shard the KV store by the first two characters of the code (62² = 3,844 possible prefixes, so shards stay balanced). Replicate each shard to at least three nodes. Route reads to the nearest replica; writes go to the primary and fan out asynchronously.
Failure handling:
- Cache down: redirects fall through to the primary store. Latency degrades to ~20–30 ms but correctness is unaffected.
- Primary node slow: client-side timeouts (~200 ms) with a fallback to a read replica. Serve stale cache entries rather than returning a 503.
- KGS unavailable during writes: the application server's local key batch provides a buffer of ~1,000 writes. Expose the batch depth as a metric and alert below a threshold.
Observability: track redirect latency (P50, P99), cache hit rate, KGS batch depth, error rates by status code (404, 5xx), and per-code redirect counts (useful for detecting abuse).
Common mistakes to avoid:
- Choosing a relational database and then fighting it with sharding complexity, when a KV store fits natively.
- Picking 301 without stating the analytics and deletion trade-off — interviewers notice this.
- Ignoring code exhaustion: always derive the minimum code length from your projected link volume.
- Using a single global counter without acknowledging it as a bottleneck and single point of failure.
- Forgetting that deleted or expired links must be reflected in the cache, not just the database.