Design a password reset service
Design the forgot-password flow for 50 million accounts: random single-use tokens stored as hashes, responses that do not reveal who has an account, links that cannot be redirected by a forged Host header, and a reset that ends the attacker's sessions instead of handing them a new one.
01Understand the problem and size it
- Generate, store and expire reset tokens so a database leak or a guess does not give access
- Keep the request step from revealing which emails have accounts
- Close the classic holes: Host header injection, token leakage via Referer, link scanners consuming tokens
- Finish the reset properly: revoke sessions, respect MFA, notify the user
What they probe: token entropy and storage, enumeration through responses and timing, where the reset link's domain comes from, what happens to existing sessions, whether reset bypasses MFA. Where candidates slip: storing the raw token, "no account with that email" messages, building the link from the request's Host header, logging the user straight in after reset.
Password reset is account recovery through a channel the user already controls, almost always their email. Whoever controls the reset flow controls every account, so it is one of the most attacked features on any site. The design goal: only the person who receives the email can set a new password, once, within a short time.
Functional requirements
- A user enters their email and, if an account exists, receives a reset link.
- Following the link lets them set a new password once, within a time limit.
- After a reset, other sessions end and the user is told by email.
- Users with MFA still prove their second factor.
Non-functional requirements
- 50 M accounts; bursts after breach news or a forced reset campaign.
- Responses and timing do not reveal whether an email is registered.
- Tokens unguessable and useless if the database is read.
- Email delivered within a minute for 99 % of requests.
accounts 50,000,000
resets per month 2 % of accounts = 1,000,000 / month
average 1,000,000 / 2,592,000 s ≈ 0.4 / s
burst (forced reset) 100x ≈ 40 / s
token table live tokens only (30 min) -> tiny; keep used rows 30 days for audit
token entropy 32 random bytes = 256 bits, base64url ≈ 43 characters
guessing 2^256 space: rate limits are a second layer, not the defence02High-level design
POST /password-resetwith an email. The API always returns 202 with "If an account exists, we have sent an email", and enqueues a job whether or not the account exists.- The worker looks up the account. If it exists and is within rate limits, it creates a 256-bit random token, stores
SHA-256(token)with user ID, expiry (30 minutes) andused = false, and invalidates earlier unused tokens for that user. - It emails a link built from a configured base URL, never from the incoming request.
GET /reset?token=...only shows a form. It does not consume the token.POST /resetwith token and new password: in one transaction, find the hash where unused and unexpired, mark it used, set the new password hash. Then revoke sessions and refresh tokens and send a "your password was changed" email.
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
const TTL_MS = 30 * 60 * 1000;
export function newToken(): { token: string; hash: Buffer; expiresAt: number } {
const token = randomBytes(32).toString("base64url"); // 256 bits from the OS CSPRNG
return { token, hash: sha256(token), expiresAt: Date.now() + TTL_MS };
}
export function sha256(s: string): Buffer {
return createHash("sha256").update(s, "utf8").digest();
}
/** Lookup is by hash, so a stolen table gives no usable links. */
export function matches(presented: string, stored: Buffer): boolean {
if (!/^[A-Za-z0-9_-]{43}$/.test(presented)) return false; // reject malformed input early
const h = sha256(presented);
return h.length === stored.length && timingSafeEqual(h, stored);
}Passwords need slow hashes like Argon2id because people pick guessable ones. A 256-bit random token cannot be guessed, so a single SHA-256 is enough to make a leaked table useless.
03Deep dives: enumeration, link safety, MFA
User enumeration
If the response or its timing differs for registered and unregistered emails, an attacker can test a list of addresses and learn who is a customer, which feeds phishing and credential stuffing. Same message, same status code, and doing the account lookup and email asynchronously keeps timing flat too. Sign-up forms leak the same fact ("email already in use"), so fix both or accept the leak knowingly.
Where the link's domain comes from
attacker sends: POST /password-reset Host: evil.example email=victim@corp.com
bad code: link = "https://" + request.host + "/reset?token=" + token
victim receives: https://evil.example/reset?token=... (real email from you, attacker's domain)
victim clicks -> token arrives at the attacker -> attacker resets the victim's password
fix: link = config.publicBaseUrl + "/reset?token=" + token, and an allow list of Host values at the proxyKeeping the token out of other places
| Leak | How | Defence |
|---|---|---|
| Referer header | Reset page loads a third-party script or image; the browser sends the full URL including token | Referrer-Policy: no-referrer on the reset page and no third-party content on it |
| Link scanners | Mail security tools fetch every link (GET) before the user does | GET only renders the form; the token is consumed by the POST |
| Logs and analytics | Access logs record the query string | On first load, bind the token to a short reset session cookie without consuming it, and redirect to a clean URL; scrub token parameters from logs |
| Browser history | URL stays in history on a shared machine | Short expiry and single use make it worthless soon after |
Do not let reset bypass MFA
If a user has MFA, the email proves only one factor. After the token, require the second factor before setting the password. Otherwise an attacker who controls the inbox skips MFA entirely. For users who have lost their factor too, route to a slower, separately designed recovery process with delays and notifications.
Ending a reset with an active session is convenient, but it turns a leaked link into an instant session. Send the user to the normal login page, where MFA and risk checks apply.
04Abuse, failure modes and trade-offs
| Threat or failure | Behaviour | Why |
|---|---|---|
| Email bombing a victim | Max 3 reset emails per account per hour, plus per-IP limits | Your service should not become a harassment tool |
| Attacker has the victim's inbox | Reset succeeds, but MFA blocks the final step; notification goes to the address on file and the user's devices | Email is the root of recovery; MFA limits the damage |
| Email provider outage | Jobs queue and retry; tokens are created at send time so the 30 minutes start when the email can actually go out | Avoid tokens that expire in a queue |
| Token table read by an attacker | Hashes only, no usable links | Defence in depth |
| Attacker already logged in | All sessions and refresh tokens revoked on reset | Otherwise the reset does not evict them |
| Choice | Gain | Cost |
|---|---|---|
| Link with token vs 6-digit code | Link: unguessable, one click | Code: typeable across devices, but needs strict attempt limits (5 per code) because a million values is guessable |
| 30 min vs 24 h expiry | Smaller window for a leaked link | More "link expired" support tickets |
| Revoke all sessions on reset | Evicts an attacker | User logs in again on every device |
05Final design, follow-ups and self-test
"The request endpoint always says the same thing and does the work asynchronously, so neither the message nor the timing tells you whether the email is registered. The worker makes a 256-bit random token, stores only its SHA-256 with a 30-minute expiry, and builds the link from configured settings, never the Host header. Opening the link only shows a form, because mail scanners prefetch links. Submitting consumes the token and sets the password atomically, then I revoke every session and refresh token, email a notice, and send the user to the normal login, where MFA still applies."
Q1Should you invalidate the token when the user's email address changes?+
Yes. Any token issued to the old address must die when the address or password changes; tie tokens to the user's current security version and check it on use.
Q2How would you support users who no longer control their email?+
A separate recovery path: identity checks proportionate to account value, a waiting period with notifications to all known channels, and support staff tools with audit. It must not be easier than the normal flow.
Q3Why not just use a JWT as the reset token?+
A signed token cannot be made single use or revoked without server state anyway, and it often carries readable claims. A random token with a server-side record is simpler and safer.
Your reset emails are built with `"https://" + request.host + "/reset?token=" + token`. What is the risk?