Design a Link-Shortening Service with Click Tracking
System DesignModel answerLast updated
Design a distributed URL shortener handling billions of daily redirects with sub-50ms latency and decoupled, accurate click counting.
Link-Shortening Service with Click Analytics
Build a service that converts long URLs into compact codes and tracks how often each link is used.
Functional Requirements
- Shorten: Accept a long URL (and an optional custom alias) and return a short URL.
- Redirect: Resolve a short code to its original URL and send the visitor there.
- Analytics: Return the total number of times a given short link has been followed.
Non-Functional Requirements
| Concern | Target |
|---|---|
| Write throughput | 100 million new links per day |
| Redirect throughput | 1 billion redirects per day, with bursty spikes |
| Redirect latency | p99 under 50 ms |
| Click-count accuracy | Accurate; eventual consistency is acceptable |
| Availability | High — traffic spikes must not cause outages |
What to Cover
- API: Define the REST endpoints for creating a link, redirecting, and fetching stats.
- Data model: Schema for the short-to-long mapping and click storage.
- Architecture: Database choice (SQL vs. NoSQL), unique ID generation with no central-per-request bottleneck, and how click counting is kept off the critical redirect path.
- Trade-offs: Compare counter strategies (synchronous write, Redis INCR, log-based aggregation) and explain how you handle hot keys — a single viral link receiving a disproportionate share of traffic.
Hints
Hint 1
Start by separating two paths: the latency-critical redirect path and the write-heavy analytics path. Ask yourself whether these paths should share any infrastructure at all.
Hint 2
Think carefully about your HTTP status code for redirects. 301 and 302 behave differently in browsers — one of them will silently break your click counts.
Hint 3
For ID generation, consider how range-based block allocation lets each server mint codes locally with zero per-request coordination, and how you can obscure the sequential nature of the resulting codes.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The central tension is this: redirects must be blazing fast, but every redirect also generates a write (the click event). The solution is to never let the write touch the redirect path. Establish this separation at the start and let it guide every other decision.
1. Estimates That Drive Decisions
Traffic
- Writes: 100M / 86,400 ≈ 1,200 QPS average, ~5,000 QPS peak.
- Redirects: 1B / 86,400 ≈ 12,000 QPS average; plan for 50–100k QPS spikes because viral links are bursty.
- Read-to-write ratio: ~10:1 overall, far higher per hot key.
Storage
- Mapping rows at ~500 B each: 100M × 365 × 5 years ≈ 180B rows ≈ 90 TB.
- Raw click events at ~100 B each: ~100 GB/day.
Key space
- Base62 with 7 characters: 62⁷ ≈ 3.5 trillion codes — roughly 20× the five-year need.
2. API
POST /api/v1/links
body: { long_url, custom_alias?, expires_at? }
201 → { short_url, code, expires_at }
GET /{code}
302 Found → Location: <long_url>
404 if unknown, 410 if expired
GET /api/v1/links/{code}/stats
200 → { code, total_clicks, as_of }
Use 302, not 301. A 301 is cached permanently by browsers, so repeat visits never reach the server and those clicks are never counted. This is a common mistake; call it out explicitly.
3. Data Model
link_mapping — partitioned by code, single-key lookups only:
| field | type |
|---|---|
| code (PK) | string(7) |
| long_url | string |
| owner_id | string |
| created_at | timestamp |
| expires_at | timestamp (nullable) |
click_counts — a counter table keyed by code, with an optional (code, day) variant for time-series breakdowns.
Raw click events flow through a message queue and land in object storage. Each event carries { event_id, code, ts, ip, user_agent, referrer }.
Database choice: NoSQL (DynamoDB, Cassandra, or Bigtable). The access pattern is a single-key lookup with no joins. At 90 TB the data must scale horizontally, and NoSQL gives partitioning, replication, and TTL without hand-rolling them. A sharded relational database works too, but you'd rebuild the same primitives manually.
4. Architecture
Client
│
▼
CDN / Load Balancer
│
▼
Redirect Service ──(L1 miss)──► Redis Cluster ──(L2 miss)──► NoSQL link_mapping
│
└──► fire-and-forget ──► Kafka (click events)
│
┌───────┴───────┐
▼ ▼
Flink aggregator S3 raw logs
│ │
▼ ▼
click_counts nightly batch reconciliation
Redirect path (target: < 50 ms)
- Check an in-process LRU cache.
- On miss, check Redis. With an 80/20 access skew, a few hundred GB of Redis serves > 95% of requests at sub-millisecond latency.
- On miss, read from the NoSQL table; populate Redis.
- Return the 302.
- Publish a click event to a local buffer, which drains asynchronously to Kafka. If Kafka is slow or unavailable, the redirect still completes. Analytics must never block a redirect.
5. ID Generation
Range-based block allocation (recommended). A coordinator (ZooKeeper, or a single counter row in a strongly consistent store) hands each API server a block of, say, 1 million IDs. Servers encode IDs to base62 locally — no per-request round trip. A lost block wastes IDs but causes no correctness problem. To prevent enumeration of sequential codes, pass each integer through a bijective permutation (e.g., a Feistel cipher over the 62⁷ space) before encoding.
Random 7-character code with a conditional insert (PUT if not exists). Simpler and stateless. Collision probability stays below 5% even at 180B codes; retries handle collisions. Acceptable if simplicity is prioritized over predictable performance.
Avoid: hashing the long URL (leaks correlation between users, needs collision handling) and Snowflake IDs (encode to ~11 characters — too long).
6. Click Counting: Three Strategies Compared
| Strategy | Latency impact | Durability | Complexity |
|---|---|---|---|
| Synchronous DB counter (per-click read-modify-write) | High — hot rows serialize writes | Strong | Low |
Redis INCR on redirect path, periodic flush | One extra network hop | Loses in-flight counts on crash | Medium |
| Kafka + stream aggregation (recommended) | None — fully async | Replayable, correctable | Higher |
Recommended: log-based aggregation.
- Redirect servers publish events to Kafka, partitioned by
code. - A Flink job aggregates per code over 1–5 second windows and issues one batched increment per code per window:
total += 437instead of 437 individual writes. - At 100k clicks/s this compresses ~100k DB writes/s into a few thousand.
- Raw events in S3 feed a nightly batch job that recomputes exact counts and corrects any drift (lambda-style architecture: stream for freshness, batch for correctness).
On exactness: Kafka delivers at-least-once by default. Use Flink's exactly-once checkpointing with idempotent sinks, or deduplicate on event_id, to match the "accurate, eventually consistent" requirement.
Near-real-time stats: the stats endpoint can expose the stored total plus the current window's in-flight delta, which Flink can publish to a Redis key. Report an as_of timestamp so callers know the freshness.
7. Hot Keys
A viral link can concentrate millions of redirects on a single cache key. Mitigations:
- Local in-process caching on each redirect server absorbs the top N hot codes with zero network hops.
- Redis key replication: store the same mapping under
code:0,code:1, …code:Nand route reads round-robin. Writes update all replicas. - On the Kafka side, a single hot
codepartition can lag. Pre-aggregate on the producer side (count locally for 500 ms, then emit one event with a weight) to reduce partition pressure.
Common Mistakes to Avoid
- Using 301 instead of 302 and losing click counts silently.
- Putting a synchronous DB counter increment on the redirect path.
- Choosing a central ID generator with one lock per request (single point of contention at 5k write QPS).
- Not accounting for cache warm-up time after a deploy or Redis failover.
- Forgetting that Kafka at-least-once delivery can inflate counts without deduplication.