Module 6: Case Studies
URL Shortener
Design a Bitly-like URL shortener — APIs, base62 IDs, schema, 301 vs 302, caching, sharding, and analytics off the redirect path.
Classic interview problem. Focus on unique code generation, a tiny schema, and a blazing-fast redirect path — then layer cache, analytics, and optional custom aliases.
What you will learn
- Clarify functional and non-functional requirements with capacity math
- Propose APIs and a minimal schema
- Compare hash-truncate vs ID→base62 code generation
- Design a low-latency redirect path with cache
- Scale writes/reads and keep analytics off the hot path
Clarify requirements
- Start by locking scope. Interviewers reward precise assumptions before boxes appear.
- Functional: create short link, redirect, optional custom alias, expiry, click analytics
- Non-functional: low redirect latency, high availability, unique codes, predictable growth
- Read-heavy: redirects usually dwarf creates by 100:1 or more — ask for ratios
- Constraints: code length, allowed character set, custom alias rules, abuse limits
- Out of scope until asked: full UI, QR codes, team workspaces
APIs
- Keep the API tiny. Two calls define the product.
- POST /api/shorten {longUrl, customAlias?, expiresAt?} → {shortUrl, code}
- GET /{code} → 301/302 Location: longUrl
- Optional: GET /api/stats/{code} for click counts (authz protected)
- Validate URLs (scheme, length, blocklist) on create
- Rate-limit create to slow spam and link farms
Capacity & code length
- Show quick math so code length is justified, not guessed.
- Base62 alphabet: 0-9, a-z, A-Z → 62 symbols
- 7 chars ≈ 62^7 ≈ 3.5e12 keys — usually enough for interview scale
- Estimate storage: rows × (code + url + metadata); URLs dominate size
- Estimate QPS: creates vs redirects; design for redirect p99
- Leave headroom — never size to 100% of the keyspace
Code generation strategies
- Two common approaches — pick one and own the collision story.
- Hash(longUrl) then truncate — deterministic; collisions need probing or longer codes
- Global unique ID (DB sequence / snowflake) → encode base62 — uniqueness is controlled
- Pre-generated unused codes in a pool — low create latency, needs replenishment workers
- Custom aliases — user-chosen strings with unique constraint + abuse checks
- Never expose raw sequential IDs if enumeration of private links is a concern (add randomness)
Data model
- A shortener is mostly one hot mapping table.
- code (PK), long_url, created_at, created_by?, expires_at?, is_active
- Optional: click counters in a separate store/table updated async
- Unique index on custom alias if supported
- Soft-delete / disable flags for abuse takedowns
- Keep redirect reads as a point lookup by code — perfect for cache + PK index
Redirect path (hot path)
- Redirects are the product. Optimize this path first.
- Client → edge/CDN or LB → app → cache → DB on miss → 302/301
- Cache code→long_url in Redis with TTL; warm on create
- On miss: DB get; if missing/expired → 404
- Do not write analytics synchronously on this path
- Connection keep-alive and tiny payloads keep p99 low
301 vs 302
- Caching behavior changes with the status code — interviewers listen for this.
- 301 Moved Permanently — browsers/CDNs may cache aggressively; fewer hits to you; harder to update/disable
- 302 Found — typically less sticky; better if links can change, expire, or need click tracking
- Many shorteners prefer 302 for control; some use 301 for public permanent redirects
- State your choice and the product implication
- Cache-Control headers still matter either way
Create path & abuse
- Creates are rarer but attract spam. Protect them.
- Auth optional for public shorten; stricter limits for anonymous users
- Normalize URLs carefully; beware open-redirect abuse to phishing sites
- Malware/phishing blocklists on create and periodic re-scan
- Idempotency: same user + same URL may return existing code
- Enqueue virus-scan / reputation checks async if needed
Analytics off the critical path
- Click counts are valuable and must not slow redirects.
- On redirect, emit an async event {code, ts, ua?, country?} to a queue/stream
- Workers aggregate into stats DB or warehouse
- Accept approximate counts if exactness is not required
- Never let a downed analytics system break redirects
- Dashboards read from the stats store, not the hot mapping table
Scaling the system
- Scale reads first; shard when mapping storage or write QPS demands it.
- Stateless app tier behind LB; Redis cache for hot codes
- DB primary for creates; read replicas rarely needed if cache hit rate is high
- Shard mapping table by code hash when data outgrows one primary
- CDN can terminate TLS and sometimes cache 302s — align with 301/302 choice
- Multi-region: replicate or shard by geography for global low latency
Interview framing
- Use this order in a 35–45 minute design interview.
- Requirements + capacity math + code length
- APIs + schema + ID→base62 (or hash with collision plan)
- Draw redirect path with Redis cache; choose 301 vs 302
- Create path with validation and rate limits
- Async analytics + scale plan (cache → shard)
Quick revision checklist
- Write capacity assumptions and code-length math.
- Discuss 301 vs 302 caching behavior.
- Prefer ID→base62 and explain why.
- Keep analytics off the redirect path.
- Cache code→URL; design for read-heavy traffic.
- Mention abuse/phishing controls briefly.
FAQs
How long should codes be?
Enough keyspace for expected URLs with headroom (e.g. 7 base62 chars ≈ 3.5e12). State the math briefly.
Hash(long URL) or ID→base62?
ID→base62 gives controlled uniqueness without collision probing. Hashing is fine if you define collision handling and accept less control over length/format.
Should redirects be 301 or 302?
302 if you need flexibility, expiry, or reliable click traffic to your servers. 301 if the mapping is permanent and edge caching is desirable. Say the trade-off.
Where do click analytics go?
Emit an async event from the redirect path; aggregate in workers. Never block the 302 on analytics writes.
How do custom aliases work?
User-supplied codes with a uniqueness constraint, stricter rate limits, and reservation rules. Fall back to generated codes when no alias is provided.
When do we shard?
When the mapping table’s storage or write QPS exceeds one primary after caching. Shard by hash(code) and keep redirect as a single-shard point lookup.
Learner’s Task
- Practice out loud for 10–12 minutes as if this were a system design interview round.
- State requirements, read/write ratio, and why 7-character base62 is enough (show the exponent).
- Propose APIs + schema and choose ID→base62 vs hash — defend uniqueness.
- Draw the redirect path with Redis; pick 301 or 302 and explain caching impact.
- Describe create-path validation/rate limits and async click analytics.
- Write a 4-sentence closing: code strategy, hot path, scale lever, and one abuse control.