Black Friday 50% off any plan, for life Ends Nov 30

System design

Design a URL Shortener

A URL shortener turns a long link into a short one, such as short.ly/a1B2c3, and sends anyone who opens the short link on to the original page. It is the classic first system design question because the whole design fits on one whiteboard, yet the redirect path has to stay fast and available at a scale where small mistakes show: a code handed out twice, a cache that keeps serving a deleted link, a database that falls over the day one link goes viral.

This write-up walks the design the way you would in a 45-minute interview: requirements, a quick estimate, entities, API, a high-level design built one requirement at a time, then the deep dives where the real decisions are made. Start with the finished system, then read how each piece earns its place.

Now draw it yourself, cold

You can nod along to a finished design and still freeze five minutes into the real round. In the 14-day free trial you draw this system yourself while an interviewer asks questions and grades every decision.

14-day free trial. Cancel anytime with one click.

I have an account

Understanding the problem

Functional requirements

Open by agreeing on what the system does. For this question the interviewer usually hands you the core features; your job is to confirm them, ask about the edges and keep the scope tight.

  1. Users can submit a long URL and receive a shortened version.
  2. Users can optionally choose a custom alias (short.ly/q3-launch) and an expiration time.
  3. Anyone can open a short URL and be redirected to the original.

Questions worth asking, with the answers you will usually get:

  • Can a link be edited or deleted? Not required. Mention that a deletion has to reach the cache too, then move on.
  • Does the same long URL always get the same code? It does not have to. Two people shortening the same page may get two codes. Say which you chose; it changes the write path.
  • Who can create links? Signed-in users. Anyone can follow a link without signing in.
  • Analytics? Out of scope. Click counts and dashboards are a different system that would read a stream of redirect events.

Write the out-of-scope list on the board. It stops the interview drifting into analytics, link previews or spam detection, and it shows you chose the scope instead of forgetting it.

Non-functional requirements

These say how well the system has to work. Each one should be specific to this system and carry a number you can defend.

  1. Short codes are unique. Creating a link must never return a code that already points somewhere else. This is the one place the design needs a hard guarantee: a duplicate sends one person's link to another person's page.
  2. Redirects are fast: under 100 ms at p99, measured at the server. A redirect sits in front of the page the user actually wanted, so every millisecond is pure overhead.
  3. Availability over consistency for redirects (99.99%). If a brand-new link takes a second to work in every region, nobody notices. If a redirect fails, the link is broken for everyone who has it, including links printed on paper.
  4. Scale to 1B URLs and 100M daily active users. The workload is read-heavy: about 100 redirects for every link created.
  5. Durable. Once a create returns a short URL, the mapping is never lost, even if the database node holding it fails a second later.

Rank them. Uniqueness, latency and the read-heavy ratio are the three that shape this design, and they map onto the three deep dives later.

Back-of-the-envelope estimation

Do the arithmetic out loud and round hard. The goal is to learn which parts of the design are under pressure, not to get the third digit right.

Traffic. Assume each of the 100M daily users follows about one short link a day.

redirects: 100M / day ÷ 86,400 s ≈ 1,160 / s on average
peak:      × 10 for daily and event peaks ≈ 12,000 / s
creates:   ÷ 100 (read to write ratio)   ≈ 12 / s on average, ~120 / s at peak
           12 / s × 86,400 ≈ 1M new links a day, so 1B links is about 3 years of growth

Storage. One row holds the short code (7 bytes), the long URL (average around 100 bytes, up to 2 KB), the expiry, the creator and the creation time. With row overhead and the primary-key index, budget 500 bytes a row.

1B rows × 500 bytes = 500 GB

500 GB fits on a single well-provisioned database node, with room for indexes. That is worth saying, because it means sharding is a future concern, not a day-one requirement.

Cache. Link popularity is heavily skewed: a small share of links takes most of the clicks.

pessimistic: the hottest 20% of all links   = 200M × 500 B = 100 GB
realistic:   links clicked in a day, ~20M   =  20M × 500 B =  10 GB

Either fits in memory, the first on a small Redis cluster, the second on one node.

Code length. Short codes use base62: the 62 characters 0-9, a-z and A-Z.

62^5 ≈ 916M      too few for 1B
62^6 ≈ 56.8B     enough for 1B with room
62^7 ≈ 3.5T      thousands of years at 1M a day

Six characters covers the requirement; seven is a comfortable default. Bandwidth is not a concern: a 302 response is a few hundred bytes, so 12,000 a second is a few MB/s.

QuantityEstimateWhat it decides
Peak redirects~12,000 / sA cache on the read path; stateless read servers
Peak creates~120 / sOne primary handles writes comfortably
Data~500 GBOne primary at first, shard later by short code
Hot set10 to 100 GBFits in Redis
Code length7 base62 characters3.5 trillion codes, no reuse needed

Core entities

Name the things the system stores before designing anything that moves them.

  • Url: the mapping from a short code to the original long URL, with an optional expiration, the creator and the creation time. A custom alias is a short code the user picked, so it lives in the same field; it is not a separate entity.
  • User: who created the link. The redirect path never needs it.

A list is enough here. The fields come out of the high-level design, when you know what each request reads and writes.

API

Walk the functional requirements in order and give each the endpoint it needs.

POST /urls
Authorization: Bearer <token>
{
  "longUrl": "https://example.com/a/very/long/path",
  "customAlias": "q3-launch",          // optional
  "expiresAt": "2027-01-01T00:00:00Z"  // optional
}
→ 201 Created   { "shortUrl": "https://short.ly/q3-launch" }
→ 409 Conflict  if the alias is taken
→ 400           if the URL is malformed or blocked

GET /{shortCode}
→ 302 Found     Location: https://example.com/a/very/long/path
→ 404 Not Found if the code does not exist
→ 410 Gone      if it has expired (or 404, if you prefer not to reveal it existed)

Two choices here say a lot about how you think.

302, not 301. A 301 (Moved Permanently) is cached by the browser, so the second click on the same link never reaches your servers. That looks like free performance, but it means an expiration or a deletion never takes effect for anyone who has clicked before, and you lose sight of how often links are used. A 302 (Found) brings every click back to you. Send Cache-Control: max-age=0, s-maxage=60 so browsers ask again every time while a CDN may keep the redirect for a minute (see the deep dives).

The creator comes from the token, never from the body. A userId field in the request lets anyone create links as anyone else.

See it in the flythrough07 · 302 Found

High-level design

Build the design one functional requirement at a time, starting with the smallest thing that works. Caches, counters and shards come later, in the deep dives, where you can say which requirement each one serves.

1. Users can submit a long URL and receive a shortened version

  • Client sends POST /urls.
  • URL Service checks the long URL is well formed, uses http or https, and is not on a list of known malicious hosts. If a custom alias was given, it uses that as the short code; otherwise it generates one (the algorithm is a deep dive). It writes the row and returns the short URL.
  • Database holds one table:
CREATE TABLE urls (
  short_code  VARCHAR(30) PRIMARY KEY,   -- generated code or custom alias
  long_url    TEXT        NOT NULL,
  expires_at  TIMESTAMPTZ,               -- NULL means never
  created_by  BIGINT      NOT NULL,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

Making the short code the primary key is the most important line on the board. The database itself now rejects a duplicate, so even two requests racing for the same alias cannot both win: one insert succeeds, the other fails, and the service turns that failure into a 409. Do not check-then-insert ("is the alias free? then insert"); two requests can both pass the check. Let the constraint decide.

See it in the flythrough10 · Creating a link

2. Users can access the original URL by using the short URL

  • The browser requests GET /a1B2c3.
  • The URL Service reads the row by primary key.
  • If the row exists and has not expired, it answers 302 with the long URL in Location, and the browser follows it. Unknown codes get a 404 and expired ones a 410.

That is a complete, working design: one service, one table, two endpoints. Say so, then turn to the non-functional requirements, because nothing so far makes redirects fast at 12,000 a second or guarantees that generated codes never collide.

See it in the flythrough09 · Every redirect

Deep dives

Each deep dive answers one non-functional requirement. Compare options out loud before choosing, and say what each one costs.

1. How do you keep short codes short and unique?

The code has to be unique (a hard requirement), short (the point of the product), and cheap to generate at the create rate.

BadA prefix of a hash of the long URL

Take md5(longUrl), encode it in base62 and keep the first 7 characters. It looks attractive: the same URL always gets the same code, and no state is shared between servers.

The problem is collisions. Seven base62 characters give 3.5 trillion values, but by the birthday bound you expect the first collision after roughly the square root of that, about 1.9M links, and by 1B links collisions are routine. Without a check, a collision silently overwrites or shadows someone else's link. Once you add a check you are doing Good below, with a slower generator.

See it in the flythrough12 · Bad: hash the URL

GoodRandom codes with an insert-and-retry

Generate 7 random base62 characters and insert. If the primary key rejects it, generate another and try again. This is correct, because the database enforces uniqueness, and simple, because servers share nothing.

It costs a round trip per collision, and the collision rate rises as the space fills: at 1B codes out of 3.5 trillion it is about 1 in 3,500, which is fine, but it never reaches zero, and every retry is a write that failed. A variant pre-generates random codes into a pool table that a key service hands out, which moves the retries off the request path at the cost of another service to run.

GreatA counter encoded in base62

Give every link a number from a global counter and encode the number in base62. Every number is handed out once, so every code is unique by construction, with no retries.

id   = 57,800,235,707              // the counter starts at 62^6
code = base62(id) = "115FTIf"      // 0-9a-zA-Z

Start the counter at 62^6 rather than 1, so every code is exactly 7 characters from the first link to the 3.4 trillionth. Starting at 1 gives one-character codes that grow with the count, which is also fine if you say so.

The counter lives in Redis, where INCR is a single atomic operation, so two concurrent callers always get different numbers. To keep Redis off the hot path, each Write Service instance reserves a block with INCRBY counter 1000 and hands those 1,000 ids out from memory. Even at the peak of 120 creates a second, that is at most one Redis call every few seconds per instance.

The details a senior candidate brings up:

  • Gaps are fine. If an instance restarts, the rest of its block is never used. With 3.5 trillion codes, a lost thousand costs nothing.
  • The counter must never go backwards. Run Redis with append-only persistence and a replica. Replication to that replica is asynchronous, so after a failover (triggered by Sentinel or your platform's failover hook) advance the counter by a safety margin, say a million, before handing out blocks again. A block issued just before the crash is then never issued twice. Keep the counter on its own Redis instance with eviction off: an evicted counter key restarts at zero.
  • Why not a database sequence? A Postgres sequence is also atomic and can hand out blocks (INCREMENT BY 1000). It works. Redis keeps id generation off the database that takes every write, and it keeps working when the data is later sharded across several databases.
  • Aliases share the namespace. A user could pick 115FTIf as an alias before the counter reaches that number. When the generated insert hits the primary key, skip to the next id. Some designs avoid this entirely by requiring aliases to contain a character generated codes never use, such as a hyphen.
  • Sequential codes are guessable. Anyone can walk 115FTIf, 115FTIg, ... and read other people's links. If that matters, pass the id through a reversible permutation (a small block cipher over the id space) before encoding it. The codes stay unique and stop looking ordered.
  • The primary key is still the backstop. Even a correct counter deserves a database that refuses a duplicate.
  • Expired rows need a sweep. The redirect already refuses an expired link, but the row stays, and so does its custom alias. A background job deletes expired rows in small batches through an index on expires_at and drops their cache entries; a store with per-row TTLs, such as DynamoDB, does the same for you. Decide whether a freed alias may be taken again. Allowing it gives popular names back to users; refusing it means a link someone shared years ago can never start pointing at a stranger's page. Generated codes are never worth reusing: the code space is far larger than the data.

See it in the flythrough13 · Great: a counter

2. How do you make redirects fast?

The target is under 100 ms at p99 for 12,000 redirects a second, almost all of them reads of a small hot set of links.

BadEvery redirect reads the database

A primary-key lookup in Postgres takes a millisecond or two, and one well-provisioned node can serve 12,000 of them a second. So this is not wrong on day one; it is fragile. Every redirect competes with every write on the same machine, the p99 rises with any slow query or vacuum on that node, and a viral link can multiply the peak by ten in minutes with no headroom to absorb it. The redirect path, the one users feel, is only as healthy as the busiest database.

GoodAn in-memory cache on the read path

Put Redis between the service and the database and read through it (cache-aside):

url = cache.get(code)
if url is None:
    url = db.get(code)
    if url and not url.expired():
        ttl = 24h if url.expires_at is None else min(24h, url.expires_at - now)
        cache.set(code, url, ttl)
if url is None: return 404
if url.expired(): return 410
return redirect(url.long_url, 302)

With a 100-to-1 read ratio and skewed popularity, the hit rate is very high and most redirects never touch the database. A Redis read is well under a millisecond inside the data center.

Keep the cache correct:

  • TTL no later than the expiry. Otherwise the cache keeps redirecting a link after it expired.
  • Evict on delete. If deletion is ever added, delete the cache key in the same request.
  • Write on create. The Write Service puts each new mapping into the cache as it creates it. The creator's first click is then a hit, even before the replicas have the row.
  • Cache misses too. Bots probe random codes. Cache "not found" for a minute so a scan does not become a stream of database reads. The write on create replaces any cached miss, so a code probed a moment before it existed still works as soon as it is created.
  • Evict the coldest links. Set maxmemory and an allkeys-lru (or allkeys-lfu) policy; Redis's default refuses writes when full instead of evicting.

See it in the flythrough04 · Check the cache

GreatThe cache plus the edge

For the hottest links, answer before the request reaches your data center. A CDN can cache the 302 at locations near the user for a short time, which removes the network round trip as well as the lookup. The edge cache time is the same trade-off as 301 against 302: keep it short (a minute) and a deletion takes effect within that minute. For a link with an expiry, set s-maxage to the smaller of 60 seconds and the time left, so the edge never redirects past the expiry.

A viral link also creates a hot key: one Redis shard taking all the traffic for one code. The edge absorbs most of it. Behind it, a small in-process cache in each Read Service instance (a few thousand entries for a few seconds) spreads the rest across every server.

See it in the flythrough02 · The edge first

3. How do you scale to 1B URLs and 100M DAU?

Start from the estimate: 500 GB of data, about 12,000 redirects a second at peak and about 120 creates a second.

BadScale the one service and one database up

The first instinct is to keep the high-level design and buy bigger machines: more cores for the one URL Service, a larger instance for the one Postgres. It needs no new code, and on paper it holds today's numbers. One well-provisioned node serves 12,000 primary-key reads and 120 inserts a second, and 500 GB fits on its disk.

The trouble is that everything still shares one machine. Redirects and creates queue for the same connections, so a burst of clicks slows link creation. A viral link that multiplies the peak by ten asks that one database for 120,000 reads a second, ten times what it was sized for, and there is no second machine to take the excess. The largest instance you can buy is the ceiling. And when that node fails, or restarts for an upgrade, every redirect and every create fails until it is back.

GoodSplit the paths, replicate the reads

  • A Read Service and a Write Service. Redirects and creates have different load, latency targets and failure modes. Split them so each scales on its own. Both are stateless behind a load balancer, so adding capacity is adding instances.
  • Read replicas. The primary takes writes and streams them to replicas; cache misses go to a replica. A redirect never touches the primary.
  • Read your own writes. Replication lag means a link created a moment ago may not be on the replica yet, and the creator usually clicks it straight away. The write on create (deep dive 2) covers this: the first click is a cache hit. Do not "fall back to the primary on a miss" instead: every bot probing an unknown code would then reach the primary.
  • Durability. Asynchronous replicas can lose the last writes if the primary dies. Commit each create synchronously to one standby (Postgres synchronous_standby_names with synchronous_commit = on) so a create that returned is on two machines. At 120 writes a second the extra round trip costs nothing that matters.

See it in the flythrough15 · Replicas take the reads

GreatShard by the short code when one primary is not enough

500 GB fits one primary today, and 120 writes a second is easy for it. When data or writes outgrow it, shard. The shard key must be the short code, because that is the only thing a redirect knows: a redirect does not know who created the link, so sharding by user would send every redirect to every shard. Hash the code and map the hash to a shard through a fixed set of logical shards (say, 1,024) assigned to physical databases. Moving a logical shard is then a copy, and adding a database never remaps every key, which is what hash % N would do.

The same reasoning applies if you choose a key-value store such as DynamoDB or Cassandra instead of Postgres: the access pattern is one lookup by one key, which these stores partition for you. Either choice is defensible. Say what you gain (automatic partitioning) and what you give up (the transactional insert that made alias uniqueness trivial, now a conditional write).

Global users. Run the read path in several regions: a Read Service, a Redis cache and a database replica in each, with writes going to one primary region. Redirects stay local and fast; a new link takes a replication delay to appear elsewhere, which the availability-over-consistency requirement already allows.

See it in the flythrough16 · At scale

Final design

Put it together and walk one request through each path.

A redirect. The browser asks for short.ly/a1B2c3. The CDN answers if the link is hot. Otherwise the load balancer sends the request to a Read Service instance, which checks Redis. On a hit it answers 302. On a miss it reads a Postgres replica by primary key, caches the mapping (or the miss) with a TTL no later than the expiry, and answers 302, 404 or 410.

A create. The client sends POST /urls. The load balancer sends it to a Write Service instance, which validates the URL, takes the next id from its block (refilled from the Redis counter with INCRBY), encodes it in base62, or uses the custom alias, and inserts the row into the Postgres primary, which commits it to a synchronous standby. A primary-key conflict on an alias is a 409; on a generated code, the service takes the next id. The service writes the mapping into Redis, and the primary streams the row to the replicas.

See it in the flythrough17 · End to end

ComponentRoleScales by
CDNAnswers hot redirects near the userThe provider
Load balancerRoutes GET /{code} and POST /urlsManaged, stateless
Read ServiceCache, then replica, then 302Instances
Write ServiceValidate, id block, base62, insertInstances
Redis cacheShort code to long URL, LRU with TTLCluster shards
Redis counterHands out id blocksOne node and a replica
Postgres primaryEvery write; the uniqueness guaranteeSharding by short code
Postgres replicasCache missesMore replicas, more regions

What is expected at each level

Junior. You drive the requirements, entities and API with little help and draw a working design for both requirements: a service, a database and a redirect that looks the code up. You choose an HTTP redirect, not a JSON response. In the deep dives it is fine to need a nudge towards caching or a counter, as long as you can reason about the trade-off once it is on the table.

Mid-level. Everything at junior, plus a design you could build: the schema beside the database, the short code as the primary key, and the status codes chosen on purpose (302 over 301, 409 for a taken alias). You land at least one deep dive on your own with a concrete mechanism, such as a counter with base62 or a cache-aside read path, and you know where it breaks.

Senior and above. You lead the interview. Your requirements carry numbers and you use them later: the read ratio picks the cache, the code space picks the code length, the data size says sharding can wait. You go deep on two or three deep dives without prompting, compare options before choosing, and name the failure modes along with your answer to each: a counter that goes backwards after a failover, a hot key, a cache serving an expired link, a replica that has not seen a new link yet. At the top of this level you also argue for the simplest design that meets the numbers (one Postgres primary and a cache, no shards yet), say how it grows (read regions, then shards by short code) and raise the trade-offs a team would care about: whether expired codes may be reused, what a CDN costs against what it saves, and the work of running Redis as a second piece of state.

Common mistakes

  • A 301 with no reason given. It is cached by browsers, so expiry and deletion stop working. If you pick 301, say that you accept this.
  • Check-then-insert for aliases. Two requests both see the alias as free and both insert. Let the primary key decide and turn the conflict into a 409.
  • Truncated hashes with no collision handling. Seven characters of a hash collide long before a billion links.
  • Sharding by user id. The redirect path does not know the user. Shard by the short code.
  • Designing analytics. It was ruled out of scope. Mention that redirects could emit events to a stream for a separate analytics system, and stop there.
  • Caches with no expiry story. A cache TTL longer than the link's expiration keeps a dead link alive.
  • Jumping to the deep dives. Caches, counters and shards before a working create and redirect leave the interviewer unsure you can build the simple version.
  • Numbers that are never used. An estimate earns its time only when it decides something later: the cache size, the code length, whether to shard.

Be ready for whichever one they pick

Practice each with an interviewer who grades every step, in the 14-day free trial

Walk into the system design round ready

Practice all 50 system design problems on a whiteboard, with graded feedback on every step, alongside 1,500+ real interview questions. A learning engine brings every problem back before you forget it. 50,000+ engineers have prepared with Firecode.

14-day free trial. Cancel anytime with one click.

Built by former engineers at

I have an account
50,000+engineers preparing with Firecode
1500+real interview questions from top tech companies
14languages, from Python to Rust
FAANG+offers landed at Google, Meta, Netflix, and more
Google Meta Amazon Apple Microsoft Netflix OpenAI Anthropic Stripe Nvidia Airbnb Uber Coinbase DoorDash Spotify Shopify Snowflake Cloudflare Bloomberg Dropbox