Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

In a URL shortener written in Java, how would you turn a numeric id from a database sequence into a short code, and what are the drawbacks of sequential ids?

We encode the numeric id in base62, using the 62 characters 0-9, a-z and A-Z, by repeatedly dividing by 62 and taking the remainders as digits; seven characters cover about 3.5 trillion ids. The drawbacks of sequential ids are that codes are guessable, so anyone can walk through all links, and they reveal how many links we create. We fix that by shuffling ids with a reversible permutation or by using random codes with a uniqueness check, allocate id ranges in blocks so one sequence is not a bottleneck, and always keep a unique index on the code.

Why this question is asked

A URL shortener looks like a toy, but turning an id into a short code touches number bases, security and database contention in a few lines of code. Interviewers like it at this level because the encoding is easy to get almost right and then the follow-up questions test whether we understand what sequential ids leak and how they behave under load. In this answer, we will recap what a short code needs, write a base62 encoder and decoder in Java, check how long the codes get, look at why sequential ids are a problem, fix it with a reversible shuffle or random codes, and deal with sequence contention and uniqueness in the database.

1A Quick Recap: From Id to Short Code

When someone shortens a link, we insert a row into a links table and the database gives us a numeric id from a sequence, an object that hands out increasing numbers such as 1, 2, 3. We then need a short, URL-safe code for that id, so https://sho.rt/4c92 can find the row again.

Writing the number in decimal works but is long: id 125,000,000,000 is 12 digits. If we use more symbols per character, each character carries more information and the code gets shorter. Base62 uses the digits 0-9, the lowercase letters a-z and the uppercase letters A-Z, all safe in URLs without escaping. Each character can hold one of 62 values instead of 10.

2Encoding and Decoding Base62 in Java

To write a number in base 62, we do what we do for any base: divide by 62, keep the remainder as the lowest digit, and repeat with the quotient until it reaches zero. The remainders come out lowest digit first, so we reverse them at the end. Decoding goes the other way: for each character, multiply the running total by 62 and add the character's value.

Java
static final String ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
static String encode(long id) {
if (id == 0) return "0";
StringBuilder sb = new StringBuilder();
while (id > 0) {
sb.append(ALPHABET.charAt((int) (id % 62))); // lowest digit first
id /= 62;
}
return sb.reverse().toString();
}
static long decode(String code) {
long id = 0;
for (char c : code.toCharArray()) {
id = id * 62 + ALPHABET.indexOf(c);
}
return id;
}
encode(61); // "Z"
encode(62); // "10"
encode(125_000_000_000L); // "2crtgcg": 7 characters
decode("10"); // 62

Notice that 62 encodes as "10", exactly as 10 does in decimal: one sixty-two and zero ones. In production we would also reject characters that are not in the alphabet when decoding, because indexOf returns -1 and would silently give a wrong id.

3How Long Do the Codes Get?

Each extra character multiplies the number of possible codes by 62, so the length grows very slowly. Six characters give 62 to the power 6, about 56.8 billion codes. Seven characters give about 3.52 trillion, which is enough for decades of a busy service.

Base62 code length and capacity
CharactersPossible codesExample last id
414.8 millionzZZZ-style codes run out fast
5916 milliona small product
656.8 billionmost shorteners
73.52 trillion125 billion is 2crtgcg

4Why Sequential Ids Are a Problem

Sequential ids give sequential codes. If my link is 2crtgcg, the next person's is 2c6vpl7. Two problems follow.

The first is guessability. Anyone can write a loop that requests every code in order and collects all our links. Short links are often shared privately, for a document, a meeting or a password reset page, and their owners assume nobody else will find them. The second is information leakage. By creating one link on Monday and one on Friday and decoding both, a competitor learns exactly how many links we created that week. That is a business metric we may not want to publish.

5Fix: Shuffle the Ids or Use Random Codes

One fix keeps the sequence but scrambles its output. We apply a reversible permutation, a function that maps every id in a range to a different id in the same range and can be undone, before encoding. Multiplying by a large odd number modulo 2 to the power 40 and XOR-ing with a secret constant is a simple example; a small block cipher over the id range, such as a Feistel network, is stronger. Because the mapping is one to one, codes never collide and we can still decode back to the id. Consecutive ids now produce codes that look unrelated.

The other fix drops the sequence for codes: generate seven random base62 characters with SecureRandom and insert them. With 3.5 trillion possible codes and, say, a billion stored, the chance of a collision on one insert is about 1 in 3,500, so we rely on the unique index and retry on a duplicate key error.

Java
long shuffled = (id * 0x5DEECE66DL ^ SECRET) & ((1L << 40) - 1); // stays within 40 bits
String code = encode(shuffled); // id 1000 and 1001 now look unrelated
// random alternative
String random = randomBase62(7); // e.g. "Qx3b9Ka"
try {
links.save(new Link(random, longUrl));
} catch (DataIntegrityViolationException e) {
// duplicate code: generate another and retry
}

Note that the multiply-and-XOR trick only hides the order from casual inspection; anyone who sees enough pairs may recover it. If guessing must be truly hard, random codes or a keyed cipher are the right choice, and for sensitive links we should also make them longer than seven characters.

6Sequence Contention and the Unique Index

At high write rates, a single database sequence can become a bottleneck, especially when many instances in several regions ask for the next value. The usual fix is block allocation: each application instance reserves a range, for example 1,000 ids at a time, by incrementing a counter once, and hands them out from memory. PostgreSQL sequences support this with an increment of 1,000, and Hibernate's pooled optimiser works the same way. An instance that restarts wastes the rest of its block, which is harmless.

Finally, whatever method generates codes, the codes column has a unique index. It is what makes random codes safe, it stops custom aliases from colliding with generated codes, and it makes the redirect lookup by code fast.

SQL
CREATE UNIQUE INDEX links_code_uq ON links (code);
CREATE SEQUENCE link_id_seq INCREMENT BY 1000; -- each nextval reserves a block of 1000

7Follow-up questions

Why base62 and not base64?

Base64 adds two symbols, usually + and /, which have special meaning in URLs and need escaping, or - and _ in the URL-safe variant, which look odd and can be trimmed by some text tools. Base62 uses only letters and digits, which work everywhere. If case-insensitive systems matter, base36 avoids mixed case at the cost of longer codes.

Can a random code collide with a shuffled id code?

Only if both schemes write into the same code space, which we avoid by choosing one scheme. Custom aliases are the real risk, and the unique index catches them; some services also reserve a prefix or length for generated codes.

Does the shuffle make the codes longer?

It can. If the permutation maps into a 40-bit range, every code can be up to 7 characters, even for small ids, because small ids now map to large numbers. That is usually fine and even makes codes uniform in length.

8Conclusion

In this answer, we wrote a base62 encoder by repeated division by 62 and saw that seven characters cover about 3.5 trillion ids. We then saw that sequential ids make codes guessable and reveal volume, fixed that with a reversible shuffle or random codes plus retries, reserved ids in blocks so one sequence is not a bottleneck, and kept a unique index on the code as the safety net for every approach.

What to say in the interviewAbout 80 seconds aloud

Open with

I would encode the id in base62, using digits, lowercase and uppercase letters, which are all URL safe. The encoding is repeated division: take id modulo 62 as the lowest character, divide by 62, repeat until zero, then reverse.

Then, if they want more

Decoding multiplies by 62 and adds each character's value. Seven characters give about 3.5 trillion codes, so that is plenty.

The problem with sequential ids is that codes become sequential too: anyone can enumerate every link we have, which matters because short links are often shared privately, and decoding two codes a week apart tells a competitor exactly how many links we create.

To fix that I would either apply a reversible permutation to the id before encoding, something like a small keyed cipher over the id range, so codes look random but never collide, or generate random seven-character codes with SecureRandom and retry on a duplicate key. For sensitive links I would make them longer.

At high write rates, I would avoid hitting one sequence for every insert by allocating ids in blocks of a thousand per instance. And in every design there is a unique index on the code column, which catches collisions, protects custom aliases, and makes redirect lookups fast.

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 "In a URL shortener written in Java, how would you turn a numeric id from a database...": https://scrivio-interview-library.netlify.app/architecture/backend-system-design/9f2b60b0dc/