Two requests grab the same short code. What stops the clash?
Question
A link shortener saves new links with the code below. candidates(url) yields 7-character base62 codes made from a hash of the URL.
Two users shorten two different pages at the same moment. Both pages get the same first candidate, k3P9xQa, and both users get that code back. Now the first user's link opens the second user's page.
- What order of events causes this?
- Change the design so one code can never point to two pages.
- Base62 gives every number its own code. Why didn't that help?
def shorten(url): for code in candidates(url): if db.get(code) is None: # is the code free? db.put(code, url) # put overwrites an existing key return code
Show hints (3)
- "FIND THE GAP"
getandputare separate calls. What if the second request'sgetruns before the first request'sput? - "WHO DECIDES"
A check made before the write can be out of date when you write. What rule could the database itself enforce?
- "CLAIM, THEN RETRY"
Make
codethe primary key. Insert only if the code is absent, in one statement. If no row was added, try the next candidate.
Show checked explanation
Both requests ran get before either ran put, so the second put overwrote the first link. Make code the primary key and claim it with one insert that does nothing if the code exists. If no row was added, try the next candidate. Base62 only writes a number; it doesn't make it unique.
import sqlite3 db = sqlite3.connect(":memory:") db.execute("CREATE TABLE links (code TEXT PRIMARY KEY, url TEXT NOT NULL)") def shorten(url, candidates): for code in candidates: added = db.execute( "INSERT INTO links (code, url) VALUES (?, ?)" " ON CONFLICT (code) DO NOTHING", (code, url)).rowcount if added: # 1 row: the code is ours; 0 rows: it was taken return code raise RuntimeError("every candidate was taken") print(shorten("https://shop.test/sale", ["k3P9xQa", "Zt81mWc"])) print(shorten("https://news.test/today", ["k3P9xQa", "b7Rr2Kd"])) print(db.execute("SELECT code, url FROM links ORDER BY code").fetchall())
k3P9xQa
b7Rr2Kd
[('b7Rr2Kd', 'https://news.test/today'), ('k3P9xQa', 'https://shop.test/sale')]Code run on CPython 3.12 with SQLite, including eight threads racing for one code. Checked by an editor other than the author.
Walkthrough
This is a race condition: the result depends on timing. Request A shortens the shop page, request B the news page:
| step | request A | request B | table |
|---|---|---|---|
| 1 | get: free | empty | |
| 2 | get: free | empty | |
| 3 | put shop | k3P9xQa → shop | |
| 4 | put news | k3P9xQa → news |
B's check was true at step 2 and out of date one step later. Any check made before the write leaves this gap.
The fix moves the decision into the write. code is the primary key, so the table holds at most one row per code. INSERT ... ON CONFLICT (code) DO NOTHING adds the row only if the code is free, in one atomic step. rowcount tells you who won: 1 means the code is yours, 0 means another request has it. The loser tries its next candidate, here b7Rr2Kd. A slow request can lose, but it can never overwrite. A plain INSERT that catches the duplicate-key error works too.
Now base62. It writes a number with 62 symbols: 0-9, then a-z, then A-Z. 1000 = 16 × 62 + 8, and g is symbol 16, so 1000 becomes g8. Different numbers always get different codes. But the same number gets the same code. Here the code came from a hash cut to 7 characters, so two URLs can share it.
Common mistakes
- Making the code longer instead. Clashes get rarer, but two requests with the same candidate still race.
- Using an upsert that updates, such as
ON CONFLICT DO UPDATEor SQLite'sINSERT OR REPLACE. It overwrites the first link and raises no error. On a clash, change nothing. - Giving each app server its own counter from 1. Both reach 1000 and make
g8. Use one shared counter, or give each server its own range.
Follow-up questions
- "How long should the code be?" 1 million links a day for 10 years is 3.65 billion. 62⁵ is about 916 million, too few; 62⁶ is about 56.8 billion. A counter fits in 6 characters, but its codes are easy to guess: after
g8comesg9. For hash or random codes, use 7: the table stays about 0.1% full, so few inserts retry. - "Should the redirect be 301 or 302?" A 301 is permanent: any cache, the browser included, may keep it without cache headers. Later clicks can then skip your server: less load, but no click counts and no way to change the target. A 302 is temporary, cached only if your headers allow it. Pick 302 to count clicks or edit links.
- "The response is lost, and the client retries. What happens?" The retry claims a second code for the same page. To return the first code instead, the client sends an idempotency key. Save it in a unique column of the same row; a retry with that key gets the saved code.
What a strong answer covers
Shows the order of events where both checks pass. Claims the code with one atomic insert on a unique key and retries on a clash. Knows base62 only encodes a number. Sizes the code from 62ⁿ and picks 301 or 302 for a reason.
Open in interactive practice deck →