Contents

System Design Interview: Design a URL Shortener (Step-by-Step) | OfferBull

System Design Interview: Design a URL Shortener (Step-by-Step)

“Design a URL shortener.”

It’s a short prompt, which is why it shows up so often. You can finish a clean design in 45 minutes, or you can spend the same 45 minutes decorating a board with services you can’t explain. The difference is usually the order of work, not a secret algorithm.

This is a full worked walkthrough of that prompt: requirements and numbers, the API and the record, how the short code gets made, the read and write paths, then caching, scaling, analytics, and the follow-ups that show up around minute 35. For the clock and the section order, use the system design interview template. That post already uses a shortener as a running example. This one goes deeper on code generation, 301 versus 302, and what you do when one link goes viral.

The numbers, dialogues, and design choices below are illustrative interview-prep frameworks, not a claim about how any named company runs its production shortener.

Requirements and the numbers I’d put on the board

Start with questions, not boxes. I’d lock three things before I draw: what we will build, what we won’t, and a few numbers that change the design.

A clarifying exchange might sound like this (illustrative):

You: “I’d treat this as create a short link and redirect it when someone opens it. Custom aliases and an expiry date are optional. I’d leave user accounts and a full analytics dashboard out unless you want them in scope. What scale should I assume?”

Interviewer: “A hundred million new links a month. Reads are much higher than writes.”

You: “I’ll assume a 100-to-1 read-to-write ratio, keep links for five years, and optimize redirects for low latency and high availability. A brand-new link can take a short time to show up in every region. I’ll also assume we want click counts, which will affect the redirect type. Fair?”

Now the rough math, out loud, with round numbers. A month is about 2.6 million seconds, so 100 million new links a month is about 40 writes per second. At 100-to-1, that’s about 4,000 redirects per second. If I assume a 3x weekday peak, just as an interview assumption, writes stay around 120 per second and reads around 12,000. Say each record is about 500 bytes and we keep five years of links: 6 billion rows, about 3 TB.

Those numbers give me a handful of decisions. Writes are not the bottleneck. Reads are. 3 TB will want a split later, but it is not a “we need a novel database” problem. A cache in front will do most of the work if a relatively small set of links gets most of the clicks, a common interview assumption, not a measurement I have in my pocket. For more practice turning a prompt into numbers, see estimation and Fermi questions.

I’d write the non-functional requirements in one line each: redirects should feel instant, the service should stay up if one app server or cache node dies, and we can tolerate a short delay before a new link works everywhere. I’d also ask whether guessing a short code is a problem, because that decides whether sequential IDs need scrambling later.

/images/posts/design-a-url-shortener-system-design/requirements-board.jpg Write the scope and the numbers first. The boxes can wait a few minutes.

The API and the record you’d store

Write the API before the architecture, so you don’t invent services with nothing to call.

POST /urls takes a long URL, and optionally a custom alias and an expiry. It returns the short URL and the code. Validate the long URL here: scheme, obvious junk, and a size cap, so you don’t store a 2 MB “URL.” If the alias is taken, return a conflict and let the client pick another. Rate-limit this endpoint. The abuse case is a bot minting millions of links.

GET /{code} looks up the code and returns a redirect. That’s the hot path. I would not do heavy analytics work in this request. A small extra, only if they want it: GET /urls/{code} returns metadata without redirecting.

Then the redirect type, said as a trade-off, not a trivia answer. A 301 is permanent: browsers and some caches remember it and stop asking you, which is great for load and bad for click counts or later edits. A 302 is temporary, so most clients come back next time, which keeps your counts and your ability to expire the link. I usually pick 302 and say why: we wanted click counts, and we wanted expiry to work. If they don’t need counts and links never change, 301 is a reasonable pick.

The record itself can stay small: code as the primary key, long_url, created_at, expires_at (nullable), is_custom so vanity aliases can have different rules, and owner_id if accounts come back into scope. Lookups are by code. A key-value store is a natural fit; a relational database also works if you index the code and plan a split later. I would not keep a live click_count on this record. Incrementing a counter on every redirect turns your read path into a write path, so click events go on a queue.

How the short code gets made

This is the deep dive I’d offer first. What they want is two or three options, a pick, and the cost of that pick. Interviewers have heard “I’ll just hash it” plenty of times.

A common encoding is Base62: 0-9, a-z, and A-Z, 62 symbols. A 7-character code has 62⁷ possibilities, about 3.5 trillion, which is far more than five years of IDs at this scale. 6 characters is about 57 billion, nicer to type, but with less headroom. I’d pick 7 unless they want shorter links, and I’d say the math in one breath.

Hash the long URL, take enough bits, and encode them in Base62. Same URL can give the same code, which is handy if you want uniqueness by destination. Collisions happen once you truncate, so you have to check the store and retry with a salt or a longer code.

Take a counter and encode it in Base62. No collisions. The problem is the counter itself: every write hits the same increment, the IDs are sequential (so people can enumerate other links), and a single generator is a single point of failure.

Hand each app server a block of IDs from a small coordination service, then encode locally. This is the option I’d pick in most versions of this interview. The service hands out ranges, say 100,000 IDs at a time. App servers mint codes without talking to each other on every request. If a server dies, it wastes the rest of its block, which is fine. The remaining issue is guessability, because the IDs are still roughly sequential. If that matters, scramble the ID before encoding.

Custom aliases sit to the side. They don’t come from the generator. They have to be unique, they shouldn’t collide with generated codes, and you want a denylist for aliases that look like login or admin. It belongs in the interview because it changes the write path.

/images/posts/design-a-url-shortener-system-design/id-generation.svg I’d put all three on the board, then pick ID blocks and say the cost: leftover IDs if a server dies, and sequential codes unless you scramble them.

The request path, the cache, and how this scales

Now draw the simple version end to end: client, load balancer, a few stateless app servers, a cache, a data store sharded by code, a small ID-block service on the write path, and a queue for click events so it can’t slow a redirect. Get a path that works, then add a box only when a number or a requirement forces it. The same caution shows up in system design mistakes to avoid, and it’s the one I see most often on this prompt.

Narrate both paths. A create request hits an app server, which validates the URL. For a generated code, it takes the next ID from its local block, optionally scrambles it, encodes it, and writes the record. For a custom alias, it tries to write that key and handles a conflict. It can put the new record in the cache, or let the first redirect fill it. Return the short URL.

A redirect hits any app server, which asks the cache for that code. On a hit, it returns the 302 and enqueues a click event. On a miss, it reads the store, fills the cache, and does the same. If the record is missing or expired, return 404. If you are getting hammered with made-up codes, cache that negative result for a short time.

Caching is doing the heavy lifting. This is cache-aside: the app owns the lookup, the cache is a speed layer, and a miss falls through to the store. A time-to-live is enough for a first pass, and you can evict on edit or delete. The caching strategies post covers the patterns and failure modes in more detail. The failure mode I’d raise myself is a hot key: one link goes viral, and a single cache entry (or shard) takes most of the peak reads. I’d mention a tiny in-process cache on the app servers for a few seconds, replicating that key, and keeping click increments off the redirect path.

For the store, shard by code. The code is already in the request, so you can route without a secondary lookup. Replication gives you read capacity and failover. A new link may take a moment to appear in another region, which matches the consistency choice we made early. If they insist a brand-new short URL must work worldwide immediately, you’d pay for tighter replication or for writing to more than one region on create.

/images/posts/design-a-url-shortener-system-design/request-flow.jpg Talk as you draw: one write path, one redirect path, cache in front of the store. Leave room to zoom in on a hot key later.

Analytics can stay modest. Every redirect publishes a small event onto a queue, and workers batch-write counts into a separate store. A redirect that waits on analytics is a redirect you’ve made fragile.

Expiry is a sweep, not a thought in the hot path. The redirect handler can reject an expired record when it sees one, and a background job archives old rows. Mention takedowns too: a flag on the record, a cached rejection, and a way to disable a code without waiting for TTL.

Follow-up questions interviewers actually ask

They usually poke the design in the last ten minutes instead of starting a second problem. Short spoken answers you can practice, all illustrative:

“What if a custom alias is already taken?” “The write is a compare-and-set on that key. If it fails, I return a conflict and ask the user to pick another alias.”

“How do you stop people from enumerating codes and scraping destinations?” “If we used raw sequential IDs, that’s easy to do, which is why I’d scramble them. I’d also rate-limit lookups and keep extra metadata off the public redirect path.”

“A link is on the front page of a news site. What breaks first?” “The cache key for that code, then maybe the shard that owns it. I’d serve it from a short in-process cache on the app servers, and keep click events on the queue.”

“Does the same long URL always get the same short code?” “Not in the ID-block design. Each create mints a new code, unless we add an index on the long URL and look it up first. I’d ask whether you want that. It saves storage, but then two users share a code, which gets awkward if one of them wants to expire it.”

“How do you handle a data-center outage?” “App servers and cache are easy to run in more than one place. The harder part is the store and the ID service. I’d run the ID service redundantly, give servers large enough blocks to ride out a short outage, and keep a store replica in a second region. During a failover, a few very new links might 404 until the replica is promoted, which is the consistency trade we already made.”

This prompt also sits on most “common questions” lists, including top FAANG system design questions.

Practice the talking version

A worked design on a blog is the easy half. In the room you still have to hear yourself ask the scoping questions, explain why you picked 302, and keep going when someone says “why not just use one Postgres and a bigger cache?”

OfferBull is an AI mock interview app for iOS and Android. A voice interviewer asks questions aloud. You answer by speaking. Paste a job description or upload a resume for tailored questions. Follow-ups based on what you said and what’s on the resume. While you practice, you get answer suggestions and STAR structures. English and Chinese. It’s for rehearsal before a design interview, not a helper during one.

Start an AI mock interview

FAQ

How long should a short code be? For an interview, walk the math. Base62 with 7 characters is about 3.5 trillion codes, which is plenty at 100 million new links a month. 6 characters can work too, with less headroom. Pick one and say why.

Is hashing better than a counter? It’s simpler to start with, and it can make the same destination reuse a code. You then have to handle collisions and retries. A counter or ID-block scheme avoids collisions and shifts the problem to allocation and guessability. I’d pick ID blocks unless the interviewer wants reuse-by-destination.

Do I have to design analytics? Ask. If click counts are in scope, a queue plus a separate store is enough. If they said analytics is out, don’t sneak in a dashboard to look thorough.

What if my interviewer wants a different scale? Redo the three or four numbers that change a decision, out loud. 10 million links a month might fit on one primary with a cache. A billion a month makes sharding and the ID service more central.


Practice This Out Loud

Tonight, if you can: set a 45-minute timer, close the notes, and talk through this prompt from requirements to one deep dive and one failure mode. Record it on your phone. On playback, check two things only. Did you pick a redirect type and an ID scheme with reasons? Did you get to a hot-key or outage discussion before the timer ended? Then run the same prompt in a voice mock that pushes back with follow-ups, and close the app before any real interview. → Practice Now


Take Control of Your Career Path: