“Send the user a code and check it” sounds like a weekend project. Then the real questions start. The user’s authenticator app says 481920 and your server computes 481925 - whose clock is wrong, and do you reject a legitimate login because a phone’s clock drifted eleven seconds? An attacker who stole a password now has one thing left between them and the account: a six-digit number with a million possibilities and, by default, all the time in the world to guess it - so how many tries do you allow, per what, before you lock the door, and how do you do that lockout atomically across a fleet of stateless servers? The SMS gateway in one region is throwing 500s during your traffic peak - do you fail the login, or silently fall over to email and a different SMS provider without double-charging the user or letting them have two valid codes at once? And every one of these checks has to come back in well under a second because it sits directly on the login path that every human hits.
A 2FA service is not a code generator. It is a security-critical state machine that has to be fast (it blocks every login), correct under clock skew and retries (false rejects are support tickets and churn), and adversarial-hardened (it is the last line against a stolen password), while orchestrating delivery across channels you do not control. The easy part - computing an HMAC - is a library call. The hard part is rate limiting that actually stops brute force without locking out real users, clock-drift tolerance that accepts honest codes without widening the attacker’s window, and failover across SMS/email/app that never leaves two valid codes live at once. Let me build the whole thing.
Functional Requirements (FR)
In scope:
- Enroll a second factor. A user registers a factor: a TOTP authenticator app (scan a QR encoding a shared secret), a phone number for SMS OTP, an email for email OTP, or a hardware token (HOTP / FIDO-style counter device). Multiple factors per account, with a designated primary and fallbacks.
- Generate and send an OTP. On a login or step-up challenge, the service generates a one-time code and delivers it over the chosen channel (SMS, email) or - for TOTP/hardware - the user reads it off their own device and nothing is sent.
- Verify an OTP. Accept a submitted code, check it against the expected value with clock-drift tolerance (TOTP) or counter-window tolerance (HOTP), enforce single-use, and return valid/invalid.
- Rate limiting and brute-force defense. Per-account and per-IP limits on verification attempts and on OTP-send requests, with lockout/backoff. This is a core feature, not an add-on.
- Fallback delivery orchestration. If the primary channel fails or times out, fall back to another channel (SMS -> email, or offer “use your authenticator app instead”) without issuing conflicting valid codes.
- Backup/recovery codes. One-time-use static recovery codes for when a user loses their device.
- Audit and anti-fraud signals. Every send and verify is logged for the account’s security history and for downstream fraud scoring (velocity, geo, device).
Explicitly out of scope (own the boundary):
- Primary authentication (password / passkey login). We are the second factor and step-up service. The identity provider owns the first factor and calls us; we return a pass/fail that the IdP folds into its session decision. We do not mint the final session token.
- The SMS/email transport itself. We integrate SMS aggregators (Twilio, MSG91, provider SMPP) and an email delivery service; we do not build the carrier gateway or the MTA. Delivery reliability is their problem; orchestration and failover across them is ours.
- Full IAM / RBAC / user directory. Accounts, roles, and sessions live in the IdP. We key off an opaque
account_id. - FIDO2/WebAuthn passkey ceremony in depth. We support hardware tokens at the OTP/counter level; the full WebAuthn attestation flow is adjacent and we note the hooks, not the whole protocol.
The decision that shapes everything: this service sits on the synchronous login path and is the last barrier after a stolen password, so its two non-negotiables are latency (sub-second, every login) and adversarial correctness (rate limiting + single-use + bounded drift windows). Generating codes is trivial. The engineering is making verification atomic and abuse-resistant across a stateless fleet, tolerating honest clock drift without handing the attacker a bigger haystack, and failing between channels cleanly. That is where the design lives.
Non-Functional Requirements (NFR)
- Scale: a large consumer platform. Assume 50 million daily active users, and because 2FA fires on login plus step-up (payments, settings changes), assume 100 million verification ceremonies/day. Each ceremony is roughly one send (for SMS/email) and one-to-few verify attempts. Peak is ~5x average (morning login surge, a marketing push, a sale), so the system must absorb bursts well above the mean.
- Latency: this is a low-latency system. Verify must be p99 under 100ms server-side - it blocks a human staring at a login screen. Generation/send acceptance must be p99 under ~50ms (the actual SMS delivery is async and out of our latency budget). The brief’s “sub-second verification” is the hard floor; we aim well under it.
- Availability: 99.99%+ on verify. If 2FA is down, logins across the whole platform stop - this is a tier-0 dependency. Generation/send can degrade to fallback channels, but verification of an already-issued code must essentially never be unavailable.
- Consistency: strong where it counts. Single-use enforcement (a code works exactly once) and rate-limit counters must be strongly consistent - a race that lets a code verify twice, or that lets an attacker exceed the attempt cap by hitting two servers, is a security hole. Audit logging can be eventual.
- Durability: enrolled secrets (TOTP shared secrets, HOTP counters, recovery codes) must be durable and never lost - losing them locks users out permanently. In-flight OTP challenge state is short-lived (TTL minutes) and can be in a fast store, but must survive a single node failure.
- Security posture: shared secrets are encrypted at rest (envelope encryption, HSM/KMS-backed), never logged, never returned over the API. Codes are compared in constant time. This is as much a security spec as a performance spec.
Back-of-the-Envelope Estimation (BoE)
Real numbers with arithmetic - they dictate the architecture.
Verification/generation throughput:
100,000,000 ceremonies/day
= 1e8 / 86,400 sec
≈ 1,160 ceremonies/sec average
Each ceremony: ~1 generate/send (for SMS/email factors) + ~1.3 verify attempts
(most users type it right; some mistype once).
Reads (verify) dominate and are the latency-critical path.
verify QPS avg ≈ 1,160 * 1.3 ≈ 1,500/sec
send QPS avg ≈ 1,160 * (fraction on SMS/email, say 60%) ≈ 700/sec
Peak (~5x): verify ≈ 7,500/sec, send ≈ 3,500/sec
TOTP/hardware-token verifies are pure compute (recompute an HMAC, compare) - no send, no external call. SMS/email ceremonies involve an outbound send but the verify is still local compute against stored challenge state. So the latency-critical path is almost never network-bound on an external provider; it is a KV lookup plus an HMAC.
Storage - enrolled factors (durable, the crown jewels):
50M users, assume ~1.4 factors each (many have app + SMS fallback) = 70M factor records.
Per factor record:
account_id 8 bytes
factor_type 1
secret (enc) ~48 -- encrypted TOTP seed / HOTP key
hotp_counter 8
phone/email hash ~32
flags/timestamps ~24
------------------------
≈ 120 bytes, round to ~250 with indexes/overhead
70M * 250 bytes ≈ 17.5 GB. Tiny. Fits comfortably, replicated.
Recovery codes: 50M users * 10 codes * ~40 bytes ≈ 20 GB. Also small.
The durable secret store is small - tens of GB. It is not a capacity problem; it is a security and durability problem. It must be encrypted, replicated, and never lost.
In-flight OTP challenge state (hot, short-lived):
A sent SMS/email OTP lives ~5 minutes (TTL). At peak send 3,500/sec:
live challenges ≈ 3,500/sec * 300 sec ≈ ~1.05M concurrent challenges
Per challenge:
challenge_id 16 bytes
account_id 8
code_hash 32
channel 1
attempts_left 1
expires_at 8
≈ 70 bytes, ~150 with overhead
~1.05M * 150 bytes ≈ 160 MB live. Trivially fits in Redis.
TOTP/HOTP verifies need NO challenge row at all - they recompute from the stored secret.
Rate-limit counters (hot, security-critical):
Per-account verify counter + per-IP counter, sliding window.
Active accounts in any 5-min window at peak: order of a few million.
Each counter is a few bytes in Redis with a short TTL.
Say 5M accounts * ~50 bytes (windowed buckets) ≈ 250 MB. Fits in memory.
These are READ AND WRITTEN on every single verify - the hottest keys in the system.
Bandwidth / external send cost:
SMS sends at peak ≈ 3,500/sec is the real money: SMS costs real currency per message
(fractions of a cent to several cents depending on country/route).
100M ceremonies/day * ~40% SMS = 40M SMS/day. At even $0.005 avg = $200K/day.
This cost pressure is why we PREFER app-based TOTP (free, no send) and treat SMS as a
fallback, and why send-side rate limiting (anti "SMS pumping" fraud) matters financially.
Audit log volume:
Every send + verify is an audit event: ~2.3 events/ceremony * 1e8 = ~2.3e8 events/day.
* ~200 bytes ≈ 46 GB/day. Write-optimized log store, TTL ~1 year for security history,
then roll to cold. Not on the latency path - fire-and-forget.
The headline: this is not a storage or throughput monster - the durable secret store is tiny and peak QPS (7,500 verify/sec) is modest for a horizontally scaled stateless tier. The genuinely hard, non-obvious constraints are (1) the rate-limit counters that are read-and-written on every verify and must be strongly consistent to actually stop brute force, (2) the sub-100ms p99 latency budget on a security-critical path, and (3) the SMS cost + delivery unreliability that forces failover orchestration. Those are the design, not the HMAC.
High-Level Design (HLD)
The spine: a stateless verification/generation API tier that the IdP calls; a rate limiter in front of (and inside) it that is checked before any crypto work; a durable secret store (SQL, encrypted) for enrolled factors; a hot challenge + counter store (Redis) for in-flight OTPs and rate-limit windows; a delivery orchestrator that fans out to SMS/email providers with failover; and an async audit/fraud pipeline. The crypto itself (TOTP/HOTP compute) happens inside the API tier with keys unwrapped via KMS.
┌──────────────────────────────────────────────┐
│ Identity Provider (owns 1st factor) │
│ calls us for enroll / challenge / verify │
└───────────────────────┬──────────────────────┘
│ (mTLS, signed service call)
┌─────────▼──────────┐
│ API Gateway │
│ authn service call │
└─────────┬──────────┘
│
┌───────────────▼─────────────────┐
│ Rate Limiter │
│ per-account + per-IP windows │
│ (checked FIRST, before crypto) │◀───┐
└───────────────┬─────────────────┘ │ atomic
│ pass │ incr/check
┌─────────────────────────┼──────────────────────┐│
│ │ ││
┌───────▼────────┐ ┌─────────▼─────────┐ ┌────────▼▼──────────┐
│ Enrollment Svc │ │ Generation Svc │ │ Verification Svc │
│ create factor, │ │ TOTP: none sent │ │ recompute TOTP/HOTP│
│ QR, store seed │ │ SMS/email: make │ │ or match challenge │
│ │ │ code + challenge │ │ single-use + drift │
└───────┬────────┘ └─────┬───────┬─────┘ └────────┬───────────┘
│ │ │ │
│ unwrap key │ │ store challenge │ read secret/
┌────▼─────┐ ┌─────▼──┐ ┌─▼──────────────┐ │ challenge
│ KMS / │ │ Secret │ │ Hot Store │◀──┘
│ HSM │◀─────────│ Store │ │ (Redis cluster)│
└──────────┘ envelope│ (SQL, │ │ challenges + │
decrypt│ enc) │ │ rate counters │
└────────┘ └────────────────┘
│ (SMS/email channels only)
┌─────────▼──────────┐
│ Delivery Orchestr. │
│ channel select + │
│ failover + dedupe │
└───┬───────────┬────┘
┌───────▼───┐ ┌───▼────────┐
│ SMS agg. │ │ Email send │
│ (multi- │ │ service │
│ provider)│ │ │
└───────────┘ └────────────┘
Async (off the latency path):
┌──────────────────────────────────────────────────────────┐
│ Audit/Fraud pipeline: every send+verify -> Kafka -> │
│ security history store + fraud scoring (velocity/geo/device)│
└──────────────────────────────────────────────────────────┘
Enrollment flow (one-time, per factor):
- IdP calls
POST /factorsfor an account. For TOTP we generate a random shared secret, envelope-encrypt it with a KMS data key, store it in the Secret Store, and return a provisioning URI (otpauth://) rendered as a QR for the user’s authenticator app. The plaintext secret leaves our boundary exactly once, to the user, and is never returned again. - For SMS/email we store the (hashed) destination. For hardware HOTP we store the key and an initial counter. We require a confirm step - the user submits one code to prove the factor works before we mark it active.
Generation/send flow (per challenge, SMS/email only):
- IdP calls
POST /challengeswithaccount_idand desired channel. The rate limiter checks send-limits first (anti-abuse/anti-SMS-pumping). - The Generation Service mints a random numeric code, stores a challenge row in the hot store (code hash, TTL ~5 min, attempts budget, single
activeflag per account), and hands it to the Delivery Orchestrator. - The orchestrator picks a provider and sends. It returns
202to the IdP immediately; delivery is async. TOTP/hardware factors skip this entirely - nothing is sent.
Verification flow (the hot path):
- IdP calls
POST /verifywithaccount_id,code, and context (IP, device). Rate limiter is checked first - if the account or IP is over its window, we reject with429before doing any crypto. This ordering is deliberate: the cheap abuse check gates the work. - The Verification Service loads the relevant factor. For TOTP/HOTP it recomputes the expected code(s) across the tolerated window and compares in constant time. For SMS/email it looks up the challenge row and compares the submitted code hash.
- On success: enforce single-use atomically (consume the challenge / advance the HOTP counter / mark this TOTP time-step used), reset the account’s failure counter, emit an audit event, return
200 verified. - On failure: atomically increment the failure counter, decrement the challenge’s attempt budget, emit an audit event, return
401. If the counter crosses the lockout threshold, return429/locked and start backoff.
The structural insight: there are two very different state stores doing two jobs. The durable SQL Secret Store holds the long-lived crown-jewel secrets - small, encrypted, rarely written, replicated for durability. The in-memory hot store holds the ephemeral, blazingly-hot state - challenge rows and rate-limit counters - that is read and written on every ceremony and must be fast and atomic. Keeping these separate is what lets verification be both sub-100ms and secure. Everything adversarial (rate limiting, single-use) lives in the hot store and leans on its atomic primitives.
Component Deep Dive
The hard parts, naive-first then evolved: (1) TOTP/HOTP verification with clock-drift and counter tolerance, (2) per-account rate limiting against brute force across a stateless fleet, (3) single-use enforcement and race safety, (4) multi-channel delivery with failover and dedupe.
1. TOTP/HOTP verification with drift tolerance
The job: accept the code a user reads off their own device (which you never communicate with) when their clock and yours disagree, without widening the attacker’s guessing window more than necessary.
TOTP is HOTP(secret, floor(current_unix_time / 30)) truncated to 6 digits - the moving factor is a 30-second time step. HOTP is the same HMAC truncation but the moving factor is a counter that increments each time the hardware token is pressed.
Naive approach: compute the code for the current time step and require exact equality
def verify_totp(secret, submitted):
step = current_unix_time() // 30
expected = hotp(secret, step) # exactly one code, "now"
return submitted == expected
Where it breaks:
- Clock drift fails honest users. The user’s phone clock and your server clock are never perfectly synced. If the user’s phone is 40 seconds fast, their app is already showing the next step’s code while your server computes the current one - instant false reject. Cheap/old devices drift by minutes. You will reject a meaningful fraction of legitimate logins and generate a flood of support tickets.
- Edge-of-window failure. Even with perfect clocks, a user who glances at the code at second 29 and submits at second 31 has crossed a step boundary - the code they typed is now “the previous step.” Exact-equality rejects it.
- Non-constant-time compare.
submitted == expectedshort-circuits on the first differing character, leaking timing information about how many leading digits matched - a (small but real) side channel. - HOTP counter desync is unhandled. A user mashes the hardware token button a few times out of your sight; its counter is now ahead of your stored counter. Exact-counter equality rejects every future code forever - the token is bricked against your service.
Exact-equality TOTP is a correctness disaster: it conflates “wrong code” with “slightly skewed clock,” and it cannot survive real-world hardware.
Evolved approach: a bounded validation window, resync, and replay protection
Accept a small window of time steps / counter values, bound it tightly, and protect single-use within it.
- TOTP validation window. Check the submitted code against the current step and one step on each side (
step-1, step, step+1) - a ±30-second tolerance, 90 seconds of total acceptance. This covers normal drift and boundary glances. We do not widen it casually: every extra step you accept multiplies the attacker’s valid-guess surface. ±1 step is the standard, defensible choice; go to ±2 only for known-bad-clock populations and accept the security cost.
def verify_totp(secret, submitted, window=1):
now_step = current_unix_time() // 30
for step in range(now_step - window, now_step + window + 1):
if constant_time_eq(submitted, hotp(secret, step)):
if not step_already_used(account, step): # replay guard
mark_step_used(account, step) # single-use
record_drift(account, step - now_step) # for adaptive sync
return True
return False
- Replay protection within the window. Because we accept 3 time steps, a code is valid for up to 90 seconds - long enough for an attacker who sniffed it to replay. So on success we record the consumed (account, time_step) in the hot store with a TTL just past the window, and reject any later submission of a code for an already-used step. This makes even a drift-tolerant TOTP strictly single-use.
- Adaptive clock-drift tracking. We record which offset actually matched (
step - now_step) per account. If a user consistently matches at+1, their device clock is reliably fast; we store a per-factor drift estimate and center the window on it (now_step + drift ± 1) rather than always on our clock. This keeps the window narrow (still 3 steps) while following the user’s real clock, so we tolerate large persistent drift without ever widening the attacker’s window. - HOTP look-ahead window and resync. For counter-based HOTP, we accept the next N counter values (look-ahead, typically ~10-20) beyond the stored counter, to absorb accidental button presses. On a match at counter
c, we advance the stored counter toc+1so all skipped values are now invalid. If the match is far out (near the window edge), we optionally require a second consecutive code to resync, so a single lucky guess cannot jump the counter. The look-ahead is bounded and one-directional - it never re-accepts a used counter.
HOTP: stored counter = 42
accept codes for counters 43..62 (look-ahead = 20)
user's token is at 47 (pressed a few extra times) -> code matches at 47
-> advance stored counter to 48; counters 43..47 are now permanently dead
- Constant-time comparison everywhere. Code comparison uses a constant-time equality to avoid timing side channels; the HMAC itself is constant-time by construction.
Why this is right: the ±1 TOTP window plus per-account adaptive drift tracking accepts honest codes across realistic clock skew while keeping the accepted-code count at the minimum (3 steps), and within-window replay protection keeps it strictly single-use. The bounded HOTP look-ahead with counter advancement un-bricks hardware tokens without ever reopening a used counter. We tolerate the real world without handing the attacker a bigger haystack - the exact balance this component exists to strike.
2. Per-account rate limiting against brute force
This is the defining security problem. A six-digit code has 1,000,000 possibilities. With a ±1 TOTP window, 3 of those are valid at any moment - roughly a 1-in-333,000 chance per blind guess. Unlimited guessing turns that into a near-certainty in minutes. Rate limiting is the only thing making the second factor actually worth anything.
Naive approach: an in-memory per-process counter, increment on each failed attempt
Each API server keeps a map account_id -> fail_count in local memory; on 5 fails, reject.
Where it breaks:
- Counters are per-process, so the fleet multiplies the limit. With 50 stateless servers behind a load balancer, an attacker’s requests spray across all of them. “5 attempts” locally becomes 5 × 50 = 250 attempts before any single server trips - and attackers deliberately spread requests to exploit exactly this. The global limit is meaningless.
- State is lost on deploy/restart. Every rolling deploy resets everyone’s counters to zero - a rolling restart loop is itself a limit bypass.
- No cross-key view. Per-account counting alone misses the attacker spraying one guess each across a million accounts (credential stuffing) - low per-account volume, massive aggregate. You need per-IP, per-device, and global dimensions too.
- Race under concurrency. Two simultaneous failed attempts both read
count=4, both write5, and the attacker got two tries at the “last” slot. Read-modify-write without atomicity leaks attempts at exactly the threshold.
Local counters do not rate-limit a distributed fleet at all; they rate-limit one process, which the attacker simply avoids by fanning out.
Evolved approach: centralized atomic counters, layered dimensions, sliding window, and graduated lockout
Move the counter to a shared, atomic store and count on several axes at once.
- Centralized atomic counters in Redis. Every failure does an atomic
INCRon a shared key with a TTL; the threshold check and increment are one atomic operation (Redis single-threadedINCR, or a small Lua script for check-and-increment). Now “5 attempts” means 5 across the entire fleet, regardless of which server handled each request. This is the core fix: one source of truth for the count.
-- Lua, atomic: increment and report whether over limit
local n = redis.call('INCR', KEYS[1])
if n == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end -- window TTL
return n -- caller compares to limit
- Layered dimensions (defense in depth). We rate-limit on multiple keys simultaneously, each with its own limit, and any one tripping blocks the attempt:
| Dimension | Key | Catches |
|---|---|---|
| Per account (verify) | rl:acct:{id} | Targeted brute force of one account |
| Per IP (verify) | rl:ip:{ip} | One host spraying many accounts (stuffing) |
| Per account (send) | rl:send:{id} | OTP bombing a user; SMS-pumping fraud |
| Global / subnet | rl:global, rl:asn:{asn} | Botnet-wide distributed attack |
Sliding window, not fixed bucket. A fixed per-minute bucket lets an attacker fire the full quota at
:59and again at:00- double rate across the boundary. We use a sliding-window counter (weighted combination of the current and previous bucket, or a sorted-set of timestamps) so the limit holds across boundaries.Graduated response, not a cliff. Rather than a hard permanent lock (which is a self-inflicted denial of service - an attacker can lock out a victim on purpose), we escalate:
- First few fails: allowed, counted.
- Over the soft threshold: exponential backoff - require an increasing delay between attempts (1s, 2s, 4s, 8s…), which collapses the attacker’s guess rate while barely inconveniencing a human who mistyped.
- Over the hard threshold: temporary lock (e.g. 15 minutes) and invalidate the current challenge, forcing a fresh factor.
- Persistent abuse: flag for step-up (CAPTCHA) or account security review via the fraud pipeline.
Separate the victim-lockout footgun. Because locking an account is itself a DoS vector, account-level lock is paired with IP/device throttling: a distributed attacker hitting one account from many IPs trips the account limit (backoff) while a single IP hitting many accounts trips the IP limit - so neither axis alone lets an attacker cheaply lock out a target or brute a victim. Legitimate users who are merely fumbling hit backoff, not a hard lock.
The math, stated. With a per-account hard cap of, say, 10 failed verifies per rolling 10 minutes before a 15-minute lock, an attacker gets ~10 guesses / 25 min ≈ fewer than 600/day against a code with ~333,000-to-1 odds per guess. Expected time to hit by blind guessing: on the order of centuries. Rate limiting is what converts “1-in-a-million, guessable in minutes unlimited” into “computationally hopeless.”
Attempt ─▶ [check rl:acct, rl:ip, rl:send, rl:global (atomic, parallel)]
any over limit? ─yes─▶ 429 + backoff/lock (no crypto done)
all ok ────────────────▶ do verification
fail ─▶ atomic INCR all dims
ok ─▶ reset acct counter
Why this is right: centralizing the counter makes the limit a true global across the stateless fleet (the naive design’s fatal flaw), atomic INCR closes the threshold race, layering dimensions defends against both targeted and distributed attacks, sliding windows prevent boundary bypass, and graduated backoff stops brute force without weaponizing lockout against real users. This component is the entire security value of the service; everything else just serves a code that this makes un-guessable.
3. Single-use enforcement and race safety
The job: guarantee a given OTP verifies exactly once, even under concurrent requests hitting different servers - a code that works twice defeats the point.
Naive approach: “check the challenge row, then delete it” as two steps
chal = redis.get(challenge_id) # read
if chal and chal.code == submitted: # compare
redis.delete(challenge_id) # consume
return True
Where it breaks:
- Read-then-delete is a TOCTOU race. Two requests with the same stolen code arrive on two servers at the same instant. Both
GETthe row (still present), both see it matches, bothDELETE, both returnTrue. The code verified twice. For a payment step-up, that is a double-authorized action. - Replayable TOTP. TOTP has no stored row to delete - it is recomputed. Without an explicit used-step marker, the same TOTP code is valid for the whole ±window (up to 90s), replayable by anyone who observed it.
- Attempt budget leaks the same way. Decrementing “attempts left” as a separate read-modify-write lets concurrent attempts each see the old value, exceeding the budget.
Any “check then mutate” split is a race; under real concurrency the single-use guarantee silently fails.
Evolved approach: atomic compare-and-consume, used-step markers, idempotency
Make consumption a single atomic operation that both validates and invalidates.
- Atomic consume for challenge OTPs. The verify is one atomic script: inside the atomic step, check the code matches and attempts remain, and if so delete/mark-consumed and return success - no window between check and consume. Redis is single-threaded per key, so a Lua script that does compare-and-delete is atomic; the second concurrent request finds the row already consumed.
-- Lua: atomic compare-and-consume
local chal = redis.call('HGETALL', KEYS[1])
if not chal then return 'EXPIRED' end
if chal.consumed == '1' then return 'ALREADY_USED' end
if chal.code_hash ~= ARGV[1] then
redis.call('HINCRBY', KEYS[1], 'attempts', -1) -- atomic budget decrement
return 'MISMATCH'
end
redis.call('HSET', KEYS[1], 'consumed', '1') -- consume in the SAME step
redis.call('EXPIRE', KEYS[1], 90) -- keep marker briefly for replay
return 'OK'
- Used-step markers for TOTP. On a successful TOTP verify we atomically
SETa keyused:{account}:{time_step}withNX(set-if-not-exists) and a TTL past the window. If theSET NXfails, the step was already consumed - replay rejected. This gives stateless-recompute TOTP the same strict single-use as a stored challenge, using the hot store’s atomic primitive. - Atomic HOTP counter advance. Advancing the HOTP counter is a conditional atomic update on the durable record (
UPDATE ... SET counter = c+1 WHERE account = ? AND counter < c+1), so two concurrent verifies cannot both advance past the same value; one wins, the other sees the counter already moved and its code is now dead. - Idempotency on retries. Network retries from the IdP must not count as new attempts or double-consume. Each verify call carries an idempotency key; a short-lived record maps the key to the first result so a retried identical request returns the cached outcome instead of re-running (and re-consuming or re-counting).
Why this is right: collapsing check-and-consume into one atomic operation closes the TOCTOU window that makes “works twice” possible; SET NX used-step markers extend strict single-use to recompute-based TOTP; conditional counter updates serialize HOTP advancement; and idempotency keys keep retries from corrupting counters. Single-use stops being a hopeful convention and becomes an atomic guarantee - which is the only kind worth anything against an attacker who can send two requests at once.
4. Multi-channel delivery with failover and dedupe
The job: get an SMS/email OTP to the user reliably across providers you do not control, failing over cleanly when one is down, without ever leaving two valid codes live or double-charging.
Naive approach: call the SMS provider synchronously; on error, immediately call a backup and send a new code
code = generate()
try:
sms_provider_A.send(phone, code)
except:
code2 = generate() # new code!
sms_provider_B.send(phone, code2) # or email
Where it breaks:
- Two valid codes at once. Generating a new code for the fallback leaves the first code (which provider A may have actually delivered despite erroring) still valid in the challenge store. Now two different codes verify - a larger attack surface and a confusing UX (“which code? I got two”).
- Synchronous send on the login path. Waiting on the SMS provider’s round-trip (hundreds of ms, sometimes seconds) blows the latency budget and couples login availability to the provider’s.
- “Error” is ambiguous. A timeout from provider A does not mean not delivered - it may have sent and the ack was lost. Blindly resending double-charges and double-texts the user (“OTP bombing” them yourself).
- No delivery feedback. Fire-and-pray: you never learn the SMS was delivered, delayed, or dropped, so you cannot make a smart failover decision or show the user honest status.
Synchronous, new-code-per-attempt failover creates multiple live codes, couples latency to the provider, and double-sends on ambiguous errors.
Evolved approach: one code per challenge, async orchestrated delivery, provider health routing, and delivery-receipt-driven failover
Decouple send from the request, keep exactly one code per challenge, and drive failover off real signals.
- One code, one challenge, many delivery attempts. The challenge (and its single code) is created once and stored. Delivery is a separate concern: the orchestrator may try provider A, then provider B, then email - all delivering the same code. The code’s validity lives in the challenge store, independent of how many send attempts happened. Fallback never mints a new code; it just tries another pipe for the same one.
- Async send off the latency path.
POST /challengescreates the challenge, enqueues a send job, and returns202immediately. A pool of delivery workers performs the actual provider calls. Login latency is decoupled from SMS latency entirely. - Provider health routing. The orchestrator tracks per-provider, per-route (country/carrier) health - success rate, latency, recent error codes - and routes to the healthiest provider for that destination, with others as ranked fallbacks. A provider throwing 500s in a region is routed around before it fails a user, not after. This is active/active across SMS aggregators, not a cold standby.
- Delivery-receipt-driven, timed failover. We use providers’ delivery receipts (DLRs) where available. The flow: send via A; if no “delivered” DLR within a short timeout (say 20-30s) and no evidence it was delivered, fail over to B (same code). We never resend on an ambiguous submit error alone without the timeout, to avoid double-send; and we cap total sends per challenge (anti-bombing). If SMS routes are degraded, we offer the user the authenticator-app path (which needs no send at all) as the cleanest fallback.
- Dedupe and cost control. Each challenge has a hard cap on delivery attempts and a per-account send rate limit (deep dive 2’s send dimension), so orchestration failover can never become a mechanism that floods or over-bills the user. An idempotency key per send job prevents a retried worker from sending twice.
POST /challenges ─▶ create ONE challenge+code ─▶ 202 (return now)
│ enqueue send job
┌──────▼───────┐
│ Delivery wkr │ route by provider health for this destination
└──────┬───────┘
send same code ▶ Provider A ──DLR delivered?──yes──▶ done
│ no DLR within 25s / hard error
send same code ▶ Provider B ──DLR?──yes──▶ done
│ still failing
offer "use your authenticator app" (no send) ──▶ user verifies TOTP
(hard cap on attempts per challenge; one code throughout)
Why this is right: one code per challenge means failover across any number of channels never creates a second valid code or confuses the user; async delivery keeps the login path fast and decoupled from flaky providers; health-based routing avoids known-bad providers proactively; DLR-plus-timeout failover resends only when genuinely needed, avoiding ambiguous-error double-sends; and per-challenge caps plus idempotency keep orchestration from becoming self-inflicted OTP bombing. The user gets their code reliably across channel failures, and the security property (exactly one live code) holds throughout.
API Design & Data Schema
API
All endpoints are service-to-service (the IdP calls us over mTLS with a signed service identity), never called directly by the browser - the user never talks to this service, only to the IdP.
Enroll a factor:
POST /api/v1/accounts/{account_id}/factors
Body: { "type": "totp" | "sms" | "email" | "hotp",
"destination": "+9199xxxxxx" | "[email protected]" // for sms/email
}
Response 201 (totp):
{ "factor_id": "f_a1b2", "otpauth_uri": "otpauth://totp/App:user?secret=...&issuer=App",
"status": "pending_confirmation" }
// secret returned ONCE, here, for the QR. Never again.
POST /api/v1/accounts/{account_id}/factors/{factor_id}/confirm
Body: { "code": "481920" } // prove the factor works before activating
Response 200: { "status": "active" }
Create a challenge (SMS/email send; no-op for totp/hotp):
POST /api/v1/accounts/{account_id}/challenges
Body: { "factor_id": "f_a1b2", "context": { "ip": "1.2.3.4", "device_id": "d_9" } }
Response 202: { "challenge_id": "c_77", "channel": "sms", "expires_in": 300,
"delivery": "dispatching" }
Errors:
429 send rate exceeded (per-account send limit / bombing protection)
404 factor not found / not active
Verify:
POST /api/v1/accounts/{account_id}/verify
Headers: Idempotency-Key: <uuid>
Body: { "factor_id": "f_a1b2", "code": "481920",
"challenge_id": "c_77"?, // present for sms/email; absent for totp/hotp
"context": { "ip": "1.2.3.4", "device_id": "d_9" } }
Response 200: { "result": "verified" }
Response 401: { "result": "invalid", "attempts_remaining": 3 }
Response 429: { "result": "rate_limited", "retry_after": 8, "locked_until": null }
Recovery codes:
POST /api/v1/accounts/{account_id}/recovery-codes -> generate a fresh set (invalidates old)
Response: { "codes": ["abcd-efgh", ...] } // shown once
POST /api/v1/accounts/{account_id}/verify-recovery
Body: { "code": "abcd-efgh" } // single-use, consumes the code
We return 202 for challenge creation (send is async) and keep verify synchronous and fast. The Idempotency-Key on verify makes retries safe. The secret and recovery codes are returned exactly once at creation and never retrievable afterward.
Data stores
Different access patterns, different stores. Be explicit.
1. Secret / factor store - SQL (Postgres), encrypted. Enrolled factors are the durable crown jewels: small (tens of GB), strongly consistent, relational (account -> factors -> recovery codes), rarely written, read on verify. We need real constraints (one active primary, foreign keys), durability (never lose a secret), and encryption. A relational store with envelope encryption fits exactly; this is not a scale problem, it is a correctness-and-security problem.
Table: factors
factor_id UUID PK
account_id BIGINT INDEX -- lookup all factors for an account
type ENUM(totp, hotp, sms, email)
secret_enc BYTES -- envelope-encrypted TOTP/HOTP key (KMS data key)
dek_id STRING -- which KMS data key wrapped it
hotp_counter BIGINT NULL -- advanced atomically on HOTP verify
dest_hash BYTES NULL -- hashed phone/email (PII minimization)
drift_steps SMALLINT DEFAULT 0 -- learned per-account TOTP clock drift
status ENUM(pending, active, disabled)
created_at TIMESTAMP
UNIQUE(account_id, type, dest_hash) -- no duplicate factors
Shard by: account_id (all reads are account-scoped; verify loads one account's factor)
Table: recovery_codes
account_id BIGINT
code_hash BYTES -- hashed, single-use
used_at TIMESTAMP NULL
PRIMARY KEY (account_id, code_hash)
Secrets are never stored in plaintext: a per-factor data key from KMS encrypts the seed (envelope encryption), the data key itself is wrapped by a KMS master key, and plaintext seeds exist only transiently in memory during compute. The DB never holds a usable secret on its own.
2. Challenge + rate-limit store - in-memory KV (Redis cluster), the hot path. In-flight challenges (TTL ~5 min) and rate-limit counters (TTL = window) are read and written on every ceremony, need sub-millisecond atomic ops, and are disposable. This is Redis’s sweet spot; durability needs are minimal (a lost in-flight challenge just means the user requests a new code).
Redis:
chal:{challenge_id} -> HASH { account_id, factor_id, code_hash, channel,
attempts, consumed, expires_at } TTL 300s
used:{account_id}:{time_step} -> "1" (TOTP replay marker) TTL ~120s
rl:acct:{account_id} -> counter (sliding window) TTL = window
rl:ip:{ip} -> counter TTL = window
rl:send:{account_id} -> counter (send/bombing limit) TTL = window
lock:{account_id} -> locked_until TTL = lock duration
All mutations via Lua scripts for atomic check-and-act.
Redis runs clustered with replicas across AZs; counters are sharded by their key (account_id / ip), which spreads load and keeps each counter on one shard for atomicity. For stricter durability on locks, back critical counters with AOF/replication so a failover does not reset an attacker’s count to zero.
3. Audit / security-event store - write-optimized append (Kafka -> wide-column / log store). Every send and verify event, ~2.3e8/day, append-only, off the latency path. Queried for a user’s security history and consumed by fraud scoring. Wide-column (Cassandra/Scylla) or a log store, TTL ~1 year then cold.
Table: auth_events
account_id BIGINT PARTITION KEY
ts TIMESTAMP CLUSTERING (desc)
event STRING -- challenge_sent | verify_ok | verify_fail | locked | recovery_used
factor_type STRING
ip INET
device_id STRING
geo STRING
Shard by: account_id (read a user's recent security history by range scan)
TTL: 365 days
Why these choices: the durable secrets are small, relational, and demand constraints + encryption + durability -> SQL, not NoSQL (there is no scale pressure here, only correctness pressure). The hot, atomic, disposable state (challenges, counters) demands sub-ms atomic ops and TTLs -> in-memory KV, where single-key atomicity gives us race-free rate limiting and single-use for free. Audit is high-volume append off the critical path -> write-optimized log store. The split is deliberate: strong consistency and durability where the secrets and security counters live, raw speed where the hot path runs, and neither store is asked to do the other’s job.
Bottlenecks & Scaling
Where it breaks first, in order, and the fix for each.
1. Rate-limit counter hot keys and the atomic-count bottleneck (breaks first). The per-account and per-IP counters are read-and-written on every verify, and under a targeted attack one account’s counter is hammered concurrently. A naive counter is both a hot key and a race.
Fix: atomic Redis INCR/Lua (single-key atomicity closes the race), key-sharded so load spreads across the cluster, and a short window TTL so counters are cheap. Under a focused attack on one key, the single-threaded per-key execution serializes safely; replicate the shard so a failover does not reset the count. The counter is the system’s hottest, most security-critical state - it gets its own capacity headroom.
2. Verify latency under load (sub-100ms p99 is the SLO). Verify blocks a human; a slow p99 is felt platform-wide.
Fix: the hot path is one KV lookup + one HMAC + atomic counter op - no SQL on the common path (the factor record is cached in-process/edge with a short TTL after first load, keyed by account_id). KMS unwrapping of the data key is cached per factor (the unwrapped key held briefly in secured memory, never persisted) so verify does not call KMS each time. Stateless API tier scales horizontally behind an LB; crypto is cheap and parallel.
3. Secret store as a single point of failure / durability risk. Losing the secret store locks out every user permanently - the worst possible outcome. Fix: synchronous replication across AZs, point-in-time backups, and envelope encryption so a DB compromise alone yields no usable secrets. Reads are cache-fronted so the DB is off the hot path; it is sized for durability and consistency, not QPS.
4. SMS provider outage / regional failure. A provider melting down in one country fails every SMS login there. Fix: multi-provider active/active with health-based routing and DLR-plus-timeout failover (deep dive 4). When SMS is broadly degraded, steer users to app-based TOTP, which needs no send at all and is the most resilient channel. SMS is a fallback by design precisely because it is the least reliable and most expensive.
5. OTP bombing and SMS-pumping fraud (cost + abuse). An attacker triggers endless SMS sends to a number (harassment) or to premium routes they profit from (pumping), running up the bill.
Fix: per-account send rate limit (the rl:send dimension), hard cap on deliveries per challenge, per-destination and per-route velocity limits, and anomaly detection on sudden send spikes to unusual routes. Prefer app TOTP (free) and gate SMS behind these limits.
6. Clock-drift false rejects at scale. Even a small false-reject rate across 100M ceremonies/day is a flood of failed logins. Fix: ±1 step window + per-account adaptive drift tracking (deep dive 1) so persistent device skew is followed, not rejected, without widening the window. Monitor the drift-match histogram as an SLI; a rising tail flags a population with bad clocks (or a server-time problem on our side - NTP discipline on our fleet is mandatory, since our clock drifting breaks everyone at once).
7. Replay within the TOTP acceptance window. A code is valid up to ~90s; an observer could replay it.
Fix: SET NX used-step markers and atomic compare-and-consume challenge rows (deep dive 3) make every code strictly single-use even within its validity window.
8. Victim lockout as a denial-of-service. Hard per-account locks let an attacker lock a target out on purpose. Fix: graduated backoff before any hard lock, pair account limits with IP/device limits so a distributed attacker trips per-IP throttles, and prefer step-up (CAPTCHA) over permanent lock. Lockout protects the account without becoming a weapon against it.
9. Audit pipeline backpressure. 2.3e8 events/day must never slow verify. Fix: audit is fire-and-forget to Kafka off the latency path; a backed-up consumer or down analytics store never blocks a login. Events buffer in Kafka and drain when downstream recovers.
10. Single points of failure, broadly. Every stateful tier (SQL secret store, Redis, Kafka) is replicated across AZs; every stateless tier (API, delivery workers) is horizontally scaled behind LBs across regions. KMS is a hard dependency for unwrapping secrets - we cache unwrapped keys briefly so a transient KMS blip does not stop verifies, and run KMS multi-region. No single node whose loss stops logins.
Shard keys, stated plainly: factors and recovery_codes -> account_id (every verify is account-scoped; one lookup serves the ceremony). auth_events -> account_id (read a user’s security history by range scan). Redis challenge rows -> challenge_id; rate-limit counters -> their dimension key (account_id / ip), so each counter lives on one shard for atomicity and load spreads across keys. Never shard by time - it concentrates all current traffic on the “now” shard, a permanent hot spot, and this is an all-live-traffic system.
Wrap-Up
The trade-offs that define this design:
- Two stores for two jobs. Durable secrets live in encrypted SQL optimized for consistency and durability (it is tiny - correctness, not scale, is the pressure); hot challenge and rate-limit state lives in an in-memory KV optimized for sub-ms atomic ops. Verification is fast and secure because the adversarial state (counters, single-use) sits on atomic primitives, not on the durable store.
- Rate limiting is the product, not a feature. A six-digit code is worthless without a strong, centralized, atomic, multi-dimension limit - it is the only thing converting “guessable in minutes” into “computationally hopeless.” Graduated backoff stops brute force without turning lockout into a DoS against real users.
- Tolerate the real world without widening the attacker’s window. ±1 TOTP step plus per-account adaptive drift tracking accepts honestly-skewed clocks while keeping the accepted-code count minimal; bounded HOTP look-ahead un-bricks hardware tokens; within-window
SET NXmarkers keep it all strictly single-use. We trade a tiny, bounded tolerance for a huge reduction in false rejects, and buy back the security with replay protection. - One code, many pipes. Delivery failover tries SMS providers then email then app for the same code, driven by provider health and delivery receipts, so a channel failure never creates a second valid code, never blocks the login path, and never becomes self-inflicted OTP bombing. App-based TOTP is the preferred, free, most-resilient channel; SMS is an expensive fallback, limited and routed defensively.
- Fast where it blocks, async where it does not. Verify is synchronous and sub-100ms (KV + HMAC + atomic counter, no SQL, no KMS call on the common path); sending and auditing are async and off the latency budget.
One-line summary: a stateless, horizontally-scaled verification tier that gates every attempt behind centralized atomic multi-dimension rate limiting, recomputes TOTP/HOTP against a tight drift-tolerant window with atomic single-use enforcement, loads crown-jewel secrets from an encrypted replicated SQL store (cached off the hot path), keeps all hot adversarial state in an atomic in-memory KV, and orchestrates one code across SMS/email/app with health-and-receipt-driven failover - delivering sub-100ms, brute-force-proof second-factor verification for 100 million logins a day.
Comments