← Problems

URL Shortener (TinyURL / bit.ly)

easymid / senior15 min read · 5 diagrams · 4 decisions
Start timed practice

Turn long URLs into short, unique aliases and redirect users at very high read volume. A classic warm-up that tests key generation, read-heavy caching and analytics.

Try it before you read it

You will remember far more of this walkthrough if you attempt the problem first. Run it as a timed 45-minute practice, then come back and compare stage by stage. Each section below opens with what the interviewer wants from that stage and how long to spend on it.

Requirements

~5 min

In the interview: Clarify functional requirements (what the system must do) and non-functional ones (scale, latency, availability, consistency). State what is out of scope.

Functional

  • Given a long URL, return a short alias (e.g. sd.io/aB3xZ9).
  • Visiting the alias redirects to the original URL.
  • Optional: custom aliases, expiry, basic click analytics.
  • Optional: user accounts to list and delete their links.

Non-functional

  • Highly available: redirects must keep working even if link creation is degraded.
  • Low latency on redirect (p99 < 50 ms from the edge, excluding client network).
  • Aliases must be unique and hard to guess (not sequential).
  • Read:write ratio is very skewed, roughly 100:1.
  • Durability: a created link must never be lost.

Out of scope

Back-of-envelope estimates

~5 min

In the interview: Estimate QPS (read and write), storage over 5 years, bandwidth and cache size. Show the arithmetic.

Assumptions

  • 100M new URLs per month.
  • 100:1 read:write ratio → 10B redirects per month.

Traffic

  • Writes: 100M / (30 × 86,400 s) ≈ 40 writes/s. A single database handles this without any special design.
  • Reads: 40 × 100 ≈ 4,000 reads/s average; plan for 5–10× peak ≈ 40K reads/s. This is the number the design has to serve, and it is why the read path gets a cache and replicas.

Storage

  • 100M/month × 12 × 5 years = 6B records.
  • ~500 bytes per record (alias, long URL, owner, timestamps) → 6B × 500 B ≈ 3 TB over 5 years. Comfortably fits a single replicated database with modest sharding, so storage is not what forces a distributed design here.

Key space

  • Base62 (a–z, A–Z, 0–9). 6 chars = 62^6 ≈ 56.8B. 7 chars = 62^7 ≈ 3.5T. Use 7 to leave headroom: 6B records over 5 years is 0.2% of the 7-char space, so random keys almost never collide.

Cache

  • 80/20 rule: about 20% of links get 80% of the clicks, so cache by access (LRU) rather than trying to hold every link.
  • Sizing: 4,000 reads/s × 86,400 s ≈ 345M redirects a day. Caching 20% of them at ~500 B each ≈ 0.2 × 345M × 500 B ≈ 35 GB. That is an upper bound, because many of those reads repeat the same links. A few Redis nodes hold it, so the database only sees the 5–10% of reads that miss.

Bandwidth

  • Redirect responses are tiny (a 301/302 with a Location header), roughly 500 B. 4,000 r/s × 500 B ≈ 2 MB/s. Not a concern.

API design

~5 min

In the interview: Define the core endpoints, their inputs, outputs and error cases.

POST /v1/urls

  • Body: { longUrl, customAlias?, expiresAt?, userId? }
  • Returns 201 { shortUrl, alias, expiresAt }
  • Errors: 400 invalid URL, 409 alias taken, 429 rate limited.

GET /{alias}

  • Returns 301 or 302 with Location: longUrl.
  • 404 if unknown, 410 if expired.

DELETE /v1/urls/{alias} (authenticated owner only)

GET /v1/urls/{alias}/stats

Notes

  • Use an API key or JWT for creation so you can rate limit per user.
  • Idempotency: the same user submitting the same long URL twice may return the existing alias.

Data model

~5 min

In the interview: Define the main entities, keys, indexes, and pick a storage technology with a reason.

Entity: url_mapping

  • alias (PK, 7-char base62 string)
  • long_url (text, up to 2 KB)
  • user_id (nullable, indexed)
  • created_at, expires_at
  • click_count (counter, may live elsewhere: updating it on every redirect would turn the read path into a write path)

Entity: user

  • user_id (PK), email, api_key_hash, created_at

Storage choice

  • The workload is a simple key → value lookup with no joins and a huge number of rows. A wide-column or key-value store (DynamoDB, Cassandra) scales horizontally with minimal operational effort because each alias lives on exactly one partition and a lookup touches exactly one node.
  • A relational DB (Postgres) also works at this size (3 TB) if sharded by alias prefix (the first one or two characters pick the shard), and makes the "list my links" query easy because user_id can be a normal secondary index.
  • Either is defensible in the interview. State the reason for your pick: operational simplicity vs query flexibility.

Analytics

  • Do not update click_count on the hot path with a synchronous DB write. Emit a click event to a queue and aggregate separately, so a viral link produces a stream of small events instead of millions of contended updates to one row.

Blue: services · Green: durable stores · Yellow: caches · Purple: queues · Red: third parties · Dashed arrows: asynchronous.

Data model

Two entities and one derived table. The mapping table is a pure key lookup, which is what makes a key-value store defensible. Click counts live in the analytics store, never as a counter column updated on every redirect.

High-level design

~10 min

In the interview: Draw the main components and the request flow for reads and writes. Keep it simple first.

Write path
1. The client calls POST /v1/urls. The load balancer forwards the request to one of the stateless URL-creation API servers.
2. The API server validates the URL (well-formed, allowed scheme, under the length limit), then obtains a unique alias: it takes the next key from the batch it holds in memory, which it fetched earlier from the key generation service (see the key generation deep dive).
3. The API server inserts one row into the URL store: alias → long URL, owner, created_at, expires_at. The insert is the only write on the path; nothing is cached yet because nobody has read this alias.
4. It returns 201 with the short URL. From this point a redirect works as soon as the row is visible on a replica, usually within tens of milliseconds.

Read path
1. The browser requests GET /{alias}. The request reaches a CDN edge or the load balancer, which forwards it to a redirect server. The CDN terminates TLS and serves static assets but does not cache the redirect itself.
2. The redirect server asks Redis for the alias. On a cache hit it has the long URL immediately and returns a 302 with the Location header; the database is never touched.
3. On a cache miss it reads the row from a database replica, writes the long URL into Redis with a TTL so the next request hits, and returns the 302.
4. Before responding, the server publishes one click event (alias, timestamp, referrer, hashed user agent) to a message queue and does not wait for an acknowledgement. An analytics consumer reads the queue, counts clicks per alias per minute, and writes the totals to a separate analytics store that the stats endpoint queries.

Why split read and write services?

  • They scale independently: reads are 100× writes and are latency-sensitive, so the redirect fleet is much larger and tuned for cache hits, while the creation fleet is small. A bug deploy in creation should not take down redirects, and a traffic spike on redirects should not slow link creation.
High-level design
Build it up
Step 1 of 4
Write path

Start with the one request that creates data. A load balancer, a stateless service and one table are enough to shorten a URL at 40 writes a second.

Say: Let me start with creating a link, then add the read path.

Faded boxes arrive in a later step; outlined boxes are new in this one.

Draw the write path (top) and the read path (bottom) as two separate flows through one load balancer. Say out loud that reads are 100× writes, which is why the redirect service, cache and replicas get all the attention.

Deep dives

~10 min

In the interview: Pick the 2–3 hardest parts (bottlenecks, hot paths, failure modes) and go deep.

1. Key generation

  • Option A: Hash the long URL (MD5/SHA-256), base62-encode the digest, take the first 7 chars. Because the hash is truncated, two different URLs can produce the same 7 characters, so every insert must first check the database for an existing alias; on a collision, re-hash with a salt appended or add a counter and try again. The upside is that the same URL always maps to the same alias, which gives you deduplication for free.
  • Option B: Key Generation Service (KGS). A background service pre-generates random unique 7-char keys and stores them in a key table with a used flag. Each API server claims a batch of about 1,000 unused keys in one atomic update (mark them used, return them) and hands them out from memory, so the write path never checks for collisions. KGS is a single point of failure for new links, so run it replicated; a server that crashes simply loses its unused batch, which the key space can afford.
  • Option C: Distributed counter (a Snowflake-style timestamp plus node id, or ranges allocated from ZooKeeper), base62-encoded. Simple and guaranteed unique, but consecutive aliases are sequential, so anyone can guess the next link; apply a bijective scramble (a reversible permutation of the bits) or mix in random bits before encoding.
  • Recommended: B for simplicity under load, or C with range allocation if you already run a coordination service.

2. Redirect caching and cache invalidation

  • Use cache-aside with a TTL: the redirect server reads Redis first, falls back to a database replica on a miss, and writes the result back into Redis. Hot aliases get long TTLs because they are read constantly and rarely change.
  • Deletions and expirations must invalidate the cache explicitly: when a link is deleted, the API server removes the Redis key in the same request as the database delete. Otherwise the deleted link keeps redirecting from the cache until its TTL runs out, which can be minutes.
  • Use a CDN for the redirect itself only if you are fine with slow invalidation, because purging a CDN takes seconds to minutes and you lose the per-click event. Most designs keep redirects at the application layer and use the CDN for static assets.

3. 301 vs 302

  • 301 (permanent): the browser caches the redirect, so repeat visits from the same browser never reach your servers. Cheaper to run, but you cannot count those clicks and cannot change the target for that browser later.
  • 302 (temporary): the browser asks your service on every click. You get the click event every time and can update or expire the link at any moment, at the cost of serving 100% of reads.
  • Pick 302 if analytics matters (it usually does for the business), 301 if pure cost minimisation.

4. Expiry

  • Lazy expiry: the redirect server compares expires_at with the current time on every read and returns 410 Gone if the link has expired. It costs nothing extra and guarantees an expired link never redirects.
  • Active expiry: a background job scans for rows whose expires_at has passed, deletes them in batches, and evicts their cache keys, so storage is reclaimed and aliases could be reused. Both together is the usual answer: lazy for correctness, active for cleanup.

5. Availability of the redirect path

  • Run the cache and database replicas across several availability zones so the loss of one zone leaves the redirect path working. The redirect service reads from replicas, which lag the primary by a few hundred milliseconds at most, so a link read immediately after creation may miss once. That is acceptable: you can say "a just-created link may take a moment to work" and the creation response already includes the short URL.
Deep dive: write path with a key generation service

Each app server pulls a batch of pre-generated keys into memory and marks them used in one atomic step, so the hot write path never does a collision check. If a server dies, its unused batch is simply lost; the key space is large enough not to care.

Deep dive: read path, cache-aside and invalidation

Cache-aside: check Redis, fall back to a replica, then populate the cache. The invalidation arrow is the part people forget: a delete or expiry must evict the cache entry, otherwise the link keeps redirecting until the TTL runs out.

Deep dive: click analytics off the hot path

The redirect service fires a click event and forgets about it. Consumers aggregate per-minute counts and write to an analytics store. At-least-once delivery means counts can double on retry: dedupe on a (alias, request id) key or accept approximate counts.

Key decisions

The choices this design turns on. For each, know the options, what you give up with each, and the condition that would make you pick differently: that condition is usually the interviewer’s next question.

How do we generate unique short aliases?

Hash the long URL + truncate

  • Stateless
  • Same URL gives same alias (dedup for free)
  • Collisions after truncation
  • Needs a DB existence check per write
  • Users can predict aliases for known URLs
Pick when: Write volume is low and dedup matters.

Distributed counter + base62

  • Guaranteed unique
  • Trivial to implement with range allocation
  • Sequential → guessable unless scrambled
  • Coordination service becomes a dependency
Pick when: You already run ZooKeeper/etcd and guessability is acceptable or fixable.
Used in this design

Pre-generated keys (KGS)

  • No collision check on write path
  • Fast writes
  • Random, unguessable keys
  • Extra service to run and replicate
  • Must avoid handing the same key to two app servers
Pick when: You want the simplest hot write path at scale.

301 or 302 redirect?

301 Permanent

  • Browser caches it → far fewer requests
  • Lower infra cost
  • No per-click analytics
  • Cannot change or expire the target for returning users
Pick when: Links are immutable and analytics are not a product requirement.
Used in this design

302 Temporary

  • Every click reaches you → analytics
  • Targets can change or expire
  • 100% of reads hit your service
  • Higher cost and latency sensitivity
Pick when: Analytics or mutable links matter, which is the common product case.

Relational vs key-value store for the mappings?

Sharded relational (Postgres/MySQL)

  • Flexible queries
  • Mature tooling, strong consistency
  • Manual sharding and rebalancing
  • More operational work at billions of rows
Pick when: Team expertise is relational and scale is moderate (a few TB).
Used in this design

Key-value / wide-column (DynamoDB, Cassandra)

  • Horizontal scaling built in
  • Access pattern is a pure key lookup
  • Secondary queries (links by user) need extra indexes
  • Eventual consistency defaults
Pick when: Scale is the main concern and queries are simple.

How do we count clicks without slowing redirects?

Synchronous DB increment

  • Exact counts
  • Simple
  • Write on every read
  • Row contention on viral links
  • Adds latency to redirect
Pick when: Tiny scale only.
Used in this design

Async events via queue (Kafka/SQS) + aggregation

  • Redirect path stays fast
  • Supports rich analytics
  • Absorbs spikes
  • Eventually consistent counts
  • More components
  • At-least-once delivery means dedup or approximate counts
Pick when: Almost always at real scale.

Wrap-up

~5 min

In the interview: Summarise the key decisions, what you gave up, and what you would do with more time.

Summary of decisions

  • 302 redirects, because the business wants per-click analytics and the extra read traffic is absorbed by the cache.
  • KGS-style pre-generated keys, so the write path never does a collision check against the database.
  • Key-value store sharded by alias, because every read is a single-key lookup; cache-aside Redis in front, because 20% of links take 80% of reads.
  • Async click events through a queue, so counting never slows a redirect; analytics are eventually consistent by a few seconds.

What was given up

  • Strong consistency between creation and first redirect: replicas can lag, so a brand-new link may miss once.
  • Simplicity of a single service: we split read and write fleets so each can scale and deploy on its own.

With more time

  • Rate limiting and abuse detection, custom domains, link previews, A/B testing of destinations.

What good looks like

What an interviewer expects you to cover at each level. Pick your target level and tick what your last attempt covered; the gaps are what to practise next.

Assess against:
0/9

Interviewer follow-ups

Questions that come after the main design. Answer each out loud in under two minutes, naming the part of the design that changes.

  1. A link goes viral and gets 1M clicks a minute. What breaks first?
  2. How would you support custom aliases without letting users squat on short popular words?
  3. A user deletes a link. How fast does it stop redirecting, and why?
  4. How would you migrate from a 6-char to a 7-char alias scheme with zero downtime?
Ready to try it under time?
45 minutes, seven stages, then a side-by-side review against this walkthrough.
Start timed practice

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Application Load BalancerLoad balancerCloud Load BalancingApplication Gateway, Azure Load BalancerNGINX, HAProxy, Envoy
Amazon EC2 Auto ScalingURL creation service, Redirect service, Key generation service, Delete / expiry job, Stats APICompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon ElastiCacheRedis cache, Redis (cache-aside, TTL)MemorystoreAzure Managed RedisRedis, Valkey, Memcached
Amazon AuroraURL store (KV / sharded SQL), Read replicas, URL store replica, URL store primaryAlloyDB for PostgreSQL, Cloud SQLAzure Database for PostgreSQL or MySQLPostgreSQL, MySQL, CockroachDB
Amazon MSK (Kafka)Click event queue, Kafka topic: clicksManaged Service for Apache KafkaEvent Hubs (Kafka API)Confluent Cloud, Redpanda
Amazon Data FirehoseAnalytics consumer + storeDataflow, Pub/Sub to BigQueryEvent Hubs Capture, Stream AnalyticsKafka Connect, Vector, Fluent Bit
Amazon DynamoDBKey table, URL storeFirestore, BigtableCosmos DBScyllaDB, Apache Cassandra
Amazon CloudFrontCDN / edgeCloud CDN, Media CDNAzure Front DoorCloudflare, Fastly, Akamai
Amazon Managed Service for Apache FlinkAggregation consumersDataflow (Apache Beam)Stream AnalyticsApache Flink, Kafka Streams, Spark Structured Streaming
Amazon S3Raw event archive (S3)Cloud StorageBlob StorageCloudflare R2, MinIO, Ceph