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.

● EasyFREEBy ·Design problem·14 min read·Beginner → Intermediate
password resetaccount recoveryreset tokensuser enumerationhost header injectionsession revocation

01Understand the problem and size it

✓What you will learn
  • 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
◎Interview radar

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

  1. A user enters their email and, if an account exists, receives a reset link.
  2. Following the link lets them set a new password once, within a time limit.
  3. After a reset, other sessions end and the user is told by email.
  4. Users with MFA still prove their second factor.

Non-functional requirements

  1. 50 M accounts; bursts after breach news or a forced reset campaign.
  2. Responses and timing do not reveal whether an email is registered.
  3. Tokens unguessable and useless if the database is read.
  4. Email delivered within a minute for 99 % of requests.
Sizingtxt
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 defence
▭On the whiteboard · Scope3 points
01
FR
request link | set new password once | end sessions + notify | MFA still required
02
NFR
50 M accounts | no enumeration | tokens hashed, 30 min | email < 1 min p99
03
out
the email provider, the login service, helpdesk recovery

02High-level design

  1. POST /password-reset with 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.
  2. 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) and used = false, and invalidates earlier unused tokens for that user.
  3. It emails a link built from a configured base URL, never from the incoming request.
  4. GET /reset?token=... only shows a form. It does not consume the token.
  5. POST /reset with 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.
Token creation and checkingts
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);
}
iWhy a fast hash is fine here

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.

▭On the whiteboard · Core3 points
01
request
always 202, enqueue, rate limit per email and per IP
02
token
256-bit random, store SHA-256, 30 min, single use, older tokens voided
03
confirm
POST only, atomic consume + set, revoke sessions, notify

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

Host header injection in reset emailstxt
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 proxy

Keeping the token out of other places

LeakHowDefence
Referer headerReset page loads a third-party script or image; the browser sends the full URL including tokenReferrer-Policy: no-referrer on the reset page and no third-party content on it
Link scannersMail security tools fetch every link (GET) before the user doesGET only renders the form; the token is consumed by the POST
Logs and analyticsAccess logs record the query stringOn 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 historyURL stays in history on a shared machineShort 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.

!Do not log the user in automatically

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 failureBehaviourWhy
Email bombing a victimMax 3 reset emails per account per hour, plus per-IP limitsYour service should not become a harassment tool
Attacker has the victim's inboxReset succeeds, but MFA blocks the final step; notification goes to the address on file and the user's devicesEmail is the root of recovery; MFA limits the damage
Email provider outageJobs queue and retry; tokens are created at send time so the 30 minutes start when the email can actually go outAvoid tokens that expire in a queue
Token table read by an attackerHashes only, no usable linksDefence in depth
Attacker already logged inAll sessions and refresh tokens revoked on resetOtherwise the reset does not evict them
ChoiceGainCost
Link with token vs 6-digit codeLink: unguessable, one clickCode: typeable across devices, but needs strict attempt limits (5 per code) because a million values is guessable
30 min vs 24 h expirySmaller window for a leaked linkMore "link expired" support tickets
Revoke all sessions on resetEvicts an attackerUser logs in again on every device

05Final design, follow-ups and self-test

▭On the whiteboard · Final design3 points
01
request
same 202 for everyone, async lookup and send, per-account and per-IP limits
02
token
256-bit random, SHA-256 stored, 30 min, single use, link from configured base URL
03
finish
POST consumes atomically, MFA required, sessions revoked, notify, then normal login
“How to say it in the room

"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.

Test yourself

Your reset emails are built with `"https://" + request.host + "/reset?token=" + token`. What is the risk?

Finished this one?
Tick it and it shows as done on the roadmap and the course.