Build a Single-Use Password Reset Token Manager
Data Structure DesignModel answerLast updated
Design an in-memory service that issues reset tokens, enforces expiry and a failed-attempt cap, rejects reused passwords, and makes each token usable only once.
Reset Token Manager
You are building the core of an account-recovery feature. The component hands out short-lived reset tokens, checks them when a user tries to choose a new password, and shuts down tokens that are abused or stale.
Implement a class with this interface:
class PasswordResetService:
def __init__(self, token_ttl: int, max_attempts: int):
"""
token_ttl: how many seconds a token stays usable after it is issued.
max_attempts: how many failed verifications a single token may absorb.
"""
def register_user(self, user_id: str, password_hash: str) -> None:
"""Create a user with a starting password hash."""
def request_reset(self, user_id: str, token: str, timestamp: int) -> bool:
"""
Issue `token` for `user_id` at `timestamp`.
Returns False if the user is unknown.
Any earlier token for this user is discarded and replaced.
Returns True otherwise.
"""
def verify_and_reset(self, user_id: str, token: str,
new_password_hash: str, timestamp: int) -> bool:
"""
Try to change the user's password using `token`.
Returns True only if the password was changed.
"""
Rules
- Expiry. A token issued at time
tis usable for anytimestampwitht <= timestamp <= t + token_ttl. A verification at a later time fails and also destroys the token. - Attempt cap. Every verification against a live token that does not succeed adds one to that token's failure count. When the count reaches
max_attempts, the token is revoked at once, so later calls fail even with the correct token. - One use. After a successful reset the token is consumed and cannot be used again.
- No password reuse. If
new_password_hashequals the user's current hash, the call fails and counts as a failed attempt. - Unknown users. Any call naming a user that does not exist returns
Falseand must not raise.
A wrong token counts as a failed attempt (rule 2), as does a correct token paired with an unchanged password (rule 4). A call made when the user has no live token (never requested, expired, consumed, or revoked) just returns False.
Example
svc = PasswordResetService(token_ttl=300, max_attempts=3)
svc.register_user("alice", "h_old")
assert svc.request_reset("alice", "T1", 100) is True
assert svc.verify_and_reset("alice", "BAD", "h_new", 120) is False # failure 1
assert svc.verify_and_reset("alice", "T1", "h_old", 130) is False # failure 2 (same password)
assert svc.verify_and_reset("alice", "T1", "h_new", 140) is True # success, token consumed
assert svc.verify_and_reset("alice", "T1", "h_other", 150) is False # token already used
What to deliver
Write the class, explain the order in which you evaluate the checks and why, state the complexity, and list the edge cases you handled. Be ready to discuss how you would harden it against timing attacks and run it across multiple servers.
Hints
Hint 1
At most one token can be live per user, so a per-user record holding the token, its issue time and its failure count is enough. Replacing the record on a new request naturally resets the count.
Hint 2
Evaluate checks in a fixed order and return at the first failure: user exists, live token exists, not expired, token matches, password differs. Think about why expiry must come before comparing the token.
Hint 3
Implement revocation and consumption by deleting the record. Then 'no live token' becomes the single rejection path for expired, exhausted, and already-used tokens.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a small per-user state machine. The hard part is not the data structure but the order of checks and making sure every way a token dies leaves no state behind. Treat the security rules as invariants.
State
users: dict[user_id -> password_hash]active: dict[user_id -> record], where a record holdstoken,created_at, andfailures.
A user has at most one live token. request_reset writes a brand-new record, which discards the old token and zeroes the failure count in one step. A token is "dead" exactly when no record exists for the user, so expiry, exhaustion and consumption all reduce to deleting the record.
Assumption to state aloud
The expiry rule is a closed interval: usable when created_at <= timestamp <= created_at + ttl. At created_at + ttl the token still works; one second later it is expired and deleted. Also, a failed call that arrives when no token is live is not charged to anything.
Verification pipeline
The first failing step returns False:
- Unknown user: return
False. - No live token: return
False. timestamp > created_at + ttl: delete the record, returnFalse.- Token mismatch: record a failure.
- New hash equals current hash: record a failure.
- Otherwise: store the new hash, delete the record, return
True.
Recording a failure means failures += 1; if failures >= max_attempts, delete the record. Either way, return False.
Why this order
- Expiry before comparison. An expired token must never succeed, and a dead token should not collect failures.
- Deletion as revocation. After the record is gone, step 2 rejects everything, including the correct token. That satisfies the exhaustion rule with no extra flag.
- Single use falls out for free. Success deletes the record, so a replay stops at step 2.
- Same-password failures count. Without this, someone holding a valid token could probe indefinitely. Steps 4 and 5 can be swapped without changing any result, since both record a failure.
- Fresh state on re-request. Building a new record means old failures never leak into the new token.
Trace of the example (max_attempts = 3)
| Time | Call | Effect | Result |
|---|---|---|---|
| 100 | request T1 | record created, failures 0 | True |
| 120 | wrong token | failures 1 | False |
| 130 | right token, same hash | failures 2 | False |
| 140 | right token, new hash | hash updated, record deleted | True |
| 150 | replay | no record | False |
Code
import hmac
from dataclasses import dataclass
@dataclass
class _Reset:
token: str
created_at: int
failures: int = 0
class PasswordResetService:
def __init__(self, token_ttl: int, max_attempts: int):
self.ttl = token_ttl
self.max_attempts = max_attempts
self.users: dict[str, str] = {}
self.active: dict[str, _Reset] = {}
def register_user(self, user_id: str, password_hash: str) -> None:
self.users[user_id] = password_hash
self.active.pop(user_id, None) # credential change voids pending tokens
def request_reset(self, user_id: str, token: str, timestamp: int) -> bool:
if user_id not in self.users:
return False
self.active[user_id] = _Reset(token, timestamp) # replaces any old one
return True
def _fail(self, user_id: str, rec: _Reset) -> bool:
rec.failures += 1
if rec.failures >= self.max_attempts:
del self.active[user_id]
return False
def verify_and_reset(self, user_id, token, new_password_hash, timestamp) -> bool:
if user_id not in self.users:
return False
rec = self.active.get(user_id)
if rec is None:
return False
if timestamp > rec.created_at + self.ttl:
del self.active[user_id]
return False
if not hmac.compare_digest(rec.token.encode(), token.encode()):
return self._fail(user_id, rec)
if new_password_hash == self.users[user_id]:
return self._fail(user_id, rec)
self.users[user_id] = new_password_hash
del self.active[user_id]
return True
Complexity
- Time: O(1) average per operation for the dictionary work, plus O(L) to compare a token of length L.
- Space: O(U) for U users, since each user has at most one record.
Edge cases
- Unknown user in either method:
False, no exception. - Verify with no request ever made:
False, and no failure is counted. timestamp == created_at + ttlsucceeds;+1fails and deletes.max_attempts == 1: the first failure revokes the token.- A fresh request after revocation or expiry starts with a clean counter.
- Re-registering a user overwrites the hash and clears any pending token (a design choice; justify it as "credential changed, so old reset links are void").
- If timestamps might go backwards, also reject
timestamp < created_at.
Common mistakes
- Comparing the token before checking expiry.
- Incrementing the counter but never deleting the token at the limit.
- Reusing the old failure count after a new request.
- Treating the same-password rejection as free, which allows unlimited probing.
- Comparing secrets with
==.
Follow-ups
Timing attacks. == may exit at the first differing byte, leaking how long a correct prefix is. Use a constant-time comparison such as hmac.compare_digest. Better, store only a hash (for example SHA-256) of each token and compare digests: a database leak then exposes no usable tokens, and the compared values have equal length. Also keep responses for "unknown user", "no token", "expired" and "wrong token" indistinguishable in content and roughly in latency, to prevent user enumeration.
Multiple servers. Move state to a shared store such as Redis. Use a key like reset:{user_id} holding the token hash and failure count, with the key TTL set to token_ttl so expiry is automatic. Verification is a read-check-write sequence, so it must be atomic, otherwise two servers could both accept one token or undercount failures. Do it in a Lua script or with optimistic transactions (WATCH/MULTI). Rate-limit by IP and by account as well, since a per-token cap alone does not stop an attacker from requesting new tokens repeatedly.
Trade-offs. In-memory maps are simple and fast but lose state on restart and cannot be shared. A durable store adds latency and needs atomicity. Relying on store-level TTL means you give up the "expired call deletes the token" behavior, which is fine as long as expired tokens are indistinguishable from absent ones.