DEV Community

Cover image for Base62 encoding for URL shortener interviews, explained
Gowtham Potureddi
Gowtham Potureddi

Posted on

Base62 encoding for URL shortener interviews, explained

Base62 encoding for URL shortener interviews, explained

Design a URL shortener and the first concrete decision is the shape of the code itself — the dBsx in short.ly/dBsx. It has to be short (that is the whole product), unique (two long URLs can never collide onto one code), and URL-safe (it rides inside a URL, so it can't contain characters a URL treats specially). You already have unique numeric IDs — a database can hand them out — so the real question is how to render a number as the shortest safe string. Base62 encoding is the standard answer: it represents an integer in base 62 using the alphabet 0-9A-Za-z, the largest alphabet that is both fully alphanumeric and URL-safe. It is a core system design interview detail because "design a URL shortener" is one of the most common prompts, base62 is the textbook key-generation step, and the follow-ups — how long is the code, can someone guess the next one, what happens on a collision — are built to test whether you understand the trade-offs behind the one-liner.

The reason it comes up is that the code is where several design forces meet at once. Make the alphabet bigger and the code gets shorter for the same number of URLs, but go past 62 and you start using characters (+, /, =) that aren't URL-safe. Generate codes from a sequential counter and they are short and dense but guessable; generate them randomly and they are unguessable but you have to handle collisions. The key length you pick is a capacity bet on how many URLs you will ever store. This guide walks what a strong candidate says out loud: why the alphabet is 62, how base62 encodes and decodes, why it fits URL shortening, the ID-to-code generation strategies, and the collision and predictability pitfalls that the interview's follow-ups are aimed at.

Title card for a system design interview explainer on base62 encoding for URL shorteners, showing a long URL being mapped to a short code by converting a numeric ID into a base62 string over the alphabet zero-to-nine, A-to-Z and a-to-z, with a note that base62 is the largest fully URL-safe alphanumeric alphabet and that seven characters address about 3.5 trillion URLs, on a dark citrus-and-lavender background.

Why base62 encoding comes up in system design interviews

The topic rarely gets its own prompt. It lives inside "design a URL shortener" (or a pastebin, or any system that mints short opaque IDs), the moment the interviewer asks what the short code actually is and how you generate it. You say "I'll base62-encode an ID," and the follow-ups arrive in a stack: how many characters, where does the ID come from, can a user guess someone else's code, and what happens when two URLs want the same one? The interviewer is not testing whether you have heard "base62" — they are testing whether you can derive the key length from a capacity estimate and name what your generation choice costs.

The interviewer rarely lets "I'll base62-encode an auto-increment ID" stand on its own. "Clean — short and dense. I just shortened a URL and got short.ly/3k9. Now I change the last character in my address bar to 3k8, then 3ka. Walk me through what I'm looking at." That question — turning your sequential counter into an enumeration attack — is the one a memorised "just base62 the ID" answer can never survive.

The rounds on Zynter are modelled on how the loop runs, not scraped from any candidate's recall. What matters for prep is the shape: you name base62 as the key step, and the next sentence attacks the alphabet choice, the capacity math, the predictability of a counter, or how you handle a collision.

What the interviewer is really testing

A base62 answer is read on the same four dimensions as any design decision. Problem solving — did you pick the key length from a real capacity estimate, and did you notice a sequential counter is enumerable? Communication — can you say in one sentence why 62 and not 64, and how encoding maps a number to a string? Technical execution — do you handle collisions with an atomic check-and-insert, and know where the IDs come from when the database is sharded? Time management — did you spend your words on the key-generation trade-off, not on hand-tracing the division algorithm? Reading this guide teaches the mechanics; it does not teach you to defend a generation scheme while someone tries to enumerate your links.

What base62 is: a positional number system over 62 symbols

Start with the mechanics, because every later decision rests on them. Base62 is an ordinary positional numeral system — like decimal (base 10) or hexadecimal (base 16) — except it has 62 digits. The alphabet maps each digit value to a character: 0-9 are the values 0–9, A-Z are 10–35, and a-z are 36–61. That is 62 symbols, every one of them alphanumeric and safe to drop into a URL path with no escaping.

To encode an integer, you repeatedly divide by 62 and read the remainders, mapping each remainder to its character, then reverse the order — exactly how you'd convert a number to any base:

encode(125): 125 / 62 = 2 rem 1  -> '1'
               2 / 62 = 0 rem 2  -> '2'
read remainders bottom-up -> "21"   (so ID 125 -> code "21")
Enter fullscreen mode Exit fullscreen mode

To decode, you run it backwards (Horner's method): start at 0 and, for each character left to right, value = value * 62 + index_of(char). Encoding and decoding are exact inverses, which is the property that makes the whole scheme work.

Why 62 and not 64? Base64 squeezes in two more symbols by using +, /, and = (padding) — but those are not URL-safe: / is a path separator, + decodes to a space, = is reserved, so a base64 code has to be percent-encoded or swapped for a URL-safe variant, which defeats the point of a clean short link. Base62 deliberately stops at the alphanumerics so the code is safe everywhere with no escaping. And why not base10 or hex? They work but are longer — a bigger alphabet packs more values into the same number of characters, so base62 gives a shorter code for the same ID.

The sentence that scores: base62 is just base conversion over the 62 alphanumerics 0-9A-Za-z — encode by repeated divide-and-mod-62, decode by the reverse — and it stops at 62 because 64 would pull in + / =, which aren't URL-safe, while base10 or hex would make the code longer for the same number. Naming the URL-safety reason for 62 and the encode/decode inverse is the core of the mechanics.

A diagram of base62 encoding steps, showing an integer ID being converted to a short code by repeated division by 62 where each step records a quotient and a remainder, the remainders are mapped through the base62 alphabet of zero-to-nine then A-to-Z then a-to-z, and the characters are read in reverse to form the final code, with a side note that decoding runs the reverse using value equals value times 62 plus the character index, and that the alphabet stops at 62 symbols to stay fully URL-safe and alphanumeric.

Why base62 fits URL shortening: compact and reversible

Two properties make base62 the right tool for a shortener. First, it is compact: because each character carries one of 62 values, a short string addresses a huge space. Second, when you encode a database ID, it is reversible: the code decodes straight back to the ID, so a redirect is a single primary-key lookup — decode 3k9 to its integer, SELECT ... WHERE id = …, and return the long URL. No separate index from code to URL is needed if the code is the encoded key.

The capacity math is what sets the key length, and interviewers want to see you do it, not guess it. Each extra character multiplies the space by 62:

  • 5 chars → 62⁵ ≈ 916 million
  • 6 chars → 62⁶ ≈ 56.8 billion
  • 7 chars → 62⁷ ≈ 3.5 trillion

So you pick the length from the expected number of URLs over the system's life. If you estimate billions of links, 7 characters gives trillions of room — comfortable headroom — while 6 might be tight. The reasoning, not the exact figure, is the signal: start from a count, multiply by 62 per character, and choose the shortest length that clears it with margin.

The sentence that scores: base62 is compact because each character holds 62 values, so a 7-char code addresses about 3.5 trillion URLs, and it's reversible when I encode the row's ID — the code decodes back to the key for an O(1) lookup — so I size the key length off a capacity estimate: count the URLs I expect, multiply by 62 per character, and pick the shortest length that clears it. Doing the capacity math out loud is exactly what the follow-up is fishing for.

A diagram showing base62 code capacity, with a table mapping code length to the number of addressable URLs: five characters to about 916 million, six characters to about 56.8 billion, and seven characters to about 3.5 trillion, each row showing the space multiplying by 62 per added character, and a callout that key length is chosen by starting from the expected URL count and picking the shortest length that clears it with headroom, next to a note that an encoded ID decodes back to the key for an O(1) database lookup.

System Design
HLD · Core concept
Derive the base62 key length from a capacity estimate out loud

Practise on Zynter →

Generating the ID: counter, distributed ticket, hash, or random

Base62 turns a number into a code — but where does the number come from? This is where the real design decision lives, because the generation strategy decides whether codes are guessable, whether they collide, and whether the generator is a bottleneck. There are four options worth naming:

  • Auto-increment counter → base62. The database hands out 1, 2, 3, … and you encode each. It is the simplest and gives the shortest, densest codes. The costs: the codes are sequential and enumerable (base62 of a counter is still a counter), and a single global counter is a write bottleneck and single point of failure.
  • Distributed ID / ticket service. When the data is sharded, a single counter won't do, so you hand out IDs from a dedicated service — Redis INCR, a ticket server that leases ID ranges to each app server, or Snowflake-style IDs — then base62-encode them. This removes the single-counter bottleneck while keeping IDs roughly ordered.
  • Hash the URL, then base62. Hash the long URL (MD5/SHA), take a slice, and base62-encode it. It needs no counter and naturally deduplicates identical URLs, but hashes can collide, so you must check-and-insert and rehash or extend on conflict.
  • Random base62 + uniqueness check. Generate a random N-character code and insert it if unused, retry on conflict. The codes are unguessable, at the cost of collision handling that grows as the keyspace fills.

The trade-off to state plainly is one axis: sequential is simple, compact, and fast but guessable; random or hashed is unguessable but needs collision handling and (for the counter) a plan for distribution. Which side you pick depends on whether your links must be unguessable and whether the system is sharded.

The sentence that scores: base62 only encodes a number, so the design decision is where the number comes from — an auto-increment counter is simplest and densest but sequential and a single bottleneck; a distributed ticket service fixes the bottleneck for a sharded store; hashing or random codes make them unguessable but force an atomic collision check — so I choose on two questions: must the codes be unguessable, and is the ID source sharded? Separating "base62 the encoder" from "where the ID comes from" is the insight the topic rewards.

A diagram of ID-to-code generation strategies for a URL shortener, showing four options that all feed into base62 encoding: an auto-increment counter that is simple and dense but sequential and a single bottleneck; a distributed ticket or ID service such as Redis INCR or a range-leasing server that removes the single-counter bottleneck for a sharded store; hashing the long URL and taking a slice, which needs a collision check-and-insert; and a random code with a uniqueness check that is unguessable but needs collision handling, with a footer noting the core trade-off of sequential-but-guessable versus unguessable-but-needs-collision-handling.

System Design
HLD · Core concept
Compare counter vs hash vs random code generation out loud

Practise on Zynter →

The pitfalls interviewers probe

The follow-ups cluster around four failure modes, and naming them unprompted is what separates a senior answer from a keyword:

  • Collisions. Hash-based and random codes can produce the same string for two different URLs. You must insert with an atomic check-and-insert — a unique constraint or a conditional write — so two concurrent requests can never both claim one code. Skipping this is a silent data-corruption bug: one URL overwrites another's code.
  • Predictability. Base62 of a sequential counter is still sequential, so anyone can decrement or increment a code to walk to other links — an enumeration/scraping risk and a privacy leak. If codes must be unguessable, add randomness, use random/hashed codes, or encode an encrypted ID rather than the raw counter.
  • Custom aliases. Vanity slugs (short.ly/launch) have to share the same keyspace and uniqueness check as generated codes, or a user alias can collide with a future generated one.
  • The redirect, not the code. Once the code resolves, you still choose the HTTP redirect: 301 (permanent) is cacheable and fast but the browser caches it, so you stop seeing per-click traffic; 302 (temporary) sends every click through your server, preserving click analytics at the cost of a hop. That choice is its own topic — 301 vs 302 redirects — and it interacts with whether you need analytics.

The point to state plainly: base62 is only the encoding — the decisions that fail an interview are around it: collisions need an atomic check-and-insert, a sequential counter is enumerable so unguessable links need randomness, custom aliases share the keyspace, and the 301-vs-302 redirect choice decides whether you keep click analytics. That awareness of what sits on either side of the encoder is where a URL-shortener answer is won or lost.

How to talk about base62 in an interview

The probes from every section rhyme. Master these five and you can defend the code design in any shortener-style problem, not just this checklist.

  • "Why base62 and not base64?" → Base64 uses + / =, which aren't URL-safe, so a code would need escaping; base62 stops at the alphanumerics so it rides in a URL cleanly, and it's shorter than base10 or hex. (communication)
  • "How long should the code be?" → Size it from a capacity estimate: 62⁶ ≈ 56.8 billion, 62⁷ ≈ 3.5 trillion, so pick the shortest length that clears my expected URL count with headroom — usually 7. (problem solving)
  • "Where does the ID come from?" → A counter (simple, dense, but sequential and a bottleneck), a distributed ticket service for a sharded store, or a hash/random code when links must be unguessable. (technical execution)
  • "Can a user guess another link?" → With a base62'd counter, yes — it's sequential and enumerable; if unguessability matters I use random or hashed codes, or encode an encrypted ID. (problem solving)
  • "Two URLs map to the same code — now what?" → That's only possible with hash/random, and I prevent it with an atomic check-and-insert on a unique constraint, retrying on conflict. (technical execution)

Each maps to a debrief dimension. Reading them teaches the answers; it does not teach you to deliver them while someone tries to enumerate your links — that only comes from saying them out loud.

How to prepare: a short plan

You do not need a new topic for every design. You need the base62 reasoning automatic, so when a shortener (or any short-ID system) comes up you derive the key length and name the generation trade-off without being pushed.

  • Day 1: Learn the mechanics — the 62-symbol alphabet, encode by divide-and-mod-62, decode by the reverse, and why 62 beats 64 and 10 — until you can convert a small number by hand.
  • Day 2: Drill the capacity math (62ⁿ for n = 5, 6, 7) and the four ID-generation strategies, with the sequential-vs-unguessable trade-off and the atomic collision check.
  • Day 3: Place base62 inside a full URL-shortener design: size the code, pick an ID source, handle collisions, and choose the redirect. Then do it out loud, timed, with someone asking "I just changed the last character of my code — what do I see?"

This explainer feeds the broader Top 25 system design interview questions — the URL shortener is a canonical prompt, and base62 plus its generation and redirect choices come up every time.

Frequently asked questions

What is base62 encoding and why is it used for URL shorteners?

Base62 encoding represents a number in base 62 using the alphabet 0-9A-Za-z — 62 symbols, every one of them alphanumeric and safe to place in a URL. URL shorteners use it because the short code has to be compact, unique, and URL-safe, and base62 is the largest alphabet that satisfies all three: a bigger alphabet makes the code shorter, but going to base64 would require +, /, and =, which aren't URL-safe. The usual flow is to take a unique numeric ID (from a database counter or an ID service) and base62-encode it into the short code; because encoding is reversible, the code decodes straight back to the ID, so resolving a short link is a single primary-key lookup. Compared with base10 or hexadecimal, base62 produces a shorter string for the same number, which is the entire point of a short link.

How many characters does a base62 short code need?

You size it from a capacity estimate, because each character multiplies the space by 62. Five characters give 62⁵ ≈ 916 million codes, six give 62⁶ ≈ 56.8 billion, and seven give 62⁷ ≈ 3.5 trillion. So you estimate how many URLs the system will ever store and pick the shortest length that clears that number with headroom. For a large-scale shortener expecting billions of links over its life, seven characters is the common choice because it leaves trillions of room; six can be tight if you expect tens of billions. The interview signal is doing this math out loud — starting from a count, multiplying by 62 per character — rather than asserting a magic number.

Is base62 the same as base64?

No. Both are base conversions, but they use different alphabets, and the difference matters for URLs. Base64 uses 64 symbols including +, /, and = (padding), and both + and / have special meaning inside a URL while = is reserved — so a base64 string has to be percent-encoded or swapped for a "URL-safe base64" variant before it can live in a link. Base62 deliberately stops at the 62 alphanumeric characters (0-9A-Za-z), so its output is safe to drop into a URL path with no escaping at all. Base64 is denser (it encodes slightly more per character) and is the right tool for embedding binary data in text, but for a clean, human-friendly short link that needs no escaping, base62 is the standard choice.

Can someone guess other short URLs if you use base62?

Yes, if you base62-encode a sequential counter — which is the trap interviewers probe. Base62 is just a change of radix, so encoding 1, 2, 3, … produces codes that are still sequential; a user can increment or decrement the characters in a code and walk to other people's links, which is an enumeration and scraping risk and can leak private URLs. If unguessability matters, you break the sequence: generate random base62 codes with a uniqueness check, hash the URL and encode a slice, or encode an encrypted version of the ID so the public code reveals no order. The trade-off is that unguessable schemes need collision handling, whereas a plain counter never collides but is fully predictable — so you choose based on whether your links carry anything sensitive.

How do I practise a system design interview out loud?

Reading about base62 is not the same as defending a code design while an interviewer tries to enumerate your links or forces a collision. On Zynter, the HLD track runs live voice rounds modelled on how real system design loops run — you talk through a design (like a URL shortener) on a shared canvas, and a voice interviewer follows up one question at a time ("why base62, not base64?", "how long is the code and why?", "I just changed the last character — what do I see?"), then gives you a debrief on problem solving, communication, technical execution and time management. The score is a practice signal, not a hiring decision.

Practise it on Zynter

You can say "I'll base62-encode an ID." The round is won on the key length, the generator, and the collision check.

Pick an HLD system design round with a URL shortener, lay out the code scheme on the canvas, and defend it out loud to a voice interviewer that keeps asking "why 62?" and "I just changed the last character of my code — what do I see?" — then read the debrief. Zynter.ai is on-demand mock interviews modelled on real company loops, with 150+ rounds across 20 companies including the HLD system design track (Sep 2026).

Practise an HLD system design round →
Browse all interview tracks

Top comments (0)