Skip to content

How to design login and authentication

The first sections are free. The deep dives, level expectations and quiz are part of Pro.

On this page
Asked at
Practice this question

The problem

Login is the front door to tens of millions of accounts: sign-up, sign-in, staying signed in, a forgotten password, a second factor, and the defenses that keep a leaked password from becoming a stolen account. The answer turns on one fact about the sign-in path: checking a password is slow on purpose, about 100 ms of a core per check, so a morning rush or an attacker replaying leaked passwords exhausts the hashing servers long before any database notices. A strong answer gives hashing its own capacity, keeps sessions as random ids looked up on the server so a stolen laptop can be signed out at once, and spends its defenses on scoring sign-ins rather than locking accounts.

Clarifying questions

AskWhy it mattersA typical answer

How many users do we have, and what does the sign-in peak look like?

Sign-in is CPU-bound, since each password check burns about 100 ms of a core. The peak rate, not the user count, decides how many hashing servers you need.

Tens of millions of users, with sign-ins peaking in the morning. No peak rate is given, so state an assumption and size from it: we take about 1,400 sign-ins a second at the top of the morning, worked out in the estimates.

Is this just email and password, or do we also sign people in through outside identity providers?

An outside provider adds a redirect flow, token exchange and account linking, which is a different design from password storage and would eat the round.

Email and password. Outside providers are out of scope unless you choose to add them at the end.

Is it a single product on a single domain, or many services and domains that share a sign-in?

One domain can look each session up on the server and end it at once. Many domains and third parties push you toward signed tokens, which are hard to pull back before they expire.

One big consumer product on one domain. Design for that, and say how you would change it for many domains or native apps if asked.

How long should someone stay signed in, and who decides when a session ends?

It fixes the idle and absolute limits, and whether sign-out and password reset have to end sessions on other devices right away.

Sessions last up to 8 hours, with a shorter idle limit. A user can end one device or all of them, and a password reset ends the rest.

Which attack worries us most: guessing one account's password, or replaying passwords leaked from other sites?

Per-account counters stop guessing but miss leaked pairs, where each account is tried about once with a password that is often right. The defenses differ.

Both, but the leaked-pair replay is the one that reaches millions of accounts. Design for it, and avoid lockouts that let an attacker lock real users out.

Is a second factor required for everyone, or asked for on risky sign-ins?

Asking at each sign-in is simpler and safer but adds friction for tens of millions of people; asking on risky ones needs a risk score and a fallback when scoring is down.

Users can turn one on, and we ask for it when a sign-in looks risky. Business customers may later want to require a stronger factor, so leave room for that.

The requirements menu

RequirementScopeWhy

Sign up and sign in with email and password

Core

The whole product. It fixes what you store at sign-up and the slow check you run at sign-in.

Stay signed in across visits, and sign out of one device or all of them

Core

Decides the session design: a random id looked up on the server, or a signed token, and how a stolen laptop gets signed out.

Reset a forgotten password by email

Core

The recovery path is the one attackers aim at when the sign-in page is hardened, so its token, its message and what it does to open sessions all matter.

Turn on a second factor, and be asked for it on risky sign-ins

Core

A leaked password on its own should not open the account. Asking on risky sign-ins keeps friction low but needs a risk score.

Slow down password guessing and attacks with leaked passwords

Core

Guessing and leaked-pair replay are different attacks with different limits: per account for one, per address, network and device for the other.

Check a new password against lists of passwords leaked in past breaches

Optional

Worth taking if time allows: it stops the most reused passwords at sign-up, and it is a lookup at write time, so it costs nothing on the sign-in path.

Email the user when a sign-in comes from a new device

Optional

Cheap and useful: the user is the one who knows the sign-in was not theirs, and the alert needs a link to end sessions. Take it if the notification queue is already on the board.

Remember a trusted device so the second factor is skipped there

Optional

It makes a risk-based second factor bearable. Leave it unless asked, because the device cookie becomes something worth stealing.

Offer a phishing-resistant factor such as a passkey or security key

Optional

Codes typed from a text message or an app can be phished; a passkey is bound to the site. Name it as the answer to business customers who want a stronger factor, then move on.

Sign in through a single-use emailed link instead of a password

Optional

It removes password storage from the design and reuses the reset-token machinery. Mention it as an alternative, but do not swap the question for it.

What each user may do once signed in (authorization)

Out of scope

Permissions are a separate model. Keep a user id on the session so a later authorization layer has something to read, and stop there.

Sign-in through outside identity providers, unless the candidate adds it

Out of scope

A redirect flow, a token exchange and account linking. Say where it would plug in, at the auth service, and park it.

Account recovery by support staff

Out of scope

A human process with its own identity checks. Note that it exists, since a user who loses their second factor needs a way back in.

Non-functional requirements

RequirementWhat it forces

Passwords are kept only as slow salted hashes, never in a form that can be reversed

A deliberately slow hash such as Argon2id or bcrypt, a random per-user salt, and, as defense in depth, a pepper held outside the database. It also forces the hashing to be paid at each sign-in, which is where the CPU goes.

Session ids carry at least 64 bits of entropy (OWASP)

Ids come from a cryptographically secure random generator, carry no meaning, and are looked up on the server. A guess is hopeless, so the id can sit in a cookie with no signature.

Sign-in stays available, and an outage never weakens the checks

The hashing pool, the session store and the risk scorer each need more than one node, and when the scorer is down the auth service falls back to fixed rate limits and challenges rather than to no checks.

At most 100 failed attempts in a row on one factor before it is disabled (NIST)

A failure counter per account and per factor, reset on success, with waits that grow before the cap is reached. It also forces a recovery path, since a disabled factor has to be restored through another factor or re-enrolled.

Sessions end on the server after an idle limit and an absolute limit

The session row stores created and last-seen times and the server checks both on each request; a client timer is a courtesy, not the control. A stolen session is worth at most the absolute limit.

Estimates

QuantityWorkingResultWhat it sizes

Password checks one core can do

1,000 ms in a second ÷ about 100 ms per bcrypt check at cost 10 = about 10 checks a second

About 10 a second per core

The ceiling of the sign-in path: everything else on the board is cheap next to this.

Sign-ins a second at the morning peak (assumption)

Assume 50 million users, of whom 10% sign in during the busiest hour: 5 million ÷ 3,600 seconds ≈ 1,400 sign-ins a second

About 1,400 a second

The load the hashing pool must carry on a normal morning. Say the assumption out loud; the interviewer may hand you a different one.

Hashing servers at that peak

1,400 checks a second ÷ 10 a core = 140 cores; on 16-core servers that is about 9 servers; double it for headroom and a lost zone ≈ 18 servers

About 18 servers doing nothing but hashing

The hasher pool, and why it should not share servers with the product: a sign-in spike would starve everything else.

Cores a leaked-pair attack burns

1 million pairs in one hour ≈ 280 checks a second ≈ 28 cores; 10 million pairs in an hour ≈ 2,800 a second ≈ 280 cores, about twice the morning peak

28 to 280 cores, before any defense

Why the defenses must act before the hash: the attack is a CPU bill before it is a security problem.

Session lookups a second at peak (assumption)

Assume 10 million people active at once, each making a request about once each 10 seconds: 10 million ÷ 10 = 1 million lookups a second

About 1 million lookups a second

The session store: an in-memory store sharded by session id, or a short-lived token so most requests skip the lookup.

Size of the session store

50 million users × 2 signed-in devices × about 200 bytes a row = 20 GB

About 20 GB

Memory for the session store: small enough that the node count is set by the request rate and by redundancy, not by data size.

Length of ids and tokens

64 bits = 16 hex characters; 128 bits = 16 bytes = 32 hex characters, or 22 base64url characters

32 hex characters for a session id or reset token you generate yourself

The session id and reset token columns, and why guessing one is not a realistic attack.

How long a revoked device keeps working with short-lived tokens

Access tokens valid for 5 minutes against an 8-hour absolute limit: 8 hours = 480 minutes; 480 ÷ 5 = 96

Up to 5 minutes instead of up to 8 hours, about 96 times shorter

The sign-out lag of the token design, and why the refresh check must happen on the server.

Core entities

EntityWhat it holds

User

One row per account: who they are and whether the account may sign in.

Credential

The password as a slow hash with everything needed to check it, and nothing that reverses it.

Session

One row per signed-in device, found by a random id the client holds in a cookie.

Reset token

A single-use secret sent by email, stored as a hash so a database leak does not hand out resets.

Second factor

An enrolled second factor: a code generator, a phone number, or a passkey's public key.

Sign-in event

A record of each attempt, written once and not updated, which risk scoring reads and the user can review.

The API

EndpointNotes

POST /signup { email, password } → 201

Checks the password against the breached-password list, hashes it on the hasher pool and inserts user and credential in one transaction. For a taken email, our choice is to return the same generic response as for a new one, following the generic-message advice for registration, and to let the existing owner know by email, so the form does not reveal who has an account.

POST /login { email, password } → session cookie, or a second-factor challenge

Scored before the hash is computed; a wrong email and a wrong password get the same message and about the same time. On success the cookie is Secure, HttpOnly and SameSite=Lax, and a fresh session id replaces any the client had. A high score returns a challenge id instead, and the session is created when the factor passes.

POST /logout → ends the session on the server

Deletes the session row, then tells the browser to clear the cookie. The server delete is the part that matters: a cookie cleared on the client with the row still live is not a sign-out.

POST /password-reset { email } → the same answer whether or not the account exists

Writes the token hash and queues the email when the account exists, and still does equal work and takes about the same time when it does not. Rate-limited per address and per IP, and it changes nothing else on the account.

POST /password-reset/confirm { token, new_password }

Hashes the token, looks it up, refuses it if expired or used, marks it used, saves the new password hash, ends the user's other sessions and emails them. It leaves the user signed out: they go back through POST /login with the new password.

The high-level design

sessionlookupsign-inrequestshashClientProductAuth serviceCredentialsSessions

Step 1 of 4

An auth service beside the product

Start with the two kinds of request. Sign-up, sign-in, sign-out and reset go to an auth service that owns the users and credentials table and the session store. Product requests carry a session cookie, and the product services look the id up in the session store to learn who is calling. The auth service is its own deployable so a release of the product does not take sign-in down with it, and so the credential table is reachable from one place.

sign-inrequestsallowalertspasswordhashpeppersessionlookupClientRate limiterRisk scoringProductAuth serviceAlert queueHashersCredentialsKeysSessions
The whole design

What breaks first

The deep dives

Storing and checking passwords. A person signs up and later signs in on a different day. What do you write at sign-up, what runs when they type the password again, and how does the design survive a copy of the credential table leaking?

A concept that helps here: Password storage and sessionsA concept that helps here: Naming the bottleneck firstA concept that helps here: Back-of-the-envelope estimation

Stopping account takeover. An attacker takes millions of email and password pairs leaked from other sites and tries each one against your sign-in page, one attempt per account. What notices, what stops it, and what does it cost the real user who signs in from a new phone?

A concept that helps here: Rate limiting algorithmsA concept that helps here: Failing open or failing closed

Staying signed in. Someone is signed in on a phone and a laptop. The laptop is stolen and they want it signed out now, while the phone stays signed in. How does a later request learn who is calling, and how fast does the sign-out reach it?

A concept that helps here: Password storage and sessionsA concept that helps here: API gatewaysA concept that helps here: Consistency models

Forgot password. A user clicks forgot password while a thief is still signed in on their stolen laptop. Walk the flow from that click to the moment the user signs in again, and say what each step stores and what the thief can still do.

A concept that helps here: Queues and logsA concept that helps here: Retries and dead-letter queues

Concepts this guide uses

Sources

  1. OWASP Cheat Sheet Series: Password Storage Cheat Sheet
  2. OWASP Cheat Sheet Series: Session Management Cheat Sheet
  3. OWASP Cheat Sheet Series: Forgot Password Cheat Sheet
  4. OWASP Cheat Sheet Series: Credential Stuffing Prevention Cheat Sheet
  5. OWASP Cheat Sheet Series: JSON Web Token Cheat Sheet
  6. OWASP Cheat Sheet Series: Authentication Cheat Sheet
  7. OWASP Cheat Sheet Series: Multifactor Authentication Cheat Sheet
  8. NIST SP 800-63B-4, Digital Identity Guidelines: Authentication and Authenticator Management
  9. Dropbox Tech Blog: How Dropbox securely stores your passwords
  10. MDN: Set-Cookie header
Sign in to report a mistake