Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

Design a URL shortener in Java and Spring Boot that handles 1,000 new links per second and 100,000 redirects per second, with custom aliases and expiry.

The write path creates codes from pre-allocated id blocks or random codes, and custom aliases go into the same code column, so one unique index protects both. Each link row holds the code, long URL, owner, creation time and expiry, in a store partitioned by code. Redirects, 100 times more frequent than writes, are served from a local Caffeine cache and Redis with a 301 or 302 depending on whether we need every click; expiry is checked on read and cleaned up later, click analytics go to Kafka asynchronously, and URL scanning plus per-user rate limits keep abuse out.

Background to this question

A URL shortener is a classic design question because it has a very clear shape: a small, write-occasionally data set and a huge, latency-sensitive read path. At 1,000 new links and 100,000 redirects per second, the design must make the redirect almost free while keeping writes correct, handle custom aliases and expiry without special cases everywhere, and avoid letting analytics or abuse slow the core feature down. In this answer, we will size the problem, design the write path and the data model, build a two-level cache for redirects, choose between 301 and 302, handle expiry, move analytics off the critical path, and add abuse controls.

1Sizing the Problem

Numbers first, because they decide what matters. 1,000 new links per second is about 86 million per day and over 31 billion per year. If a row takes around 300 bytes with indexes, a year of links is close to 10 TB, so the store must scale horizontally or links must expire. Redirects are 100 times more frequent than writes, which tells us that the read path is the system: anything that saves a millisecond there is worth more than any write optimisation.

Redirect traffic is also very skewed. A link in a marketing email may get millions of clicks in an hour while most links are clicked a few times. That skew is good news for caching: a small cache holds the links that most clicks are for.

2The Write Path: Codes and Custom Aliases

When a request to shorten arrives, a Spring Boot link service validates the URL, checks the caller's rate limit, and produces a code. For generated codes, each instance reserves a block of ids, say 10,000 at a time, from a central counter and encodes each id, shuffled, in base62. With 1,000 writes per second, a block lasts several seconds per instance, so the counter is touched rarely. Random seven-character codes with a retry on duplicate are a fine alternative.

A custom alias such as /spring-sale is simply a code chosen by the user. It goes into the same code column and the same unique index, so an alias can never collide with a generated code or another alias: the insert either succeeds or fails with a duplicate key error, which we turn into a clear 409 Conflict. We also reserve words such as api, login and admin, and keep aliases to a safe character set.

SQL
CREATE TABLE links (
code varchar(32) PRIMARY KEY, -- generated code or custom alias, unique by definition
long_url text NOT NULL,
owner_id bigint NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz -- null: never expires
);

Because the code is the primary key, every lookup on the redirect path is a single key read. That is why the store can be a key-value database such as DynamoDB or Cassandra, or PostgreSQL partitioned by hash of the code across several nodes. Either way, data is partitioned by code, which spreads both writes and reads evenly. A secondary index on owner_id serves the user's my-links page; it is used far less and can live in a separate store if needed.

3The Redirect Path: Two Cache Layers

A redirect looks up the code and returns a response whose Location header is the long URL. At 100,000 per second we do not want each one to reach the database. So the lookup goes through two caches: a local Caffeine cache in each instance, an in-memory map with size limits and expiry, and then a shared Redis cache, before the database.

The local cache answers the hottest links in microseconds with no network call at all. With 20 instances, each holding the top 100,000 links for 60 seconds, most redirects never leave the process. Redis catches the next tier, and the database sees only misses. We also cache not-found results for a short time, so someone hammering random codes does not hit the database every time.

Java
@GetMapping("/{code}")
ResponseEntity<Void> redirect(@PathVariable String code) {
Link link = links.find(code); // Caffeine, then Redis, then the database
if (link == null || link.isExpiredAt(clock.instant())) {
return ResponseEntity.notFound().build(); // 404
}
clicks.publish(code, request); // async Kafka send, never awaited
return ResponseEntity.status(HttpStatus.FOUND) // 302: every click comes back to us
.location(URI.create(link.longUrl()))
.build();
}
Step throughA redirect with a warm cache
BrowserRedirect serviceCaffeineRedisKafka
GET /4c92ab1
get 4c92ab1
miss
GET link:4c92ab1
long URL, expiry
put for 60 s
click event, async
302 Location: long URL

8 messages in order. Play them, or step through them one at a time.

The database is not involved; the Kafka send does not delay the response.

Notice the status code. A 301 Moved Permanently tells browsers they may cache the redirect, so a returning visitor goes straight to the long URL without asking us. That saves load but makes us blind to repeat clicks, and it means we cannot change or disable the link for that browser. A 302 Found is not cached by default, so every click reaches us and is counted. Shorteners that sell analytics use 302; a pure internal shortener may prefer 301.

4Expiry: Check on Read, Clean Up Later

Expiry has two parts with different urgency. The user-visible part must be exact: a link that expired one second ago must not redirect. So the redirect path compares expires_at with the current time on every request, even for cached entries, and the cache TTL is never longer than the time left before expiry.

The storage part is not urgent. A scheduled job deletes expired rows in batches of a few thousand, oldest first, during quiet hours, so it never competes with redirect traffic. Key-value stores with native TTL can do this for us. Deleted codes are usually not reused for a while, because someone may still hold an old printed link and should not land on a new owner's page.

5Click Analytics Off the Critical Path

Analytics are valuable, but a redirect must not wait for them. The service publishes a small click event, with code, timestamp, referrer, country from the IP and a user agent class, to Kafka with an asynchronous send and returns immediately. The producer batches events, so 100,000 clicks per second become a few thousand Kafka requests.

If Kafka is slow, the producer's buffer fills and we drop events rather than block redirects, and we count the drops. Losing a tiny fraction of clicks during an incident is acceptable; making redirects slow is not. Consumers aggregate clicks per link per minute into an analytics store that powers dashboards.

6Abuse Controls

Any public shortener will be used to hide malicious links. At creation time, we check the long URL against a malicious URL list or scanning service, block known bad domains, and apply per-user and per-IP rate limits so one account cannot create 50,000 links in a minute. Because a URL can turn malicious after creation, we re-scan popular links periodically and on abuse reports, and a disabled link returns a warning page instead of a redirect. This is also one more reason to prefer 302: we can still stop a link after it has been clicked.

7Follow-up questions

Why use both Caffeine and Redis instead of only Redis?

Redis is fast, but every lookup is still a network round trip, and at 100,000 per second that is a lot of traffic on one cluster, concentrated on a few hot keys. The local cache serves the hottest links with no network at all and protects Redis from hot-key overload. The cost is a short staleness window, so local entries live only about a minute, and disabling a link also publishes an invalidation event.

How do you handle a link that is disabled for abuse while it is cached?

We publish an invalidation message that every instance consumes to evict the code from Caffeine, delete the Redis entry, and keep the local TTL short as a backstop. With 302 responses, the next click comes to us and gets the warning page.

Would you use PostgreSQL or a key-value store?

Both work. The access pattern is a key lookup by code, which suits a key-value store and its easy horizontal scaling. PostgreSQL with hash partitioning is fine if the team already runs it well and the volume, around 10 TB a year, is handled with partitioning and expiry.

8Conclusion

In this answer, we sized a shortener at 1,000 writes and 100,000 redirects per second, generated codes from id blocks or random values with custom aliases in the same unique column, stored links partitioned by code, served redirects through Caffeine and Redis with a 302 when analytics matter, checked expiry on every read while cleaning up asynchronously, sent clicks to Kafka without waiting, and guarded creation with scanning and rate limits.

What to say in the interviewAbout 80 seconds aloud

Open with

I would design the write and read paths separately, because redirects are a hundred times more frequent. On the write path, a Spring Boot service validates the URL, applies a per-user rate limit and scans the URL, then generates a code from pre-allocated id blocks encoded in base62, or a random code with retry.

Then, if they want more

Custom aliases go into the same code column, which is the primary key, so one unique constraint stops any collision and we return 409 for a taken alias. Each row has code, long URL, owner, created and expires_at, in a key-value store or PostgreSQL partitioned by code.

The redirect path checks a local Caffeine cache, then Redis, then the database, and caches misses briefly too. I would return 302 if we need analytics on every click, because 301 lets browsers skip us; 301 only for an internal shortener that wants minimal load.

Expiry is checked on every read, and cache TTLs never outlive the link, while a batch job removes expired rows later. Click events go to Kafka with an async send; if Kafka is slow we drop and count events rather than slow redirects. Finally, popular links are re-scanned so we can disable a link that turns malicious.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Design a URL shortener in Java and Spring Boot that handles 1,000 new links per second...": https://scrivio-interview-library.netlify.app/architecture/backend-system-design/dc912edf19/