Design a URL Shortener: The Junior, Senior and Staff Answer
When you hear "design a URL shortener" the interviewer is looking for three things: how you translate a simple user story into a scalable service, how you choose data structures and AWS primitives, and how you think about reliability and cost at scale.
What the interviewer is testing
- Requirement gathering – can you elicit functional and non-functional needs?
- System decomposition – do you break the request path into clear hops?
- Trade-off reasoning – are you aware of latency vs. consistency, cost vs. durability?
- Operational mindset – especially at senior and staff levels, do you think about monitoring, alerts, and failure isolation?
Core requirements and driving numbers
| Requirement | Typical value (hedged) |
|---|---|
| Total URLs stored | about 3 billion after a year at the write rate below (100/s × 86,400 × 365 ≈ 3.15 B; roughly 315 GB if each entry is ~100 bytes) |
| Read traffic | about 1 k requests / second (≈86 M per day) |
| Write traffic | about 100 requests / second (≈8.6 M per day) |
| Availability | 99.9 % uptime, sub-100 ms latency for redirects |
These numbers drive three major design decisions: the choice of a low-latency key-value store, a caching layer to absorb the read burst, and a sharding strategy that can grow as traffic increases.
Core design in prose – request path hop by hop
- Client request –
POST /shortenwith a long URL. - API layer – Amazon API Gateway forwards to a Lambda function.
- Key generation – Lambda creates a short token (e.g., base-62 of a counter or a hash). The token is the primary key.
- Persistence – The token and original URL are written to a DynamoDB table. A Global Secondary Index (GSI) on creation time enables analytics.
- Cache warm-up – The Lambda also writes the mapping to an ElastiCache Redis cluster (write-through). This ensures the next read hits the cache.
- Redirect –
GET /{token}hits CloudFront edge. CloudFront serves the redirect from its own edge cache when it has one; on a miss the request goes to a Lambda that checks Redis first, falls back to DynamoDB, returns a 302 (a 301 lets browsers cache the redirect, so repeat clicks would never reach the service or be counted), and updates the cache. - Analytics – Each redirect that reaches the Lambda fires an event to an SQS queue (redirects answered from the CloudFront cache are counted from CloudFront's logs instead), later processed by a consumer Lambda that writes aggregates to Aurora for reporting.
Data model
- Table: UrlMapping
PK(string) – the short token, e.g.,b3K9X.LongUrl(string) – the original URL.CreatedAt(timestamp) – for analytics; DynamoDB's TTL attribute must hold the expiry time in epoch seconds, so TTL usesExpiration, not this field.- Optional fields:
OwnerId,Expiration,Clicks(incremented via DynamoDB atomic counter).
The short token is chosen over a sequential numeric ID because it avoids exposing traffic volume and reduces predictability. A random or hash-based token also needs no shared counter, so there is no single counter row that every write must update. DynamoDB hashes the partition key, so either kind of token spreads evenly across partitions.
What a complete junior answer covers
- Functional flow – describe the POST and GET paths.
- Single DynamoDB table – explain why a NoSQL key-value store fits the low-latency requirement.
- Basic caching – mention CloudFront for static assets and a simple in-memory cache (e.g., Redis) for redirects.
- Scalability estimate – use the numbers above to show DynamoDB can handle 100 req/s writes and 1 k req/s reads with provisioned throughput or on-demand mode.
- Missing pieces – a junior often omits async analytics, TTL handling, and operational concerns.
What a senior answer adds
- Read-through cache pattern – detail how Redis is populated on write and refreshed on cache miss.
- Hot keys, not manual sharding – DynamoDB already hashes the token across partitions, so prefix sharding adds nothing; the real hot spot is one viral link, which CloudFront and Redis absorb.
- Rate limiting – API Gateway usage plans or a Lambda authorizer to protect against abuse.
- Partial consistency – explain eventual consistency of DynamoDB reads and why it is acceptable for redirects.
- Monitoring – CloudWatch metrics for latency, error rates, and cache hit ratio; alarms on 5 xx spikes.
- Cost awareness – estimate DynamoDB read/write units and Redis node count, showing how on-demand pricing scales with traffic.
What a staff answer adds
- Failure modes – discuss DynamoDB regional outage, Redis node failure, and CDN edge cache miss storms. Show how a fallback to S3 static redirects can keep the service alive.
- Operational playbook – describe a runbook for cache invalidation, table scaling, and automated backups (DynamoDB point-in-time recovery, S3 versioning for static assets).
- Cost optimization – use DynamoDB TTL to purge expired URLs, reserve capacity for predictable traffic, and right-size the Redis cluster, with reserved nodes for the steady baseline.
- Trade-off defense – argue why a hash token is chosen over a sequential ID despite the extra compute, citing no shared counter on the write path and codes that do not leak volume or invite guessing.
- Advanced analytics – batch processing with Athena on S3-stored click logs, enabling A/B testing of token length.
Common mistakes that sink this question
| Mistake | Why it hurts |
|---|---|
| Using a relational database for the primary mapping | Too slow for sub-100 ms redirects is the wrong objection, since an indexed lookup takes milliseconds; what hurts is having no plan for growing writes and storage past one primary. |
| Generating a token by incrementing one global counter on every write | Every create updates the same counter item, which caps write throughput, and sequential codes leak traffic volume; leasing blocks of IDs fixes the first. |
| Ignoring cache miss storms after a cold start | Leads to latency spikes and higher DynamoDB read cost. |
| Forgetting TTL or expiration handling | Table size grows unchecked, raising storage cost and scan time. |
| Over-engineering analytics in the core path | Increases latency; analytics should be async. |
Comparison of answer depth by level
| Aspect | Junior | Senior | Staff |
|---|---|---|---|
| Core flow | Describes POST/GET, single DynamoDB table | Adds Redis cache, hot-key handling, rate limiting | Includes fallback paths, runbooks, cost trade-offs |
| Data model | Simple PK-value | PK + GSI, TTL, atomic counters | Same model + audit logs, versioning |
| Scaling | On-demand DynamoDB capacity | Hashed-key partitioning, hot-key caching | Multi-region replication, right-sized Redis, async pipelines |
| Reliability | Basic error handling | Cache hit-ratio monitoring, alarms | Failure injection testing, disaster recovery plan |
| Cost | Rough estimate | Detailed unit calculations, reserved capacity | Cost-benefit analysis, lifecycle policies |
How to practice this
- Read the free worked design, Design a URL Shortener: start with the board for your level. It also stores links in DynamoDB behind Redis and CloudFront, but generates codes differently by level (seven random characters at junior, leased counter ranges at senior) and counts clicks through Kafka; compare its choices with yours.
- Write your own answer on paper or a whiteboard. Start with the request path, then add layers (cache, analytics, ops) as you move from junior to senior to staff.
- Run a mock interview with a peer. Ask them to critique each layer and to point out missing failure scenarios. With Pro ($10/month), draw it on the practice canvas and have the Coach review it against the brief's rubric.
Questions people ask
What is the simplest way to generate a short token?
Draw seven random base-62 characters (62^7 ≈ 3.5 × 10¹², about 3.5 trillion codes) and write with a condition that fails if the code already exists, retrying on the rare clash. A random 64-bit integer would need up to 11 characters, which is no longer short.
Do I need a relational database for analytics?
No. Capture click events in an SQS queue, process them with Lambda, and store aggregated counts in Aurora or Athena-queried files on S3 for reporting.
How do I handle a hot token prefix?
DynamoDB hashes the partition key, so tokens spread across partitions whatever their first characters; a shared prefix cannot create a hot partition. The hot spot to plan for is one viral link, which CloudFront and Redis absorb.
What monitoring metrics are critical?
Watch API latency, DynamoDB read/write throttling, Redis cache hit ratio, and CloudFront 4xx/5xx rates. Set alarms on any metric that drifts beyond acceptable thresholds.