Walkthrough — Design a URL Shortener (TinyURL / Bitly)¶
The single most common system design interview question. This walks the full four-step approach from the Introduction.
Step 1 — Requirements, constraints, and assumptions¶
Clarifying questions¶
- Traffic volume? (e.g., "100 million URLs generated per day")
- How short? (as short as possible)
- Custom aliases allowed?
- Expiry / TTL on links?
- Analytics (click counts, geography) needed?
Functional requirements¶
- Shorten: given a long URL, return a unique short alias.
- Redirect: given a short URL, redirect to the original.
- (Optional) custom alias, expiration, analytics, user accounts.
Non-functional requirements¶
- Highly available and very low-latency redirects.
- Read-heavy (roughly 100:1 read-to-write).
- Short codes must be unique and shouldn't collide.
Back-of-the-envelope¶
| Metric | Estimate |
|---|---|
| New URLs / day | 100 million |
| Write rate | 100M / 86,400 s ≈ 1,157 writes/sec |
| Read rate (100:1) | ≈ 115,700 reads/sec |
| Rows over 5 years | 100M × 365 × 5 ≈ 182.5 billion |
| Storage (≈500 B/row) | ≈ 91 TB |
| Cache (hot 20%) | ≈ 20M entries in RAM |
Step 2 — High-level design¶
┌──────────────┐
Client ──────────▶ │ DNS / CDN │
└──────┬───────┘
│
┌──────▼───────┐ ┌──────────────┐
│ Load Balancer│──────▶│ App servers │ (stateless)
└──────┬───────┘ └──────┬───────┘
│ │
write │ │ read
▼ ▼
┌────────────┐ ┌────────────┐ miss ┌───────────┐
│ Key pool / │ │ Redis │──────────▶ │ Sharded │
│ generator │ │ (cache) │ │ SQL DB │
└────────────┘ └────────────┘ └───────────┘
Two distinct paths:
- Write path:
POST /shorten→ generate a code → store in DB (and warm cache). - Read path:
GET /{code}→ check cache → on miss, read DB → return301.
Step 3 — Core components¶
3.1 Short-code generation¶
Three common approaches, each with trade-offs:
| Approach | How | Pros | Cons |
|---|---|---|---|
| Hash + Base62 | MD5/SHA of URL, take first 7 chars, encode Base62 | No coordination | Collisions (mitigate by retry / appending) |
| Base62 of a counter | Encode a unique 64-bit ID (Snowflake) to Base62 | Collision-free, short | Needs a distributed ID generator |
| Pre-generated key pool | Offline service generates keys, hands them out | Fast writes, no in-line collision | Key pool can exhaust; more moving parts |
Base62 alphabet: [a-z A-Z 0-9] = 62 chars. A 7-char code gives 62^7 ≈ 3.5
trillion combinations.
Collision handling: use a unique DB constraint; on collision, retry with a different salt/counter. This is why the counter approach is usually preferred — it can't collide.
3.2 Data model (SQL is a natural fit)¶
CREATE TABLE urls (
short_code VARCHAR(10) PRIMARY KEY, -- indexed, unique
long_url TEXT NOT NULL,
created_at TIMESTAMP NOT NULL,
expires_at TIMESTAMP, -- optional
user_id BIGINT -- optional
);
Why SQL here: structured data, strict schema, need for uniqueness and fast indexed lookups.
3.3 Redirect path¶
- Receive
GET /{short_code}. - Look up
short_code(cache first, then DB). - Return 301 (permanent — cacheable) or 302 (temporary — if you want to count every click for analytics).
3.4 API¶
POST /shorten
{ "long_url": "...", "custom_alias": "optional", "expiration": "optional" }
→ { "short_url": "https://short.ly/abc123" }
GET /{short_code}
→ 301 Location: https://original.example.com/very/long/url
Step 4 — Scale the design¶
Caching (read path is hot)¶
- Use cache-aside with Redis: cache
short_code → long_url. - The 80/20 rule: a small set of URLs drive most traffic — cache them.
- TTL for freshness; evict when a URL expires or changes.
Sharding (write volume grows)¶
-
Shard the
urlstable byshort_code(e.g., first 2–3 chars) or via consistent hashing on the code. -
A distributed ID generator (Snowflake) gives collision-free, roughly sortable IDs to encode as Base62 codes.
Replication & availability¶
- Master-slave replication to serve the read-heavy load from replicas.
- Stateless app servers behind a load balancer for horizontal scaling.
Hardening¶
-
Rate limiting to prevent abuse (see 02 Latency vs Throughput).
-
Validate/sanitize inputs; prevent open-redirect and SSRF (see 16 Security).
-
Analytics as an async side-channel (see 14 Asynchronism).
Key trade-offs to mention¶
- Hash vs counter: collision risk vs the need for a coordinated ID generator.
- 301 vs 302: cacheability vs per-click analytics.
-
SQL vs NoSQL: uniqueness + indexed lookups favor SQL; a KV store also works for the pure redirect path.
-
Cache vs DB: cache absorbs the hot read load but introduces staleness and invalidation complexity.
URL Shortener Full Prose Design¶
The service must turn a long URL into a unique short alias and redirect a short alias back to the original URL. For a large public shortener, assume around 100 million new URLs are created per day, which is roughly 1,157 writes per second and, at a 100:1 read-to-write ratio, about 115,700 redirects per second. Over five years this creates about 182.5 billion rows and roughly 91 TB of row data, while the hot subset of URLs must fit in memory for fast redirects. The system must be highly available, redirect with very low latency, and guarantee that no two URLs receive the same short code.
The high-level architecture separates the write path from the read path. Clients reach the system through DNS and an optional CDN, then pass through a load balancer to stateless application servers. On a shorten request, the application server coordinates short-code generation and stores the mapping in a sharded SQL database. On a redirect request, the application server first checks a Redis-style cache for the short code. If the cache misses, it reads the mapping from the database, warms the cache, and returns an HTTP redirect to the original URL. This split is important because the workload is dominated by reads, so the cache and read replicas absorb most traffic while the write path can be optimized independently.
The data model is simple and strongly structured. The core table is urls, with short_code as the primary key, long_url as the required target, created_at for auditing, and optional expires_at and user_id for expiration and user-specific behavior. A relational database is the natural choice because the data has a fixed schema, the short_code must be unique, and the dominant operation is a fast indexed lookup by primary key. A key-value store could handle the redirect path, but SQL gives better support for uniqueness constraints, expiration queries, and administrative operations such as listing a user's links. Large binary content is not stored in the database because the rows contain only text and metadata.
The core mechanism is generating a unique short code and resolving it efficiently. The preferred approach is to generate a unique 64-bit ID from a distributed ID generator such as Snowflake and encode it as Base62 using uppercase letters, lowercase letters, and digits. A seven-character Base62 code provides about 3.5 trillion combinations. This avoids collisions by construction, unlike hashing the long URL with MD5 or SHA-1 and truncating the result, which requires collision retries. The database uses a unique constraint on short_code as a safety net. On redirect, the application returns 301 Permanent Redirect when Click-through analytics are not needed because browsers may cache the response, or 302 Found when every click must be counted because the client will revalidate with the server. The short code therefore acts as a compact, indexed key into the URL mapping.
To scale, the read-heavy system relies on caching, replication, and sharding. A cache-aside Redis layer stores hot short_code to long_url mappings under a TTL, and only a small fraction of URLs drive most traffic, so caching dramatically reduces database load. The SQL database uses master-slave replication so read replicas can serve misses and administrative reads while the master absorbs writes. When the urls table grows too large for one database, it is sharded by short_code using consistent hashing or the first few characters of the code, which spreads both storage and query load across many nodes. Application servers remain stateless so the load balancer can add and remove instances freely. Rate limiting prevents abuse of the shorten API, and analytics such as click counts are emitted asynchronously so they do not slow the synchronous redirect path.
The important trade-offs are between coordinated uniqueness and simplicity, cacheability and analytics, and consistency and cost. Base62 encoding of a distributed ID avoids collisions but requires a reliable ID generator, while hashing is simpler but must handle collisions and retries. Using 301 improves redirect performance and reduces origin load because clients cache it, while 302 enables accurate per-click analytics at the cost of repeated requests. SQL provides strong consistency and uniqueness, while a key-value store could lower latency but would require the application layer to enforce more guarantees. Finally, caching improves read latency but introduces staleness and invalidation complexity, so expired or changed URLs must be evicted or allowed to remain briefly stale according to the product requirements.
flowchart LR
U[Client] --> DNS[DNS / CDN]
DNS --> LB[Load Balancer]
LB --> A[Stateless App Servers]
A -->|POST /shorten| ID[Snowflake ID + Base62 Generator]
ID --> DB[(Sharded SQL Master)]
DB --> R[(SQL Read Replicas)]
A -->|GET /code| C[(Redis Cache)]
C -->|miss| R
C -->|hit / populate| A
A -->|301/302| U
A --> Q[Analytics Queue]
Q --> W[Async Workers]
Security Hardening for the URL Shortener¶
A public URL shortener is a high-abuse target, so security must be designed into the write path, the redirect path, and the analytics path rather than treated as a separate layer. The service must enforce authentication or at least strong client identification for privileged operations and per-user, per-IP, or per-API-key rate limiting at the edge. The rate limiter uses distributed counters in Redis and returns HTTP 429 when a client exceeds the configured threshold. This prevents spammers and bots from creating huge numbers of short links and using the service to disguise phishing or malware destinations at scale. All traffic uses HTTPS, database storage and backups are encrypted at rest, and any API keys or secrets are stored only as hashes or in a dedicated key management system. Access to takedown, user link history, and analytics endpoints follows least privilege with scoped authorization checks.
Before creating a short code, the application must validate and normalize the submitted long URL. It should allow only http and https schemes and reject dangerous schemes such as javascript:, file:, or data:. If the system performs a server-side fetch for preview, favicon, or safe-browsing analysis, that fetch must run through a hardened egress proxy that blocks private address ranges, loopback addresses, link-local addresses, and cloud metadata endpoints; this prevents server-side request forgery. The redirect endpoint must not redirect to a user-supplied parameter. It must look up the target that was accepted and stored at creation time, and redirect only to that stored value. This prevents open redirect attacks in which an attacker sends a victim a short link that appears to belong to the shortener but then redirects to a malicious site. Any short-link metadata rendered back to users must be HTML-escaped and sanitized to avoid cross-site scripting.
Short code generation also has security implications. Encoding a Snowflake ID in Base62 avoids collisions and is not as easily enumerated as an auto-increment integer, but it still should not be considered secret. For unlisted or private links, the system should add an additional unguessable token or require authentication before redirect. Short codes that are not public can use a cryptographically random secret component stored as a hash or in the metadata record so the database itself does not leak link privacy if read. The lookup failure path should return a generic 404 or a harmless page rather than revealing whether a code exists, which makes enumeration harder. Expired links must be disabled both in the database and in cache; if a link is taken down, the redirect path must deny it immediately after the cache is invalidated.
Rate limiting, validation, and safe-browsing checks add latency and complexity, so the system should make them asynchronous or layered where possible. Link creation may trigger asynchronous Safe Browsing or reputation checks after the record is created; if a link is later flagged, a takedown worker disables it and invalidates cache. Analytics can collect click counts and referrers but should strip sensitive query parameters from logs and avoid storing full visitor IP addresses beyond the required retention period. Redirect status code choice matters for security: 302 Found forces clients to revalidate and allows the shortener to enforce takedowns and per-click policy, whereas 301 Permanent Redirect can be cached by browsers and bypass future checks. These controls address abuse, open redirect, SSRF, enumeration, and malicious content while still allowing the shortener to scale with stateless services, Redis counters, and asynchronous safety workers.
flowchart LR
U[Client] --> TLS[HTTPS Terminator / WAF]
TLS --> RL[Rate Limiter / Auth]
RL --> A[Stateless App Servers]
A --> V[URL Validator and Sanitizer]
V -->|reject unsafe scheme or private target| U
V --> ID[Snowflake Base62 Code Generator]
ID --> DB[(Sharded SQL URLs DB)]
DB --> R[(SQL Read Replicas)]
A --> C[(Redis Cache / Rate Counters)]
C -->|miss| R
A --> Q[Async Safety / Analytics Worker]
Q --> SB[Safe Browsing / Takedown Service]
SB --> DB
U -->|GET /code| A
A -->|redirect only to stored target| U