"Design a URL shortener" sounds like one function: take a long URL, return seven characters. A weak answer keeps a counter, turns it into base62, stores the pair in a map and stops. That answer has no reply when two users ask for the alias launch at the same moment, when many redirects add to one click count at once, or when someone shortens javascript:alert(1).
The interviewer is checking whether you can turn that one function into a few classes with clear jobs. How is a code made, and what happens when the rule for making codes changes? Who makes sure a code is free, and in how many steps? What does a code answer after its link expires? What stops two threads from both winning one alias, or from losing a click between them?
This article walks through the question the way a 45 minute interview goes. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.
This is the version that runs inside one process, with everything in memory. Running a shortener for millions of users, with databases, caches, sharding and ID generation across machines, is the URL shortener breakdown in the System Design course.
Ask before you design
The question is vague on purpose. Each question below changes the code, and the right-hand column says how.
| Question | What we assume | What it changes |
|---|---|---|
| How long is a code, and from which characters? | 7 characters from 0-9, a-z and A-Z (base62), so about 3.5 trillion codes | A shared alphabet, Base62, and a code length |
| May someone guess the next link? | No. A link can point at a private document | Random codes by default, a counter only as the other option |
| Can users choose their own code? | Yes: 4 to 30 letters, digits or hyphens, and not a word the site uses for its own pages | AliasPolicy, and a claim two users can race for |
| What if the same URL is shortened twice? | The same user with the same request gets the same link. Another user gets their own | A reuse map keyed by owner, URL and lifetime |
| Do links expire? | Optionally, after a lifetime of up to 3650 days | An expiry time on each link, and a Clock passed in |
| Can an expired code point somewhere new? | Never | Expired links stay in the map |
| What do we count? | Clicks per link, exactly | A counter on each link that many threads add to |
| Which long URLs do we refuse? | Anything but http and https, a name before @, our own host, and blocked hosts | TargetUrlPolicy |
| What happens to a reported link? | A moderator disables it and can block its host | disable and blockHost |
| How many threads? | Many redirects and many shorten requests at once | Thread-safe maps and counters, and no lock held for a whole request |
The second question matters most. A counter is the simplest code rule and never repeats itself, but it hands out 0000001, 0000002, 0000003, and anyone who sees one link can visit the links around it. The answer decides the code rule, and the code rule decides whether a new code can collide with one already taken.
Requirements
Functional:
- A user gives a long URL and gets a link with a 7-character code. A URL that is not http or https, that points at our own host, or that points at a blocked host is refused.
- A user may choose the code instead: an alias of 4 to 30 letters, digits or hyphens that is not reserved and not taken. If two users claim one alias at the same moment, exactly one gets it.
- The same user sending the same request again, with or without an alias, gets the same live link back. If that link was disabled, the request is refused. Another user gets their own link, with its own click count.
- A link may have a lifetime. From the moment it ends, the code answers "expired", and the code never points anywhere else.
- A redirect for a live code answers 302 with the long URL and counts one click. An unknown code answers 404, and an expired or disabled one answers 410. The count stays exact when many redirects run at once.
- A moderator can disable a link and block a host.
Out of scope: sign-in and accounts, changing where a link points, deleting links, click reports by day or country, and custom domains. We come back to these at the end, as follow-ups.
Everything lives in memory, as is normal for a low-level design interview. Keeping links after a restart is a storage question, and the System Design article covers it.
What the code itself must handle:
- Many threads at once.
shortenandresolveare called from many server threads together, often for the same code. - A rule that changes. The way codes are made should change without editing the class that stores them.
- Testable. Expiry depends on time, and random codes depend on a random source, so a test must control both.
Finding the classes
We read the requirements and pick out the nouns. Most become classes. Some do not, and dropping them is part of the design.
One dropped noun needs a decision of its own. A custom alias looks like a different thing from a generated code, and a first design often gives it a class and a map of its own.
Do custom aliases get their own map?
One map for generated codes, another for aliases
This keeps the two kinds apart, and a report can list aliases easily. But the code diwali7 might be made by the generator after a user took it as an alias, and then one code points at two URLs. Every claim would have to check both maps, and checking two maps cannot be one atomic step.
One map for both, keyed by the codeOur pick
An alias is a code the user picked. links holds every code in use, so a generated code and an alias can never clash, and every claim is one putIfAbsent on one map. The link's owner and its other fields say everything a report needs.
Data or behaviour?
A request to shorten is data that never changes once it is made, so it is a record, Java's type for data with fixed fields and a generated equals. So is the answer to a redirect. A short link is not: its click count goes up and it can be disabled. That makes ShortLink a class, and the class keeps those two changes package-private, so only the shortener can make them.
The class diagram
The classes fall into three groups:
- Data:
ShortenRequest,ReuseKey,Redirect,RedirectStatusandRefusalReason. These are records and enums. - The core:
UrlShortenerandShortLink. These hold the state that changes (which codes are taken, how often each was clicked) and keep it correct under many threads. - Rules:
CodeGeneratorwith its two implementations,TargetUrlPolicyandAliasPolicy. The shortener asks them and never decides these things itself.
The rest of the article builds these one at a time.
Building it
The request and the link
A request carries an owner, a long URL, and two optional parts: an alias and a lifetime.
public record ShortenRequest(String ownerId, String longUrl, Optional<String> alias, Optional<Duration> lifetime) { public ShortenRequest { Objects.requireNonNull(ownerId, "ownerId"); Objects.requireNonNull(longUrl, "longUrl"); Objects.requireNonNull(alias, "alias"); Objects.requireNonNull(lifetime, "lifetime"); if (ownerId.isBlank()) { throw new IllegalArgumentException("ownerId must not be blank"); } } public static ShortenRequest of(String ownerId, String longUrl) { return new ShortenRequest(ownerId, longUrl, Optional.empty(), Optional.empty()); } public ShortenRequest withAlias(String newAlias) { return new ShortenRequest(ownerId, longUrl, Optional.of(newAlias), lifetime); } public ShortenRequest withLifetime(Duration newLifetime) { return new ShortenRequest(ownerId, longUrl, alias, Optional.of(newLifetime)); }of makes the plain request, and withAlias and withLifetime return a new request with one more part. The record never changes, so a request can be passed between threads safely. A null or a blank owner throws at once, because those are mistakes in the calling code, not choices a user made.
The link holds what was asked for and what has happened since:
public final class ShortLink { private final String code; private final String targetUrl; private final String ownerId; private final Instant createdAt; private final Instant expiresAt; private final LongAdder clicks = new LongAdder(); private volatile String disabledReason;Two fields change after the link is made. clicks is a LongAdder, which we come back to with the threads. disabledReason is volatile, so that once a moderator disables a link, every server thread sees it on its next read.
Checking the long URL
Every long URL passes through TargetUrlPolicy.check before anything else happens. It refuses, or it returns the URL with its scheme and host in lower case:
public String check(String url) { Objects.requireNonNull(url, "url"); if (url.isBlank() || url.length() > MAX_LENGTH) { throw invalid("A link must be 1 to " + MAX_LENGTH + " characters long"); } URI uri; try { uri = new URI(url); } catch (URISyntaxException e) { throw invalid("This is not a valid web address"); } String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT); if (!scheme.equals("http") && !scheme.equals("https")) { throw invalid("Only http and https links can be shortened"); } if (uri.getRawUserInfo() != null) { throw invalid("A name before @ in the host hides the real site"); } String host = uri.getHost() == null ? "" : normaliseHost(uri.getHost()); if (host.isEmpty()) { throw invalid("The link has no host"); } if (isSameOrSubdomain(host, ownHost)) { throw invalid("A link to " + ownHost + " itself would redirect to us"); } for (String blocked : blockedHosts) { if (isSameOrSubdomain(host, blocked)) { throw new ShortenRefusedException(RefusalReason.BLOCKED_HOST, "Links to " + blocked + " are blocked"); } } return scheme + "://" + host + (uri.getPort() == -1 ? "" : ":" + uri.getPort()) + uri.getRawPath() + (uri.getRawQuery() == null ? "" : "?" + uri.getRawQuery()) + (uri.getRawFragment() == null ? "" : "#" + uri.getRawFragment()); }Four rules matter here, and each one blocks a real attack or mistake:
- Only http and https (line 49). A link to
javascript:alert(1)or adata:URL would run code in the visitor's browser under our name. - No name before
@(line 52). Inhttps://bank.example@phish.example/login, the host isphish.example, andbank.exampleis only a user name. The link reads like the bank's and lands on the phishing site. - Not our own host (line 59). A short link to another short link makes a chain, and two links pointing at each other make a loop.
- Not a blocked host (line 63), which also covers every subdomain of it. The set is concurrent, so a moderator can add to it while requests are being checked.
Lower-casing the scheme and host means https://Docs.Example.com/guide and https://docs.example.com/guide are the same URL when we look for an earlier link. The path keeps its case, because servers treat /Guide and /guide as different pages.
A refusal is a ShortenRefusedException with a RefusalReason. Its message is written for the person who typed the URL. A null is a NullPointerException instead, because no person can type a null. Every class in the project uses this same split.
Making a code
The first rule that changes is how a code is made. Two answers are both reasonable, and they fail in different ways.
/** Makes a candidate short code. It knows nothing about which codes are taken. */public interface CodeGenerator { String next();}The interface only makes a candidate. It does not know which codes are taken, and the next section says why.
The counter turns 1, 2, 3 into base62 and pads to seven characters:
@Override public String next() { String digits = Base62.encode(counter.getAndIncrement()); return "0".repeat(Math.max(0, MIN_LENGTH - digits.length())) + digits; }The random rule picks seven characters from the same alphabet:
// synchronized because the RandomGenerator passed in may not be thread-safe @Override public synchronized String next() { StringBuilder code = new StringBuilder(length); for (int i = 0; i < length; i++) { code.append(Base62.ALPHABET.charAt(random.nextInt(Base62.ALPHABET.length()))); } return code.toString(); }It takes a RandomGenerator in its constructor. Production passes a SecureRandom, so the next code cannot be worked out from the last one. The demo passes a SplittableRandom with a fixed seed, so its output is the same on every run. SplittableRandom is not safe to share between threads, so next() is synchronized. The lock is held for seven calls to nextInt, which takes far less time than the rest of a request.
Counter codes or random codes?
A counter in base62
This is the shortest code, and it never repeats itself. But the codes come in order, so a link to a private document sits next to one anybody can guess, and a competitor can count our links by shortening one a day. A user can also claim the next few codes as aliases before the counter reaches them, and five aliases in a row make the next shorten fail, which that user can repeat whenever they like. Passing the counter through a keyed shuffle of the whole code space hides the order, and the System Design article does that at scale.
A hash of the long URL, cut to 7 characters
The same URL always gives the same code, which looks like free reuse. But two users shortening one URL then share a link and a click count, which breaks requirement 3. Two different URLs can also give the same 7-character prefix, so the design still needs a retry, and the retried code no longer matches the hash.
Random codes from SecureRandom, retried on a collisionOur pick
Nobody can guess a code or count our links. With 3.5 trillion codes, a collision is rare until the map holds billions of links, and one retry handles it. The cost is the retry loop, and a test needs a way to force a collision, which a seeded RandomGenerator or a scripted CodeGenerator gives. We keep CounterCodeGenerator in the project, because a test or a small internal tool may prefer readable codes.
Storing a new code
A candidate becomes a code only when the shortener claims it:
private ShortLink storeWithNewCode(String url, String ownerId, Instant now, Optional<Instant> expiresAt) { for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) { String code = codes.next(); if (aliasPolicy.isReserved(code)) { continue; } ShortLink link = new ShortLink(code, url, ownerId, now, expiresAt); if (links.putIfAbsent(code, link) == null) { return link; } } throw new IllegalStateException("no free code after " + MAX_ATTEMPTS + " attempts"); }The loop asks for a candidate, skips it if it is a reserved word, and claims it with links.putIfAbsent. putIfAbsent stores the link only if the code is free, and returns null when it did. It checks and stores in one atomic step, so two threads can never both claim one code. After five candidates that were reserved or taken, the shortener throws an IllegalStateException. With random codes, that means the code space is nearly full, which is an operator's problem and not a refusal for the user.
The reserved-word check matters even for random codes. A reserved word such as privacy is seven letters long, and a random code could come out as privacy and hide the site's own page.
Who checks that a new code is free?
The generator, before it returns a code
The generator would need the map, so every new rule would repeat the check. Worse, a generator that checks and returns leaves a gap: between its check and the store, another thread can take the code. The check and the store would sit in two classes.
UrlShortener, with putIfAbsent on the links mapOur pick
The check and the claim happen in one step, in the class that owns the map. A generator stays a pure "make me a candidate" rule, ten lines long. This also covers a case that is easy to miss: a counter can produce 0000002 after a user took 0000002 as an alias, and the loop simply moves on to 0000003.
Custom aliases
A custom alias first passes AliasPolicy:
public void check(String alias) { Objects.requireNonNull(alias, "alias"); if (!SHAPE.matcher(alias).matches()) { throw new ShortenRefusedException(RefusalReason.INVALID_ALIAS, "An alias is 4 to 30 letters, digits or hyphens: \"" + alias + "\""); } if (isReserved(alias)) { throw new ShortenRefusedException(RefusalReason.RESERVED_ALIAS, "\"" + alias + "\" is kept for the site's own pages"); } } public boolean isReserved(String word) { return reservedWords.contains(word.toLowerCase(Locale.ROOT)); }The shape is 4 to 30 letters, digits or hyphens, so an alias never contains a /, a ? or a space that would break the URL. The reserved words are compared in lower case, so Admin is refused as well as admin. Aliases themselves keep their case, like generated codes, so Diwali-Sale and diwali-sale are two different aliases.
Then the shortener claims it, with the same putIfAbsent as a generated code:
private ShortLink claimAlias(ShortenRequest request, String url, Instant now, Optional<Instant> expiresAt) { String alias = request.alias().orElseThrow(); aliasPolicy.check(alias); ShortLink link = new ShortLink(alias, url, request.ownerId(), now, expiresAt); ShortLink holder = links.putIfAbsent(alias, link); if (holder == null) { return link; } boolean sameRequest = holder.ownerId().equals(request.ownerId()) && holder.targetUrl().equals(url) && holder.expiresAt().equals(request.lifetime().map(holder.createdAt()::plus)); if (sameRequest && holder.isDisabled()) { throw new ShortenRefusedException(RefusalReason.LINK_DISABLED, "Your earlier link with this alias was disabled"); } if (sameRequest && !holder.isExpiredAt(now)) { return holder; } throw new ShortenRefusedException(RefusalReason.ALIAS_TAKEN, "\"" + alias + "\" is already taken"); }The policy runs first, so a refused alias never touches the map. If putIfAbsent finds the code taken, it returns the link that holds it. Lines 95 to 97 ask whether the holder came from the same request: the same user, the same URL and the same lifetime. If it did and it was disabled, the user hears LINK_DISABLED. If it did and it has not expired, this request is a retry, and the user gets their link back. Anyone else hears "already taken", and the first owner's link stays exactly as it was. There is no second try with another code, because the user chose this exact code.
The same URL twice
A user who double-clicks "Shorten", or whose browser retries, should not end up with two links that split one campaign's clicks. Here is shorten in full:
public ShortLink shorten(ShortenRequest request) { Objects.requireNonNull(request, "request"); String url = urlPolicy.check(request.longUrl()); Instant now = clock.instant(); Optional<Instant> expiresAt = expiryFor(request.lifetime(), now); if (request.alias().isPresent()) { return claimAlias(request, url, now, expiresAt); } ReuseKey key = new ReuseKey(request.ownerId(), url, request.lifetime()); return reusable.compute(key, (sameRequest, earlier) -> reuseOrCreate(earlier, url, request.ownerId(), now, expiresAt)); }A request without an alias builds a ReuseKey from the owner, the cleaned-up URL and the lifetime. reusable.compute runs reuseOrCreate for that key while holding the map's lock for it:
private ShortLink reuseOrCreate(ShortLink earlier, String url, String ownerId, Instant now, Optional<Instant> expiresAt) { if (earlier != null && earlier.isDisabled()) { throw new ShortenRefusedException(RefusalReason.LINK_DISABLED, "Your earlier link to this URL was disabled"); } if (earlier != null && !earlier.isExpiredAt(now)) { return earlier; } return storeWithNewCode(url, ownerId, now, expiresAt); }If the earlier link was disabled, the request is refused with LINK_DISABLED, so repeating the exact request does not bring the link back. A changed lifetime, an added alias or a slightly different spelling of the URL is a new request and still gets a new code. Stopping those is the job of blockHost. If the earlier link has not expired, the request gets it back. Otherwise, storeWithNewCode makes a new one, and compute stores it under the key. Two copies of one request arriving at once get one link, because the second compute waits for the first and then sees its link.
A request repeated days later also gets the earlier link, with its first end time. A seven-day link asked for again on day six has one day left. If that surprises users, the change is a retry window: reuse only a link created in the last few minutes.
While compute runs, it can block updates to other keys that share its slot in the table, so the function must be short. Ours makes up to five candidates and calls putIfAbsent on a different map, which takes microseconds.
What does the same URL shortened twice get?
Always a new link
This is the simplest code. But a retried request makes a second link, and the user's clicks end up split between two codes they cannot tell apart.
One link per URL, shared by everyone
This saves codes. But Asha's campaign and Ravi's newsletter would share one click count, and disabling Ravi's link for abuse would break Asha's.
The same link for the same user's same request, a new link for anyone elseOur pick
The key is owner, URL and lifetime, so a retry is harmless and each user keeps their own count. A request with a different lifetime is a different request and gets its own link. If the earlier link has expired, the request gets a fresh code, and if it was disabled, the request is refused. Requests with an alias skip this map, because the alias itself finds the earlier link.
Expiry
A link with a lifetime stores the moment it ends. The shortener reads the time from a Clock it is given, so a test moves the clock seven days forward in one line:
public boolean isExpiredAt(Instant now) { return expiresAt != null && !now.isBefore(expiresAt); } public boolean isLiveAt(Instant now) { return !isDisabled() && !isExpiredAt(now); }At exactly expiresAt, the link has expired: !now.isBefore(expiresAt) is true from that moment on. A lifetime must be at least one second and at most 3650 days, which also keeps now.plus(lifetime) far from overflowing.
What happens to a code when its link expires?
Remove it, so the code can be given out again
Memory stays small. But the old link is still printed on posters and saved in chats. Someone else's new link would take over every one of those clicks, which turns an old sale poster into a link to a stranger's page.
Keep it taken forever, and answer 'expired'Our pick
A code means one URL for as long as the service runs. A visitor to an old link gets a clear 410 page instead of somebody else's site. The cost is memory: expired links stay in the map. A follow-up can drop the long URL and keep only the code as a marker, which saves most of it.
Redirects
resolve turns a code into an answer for the web layer:
public Redirect resolve(String code) { Objects.requireNonNull(code, "code"); ShortLink link = links.get(code); if (link == null) { return Redirect.refused(RedirectStatus.NOT_FOUND); } if (link.isDisabled()) { return Redirect.refused(RedirectStatus.DISABLED); } if (link.isExpiredAt(clock.instant())) { return Redirect.refused(RedirectStatus.EXPIRED); } link.recordClick(); return Redirect.to(link.targetUrl()); }The order of the checks is deliberate. Disabled comes before expired, so a phishing link that has also expired still shows the "disabled" page. The click is counted only after both checks pass, so an expired or disabled link never gains clicks. resolve takes no lock at all: links.get is safe on a ConcurrentHashMap, disabledReason is volatile, and the counter is thread-safe.
Not finding a code is normal traffic, so resolve returns a Redirect instead of throwing. The enum carries the HTTP code:
public enum RedirectStatus { FOUND(302), NOT_FOUND(404), EXPIRED(410), DISABLED(410);301 or 302 for a live link?
301 Moved Permanently
A browser caches a 301 and stops asking us, often for as long as the browser profile lives. A link we disable then keeps working for every browser that cached it, and nothing we do can recall it. Those later clicks are never counted either.
302 FoundOur pick
A browser does not cache a 302 by default, so it asks us on every click. A disabled link stops working on the next click, and every click is counted. The cost is one request to us per click. The System Design article adds a short Cache-Control time at scale, which trades a few minutes of that for less traffic.
Many threads, one alias and one counter
Two places in this design are hit by many threads at once. Many users can claim one popular alias, such as launch, in the same millisecond. And one link shared on a busy page can get thousands of redirects a second, all adding to one count.
The alias race is settled by putIfAbsent, as above. The click race is settled by LongAdder. A plain clicks++ on a long is three steps (read, add one, write), and two threads can read the same value. A LongAdder starts with one counter. When threads collide on it, it adds more counters, up to about one per CPU core, and spreads the threads over them, so threads hitting one hot link rarely wait for each other. clicks() adds them up.
The project includes demo/RaceCheck.java. It sends 16 threads at one link, 20,000 redirects each, then runs 500 rounds in which 16 users claim the same alias at once:
16 threads redirect one link 20000 times each redirects sent 320000, clicks counted 320000 16 users claim the same alias at once, 500 rounds rounds with more than one winner 0, claims refused 7500
Every one of the 320,000 redirects was counted. In each of the 500 rounds, one user won and 15 were refused, which is 7,500 refusals. We ran the same program with LongAdder replaced by a plain long, and with putIfAbsent replaced by containsKey followed by put. Every run lost a large share of the clicks, often more than a third. Most runs also had a round or two with two winners, and some had none, because the gap between the two calls is short. The exact numbers change from run to run and from machine to machine.
How are clicks counted when redirects run at once?
A synchronized method on the link
This is correct and easy to explain. But every redirect for a hot link waits for the one before it, so one viral link queues up server threads.
An AtomicLong
This is correct with no lock. But every thread updates one shared memory location, so under heavy load on one link the threads queue for it.
A LongAdder per linkOur pick
Under contention, threads add to separate cells, so a hot link scales with the number of CPU cores instead of queuing on one value. sum() is exact once the redirects stop. While they run, a reading can miss clicks that are still being added, which is fine for a count shown on a page. Once threads contend, a LongAdder uses more memory than an AtomicLong.
How do two claims on one alias get settled?
containsKey, then put
This reads naturally. But another thread can claim the alias between the two calls, and then the second put overwrites the first owner's link while telling both that they won.
One lock around the whole shorten method
This is correct. But every shorten request in the service then waits for every other, including requests for different aliases and generated codes.
putIfAbsent on the links mapOur pick
The check and the store are one atomic step, on the one map that holds every code. Claims for different aliases do not wait for each other, and the loser's link is never stored.
Disabling a link
A moderator acts in two steps. disable stops one link, and blockHost on TargetUrlPolicy stops new links to the host:
public boolean disable(String code, String reason) { Objects.requireNonNull(code, "code"); Objects.requireNonNull(reason, "reason"); if (reason.isBlank()) { throw new IllegalArgumentException("reason must not be blank"); } ShortLink link = links.get(code); if (link == null) { return false; } link.disable(reason); return true; }disable writes the reason into the volatile field, so the next resolve on any thread answers 410. A redirect that read the field a moment before disable can still go out, so a few in-flight clicks may reach the site. The owner of a disabled link who repeats the same request is refused with LINK_DISABLED, as the section on repeated requests showed. A slightly changed request, or another user, can still shorten that URL until its host is blocked, which is why the moderator does both. Blocking a host does not touch links already made, because a host can be blocked for one bad page while other links to it are fine. Each existing link is disabled on its own.
The final design
UrlShortener is the core. It owns the links map, where every code in use lives, and the reusable map for repeated requests. It reaches the code rule, the URL rules and the alias rules only through the objects it is given, and it reads the time from a Clock.
| S.No. | The question | What we chose | Why |
|---|---|---|---|
| 1 | Do custom aliases get their own map? | One map for both, keyed by the code | A generated code and an alias can never clash. |
| 2 | Counter codes or random codes? | Random codes from SecureRandom, retried on a collision | Nobody can guess a code or count our links. |
| 3 | Who checks that a new code is free? | UrlShortener, with putIfAbsent on the links map | The check and the claim are one step. |
| 4 | What does the same URL shortened twice get? | The same link for the same user's same request, a new link for anyone else | A retry is harmless and each user keeps their own count. |
| 5 | What happens to a code when its link expires? | Keep it taken forever, and answer "expired" | An old poster never leads to a stranger's page. |
| 6 | 301 or 302 for a live link? | 302 Found | Every click is counted and a disabled link stops on the next click. |
| 7 | How are clicks counted when redirects run at once? | A LongAdder per link | Threads on one hot link rarely wait. |
| 8 | How do two claims on one alias get settled? | putIfAbsent on the links map | Exactly one claim wins, with no lock. |
Here is Asha's first request from the demo, step by step:
- The web layer calls
UrlShortener.shortenwithShortenRequest.of("asha", "https://Docs.Example.com/guide?page=2"). TargetUrlPolicy.checkaccepts the URL and returns it with the host in lower case.shortenreads the time fromclock.instant().reusable.computetakes the lock for Asha'sReuseKeyand callsreuseOrCreate, which finds no earlier link and callsstoreWithNewCode.RandomCodeGenerator.nextmakesRyNIddYunder its own short lock.AliasPolicy.isReservedsays no, andlinks.putIfAbsentclaims it.computestores the link under the key, andshortenreturns it. Her second request finds it incomputeand gets the same link.
A request with an alias takes a shorter path. AliasPolicy.check runs first, and then one links.putIfAbsent either claims the alias, finds the link from the same user's same request, or refuses with ALIAS_TAKEN. The redirect path takes no lock at all. resolve reads the link with links.get, checks the volatile disabled field and then the expiry against the clock, adds one to the link's LongAdder, and returns a 302 with the long URL.
The complete code
Here is the whole project. Click any class name to jump to its file, or use Find a file to search. Badges in the tree show what each file is: a class, an interface, an enum or a record.
package shortener; import java.time.Clock;import java.time.Duration;import java.time.Instant;import java.util.Objects;import java.util.Optional;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ConcurrentMap; import code.CodeGenerator;import exception.RefusalReason;import exception.ShortenRefusedException;import redirect.Redirect;import redirect.RedirectStatus;import validation.AliasPolicy;import validation.TargetUrlPolicy; public final class UrlShortener { static final int MAX_ATTEMPTS = 5; static final Duration MIN_LIFETIME = Duration.ofSeconds(1); static final Duration MAX_LIFETIME = Duration.ofDays(3650); private final CodeGenerator codes; private final TargetUrlPolicy urlPolicy; private final AliasPolicy aliasPolicy; private final Clock clock; // Generated codes and custom aliases share this one map, so they can never clash. private final ConcurrentMap<String, ShortLink> links = new ConcurrentHashMap<>(); private final ConcurrentMap<ReuseKey, ShortLink> reusable = new ConcurrentHashMap<>(); public UrlShortener(CodeGenerator codes, TargetUrlPolicy urlPolicy, AliasPolicy aliasPolicy, Clock clock) { this.codes = Objects.requireNonNull(codes, "codes"); this.urlPolicy = Objects.requireNonNull(urlPolicy, "urlPolicy"); this.aliasPolicy = Objects.requireNonNull(aliasPolicy, "aliasPolicy"); this.clock = Objects.requireNonNull(clock, "clock"); } public ShortLink shorten(ShortenRequest request) { Objects.requireNonNull(request, "request"); String url = urlPolicy.check(request.longUrl()); Instant now = clock.instant(); Optional<Instant> expiresAt = expiryFor(request.lifetime(), now); if (request.alias().isPresent()) { return claimAlias(request, url, now, expiresAt); } ReuseKey key = new ReuseKey(request.ownerId(), url, request.lifetime()); return reusable.compute(key, (sameRequest, earlier) -> reuseOrCreate(earlier, url, request.ownerId(), now, expiresAt)); } public Redirect resolve(String code) { Objects.requireNonNull(code, "code"); ShortLink link = links.get(code); if (link == null) { return Redirect.refused(RedirectStatus.NOT_FOUND); } if (link.isDisabled()) { return Redirect.refused(RedirectStatus.DISABLED); } if (link.isExpiredAt(clock.instant())) { return Redirect.refused(RedirectStatus.EXPIRED); } link.recordClick(); return Redirect.to(link.targetUrl()); } public boolean disable(String code, String reason) { Objects.requireNonNull(code, "code"); Objects.requireNonNull(reason, "reason"); if (reason.isBlank()) { throw new IllegalArgumentException("reason must not be blank"); } ShortLink link = links.get(code); if (link == null) { return false; } link.disable(reason); return true; } public Optional<ShortLink> find(String code) { Objects.requireNonNull(code, "code"); return Optional.ofNullable(links.get(code)); } private ShortLink claimAlias(ShortenRequest request, String url, Instant now, Optional<Instant> expiresAt) { String alias = request.alias().orElseThrow(); aliasPolicy.check(alias); ShortLink link = new ShortLink(alias, url, request.ownerId(), now, expiresAt); ShortLink holder = links.putIfAbsent(alias, link); if (holder == null) { return link; } boolean sameRequest = holder.ownerId().equals(request.ownerId()) && holder.targetUrl().equals(url) && holder.expiresAt().equals(request.lifetime().map(holder.createdAt()::plus)); if (sameRequest && holder.isDisabled()) { throw new ShortenRefusedException(RefusalReason.LINK_DISABLED, "Your earlier link with this alias was disabled"); } if (sameRequest && !holder.isExpiredAt(now)) { return holder; } throw new ShortenRefusedException(RefusalReason.ALIAS_TAKEN, "\"" + alias + "\" is already taken"); } private ShortLink reuseOrCreate(ShortLink earlier, String url, String ownerId, Instant now, Optional<Instant> expiresAt) { if (earlier != null && earlier.isDisabled()) { throw new ShortenRefusedException(RefusalReason.LINK_DISABLED, "Your earlier link to this URL was disabled"); } if (earlier != null && !earlier.isExpiredAt(now)) { return earlier; } return storeWithNewCode(url, ownerId, now, expiresAt); } private ShortLink storeWithNewCode(String url, String ownerId, Instant now, Optional<Instant> expiresAt) { for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) { String code = codes.next(); if (aliasPolicy.isReserved(code)) { continue; } ShortLink link = new ShortLink(code, url, ownerId, now, expiresAt); if (links.putIfAbsent(code, link) == null) { return link; } } throw new IllegalStateException("no free code after " + MAX_ATTEMPTS + " attempts"); } private static Optional<Instant> expiryFor(Optional<Duration> lifetime, Instant now) { if (lifetime.isEmpty()) { return Optional.empty(); } Duration chosen = lifetime.get(); if (chosen.compareTo(MIN_LIFETIME) < 0 || chosen.compareTo(MAX_LIFETIME) > 0) { throw new ShortenRefusedException(RefusalReason.INVALID_LIFETIME, "A link can live from one second to " + MAX_LIFETIME.toDays() + " days"); } return Optional.of(now.plus(chosen)); }}demo/Main.java follows Asha and Ravi through a week. They shorten links and claim aliases, some requests are refused, browsers follow the links, a sale link expires, and a moderator steps in. At the end, the same requests run against a shortener with a counter:
-- Shortening asha https://Docs.Example.com/guide?page=2 -> s.example/RyNIddY asha https://docs.example.com/guide?page=2 -> s.example/RyNIddY ravi https://docs.example.com/guide?page=2 -> s.example/ZK4jX3c asha https://shop.example/diwali as diwali-sale -> s.example/diwali-sale ravi https://shop.example/other as diwali-sale -> refused, ALIAS_TAKEN: "diwali-sale" is already taken ravi https://shop.example/other as Admin -> refused, RESERVED_ALIAS: "Admin" is kept for the site's own pages ravi https://shop.example/other as hi! -> refused, INVALID_ALIAS: An alias is 4 to 30 letters, digits or hyphens: "hi!" ravi javascript:alert(1) -> refused, INVALID_URL: Only http and https links can be shortened ravi https://s.example/RyNIddY -> refused, INVALID_URL: A link to s.example itself would redirect to us ravi https://bank.example@phish.example/login -> refused, INVALID_URL: A name before @ in the host hides the real site -- Redirects GET /RyNIddY -> 302 FOUND https://docs.example.com/guide?page=2 GET /RyNIddY -> 302 FOUND https://docs.example.com/guide?page=2 GET /RyNIddY -> 302 FOUND https://docs.example.com/guide?page=2 GET /diwali-sale -> 302 FOUND https://shop.example/diwali GET /nosuchcode -> 404 NOT_FOUND RyNIddY clicks 3, ZK4jX3c clicks 0 -- Seven days later GET /diwali-sale -> 410 EXPIRED ravi https://shop.example/other as diwali-sale -> refused, ALIAS_TAKEN: "diwali-sale" is already taken diwali-sale still holds https://shop.example/diwali for asha -- A moderator steps in ravi https://login.phish.example/verify -> s.example/Qxoxmgc GET /Qxoxmgc -> 302 FOUND https://login.phish.example/verify GET /Qxoxmgc -> 410 DISABLED Qxoxmgc clicks 1, disabled: reported as phishing ravi https://login.phish.example/verify -> refused, BLOCKED_HOST: Links to phish.example are blocked -- The same requests with a counter instead asha https://docs.example.com/guide?page=2 -> s.example/0000001 ravi https://docs.example.com/guide?page=2 -> s.example/0000002 ravi https://shop.example/other -> s.example/0000003
Notice three things in the output. Asha's two requests for the docs page, the first with capital letters in the host, both got RyNIddY, while Ravi got his own ZK4jX3c, and only Asha's link counted the three clicks. Seven days later, diwali-sale answered 410 and Ravi still could not claim it, because it still holds Asha's URL. And after the moderator stepped in, the phishing link kept its one click from before, and Ravi's next try was refused as BLOCKED_HOST.
Follow-up questions
After the core design, the interviewer adds a requirement to see how the design bends. For each one, say which class changes and which do not.
| The interviewer asks | What changes | What does not |
|---|---|---|
| "Let owners change where a link points." | A new retarget method that checks the new URL with TargetUrlPolicy. targetUrl becomes a volatile field with a setter only the shortener can call, and retarget removes the old ReuseKey from reusable. | The links map, the generators and resolve. |
| "Show clicks per day and per country." | resolve hands a click event to a queue, and a separate worker builds the reports. | The LongAdder total, the maps and the code rules. |
| "Let a user delete a link." | A delete that marks the link as gone, so the code answers 410 and stays taken, the same as expiry. | The code space, which still never reuses a code. |
| "Expired links use too much memory." | A cleanup task replaces old links with a small marker that holds only the code. | resolve's answers and the rule that codes are never reused. |
| "Check every URL against an unsafe-sites service." | TargetUrlPolicy gains a call to that service, probably behind an interface with a timeout. This is where a chain of rules starts to fit. | UrlShortener, apart from waiting a little longer. |
| "Customers bring their own domain." | The links key becomes the domain plus the code, and each domain has its own reserved words. TargetUrlPolicy refuses links to every customer domain, not only ours. | The generators and the counters. |
| "Make codes shorter for a few premium users." | A third CodeGenerator, or a length passed per request. | The retry loop and the map. |
| "Restore everything after a restart." | A repository interface behind the two maps, written to on each claim. | The rules, and the order of the steps in shorten. |
Most rows add a class or a method beside the core, and the rules for codes and URLs stay where they are. The two that change the map's key or add storage do touch UrlShortener.
What the interviewer looks for
Mid-level
A mid-level candidate shows a working shorten and resolve, a base62 encoder, a map from code to URL, and a check that a custom alias is not taken. They mention that many threads will call it, even if the check and the store are still two steps.
Senior
A senior candidate puts the code rule behind an interface and compares a counter with random codes. They claim codes and aliases with one atomic putIfAbsent on one map, count clicks without losing any, refuse dangerous URLs, and explain why an expired code is never reused. They pass in a Clock and a random source so tests can control both.
Staff+
A staff candidate leads with the trade-offs: guessable codes against collisions, 301 against 302, and memory against never reusing a code. They say what the design does not handle, such as a few clicks reaching a site just after it is disabled, and what changes when the maps move to a database across many machines.
Common mistakes
- A plain counter for public links. Anyone who sees one code can walk through every other link, including private ones.
- Checking with
containsKey, then callingput. Two users can both win one alias, and the second silently replaces the first. clicks++on a shared field. Two redirects read the same number and one click disappears.- Separate maps for aliases and generated codes. A generated code can land on an alias someone already took.
- Reusing a code after its link expires. Every old copy of that link now leads somewhere its author never chose.
- Shortening any string. A
javascript:URL, a name before@, or a link to the shortener itself turns the service into a tool for attacks. - Calling
Instant.now()inside the link. A test of a seven-day expiry then needs seven days.
Summary
- Ask whether codes may be guessable before choosing how to make them.
- Put the code rule behind
CodeGenerator, and keep the "is it free?" check in the shortener. - Keep every code, generated or chosen, in one map, and claim with
putIfAbsent. - Give the same user the same link for the same request, and everyone else their own.
- Never give out a code twice, even after its link expires.
- Answer with 302, count clicks with a
LongAdder, and disable a link with avolatilefield. - Check every long URL before storing it.