System design interview guide
Auth System Design
Picture opening an app on a new phone and typing your email and password. A second or two later you are inside your account, and the app keeps you signed in so you do not have to type the password again on every tap. Behind that screen, strangers are sending thousands of email and password pairs that leaked from other websites, hoping some of them also work here. Every one of those guesses makes the server run a deliberately slow password check, so if the server is not careful the strangers use up all of that capacity and your real login times out. The part of the system that proves who you are, remembers that you proved it, and can take that proof back later is called an authentication system, and a good answer explains how it stays both safe and fast.

Problem statement
Picture a shopping app where people create an account with an email and password, stay signed in on their phone, reset a forgotten password by email, and sometimes enter a one-time code before the login finishes. Design the authentication system behind that: create accounts, check the password once, hand out a proof of login, check that proof on every later request, support sign-out and password reset, and optionally require a second step. The main design work is choosing where secrets live, how they expire, how they are taken back, and how the system behaves when attackers try many reused passwords from other website leaks.
Introduction
The problem: a new phone, a stolen phone, and a list of leaked passwords
Maya downloads a shopping app and signs up with her email and a password. A week later she opens the app and she is straight inside her account, with her saved address and her past orders, even though she did not type anything. Three small things have to be true for that to work. The company must have kept something that lets it recognise her password later. The app must have been handed some proof that she already logged in. And every request the app sends afterwards must carry that proof, so the server knows whose orders to show.
Now think about what can go wrong in that quiet picture. The company’s database could leak, and if it held real passwords, then everyone who reuses a password on other sites is exposed. Maya’s phone could be stolen, and whoever holds it opens the app as her until she can cut that phone off. A forgotten password could be fixed with an email link, but then anyone who gets hold of that link can take over the account. And on the other side of the internet, strangers hold long lists of email and password pairs that leaked from unrelated websites, and they feed those pairs into the login form thousands of times a minute, hoping that some of them also work here.
The part of the system that handles all of this is called an authentication system. It looks like a small box in a diagram, which is why interviewers like it, but nearly every line of it is a security decision. This page walks through those decisions in the order you would make them in the room: first what we are solving and why it matters, then what the system must do, then how big it is, and only after that the design itself.
Why teams bother with authentication
Almost every product you use has a login, so it is easy to forget how much a company puts at stake on that one screen. A few reasons explain why teams spend real engineering time on it.
Trust. An account takeover is the kind of problem users remember. Someone loses their saved cards, their messages or their money, and they blame the company, not the attacker. One well-publicised leak can cost more than a year of new features can earn back.
Everything else depends on it. Orders, messages, payments and settings all assume that the system knows who is asking. If that answer is wrong even occasionally, every other feature is wrong along with it.
Availability. Login is the front door. If it is slow or down, nobody can use anything behind it. Attackers know this, which is why a flood of fake logins can hurt a company even when none of the guesses succeed.
Cost and support. Locked-out users call support. Reset emails and text messages cost money per message. Fraud and refunds cost far more. A system that handles these cases well saves a surprising amount of human effort.
Rules and expectations. Customers, partners and regulators all expect that passwords are never kept in readable form, that old devices can be signed out, and that security events leave a record. You do not need to quote any law in an interview, but you should be able to say that these expectations exist and that they shape the design.
What problem are we solving?
The system has to answer one question at two very different speeds. When someone logs in, the system asks: “Is this person who they say they are?” That happens rarely, and it is allowed to take a little time. After they are in, every request the app sends asks a cheaper version of the same question: “Is this still that same person, and has their access been taken away since?” That second question is asked on every tap, every page and every call, so it has to be quick.
Here is what goes in and what comes out. A person gives an email and a password to create an account, and the system answers with a new account. Later they give the same email and password, and the system answers with some proof that lasts for a while. On every request after that, the system takes the proof and answers with a user id or a rejection. Around that main path sit a few more actions: signing out one device or all devices, extending a long login, resetting a forgotten password, and asking for a second step such as a one-time code.
Success looks like four things. A real person gets in within a few hundred milliseconds. A copy of the company’s database does not hand over anyone’s password. A stolen phone can be cut off, and “cut off” means it really stops working. And a flood of fake login attempts does not stop real people from getting in.
How to get there is the whole interview, and we will not guess at it yet. First we need to be clear about what the system must do and how well, so that every design choice later has a reason behind it.
This page is the interview deep dive in the system design interview guides hub. If the idea of limiting how often someone can try is new to you, the rate limiting fundamentals are a short and useful read first.
How to approach
In an interview you do not start by drawing boxes. You start by turning a short, vague prompt into a clear contract: who the users are, what the system must do, how well it must do it, and what is out of scope. Only then do you size the problem, make the design decisions one at a time, and draw the result. The list below is the order this page follows.
How to design an authentication system in an interview
- Clarify the problem: email and password or also sign-in through another company, which clients (browser, phone), how fast a lost device must be cut off, whether a second step is needed, how heavy an attack to expect, and what should happen when something fails.
- Write the functional requirements (what the system does) and the non-functional requirements (how safe, how fast, how big, how reliable).
- Estimate the size: how many people log in, how many requests check an existing login, and how much work one password check costs.
- Make the design decisions in order: how to store the password, what the proof of login is, where the client keeps it, how to end it, where the second step fits, how to protect the slow check, how reset works, and what to do when the store is down.
- Draw the picture those decisions produce, then walk one login and one later request through it.
- Go deeper where the interviewer pushes: the exact signed-in check, refresh tokens, password hashing details, bot traffic, reset links, and one production failure.
Clarifying questions (say these in the room)
In a real interview the prompt is only a few words: “Design an authentication system.” Before you design anything, ask questions until the problem is clear. Each answer below changes the design, which is why it is worth asking.
You: “Are we designing email and password login, sign-in through another company such as Google, or both?”
Interviewer: “Email and password. You can mention sign-in through another company as an extension.”
That answer means your core design must include storing passwords, logging in, remembering that someone is signed in, resetting, and ending a login. Signing in through another company can prove who someone is, but your product still has to hand out and check its own proof of login afterwards, so it does not remove that part of the design.
You: “Which clients do we support: a browser, a phone app, third-party API callers, or all of them?”
Interviewer: “Browser and phone app are enough.”
That answer decides where the proof of login is kept. A browser can hold it in a protected cookie, and a phone app usually keeps it in the phone’s secure storage and sends it in a header. The idea is the same, only the storage differs.
You: “If a password changes or a device is lost, how fast must the old login stop working: instantly, within a few seconds, or within a few minutes?”
Interviewer: “Within a few seconds is fine, but it has to be real. Support must be able to say it is cut off.”
This is the exactness question for this problem. “Within a few seconds” lets you accept a tiny delay in exchange for speed, and “has to be real” rules out the idea that signing out only deletes a cookie on the phone. You will use this answer to choose how logins are remembered.
You: “Is a second step, like a code from an authenticator app, required for everyone, or optional?”
Interviewer: “Optional, but show where it fits.”
So the design needs a place between “the password was right” and “you are now fully logged in” for a second check to happen, even if many users never see it.
You: “Roughly how many users are there, how many are active at once, and how heavy is an attack on the login form?”
Interviewer: “Assume about ten million users and a few million active at peak. Attacks using leaked passwords can send many times the normal number of logins.”
Those numbers feed the capacity estimate in the next section. They also tell you early that the password check needs protection, because attackers choose the most expensive thing you do and ask for it again and again.
You: “If the store that remembers who is signed in becomes unreachable, should every part of the product behave the same?”
Interviewer: “You choose, and defend it.”
Two words come up here. Fail closed means refuse requests when you cannot check who someone is, which is the usual choice for money and account settings. Fail open means let requests through on a best-effort basis, which is sometimes acceptable for harmless reads where staying available matters more. The interviewer wants to hear you choose a policy and say why.
You: “I want to keep deciding what a user is allowed to do inside each product, enterprise single sign-on, and a machine-learning fraud platform out of scope, so we can focus on proving who someone is. Does that match what you want?”
Interviewer: “Yes, focus on proving identity.”
If the interviewer later asks about hash settings, token formats or Redis, you do not need to answer yet. Park them until the design decisions, where each one has a natural place.
Functional requirements
Functional requirements describe what the system does. From the answers above, an authentication system must:
- Create an account. A person signs up with an email and a password, and the system keeps what it needs to recognise them later without keeping the password itself.
- Log a person in. The system checks the email and password once and, if they match, gives the client some proof that it logged in.
- Recognise a signed-in person on every later request. The system takes that proof and answers with a user id, or says no, without asking for the password again.
- End a login. A person can sign out one device, or sign out everywhere, and an administrator can do the same when a device is lost.
- Keep a long login alive safely. A phone app should stay signed in for weeks without holding a long-lived, powerful proof that would be dangerous if stolen.
- Reset a forgotten password. A person can prove they own the email address and choose a new password, and the old logins stop working.
- Ask for a second step when needed. For people who turned on a second factor, or when something about the login looks risky, the system asks for a code before the login is finished.
- Record security events. Logins, failures, resets and sign-outs leave a record for investigation, and that record never contains a password or a secret link.
Non-functional requirements
Non-functional requirements describe how well the system must do its job. They are the numbers and promises that shape the design.
- Login speed. A real person’s login should finish within a few hundred milliseconds most of the time, because a slow login screen feels broken.
- Safe storage. If someone copies the whole database, they must not be able to read anyone’s password, and they must not be able to use stored sign-in proofs directly.
- Fast, available checks of an existing login. The check that runs on every request must add very little time, and it must keep working when the login screen is under attack.
- Real revoke. When a login is ended, it must stop working within the few seconds the interviewer agreed to, not “eventually” and not “when the token expires tomorrow”.
- Resistance to guessing without hurting real people. Attackers must find guessing slow and expensive, while a real person who mistypes once is not locked out and is not made to wait.
- Stated behavior on failure. For each dependency that can fail, such as the session store or the email provider, the system has a rule decided in advance.
- Scale. About ten million users, a few million active at once, and request checks far more common than logins (all estimates, which we tune in the next section).
- Visibility. The team can tell whether login is healthy and whether an attack is under way, not just whether the website returns “OK”.
Out of scope (and why you park these)
Write a short out-of-scope list on the board so the interviewer sees you can bound the problem.
Full identity-provider features. Enterprise single sign-on, SAML, automatic account provisioning and company-wide admin policy would turn this into an identity-platform interview. Keep the base system focused on one account, its password and its logins.
Deciding what each user may do inside the product. Authentication proves who someone is. Authorization decides what that person is allowed to open. Mention the boundary, hand the user id to the services that decide, and keep the design on login and checking.
Phone biometrics. Face or fingerprint unlock opens a locked item on the phone itself. It does not replace the server’s check of a login, the revoke, or the password reset.
A fraud machine-learning platform. Risk scoring is useful, but the core system can use simple signals such as the network address, the device, a new location, and the number of recent failures. Leave model training out unless you are asked.
Customer support tooling. Support matters, but support staff must never be able to read passwords, raw reset links, authenticator secrets or recovery codes. Say that admin actions are audited, then park the workflow.
That is the requirements stage. If you want to practice it before reading on, try the requirements stage on Practice System Design (about 5–10 minutes), then come back for the sizing and the decisions.
Minute pacing (about 40 minutes)
| Minutes | Focus |
|---|---|
| 0–5 | Clarify the problem; write functional and non-functional requirements; agree out of scope |
| 5–10 | Capacity: logins, request checks, cost of one password check |
| 10–20 | Design decisions: password storage, proof of login, ending a login, second step, protecting the slow check |
| 20–28 | High-level boxes, then one login and one later request told as stories |
| 28–36 | Deep dive: ending a login for real, refresh tokens, bot traffic, reset links |
| 36–40 | One production war story and questions |
In the room (how you open): “I’d start by agreeing what we are building: email and password login for a browser and a phone app, a second step that is optional, and a logged-in person who must be cut off within a few seconds when a device is lost. I’ll ask how many people use it and how heavy an attack on the login form is, because that decides how much the password check can cost. I’ll write the functional and non-functional requirements on the board, and name what is out of scope. Only then will I size the problem and make the design choices one at a time.”
If you remember one thing: Ask first, write the requirements down, and only then design. Tell one login story and one later request story before you recite algorithm names.
Capacity estimation
Now that the requirements are clear, we need to know how big the problem is, because the size decides how much the password check can cost and what kind of store the signed-in check needs. Authentication has two very different traffic shapes. Logging in is rare and expensive, since it has to run a deliberately slow password check. Checking that someone is still signed in is constant and cheap, because every request the app sends needs it.
Rough numbers to anchor the whiteboard (all of them are estimates to tune in the room):
| Input | Order of magnitude (estimate) | Design implication |
|---|---|---|
| Registered users | About 10 million | Credentials need clear user ids, and every record carries its own version of the password settings |
| People active at once | A few million at peak | The signed-in check is the hot path, not login |
| Signed-in checks | About 50,000 a second at peak (3 million active people × about one call a minute) | One cheap lookup per request, with no password work and no slow database query |
| Normal logins | A few hundred a second at peak | Fine, as long as each one costs bounded CPU |
| Password check cost | Around 100 ms of CPU and tens of megabytes of memory for one check (an illustrative setting; tune to your hardware) | One processor core finishes only about 10 checks a second, so 200 logins a second already needs about 20 cores |
| Attack logins | Possibly 20,000 a second or more | If every attempt ran the full check, that would need about 2,000 cores, which is why the check must be protected before it runs |
| Live logins stored | About 20 million (10 million users × about 2 devices) × roughly 200 bytes ≈ 4 GB | Memory is modest, so a few nodes are enough for size; they are there for speed and availability |
| Check budget | Under about 5 ms added to each API call at the 99th percentile (p99: 99 of every 100 checks finish at least this fast) | One lookup in the same zone as the gateway, with connections kept open |
What the numbers imply
- Never run the password check on every request. At about 10 checks a second per core, 50,000 requests a second would need thousands of cores just to answer “who is this”. That is the whole reason a login hands back a cheap proof.
- Attackers choose the most expensive thing you do. A real person logs in a few times a month, but a bot can ask for the slow check thousands of times a second. The estimate above shows that the slow check can be turned into an outage, so protection has to run before it.
- The signed-in check is small in count but large in blast radius. 50,000 lookups a second fits on a couple of busy nodes, but if that store is down, nobody can use the product. The question is therefore less “how many nodes” and more “what happens when it fails”.
- Memory is not the problem, but memory per password check is. A modern password hash deliberately uses memory so that attackers cannot cheaply run it on graphics cards. A few dozen of them running at once on one machine use gigabytes, so the number running in parallel must be capped.
- Reset and second-step traffic is small in normal times and spikes in attacks. A phishing campaign or an attack on the reset form can send many emails at your cost, so those unauthenticated endpoints need limits too.
Checkpoint: Why can a login be slow while the check on every request cannot?
If you remember one thing: The password check is rare, slow and expensive, so protect it. The signed-in check is constant and cheap, so keep it boring.
Design decisions
We now know what the system must do, how well, and roughly how big it is. Now we choose. Each decision below answers one question that the requirements raised, and each one rules out an easier idea that would not survive those requirements. Read them in order, because every decision builds on the one before it.
Decision 1: How do we store the password?
The first requirement says a copied database must not reveal anyone’s password. So the question is how the system can recognise a password later without keeping the password itself.
The simplest idea is to store the password exactly as the person typed it and compare on login. It is easy and it works, until the day someone copies the database. Then every password is readable at once, and since many people reuse passwords on other sites, the damage spreads to those sites too. It also means that staff, backups and logs can all see passwords by accident. That breaks the safe storage requirement outright.
A second idea is to encrypt the passwords. Encryption can be undone with a key, so the server must have access to the key at all times in order to check logins. Anyone who steals the database through the server very often steals the key too, and the passwords are readable again. The key point is that the server never needs to read a password back. It only needs to answer “does this typed password match the one we saw at signup?”.
A third idea is to store a hash, which is a one-way scramble: the same input always gives the same output, but the output cannot be turned back into the input. On login the server scrambles what was typed and compares. This is the right direction, but a fast hash such as SHA-256 is built to be quick, and a thief with a graphics card can try billions of guesses per second against a stolen list. Two people with the same password also get the same hash, which shows up as a pattern in the leak.
The choice is a salted, deliberately slow, one-way hash. A salt is a random value stored next to each hash and mixed in before scrambling, so two people with the same password get different hashes and ready-made lookup tables are useless. “Slow” means an algorithm designed to cost real time and memory per guess. The usual names are Argon2id (a modern choice that also needs a lot of memory) and bcrypt (older and still widely used). The system stores the algorithm name and its settings next to each hash, so that the cost can be raised later and old hashes upgraded the next time that person logs in. It also helps to refuse passwords that already appear in public breach lists.
This choice creates a new problem that we will handle in Decision 6. Every real login now costs about a tenth of a second of CPU, so anyone who can make the server run it thousands of times a second can overload the login.
Decision 2: What does “still signed in” mean on the server?
After the password is checked once, the person has proved who they are. The capacity numbers showed that we cannot repeat the password check on every request. So what do we hand back, and what does the server check on later requests?
The simplest idea is to put the user id in a cookie and trust it. That fails immediately, because anybody can edit their own cookie to say they are user 1. The proof has to be something nobody else can forge or guess.
There are two ways to do that, plus a mix of both.
- A session row. The server creates a long random value (the session id), stores a row for it that says which user it belongs to and when it expires, and gives the client only the random value. On every request the server looks the value up. Ending a login is simple: delete the row. The cost is one lookup per request.
- A signed ticket. The server builds a small piece of text that holds the user id and an expiry time, and signs it with a secret key so that nobody can change it without the signature breaking. A well-known format is the JWT (JSON Web Token). Anyone who has the matching key can check the ticket on their own, with no lookup. The cost is that the server holds no row to delete, so ending a login early is hard until the ticket expires.
- A mix. A very short-lived signed ticket (five to fifteen minutes) for normal calls, plus a longer-lived random refresh token stored on the server. When the short ticket expires, the client trades the refresh token for a new ticket, and that trade is the moment the server can say no.
The requirement that matters here is real revoke within a few seconds, together with a fast check that works at 50,000 requests a second. A session row gives the best revoke and costs a lookup we can afford. A signed ticket gives the cheapest check but weakens revoke. So for a browser, where instant revoke matters and a lookup is cheap, we choose an opaque session row (opaque because the random value means nothing on its own). For a phone app, or when many services must verify identity without calling a central store, we choose the mix. The decision matrix below puts the choices side by side, and the deep dive shows what revoke looks like in each.
Decision 3: Where does the client keep the proof?
Once we have a proof, the client has to hold on to it and send it with every request. The simplest idea for a web page is to keep it in the browser’s localStorage and attach it with JavaScript. That fails a requirement from earlier: if the site has a cross-site scripting bug (a way for an attacker to run their own JavaScript on your page), that script can read the proof and send it away. The attacker then owns the login.
For a browser, the choice is a cookie with three protective flags. HttpOnly means page scripts cannot read it. Secure means the browser only sends it over an encrypted connection. SameSite tells the browser not to send it on requests started from other websites, which cuts down a trick called cross-site request forgery (a malicious page makes your browser send a request you did not mean to send). SameSite helps but is not the whole answer, so state-changing requests still need an anti-forgery check. HttpOnly also does not stop a script from acting as the user inside the page, only from stealing the proof.
For a phone app, there are no cookies in the same sense, so the choice is the phone’s secure storage (the keychain on iPhones, the keystore on Android) and an Authorization: Bearer header on each request. A bearer proof is “whoever holds it can use it”, which is why it must stay short-lived or revocable.
Decision 4: How does a sign-out really end a login?
The requirements said a lost phone must stop working within a few seconds, and “has to be real”. The simplest idea is for the app to delete its own copy of the proof when the person taps sign out. That only works if the person still holds the phone and nobody copied the proof. A stolen phone, or a proof copied by an attacker, keeps working, so this fails the real revoke requirement.
So the server has to be the one that forgets. For a session row, ending a login means deleting the row, and the next request carrying that session id finds nothing and is refused. For the mixed design, ending a login means marking the refresh token (and every token descended from it, called its family) as revoked, and accepting that the short signed ticket may still work until it expires in a few minutes.
“Sign out everywhere” needs one more idea. A person might have a handful of sessions, and deleting each is fine at that scale. But it is simpler and safer to keep a session version number on the user record. Every login stores the version that was current when it was created, and every check compares the two. To sign out everywhere, the server adds one to the user’s version, and every older login fails its next check at once. This also covers signed tickets, because the ticket carries the version and a sensitive route can compare it with the current one.
Decision 5: Where does the second step fit?
The functional requirements say an optional second factor must fit somewhere. A second factor is an extra proof beyond the password: a six-digit code from an authenticator app (called TOTP, a code that changes every thirty seconds), a hardware key or phone prompt (called WebAuthn), or a one-time recovery code printed when the person set it up.
The simplest idea is to log the person in with the password, hand over the proof, and have the app then ask for the code. This fails because the real proof already exists. An attacker who knows the password can skip the app’s code screen and call the API directly with the proof they were just given.
The choice is to keep the proof back until the second factor passes. When the password is right and a second factor is needed (because the person turned it on, or because the login looks risky), the server returns only a short-lived challenge id that says “this person passed step one”. The client sends that id plus the code to a second endpoint, and only then does the server create the real session. The challenge itself expires quickly and allows only a few wrong codes. Recovery codes are stored as hashes, and the authenticator secret is stored encrypted, so support staff and database copies cannot read them.
Decision 6: How do we keep guessing bots from using up the slow check?
Decision 1 made the password check slow on purpose. The capacity numbers showed what that means under attack: 20,000 guesses a second would need about 2,000 cores if every one ran the full check.
The simplest idea is to trust the slow hash, on the grounds that slow means guessing is hard. That is true for someone who stole the database and has to guess offline. It does not help here, because the attacker is not guessing offline. They are asking our servers to do the slow work for them, so the slowness hurts us.
A second idea is to lock the account after a few wrong tries. That stops guessing on one account, but it hands attackers a new weapon: they can lock out any real user by failing on purpose. That breaks the requirement that real people are not harmed. A third idea is to limit by network address only. Large botnets spread attempts over many addresses, while a whole office or phone carrier can sit behind one address and be blocked together.
The choice is layers that run before the expensive work, from cheapest to most expensive:
- Edge limits by network address and device, applied before the request reaches the login service (see Rate Limiter System Design for how those counters work).
- Identity limits by a hash of the normalized email address, with growing delays rather than hard lockouts, so one attacker cannot freeze a real person’s account.
- Risk step-up: when a login looks unusual (new device, new country, many recent failures), ask for a second factor or a CAPTCHA before spending password-check CPU.
- A bounded pool of hash workers: only a fixed number of password checks run at once, and extra attempts wait briefly or are turned away, so real people are not stuck behind a queue of bots.
- The same generic answer (“invalid email or password”) for an unknown email and a wrong password, and a dummy hash for unknown emails, so attackers cannot learn which emails are registered, either from the message or from the response time.

Figure: Cheap checks run first. Only the attempts that survive the edge, identity and risk layers reach the slow password check and, after it, session issue.
Decision 7: How does password reset avoid becoming a back door?
Someone who forgot their password has to be able to get back in, and an attacker will try to use that same path. The simplest idea is to email the person their password, or to ask security questions. The first fails because we do not know the password (Decision 1), and the second fails because answers like a school name are easy to find.
The next idea is to email a link that contains the user id. That is guessable, so anyone could build links for other people. The link has to carry something unguessable, and the server must be able to recognise it later.
The choice is a one-time reset token. The server creates a long random value, stores only a hash of it with a short expiry (often under an hour), and emails a link that contains the raw value over HTTPS. A fast hash is enough here, because the token is already long and random and is not a human-chosen password. When the person opens the link and sets a new password, the server hashes what it received, finds the matching row, checks the expiry, marks the token used in the same step, saves the new password hash, and ends all older logins. The request form answers the same way whether the email exists or not, and the person gets an email after the change so that a takeover is noticed.
Decision 8: What if the store that remembers logins is down?
The signed-in check now sits on every request, so we need to decide ahead of time what happens when it cannot be reached. There is no neutral answer. Refusing everything protects accounts but looks like an outage. Letting everything through keeps the product up but removes the protection.
So the decision is made by how risky the action is. For a bank transfer, a password change or any account setting, the system fails closed: no check means no access. For low-risk reads, a product can accept signed tickets that it can verify without the store, and live with the fact that someone who was just signed out might keep reading for a few minutes. Whatever you choose, say it out loud and name the revoke delay you are accepting, because the interviewer is looking for that reasoning more than for a single right answer. If the main credentials database is down instead, people who are already signed in can keep working, while new logins, sign-ups and resets return a clear temporary error.
Putting the decisions together
Taken together, the eight decisions are the design. Signup stores a salted, slow hash with its settings. Login passes through edge, identity and risk checks first, then runs one password check on a limited pool of workers, then, if needed, a second factor, and only after that creates a session row (browser) or a short signed ticket plus a stored refresh token (phone). Every later request checks that proof and never touches the password. Sign-out removes the row or revokes the refresh family, and “sign out everywhere” bumps a version. Reset is a one-time random token stored as a hash. When the login store is down, risky actions are refused and low-risk reads follow a rule decided in advance.
In the room (a fuller opening you can actually say): “Signup stores a salted slow hash, Argon2id or bcrypt, with the algorithm and settings next to it, so a copied database is not a list of passwords. Login is the expensive step, so before I run it I rate-limit by address and by a hash of the email, ask for a second step when the login looks risky, and cap how many hash checks run at once. After the password is right, and the second factor if there is one, I hand the client a proof: for a browser, an opaque session id in an HttpOnly cookie that points to a row I can delete, and for a phone, a short signed ticket plus a rotating refresh token I can revoke. Every later request checks only that proof, so the password never travels again. Signing out removes the row or revokes the refresh family, and signing out everywhere bumps a version on the user. Reset sends a random one-time link whose token I store hashed, and the page answers the same whether the email exists. If the session store is down, I fail closed for anything sensitive and say how long a signed-out device might still work for low-risk reads.”
The next section draws these decisions as one picture and shows who owns what.
High-level architecture
The decisions above were made one at a time. This section puts them on one page as a picture: which boxes exist, who owns what, and how one login and one later request travel through them. The deeper mechanics come later, so keep this at the level of a map.
The system is easier to reason about when you draw the slow credential path and the fast session path separately, because they have different speeds, different protections and different failures.
Signup / login / reset (slow, rare, protected):
[ Client ] --> [ Edge / WAF ] --> [ Auth service ] --> [ User credentials DB ]
| |
| +--> [ MFA / Risk service ]
| |
| +--> [ Session store / Refresh store ]
|
+--> [ Rate limiter ]
Every authenticated request (fast, constant):
[ Client ] --> [ Gateway / Middleware ] --> validate cookie or bearer token
|
+--> opaque session lookup in Redis
| or
+--> JWT signature verify + optional version check
|
v
upstream service receives user_id
The auth service owns credential changes and the creation of a login. The gateway or middleware (the code every request passes through before it reaches a product service) owns the repeated check. Other services receive a trusted user_id and a few security details from the gateway, and they never see the password again.
For browsers, a common default is an opaque session_id in an HttpOnly Secure SameSite cookie. Redis (a very fast store that keeps data in memory) or a session database maps that id to user_id, expiry, device information and session version. For phones, a common design is a short-lived access JWT plus a rotating opaque refresh token. The access token keeps normal calls fast, while the refresh token gives the server a place to say no.
Who owns what:
- Edge and WAF apply coarse address, device and country controls before expensive hash work. (A WAF is a web application firewall, a filter in front of the site.)
- Rate limiter tracks attempts by address, device and normalized email or account id.
- Auth service owns signup, login, second-factor handoff, reset, logout, refresh and credential changes.
- Credentials database stores account state and password hash settings, never plaintext passwords.
- Session store stores active opaque sessions or refresh-token families.
- Gateway validates sessions or access tokens on every request and attaches the user context.
- Audit log records security events with no secrets in the payload.
In the room: Say that login proves the password once, then every later request proves a session. That one sentence keeps the architecture from becoming “hash on every call.”
If you remember one thing: Two paths: the slow path proves the password once, and the fast path checks a cheap proof on every request.
Core design approaches
Decision 2 chose a proof of login for each kind of client. This section lines the choices up side by side, so you can say in the room exactly when you would pick each one.
Decision matrix (pick the ticket style)
| Style | What the server stores | Cost per request | Revoke | When to pick |
|---|---|---|---|---|
| Opaque session row | One row per login | One store lookup | Delete the row or bump the version | Browsers and any app that needs fast, real revoke |
| Signed ticket (JWT) only | Nothing per login | Local signature check, no lookup | Hard: only by short expiry, a block list, or a version check | Short sessions between internal services |
| Short signed ticket + rotating refresh token | One refresh record per login | Local check for most calls, one lookup per refresh | At the next refresh, or immediately for sensitive routes with a version check | Phone apps, edge validation, many services that cannot all call one store |
Opaque server-side sessions
When you want ending a login to be a simple “forget this row”, the proof is an opaque session: a random, unguessable id the client holds in a cookie or a header, while the server alone stores what that id means. The meaning usually lives in Redis (a very fast store that keeps data in memory) or a session table: user id, expiry, device, created time, last seen time and version. Ending the login is straightforward, because deleting the row, or adding one to the user’s version, makes the next check fail.
This is a strong default for web apps that care about instant sign-out, administrator revoke and stolen-device response. The cost is that every request needs a lookup, unless you add a short local cache and say how stale that cache is allowed to be.
JWT access tokens
When many services need to check identity without calling one central store, a common choice is a signed ticket, often in the JWT format (JSON Web Token): a small piece of text that may include the user id (sub), when it expires (exp), who issued it, who may accept it, and a session version, all protected by a signature. The gateway can check the signature on its own, with no Redis lookup, which helps at high request volume and across regions. The hard part is ending the login early. A ticket that expires in eight hours stays valid for eight hours unless you add a block list, ask the auth service about it, or check a version.
Signed tickets work best when the short access ticket is short-lived and the longer refresh token is remembered on the server. That refresh token becomes the handle you can revoke.
Hybrid access JWT plus rotating refresh token
The common production compromise mixes both ideas: a short-lived signed access ticket for ordinary calls, plus a longer-lived random refresh token the server remembers, kept in an HttpOnly cookie for browsers or in the phone’s secure storage. Normal API calls verify the signed ticket locally. When it expires, the refresh endpoint checks server-side state, replaces the refresh token with a new one (rotation), and issues a new access ticket.
Rotation means each refresh token works once. If an old token is used again, the system can treat it as possible theft and end the whole family of tokens from that login, with one care for lost responses that the deep dive covers.
If you remember one thing: Pick the proof from how fast revoke must be and how often the check runs, not from which name sounds modern.
Data model
The decisions need somewhere to keep their state, so the next question is what exactly gets stored. Keep the password record, the remembered logins, the refresh tokens used to stay signed in, the one-time reset tokens, and the security event log in separate places. They live for different lengths of time and different people are allowed to read them, so mixing them into one pile makes leaks and bugs harder to contain.
One login first: Maya logs in on her phone. The credentials row for her user id already holds her password hash and its settings. A new refresh-token row is created for this device, and the server returns a short access token. The tables below are the same idea in every shape the system needs.
| Entity or store | Important fields | Why it exists |
|---|---|---|
users | user_id, email_normalized, email_verified_at, password_hash, password_alg, password_params, password_changed_at, session_version, status | Source of truth for account and credential state |
sessions | session_id_hash, user_id, device_id, created_at, expires_at, last_seen_at, session_version, revoked_at | Opaque session lookup and revoke |
refresh_tokens | refresh_token_hash, family_id, user_id, device_id, expires_at, rotated_from, revoked_at | Stateful refresh and theft detection for the JWT hybrid design |
reset_tokens | token_hash, user_id, created_at, expires_at, used_at, request_ip | One-time password reset proof |
mfa_factors | factor_id, user_id, type, encrypted secret or public key, enabled_at | Authenticator, hardware key and recovery setup |
rate_limit_counters | keys such as login:ip, login:email_hash, counters, expiry | Protects login and reset endpoints from abuse |
auth_audit_events | event_id, user_id, event type, IP, device, outcome, timestamp | Investigation trail with no passwords, raw tokens or authenticator secrets |
Why hashes of tokens, and which hash. Store hashes of session ids, refresh tokens and reset tokens if they live in a database, so that a leaked table does not hand out working logins. These values are long and random, so a fast hash such as SHA-256 is enough, and in fact it is the right choice, because a slow password hash on every request would waste exactly the CPU we are trying to save. Slow hashes are for passwords, which people choose and which can be guessed.
Illustrative Redis shapes for the fast path: a session at sess:<sha256(session_id)> holding user_id, expires_at and session_version with a time-to-live equal to the session’s expiry, a user’s current version at ver:user:42, and counters such as rl:login:ip:<address> and rl:login:email:<sha256(email)> with a short expiry. The version key is small and read often, so gateways may cache it for a few seconds, and that cache length is the revoke delay you agreed to in the requirements.
Detailed design
We now know what is stored and where, so we can put the pieces in motion. This section follows one person from signup to login to an ordinary request, then through refresh, sign-out and reset, and then shows the calls and responses a client actually sees. Read it once as a story. The deeper mechanics and the follow-up questions come in the deep dive right after it.
Signup, login, and the checks that follow
Signup. The user submits an email and a password over an encrypted connection. The auth service normalizes the email (lower-cases it and trims spaces so that two spellings do not become two accounts), checks the password rules, and optionally checks whether the password appears in a known breach list. It then turns the password into a one-way hash using Argon2id or bcrypt with a per-user salt, and stores the algorithm name and settings next to the hash so that old hashes can be upgraded later. The service may log the person in at once or may wait until they confirm their email. That is a product choice, and if confirmation is required, the confirmation link follows the same rules as a reset link: random token, hashed at rest, short life, one use.
Login. Login begins before the password check runs. The edge and the auth service rate-limit by address, device and normalized email, because that protects the limited pool of hash workers. The service then fetches the user by email. If the email does not exist, it still runs a comparable dummy hash so that the response time does not reveal which emails are registered. If the user exists, the service verifies the typed password against the stored hash, using a comparison that takes the same time whether it matches or not. If the stored hash uses older settings and the password is right, the service can rehash with stronger settings during the same login.
If a second factor is required, login does not create a session yet. It creates a temporary challenge id with a short life. After the person completes the code or hardware-key step, the service issues the real proof. This avoids the common mistake where a password-only login briefly creates a usable token before the second step.
When login succeeds, the service creates a new session id instead of reusing any id the client arrived with, because reusing a pre-login id lets an attacker plant a known id before login (called session fixation). For a browser, it sets an HttpOnly Secure SameSite cookie holding an opaque id. For a phone, it returns a short access token and a refresh token according to the client’s rules. The audit log records success, address, device and risk result, with no password and no token.
Every later request. The client sends the cookie or the bearer token to the gateway. With opaque sessions, the gateway looks up the session id (after hashing it), checks expiry and revoked state, compares the session’s stored version with the user’s current version, and attaches user_id to the request context. With JWTs, the gateway verifies the signature, issuer, audience and expiry, and for sensitive routes also compares the version or a token id. The product service downstream receives identity details such as user_id, tenant id, how strongly the person was authenticated and any scopes, and never receives the password or the raw session secret. That keeps authentication in one place and makes audit easier.
Refresh and sign-out. If the design uses short access JWTs, the refresh endpoint is the server’s checkpoint. The client sends the refresh token, the server hashes it, finds its family, checks that it was not used or revoked, and rotates it: the old token is marked used, and a new refresh token and a new access JWT are issued. Logout deletes the current opaque session, or revokes the current refresh family. “Sign out everywhere” adds one to the user’s session_version, so every older session fails its next check.
Password reset. The reset form answers with the same message whether the email exists or not. If it does, the system creates a random token, stores only its hash with a short expiry, and emails an HTTPS link. The raw token is never logged, and the link does not contain the user id. On confirm, the server hashes the token, checks expiry, marks the token used in the same step, stores the new password hash, adds one to the session version, and emails a notice that the password changed.
- Rate-limit by address, device and email before any hash work.
- Fetch the user (or run dummy work if there is none), and verify the password hash.
- If a second factor is needed, return a challenge id, not a session.
- Create a fresh session or token pair and record the event with no secrets.
- On every later request, check only the proof (and its version), never the password.
- On sign-out, delete or revoke on the server. On reset, burn the token and bump the version.
POST /v1/auth/login
-> rate limit -> lookup user -> verify hash -> MFA challenge if needed
-> issue session cookie (or access JWT + refresh token)
GET /v1/account
-> gateway: validate session or JWT (+ version) -> user_id
-> product service sees only user_id
POST /v1/auth/logout-all
-> session_version += 1
-> every older login fails on its next check
API design: what callers see and what operators change
An authentication system is usually not one public API in an interview. It is a small set of endpoints for credential changes, plus the check that runs inside the gateway on every request. So the API design is about three things: the calls clients make, the call the gateway makes inside the system, and the small admin API operators use.
What clients call. Each endpoint is separate enough that it can be protected and observed on its own.
| Endpoint | Role |
|---|---|
POST /v1/auth/register | Create account and password hash; optionally send verification email |
POST /v1/auth/login | Verify credentials, create a second-step challenge or issue a session |
POST /v1/auth/mfa/verify | Complete a pending challenge before a session is issued |
POST /v1/auth/logout | Revoke the current session or refresh family |
POST /v1/auth/logout-all | Revoke every session by deletion or version bump |
POST /v1/auth/token/refresh | Rotate the refresh token and issue a short access token |
POST /v1/auth/password/reset-request | Send a generic reset response, and email a token if the account exists |
POST /v1/auth/password/reset-confirm | Verify the one-time token and set the new password |
Login request:
| Field or header | Role |
|---|---|
email | Normalized for lookup and for the rate-limit key |
password | Never logged; verified only inside the auth service |
device_id | Optional stable client signal for risk checks and a “your devices” list |
The internal call. Inside the gateway, one small function turns the client’s proof into an identity, and the same function is used by every route.
Authenticate(credential_from_cookie_or_header)
-> { user_id, session_id, auth_strength, issued_at, session_version_ok }
or { error: invalid | expired | revoked }
What the client receives and how it is carried:
| Mechanism | Role |
|---|---|
Cookie: sid=... | Browser opaque session; HttpOnly, Secure, SameSite |
Authorization: Bearer <access_jwt> | Phone or API client access token |
| Gateway context | Upstream receives user_id, auth strength and scopes |
Which status code means what. 401 with a generic message means the credentials were wrong or the proof is missing, expired or revoked, and it never says whether the email exists. A 403 or a challenge response means a second step is required. 429 with Retry-After means too many attempts, and clients should wait that long and add a little random delay (jitter) before retrying. 503 means the auth system or one of its dependencies is unavailable, which clients should treat differently from 429. Do not return “email not found”.
How operators work. A small internal admin API lets support and security act without reading secrets. It should be authenticated more strongly than normal users, and every call should be audited.
POST /v1/admin/users/{id}/revoke-sessions # sign the user out everywhere
POST /v1/admin/users/{id}/force-password-reset
GET /v1/admin/users/{id}/audit-events # event types and outcomes, never secrets
In the room: “For one login the gateway rate-limits, the auth service verifies a salted slow hash, runs a second step if needed, and only then issues a proof: a cookie holding an opaque session id for a browser, or a short access token plus a rotating refresh token for a phone. Every later request is checked by the gateway against that proof and a version number, so the password never travels again. Sign-out deletes or revokes on the server, and sign-out-everywhere bumps a version. Reset is a one-time hashed token and ends older logins. If the session store is down I fail closed for sensitive routes.”
Deep dive: the questions an interviewer asks next
You have drawn the design and walked one login and one later request through it. This is the point where a good interviewer starts digging, and the questions usually come in a fairly predictable order, because each answer raises the next one. Read this section as that conversation. Each question is followed by an answer you can give, plus a hint of where the interviewer is likely to go next. When the next question is already obvious from your answer, you can volunteer it before they ask.
“Everyone says JWT scales because it is stateless. Why not just use that?”
Signed tickets sound free until the first stolen device. The first time someone loses a laptop, the “no server state” story stops being free. If the ticket lasts a day and a user reports the theft, the server cannot kill that ticket unless every request checks a block list or a version store, and at that point the design is no longer free of lookups. It is “stateless” only until the first compromise.
So you say what each choice moves around. Signed tickets (JWTs) move the work from the lookup on every request to ending the login. Remembered login rows move the work from ending the login to the lookup on every request. Neither is always right, and the product’s needs decide.
Where it goes next: “Fine, so why not keep a session in Redis for everything?”
“Then why not store every session in Redis and check it on every request?”
That is a good default, with a cost to name. Revoke becomes easy, but every request depends on that store. If it goes down, the product can go down with it unless you decided ahead of time whether to fail closed, fail open for low-risk reads, or keep a short local cache. The store itself is easy to size, since around 50,000 lookups a second fits on a couple of nodes, so the real question is what happens when it is unavailable.
“How does a request get checked, and how does sign out everywhere hit it within seconds?”
Take the browser design with session rows. The cookie holds a random session id. The gateway hashes it (with a fast hash), reads one record from the session store, and then compares one number against the user’s current version.
Authenticate(sid):
key = sha256(sid)
s = store.get("sess:" + key) # one round trip
if s is missing or s.expires_at < now: reject # unknown, expired or deleted
v = cached_or_get("ver:user:" + s.user_id) # a tiny value, cached a few seconds
if s.session_version < v: reject # signed out everywhere
return s.user_id
To sign out everywhere, the server adds one to the user’s version. Every older session now carries a smaller number than the user’s current one, so it fails its next check, with no need to find and delete each row. The version value is tiny and read often, so gateways cache it for a few seconds, and that cache length is the delay you accept before a sign-out is fully real. This is the answer to the “within a few seconds” the interviewer agreed to earlier: say the number, for example “at most five seconds, and I can read it directly on sensitive routes”.
Where it goes next: “And on a phone, where you use JWTs, what does revoke mean?”
“On a phone with short JWTs and refresh tokens, what happens when a refresh response gets lost?”
Start with how refresh works. The access token lasts five to fifteen minutes. When it runs out, the phone sends its refresh token to the server. The server hashes it, finds its family, checks that it was not already used, marks it used, and returns a new refresh token and a new access token. Each refresh token works once, which is called rotation.
The reason for rotation is theft detection. If a refresh token that was already used shows up again, then two parties hold the same family, and one of them is probably an attacker. The safe reaction is to revoke the whole family and force a fresh login.
Here is the catch that bites in production. Phones lose network all the time. Suppose the server rotates the token, but the response never reaches the phone.
t0 phone sends refresh token R1
t1 server marks R1 used, issues R2 + new access token
t2 response is lost on a bad network
t3 phone retries with R1
naive rule: R1 was already used -> "theft" -> revoke family -> user is logged out
better rule: R1 was used 5 seconds ago and R2 has not been used yet
-> allow once: issue R3, retire R2, keep the family
t4 R1 shows up again after the grace window, or R2 was already used
-> treat as theft: revoke the family and alert the user
So you add a short grace window (for example 10 to 30 seconds, a common but tunable choice) in which the immediately previous token can be retried exactly once if its replacement was never used. Outside that window, or after the replacement has been used, a reuse is treated as theft. Say plainly that an idempotency key on the refresh call is not the fix, because the server does not keep the raw new token and so cannot send the same reply twice.
Where it goes next: “Let’s go back to login. Bots send 50,000 attempts a minute. Who pays for the slow hashes?”
“Bots send fifty thousand logins a minute. Who pays for all those slow hashes?”
Do the arithmetic first, because it makes the answer concrete. Fifty thousand a minute is about 830 a second. If one check costs about 100 ms on one core, that is roughly 83 cores of password work, all of it spent on strangers, while real people queue behind them. A slow hash protects a copied database, but it does not protect the login form from being used as a CPU furnace.
So you protect it in layers, as in Decision 6, and you cap the work at the end. Suppose each auth node runs a pool of 32 hash workers, so it finishes about 320 checks a second. Behind the pool you allow a short waiting line of, say, 64. A real person who arrives when the line is full gets a fast 429 or 503 with Retry-After, instead of waiting thirty seconds for a timeout. The line keeps the longest wait for the people who do get in to about a fifth of a second (64 ÷ 320).
There is an honest weakness in layers 1 and 2. Credential stuffing tools often try each account only once or twice, spread over thousands of addresses, so a per-address limit and a per-email limit barely notice. That is why the system also watches the whole login endpoint: when the overall failure rate or the number of never-seen devices jumps, it switches into an “under attack” mode that asks unknown devices for a second step or a CAPTCHA before spending any hash CPU, and lets known devices through. Breached-password checks at signup and at login help too, because attackers are feeding in passwords that are already in public lists.
Where it goes next: “Why not just lock the account after five wrong passwords?”
“Why not lock the account after five wrong passwords?”
Because it gives attackers a free way to hurt your customers. If five wrong tries lock an account, then anyone can lock any account by typing five wrong passwords, which breaks the requirement that real people are not harmed. It also does nothing against the stuffing pattern above, where each account sees only one or two attempts.
So you use delays that grow rather than hard locks (each extra failure within a window makes the next try wait a bit longer), you tie the delay to the email and to how unusual the device is, and you send the real owner a notice when there is a burst of failures. For high-risk accounts, a second step or a recovery flow does the protecting instead of a lock.
Where it goes next: “OK, back to the password itself. What exactly do you store and how do you upgrade it?”
“What exactly do you store for a password, and how do you upgrade it later?”
You store four things: the hash, the per-user salt (often kept inside the same encoded string), the algorithm name, and its settings such as memory, number of passes and parallelism. Argon2id or bcrypt are the usual picks. You tune the settings to a measured budget, for example around a tenth of a second per check on your real hardware, and you revisit them each year as hardware gets faster.
To upgrade, you do not need everyone to reset. On the next successful login you already have the correct plaintext password in memory for a moment, so if the stored settings are older than today’s target, you hash it again with the new settings and replace the row. Accounts that never log in stay on old settings until they do. Some teams also add a pepper, a secret value kept in a key service or secrets manager (not in the database) and mixed into the hash, so that a stolen database alone is not enough to start guessing.
Two small details earn credit. The comparison of the final hashes should take the same time whether they match or not, so response time does not leak information. And an unknown email should run a dummy hash of the same cost, so that “no such user” and “wrong password” look and take the same.
Where it goes next: “Now the reset link. What can go wrong with it?”
“What can go wrong with a password reset link?”
Several things, and each has a small fix.
First, two requests can use the same link at the same moment. If the code reads “is this token unused?” and then writes “mark it used” as two steps, both can succeed. Make it one step in the database.
UPDATE reset_tokens
SET used_at = now()
WHERE token_hash = $1 AND used_at IS NULL AND expires_at > now()
RETURNING user_id;
-- zero rows returned means: unknown, already used, or expired -> reject
Second, many email systems and company security scanners open every link in an email automatically to check it for danger. If a plain GET of the link consumes the token, the scanner uses it up before the person clicks. So the GET should only show the “choose a new password” form, and the token should be consumed by the POST that sets the password.
Third, the link and the raw token must stay out of logs, analytics and the Referer header that browsers send to other sites. Fourth, the page should answer the same way whether the email exists, and the system should notify the person after any change. And last, a successful reset must end older logins by adding one to the session version, because the usual reason to reset a password is that someone else may have it.
Where it goes next: “You mentioned a second step. What stops someone from guessing the six-digit code?”
“Where exactly does the second step fit, and what stops guessing the six-digit code?”
Right after the password check and before the proof of login is created. The password step returns a challenge id, which is a random value that points to a short-lived record saying “this person passed step one on this device”. The code is sent with that id to the second endpoint, and only a correct code creates the session.
Six digits is only a million possibilities, so guessing has to be capped. The challenge allows a handful of wrong codes and expires after a few minutes, and failures count against the account’s rate limits too. A code that was already accepted in its thirty-second window must be rejected a second time, so that someone who watched it over a shoulder cannot reuse it. Recovery codes are one-time, stored as hashes, and shown to the person only once at setup. The authenticator secret itself is stored encrypted, because the server must read it back to check codes, unlike a password. A hardware key (WebAuthn) is stronger against phishing, because it signs a challenge that is tied to the real website, so a fake page cannot reuse it.
Say it in the interview: “JWTs move work from the lookup to revoke; opaque sessions move work from revoke to the lookup, so I choose from how fast revoke must be. The password is checked once, with a slow salted hash that I protect with layered limits and a capped worker pool. Everything after that checks a cheap proof plus a version, and every one-time secret is stored as a hash and burned on use.”
Pool wait, hash queue depth and revoke delay belong in Observability. The rest of the hard parts are in Key challenges and Bottlenecks and tradeoffs.
If you remember one thing: The deep dive is a conversation. The password is checked once and protected before the check, the proof is cheap to check and real to revoke, and every secret that is stored is stored as a hash.
Key challenges
The deep dive showed that each flow is simple on its own. What makes authentication hard is that the flows pull in different directions, and five hard parts keep coming back. Name them early in the interview, because each one is a place the interviewer is likely to push.
Password storage is irreversible by design. You should be able to check a typed password without ever being able to read the original back out. That is why a slow one-way scramble beats encryption for stored passwords, and why you keep the algorithm settings next to the hash, so the cost can rise over time.
Bots with leaked passwords are both a security and an availability problem. Attackers can send millions of email and password pairs that already leaked elsewhere (credential stuffing). Even failed attempts consume password-check CPU unless you limit and step up before the expensive work, and the attempts are often spread so thinly that per-address and per-account limits barely notice.
Ending a login must be real. Sign-out, password change, a stolen device and an administrator response all need a clear path that actually stops the old proof. A long-lived signed ticket without a refresh token the server remembers makes this hard, and a session store that every request depends on makes availability hard.
Account recovery is an attack path. Reset links and recovery codes can take over an account without knowing the old password. Treat them as bearer secrets (whoever holds them can use them): store hashes, keep short lifetimes, allow one use, and write an audit event.
Errors can leak whether an account exists. Login and reset should not reveal whether an email is registered, either through the message or through response time. Return generic messages to users and keep the detail in server logs.
If you remember one thing: Stuffing protection and real revoke are design requirements, not afterthoughts.
Scaling the system
Those hard parts get worse as the number of users and the size of attacks grow, so the next question is what happens when traffic multiplies. You do not have to wait for the interviewer to ask. Right after you finish the design, say the scaling story yourself, then be ready for the follow-ups.
What you can say upfront: “I scale login and the signed-in check separately. The signed-in check is the hot path, so it is a single lookup spread across a few session-store nodes by hashing the session id, or a local signature check for tokens. Login is rare but expensive, so it gets its own pool of auth nodes with a capped number of hash workers, and I add nodes when real login traffic grows, never because of bots. Attacks are handled by shedding load before the hash, not by buying more cores. For sign out everywhere I bump a version number instead of deleting rows, signing keys rotate with key ids, and across regions I either keep login in the region that owns the user or accept a stated revoke delay.”
That paragraph answers most of what follows. Here are the follow-ups, in the order they usually come.
Interviewer: “Traffic doubles next quarter. What do you change?”
You: “First I look at which kind of traffic doubled. If it is signed-in checks, the gateways and the session store absorb it, and about 100,000 lookups a second still fits on a handful of nodes, so I add nodes and check memory. If it is real logins, I add auth nodes in proportion, because each one has a fixed number of hash workers. I would not add hash capacity to answer a spike of bot traffic, because that just buys the attacker more of my CPU.”
Interviewer: “How do you shard the session store?”
You: “By a hash of the session id, so lookups spread evenly. Sharding by user id would put all of one user’s sessions together, which is handy for listing them, but it makes busy users hot and it is not needed for the normal check. For listing a user’s devices or signing out everywhere I use a per-user version and a small per-user index, so I never scan the store.”
Interviewer: “After a serious incident, security wants to sign out all two million users at once. Do you update two million records?”
You: “No. Besides the per-user version, I keep one global marker that says ‘any login created before this moment is invalid’, and the check compares against both. It is one small write, and gateways pick it up within the same few seconds. If tokens are signed, rotating the signing key does the same job for access tokens. The old rows and refresh records expire on their own later.”
Interviewer: “JWT verification is local. Is there anything to scale there?”
You: “Key management. Each token names the key that signed it, so I can rotate signing keys without breaking live tokens. Private keys live in a key management service, the gateways only need the public keys or a cached copy of them, and an old key is retired after the longest access token that used it has expired.”
Interviewer: “What about more than one region?”
You: “I either keep login and refresh in the region that owns the user, so the state they touch is in one place, or I replicate state and accept that a sign-out takes a moment to show up elsewhere. Signed-token checks can happen at the edge in every region. Sensitive actions, such as changing a password, force a fresh check against the owning region.”
Interviewer: “Do login, refresh and reset share infrastructure with the rest of the product?”
You: “No. They get their own limits, dashboards and capacity, because attackers aim at exactly those endpoints and a flood there should not slow down checkout or search.”
If you remember one thing: Scale the signed-in check by adding cheap lookups. Scale login by capping hash work, never by chasing bots with more cores.
Failure handling
Scaling answers “what if there is more traffic”. This section answers “what if something breaks”. Again, say it first. Failures here come from the session store, the credentials database, the email provider, or from clients reacting badly, and what impresses an interviewer is that each answer was decided before the failure happened.
What you can say upfront: “Every dependency has a rule chosen in advance. If the session store is down, sensitive routes fail closed, and low-risk reads may accept short-lived signed tokens, with the revoke delay stated. If the credentials database is down, people who are already signed in keep working and new logins, signups and resets return a clear temporary error. If the hash workers are saturated, the system sheds bot traffic first and keeps a line for known devices. If a refresh token is replayed outside the grace window, I revoke the family and tell the user. If a signing key leaks, I rotate keys and revoke refresh families. If the email provider is down, reset and verification emails retry with backoff and I do not create permanent tokens.”
The follow-ups are about the details of those decisions.
Interviewer: “The session store goes down. What does a user see?”
You: “It depends on the route, and I chose that ahead of time. For anything that moves money or changes the account, the gateway refuses with a clear
503, because I cannot tell whether the login was revoked. For low-risk reads, a product can accept short-lived signed tokens that verify without the store, and I say plainly that a device that was just signed out might keep reading for a few minutes. I also put a circuit breaker on the store, which works like a fuse: after repeated failures the gateway stops waiting on it and applies the rule at once. Users see slower pages or errors on sensitive screens, which is degraded service, not a full outage.”
Interviewer: “The credentials database is down. Can anyone use the product?”
You: “Yes, anyone who is already signed in, because the signed-in check never reads the credentials database. New logins, signups, resets and password changes return a controlled
503with a retry hint. I keep the two stores separate for exactly this reason.”
Interviewer: “The hash workers are saturated and real users time out. What now?”
You: “That means protection ran too late. I shed load before the hash by tightening address and email limits, switching to the under-attack mode that asks unknown devices for a second step, and shortening the waiting line so people get a fast
429instead of a timeout. I alert on hash queue depth and login p99, because HTTP can look healthy while real people wait.”
Interviewer: “A refresh token is used twice. Is that always theft?”
You: “No. A lost response on a weak network looks exactly the same as a replay. So I allow a short grace window for the previous token if its replacement has not been used. Outside that window, or after the replacement is used, I treat it as theft: revoke the family, force a new login, email the user and write an audit event.”
Interviewer: “You find out the signing key leaked. What do you do?”
You: “I rotate to a new key right away and stop accepting the old key id, which makes every token signed by it fail. Then I revoke refresh families so people log in again, shorten access token lifetimes for a while, and read the audit log to see what the forged tokens did. This is expensive for users, which is why keys live in a key service and not in application code.”
Interviewer: “The email provider is down during a reset storm. What happens?”
You: “Emails queue and retry with backoff, and the page says honestly that the email may be delayed. I do not create tokens that last longer to make up for it. I also rate-limit the reset form, so a storm of requests does not become a storm of emails at my cost.”
| Failure | What users or teams see | What to build |
|---|---|---|
| Session store down | Users get 401s or pages fail to load | Fail closed on sensitive routes; optional short JWT fallback only for low-risk reads with the revoke risk stated; circuit breaker |
| Credentials DB down | New login, signup and reset fail | Existing sessions continue; return a controlled 503 for credential writes |
| Hash worker pool saturated | Real users time out during stuffing | Edge limits, identity limits, bounded queue, under-attack step-up, queue depth alerts |
| Refresh token replay | Possible token theft, or a lost response | Grace window for a retry; otherwise revoke the family, force login, alert the user |
| JWT signing key leak | Forged access tokens possible | Rotate keys, revoke refresh families, shorten token lifetimes, inspect audit logs |
| Email provider down | Reset and verification emails delayed | Retry with backoff, honest status, no long-lived tokens |
If you remember one thing: The safety rule is to fail closed for identity decisions when the risk is high. A catalog page might tolerate a short degraded read, and a bank transfer should not.
Observability (what you measure)
Failure handling decided what to do when something breaks; observability is how you notice the break before support phones start ringing. Once the system is live, you need a way to tell whether login is healthy, and that takes more than the website returning “OK”. Many authentication attacks look like successful HTTP responses, so a dashboard that shows only availability will stay green while real users wait.
| Signal | Why it matters |
|---|---|
| Login success rate and failed login rate, by reason | Separates real trouble from a spike of bad passwords |
| p95 and p99 login latency (how long the slowest 1 in 20 and 1 in 100 logins take) | The experience of a real person, which averages hide |
| Hash worker queue depth and wait time | The first sign that bots are using up password-check capacity |
| Rate-limit decisions by layer | Shows which layer is catching the attack |
| Signed-in check latency and session-store error rate | The tax on every request, and the early sign of a store problem |
| Refresh failures and replay events | Separates a mobile bug from a stolen token |
| Revoke propagation time (sign-out to first rejected request) | Proves the “within a few seconds” promise |
| Reset request-to-confirm ratio and reset email volume | A spike means phishing or abuse |
| New-device logins, top addresses and email hashes after privacy-preserving hashing | Lets security investigate without exposing raw user data broadly |
Break metrics down by endpoint and reason. /login under stuffing behaves differently from /token/refresh during a mobile bug.
Audit events should record security-relevant facts: signup, login success and failure, second-step failure, reset request and confirm, password change, refresh replay, logout, logout-all and administrator revoke. They should never record passwords, raw session ids, raw refresh tokens, reset tokens or authenticator secrets.
Alert ideas: sudden login p99 increase; hash queue saturation; a spike in 429; a spike in reset emails; refresh replay events; session-store error rate; unusual new-device logins; and a sudden drop in revoke events or failures during a traffic spike, which can mean a check stopped running.
Security and abuse
A login system is a security tool, and people will try to get around it, so this section covers how to keep it honest after the architecture is drawn. Store secrets so that a copied database does not immediately become an account takeover. Passwords use a salted, deliberately slow one-way scramble. Reset tokens, session ids and refresh tokens are stored as fast hashes when they live in a database, so a leaked table does not hand out working logins. Signing keys, and any extra secret mixed into the password scramble (sometimes called a pepper), belong in a key service or secrets manager, not in application code next to the database.
Protect against password guessing and bots that try leaked passwords in layers: address and device limits at the edge, identity limits on a hash of the email, delays that grow with failures, a risk score that can ask for a second step or a CAPTCHA, and checks against known breached passwords. Avoid a hard account lock after a few wrong tries, because that lets an attacker lock real people out on purpose.
Use generic messages for users. The login form and the reset form should not reveal whether an email is registered, either in the words on the screen or in how long the response takes. Server-side logs can hold structured reason codes for support and security teams.
For browser logins, use cookie flags that keep the proof harder to steal: HttpOnly so page scripts cannot read it, Secure so it only travels on an encrypted connection, SameSite so other sites cannot easily trigger it, and never put the session id in a URL. Protect against cross-site request forgery (a malicious page that makes the browser send a request the person did not mean to send) wherever cookies go out automatically. Protect against cross-site scripting too, because HttpOnly stops a script from stealing the cookie but does not stop it from acting as the user inside the page. For the second step, encrypt authenticator secrets, store recovery codes as hashes, and record when factors are added or removed. A full login is handed out only after the required second step succeeds.
Cost awareness
Every choice so far also has a price, and interviewers like to hear that you noticed. The deliberately slow password scramble costs CPU and memory on purpose, which protects a leaked database, but it also means bots can turn that defense into a large compute bill or an outage if you do not limit attempts before the scramble runs. Plan how many hash workers you can afford, and watch how deep the waiting line gets.
The cost of checking “are you still signed in?” depends on the model you chose. A remembered login row costs a store lookup on every request. A signed access ticket costs a local signature check and more care when signing keys rotate. A hybrid of a short signed ticket plus a remembered refresh token cuts most store reads while keeping the revoke handle at refresh time.
Audit logs and security events grow quickly during attacks. Store enough detail to investigate an incident, keep each event small, and never put passwords or raw tokens in the payload. How long you keep those logs should match security and compliance needs, not the default for ordinary application logs. Email and second-step providers charge per message, and storms of reset requests or code sends become real money, so limit those unauthenticated flows and watch provider failures.
Green Dashboard. Angry Users. The Production Mindset System Design Interviews Expect.
Everything so far describes how authentication should work on a good day. This section is about a bad day, told as short stories from the people who carry the pager (the on-call engineers). Textbooks teach boxes and arrows. On-call teaches something else: an authentication system can look healthy while real people are locked out, and it can look busy while it protects nothing.
A calm login dashboard can mean “everything is fine” or “bots are using every hash worker and real users are waiting”. A low number of failed logins can mean “nobody is attacking” or “the limiter stopped counting”. Interviewers like this gap because it separates a diagram from someone who has run the thing.
Four nightmares that look fine on a dashboard:
| What the dashboard shows | What is actually happening |
|---|---|
| Almost no 5xx errors, and support is flooded | Bots are using the hash workers, and real logins time out |
| Everyone seems to be signed in normally | A laptop was stolen and its JWT will keep working for hours |
| Reset emails are going out normally | An attacker is requesting resets for many accounts, or reusing a link |
| Refresh traffic is steady | A mobile bug is retrying, the server calls it theft, and thousands of people are being logged out |
Scene 1: Credential stuffing looks like a healthy API
The moment: It is a Monday morning at a shopping app. People are trying to buy things as usual. Support starts getting messages from shoppers who say login hangs and then fails, and a few customers say they found orders they did not place. The HTTP dashboard that the on-call team watches shows no server errors at all.
The trap: Bots are trying email and password pairs that leaked from another company’s breach, hoping some still work here. Every attempt returns a normal 200 or 401, so “5xx rate” and “availability” stay green. The expensive part is the slow password check and risk evaluation behind each answer, and the hash worker waiting line has been growing since six o’clock. The metric that lied was the HTTP success rate: the site looked healthy while real people waited.
What to build:
- Add cheap checks before the expensive work: limits by address and device at the edge, limits and growing delays by email in the auth service, and a step-up to a second factor or CAPTCHA for unknown devices when the login failure rate climbs.
- Cap how many password checks run at once and keep a short waiting line, so real people get a fast “try again” instead of hanging until a timeout.
- Put hash queue depth, login p99 (how slow the slowest real logins feel), and the failure rate of the whole login endpoint on the same dashboard as ordinary API health.
Scene 2: A stolen laptop that keeps working
The moment: Someone is working from a cafe on a shopping-app laptop. They step away for a minute, and the laptop is gone. At lunchtime they phone support from their phone, press “sign out everywhere”, and support says the lost laptop is cut off.
The trap: The app uses long-lived signed tickets that the gateway checks on its own, with no remembered row to delete. Pressing sign out everywhere changed nothing the gateway looks at, so the thief’s ticket stays valid until it expires eight hours from now. Support cannot honestly promise that the laptop is cut off. The mistake was selling “stateless” tickets as free scale, because a check with no server memory also has no kill switch.
What to build:
- Use short access tickets that last minutes, not hours, plus a refresh token the server can revoke—or use opaque session rows that can be deleted outright.
- Keep a session version on the user, check it on sensitive routes, and make “sign out everywhere” add one to that version so older proofs fail on the next check.
- Measure how long it takes from sign-out to the first rejected request, and tell support that real number instead of “it is done.”
Scene 3: Reset links become a way in
The moment: A customer opens their email and finds a password reset message they did not ask for. They write to support. An hour later, three other accounts show a password change that the owners say they did not make.
The trap: The reset form answered differently when the email was registered, so attackers used it to learn which emails exist. The reset tokens were reusable and stayed valid for a day, and one of them also appeared in a log that many engineers can read. A reset link is a bearer secret—whoever holds it can set the password—so the team had treated reset as a support convenience instead of as part of authentication.
What to build:
- Return the same message whether the email exists, and limit both the “send reset” and “confirm new password” steps so attackers cannot flood them.
- Store only a hash of the token, keep a short life, burn the token in one database step on first use, and keep the raw value out of logs and browser referrers.
- Email the owner after every password change, and end older logins so a stolen link cannot leave old devices signed in.
Scene 4: The retry that logged everyone out
The moment: A phone app release goes out on a Thursday. People open the app on trains and in lifts, where the network drops for a few seconds at a time. Within an hour, support sees thousands of messages saying “the app signed me out.”
The trap: The refresh endpoint replaces the refresh token each time and treats any reuse as theft, which is the right rule when two parties hold the same token. But on a weak connection the new token never reached the phone, so the phone retried with the old one, and the server ended the whole family. Nothing was wrong with security, and the service was up. The metric that lied was “refresh success rate,” which looked steady because each revoke was counted as a correct rejection.
What to build:
- Add a short grace window that lets the immediately previous token be retried once while its replacement has not been used yet, so a lost response is not mistaken for theft.
- Track refresh-replay events separately from other failures, and break them down by app version, so a bad release shows up in minutes.
- End a whole token family only when a reuse cannot be explained by a lost response.
In the interview: Pick one scene and tell it like a short story: what people felt, which metric lied, and what you would build next. You do not need all four. You need to sound like someone who knows that green does not mean done.
Bottlenecks and tradeoffs
Those stories all trace back to a few choices where you cannot have both things you want. Interviewers listen for whether you can name the tension, say what breaks, and pick a side on purpose. Here are the four that matter most for authentication.
Opaque sessions vs JWT
The tension — A remembered login row on the server makes ending a login simple, but every request pays for a store read. A signed ticket (JWT) makes the check cheap at the gateway, but ending that login instantly is harder.
What breaks — Pure remembered rows: the session store becomes the point every request depends on, so a store outage can look like a product outage. Pure signed tickets: a stolen ticket lives until it expires, and “sign out everywhere” has nothing to delete.
What teams do — Server-side sessions for admin panels, banks and other sensitive apps; short access tickets plus rotating refresh tokens for phone APIs, with a session-version check on sensitive routes when immediate kill matters.
Say in the interview — “Signed tickets move work from the lookup to revoke; remembered rows move it from revoke to the lookup, and I choose from how fast revoke must be.”
Hash strength vs login latency
The tension — Stronger password-scramble settings make offline guessing harder, but they also make every real login and every bot attempt more expensive on your own machines.
What breaks — Too weak, and a copied database is easy to crack on a graphics card. Too strong, and bots that try leaked passwords can use up all CPU and memory before real people get in.
What teams do — Tune the scramble to a measured time budget on real hardware, protect it with limits before it runs and a capped worker pool, and keep algorithm settings next to every hash so the cost can rise later without a forced reset.
Say in the interview — “The scramble protects a leaked database, and the limits protect the login form. I need both.”
Generic errors vs user clarity
The tension — Saying “email not found” helps an honest person who mistyped their address, but it also helps attackers build a list of which emails are registered.
What breaks — Specific errors leak account existence. Fully generic errors frustrate support and some users who cannot tell whether they mistyped the email or the password.
What teams do — One generic public message, detailed private audit events for support, and the same rule on reset and recovery flows, including matching response times so timing does not leak the answer.
Say in the interview — “The user sees one message; the audit log sees the real reason.”
Instant revoke vs global availability
The tension — Strict, immediate revoke means checking current server state on the path that matters. Fast checks in every region mean verifying signed tickets locally without a round trip.
What breaks — Instant revoke everywhere makes the central store a dependency of every region. Local-only checks mean a stolen ticket can keep working for a while after sign-out.
What teams do — Short ticket lifetimes, version checks on sensitive routes, and clear regional policies stated as numbers. They do not promise both perfect instant global revoke and zero server lookup without explaining the mechanism that makes both true.
Say in the interview — “I would say the revoke delay as a number, and read the server directly on routes where that number is too long.”
If you remember one thing: Every authentication tradeoff is revoke speed versus lookup cost or protection versus real-user friction. Say which side you chose and why.
Interview tips
You now have a full design and the tradeoffs behind it, so the last thing to practice is defending it when the interviewer pushes back. These five are the pushes that come up most after you finish the design:
JWT is not a magic answer
In the room
You might say: “I’d use signed tickets (JWTs) because they need no server lookup, so the design scales.”
Interview Push: “A user loses a laptop. How do you kill that token in five minutes?”
Land here: Start with how you end the login, not with how cheap the check is. A signed ticket that lasts a day stays valid for a day unless every request also checks a block list or a session version—and at that point the design is no longer free of server state. Prefer a remembered login row when instant revoke matters. Prefer a short access ticket plus a rotating refresh token the server can revoke when edge checks matter, and add a version check on sensitive routes if the product needs an immediate kill. Say the delay as a number, for example “at most five seconds.”
“We encrypt the passwords”
In the room
You might say: “We encrypt passwords before we store them, so a leak is safe.”
Interview Push: “Who has the key, and can they decrypt every user’s password?”
Land here: Encryption can be undone, and the server has to hold the key in order to check logins, so a thief who reaches the server often gets the key too. Store a salted, slow, one-way scramble instead. The server scrambles what was typed and compares, and it cannot recover the original. Argon2id or bcrypt settings are tuned so each guess is expensive for an attacker and still acceptable for a real login, and those settings sit beside the hash so they can be raised later without forcing everyone to reset.
The slow hash already stops brute force
In the room
You might say: “The password scramble is slow on purpose, so guessing is already hard.”
Interview Push: “Bots send fifty thousand attempts a minute. Who pays for those slow hashes?”
Land here: Your servers pay. The slow scramble protects a copied database, where the attacker has to do the guessing on their own machines. At the login form, the attacker is asking your machines to do the slow work for them. Limit by address, device and a hash of the email before the scramble runs, ask for a second step when the login looks risky, cap how many checks run at once, and watch how deep the waiting line gets. Say that bots often try each account only once or twice across many addresses, so you also watch the failure rate of the whole login endpoint.
Lock the account after five wrong tries
In the room
You might say: “After five failed logins we lock the account so guessing stops.”
Interview Push: “Can an attacker use that to lock out a well-known account on purpose?”
Land here: Yes, and that breaks the promise that real people are not harmed. Prefer delays that grow with each failure, tied to how unusual the device looks, plus a notice to the owner, and a second step or recovery flow for risky accounts. A hard lock is a denial-of-service switch handed to anyone who knows an email address.
Reset links are bearer secrets
In the room
You might say: “We email a password reset link and the person chooses a new password.”
Interview Push: “If that email is forwarded, scanned by a security tool, or the link is logged, can it be reused?”
Land here: Treat the link as a one-time secret. Use a long random token, store only its hash, keep a short life, and burn it in one database step on the first successful use. A plain
GETof the link should only show the “choose a new password” form, so automatic link scanners cannot consume it, and thePOSTthat sets the password is what burns it. Keep the raw value out of logs and browser referrers, end older logins after the change, notify the owner, and return the same response whether the email exists.
Audit logs that leak secrets
In the room
You might say: “We log authentication events so we can debug login problems later.”
Interview Push: “Do those logs contain passwords, reset tokens or session ids?”
Land here: Record what helps an investigation—event type, user id, network address, device, outcome and risk reason—and leave raw secrets out. Logs should help you understand an account takeover without becoming a second place where working passwords and links are stored, and the people who can read them should be few and themselves audited.
Red flags to avoid without correcting yourself: “we encrypt passwords,” “JWT, so it is stateless and revoke is free,” “lock the account after five tries,” “email not found,” “reuse of a refresh token is always theft,” and “run the hash on every request.”
After each push, close with one real part of the design you would build: a salted slow hash with stored settings, a capped hash worker pool, a session version, a hashed one-time reset token. Do not close with “we will scale it later.”
What should stick
After working through the requirements, the decisions and the depth sections, you should be able to explain:
- Two speeds. Login is slow and protected. Checking “are you still signed in?” on every request is fast. Never run the password check on every call.
- Three secrets. Passwords, session or refresh tickets, and reset links each need different storage, expiry and revoke rules. Passwords get a slow salted hash, and the random tokens get a fast hash.
- Signed ticket vs remembered row. A signed ticket (JWT) avoids a lookup but makes “log out everywhere” harder, unless tickets are short-lived and refresh is stateful. An opaque session row makes revoke easy and costs one lookup.
- Stuffing burns your CPU. The slow hash protects a leaked database, not the login form. Layered limits before the hash, a capped worker pool, and a step-up for unknown devices protect real users.
- Recovery is authentication. A reset link or recovery code can take over an account, so treat it as a one-time, short-lived, hashed bearer secret that ends older logins.
Tell it in the room: “Signup stores a salted slow hash with its settings. Login is limited by address and hashed email, uses a capped pool of hash workers, runs a second step if needed, and then issues a session row or a short token plus a rotating refresh token. Every API call checks that proof and a version, never the password. Sign-out removes it on the server, and sign-out-everywhere bumps a version. Reset is a one-time hashed token that ends older logins. If the session store is down I fail closed on sensitive routes.”
Quick check before a mock: (1) Why is “we encrypt passwords” the wrong phrase? (2) How does revoke work for opaque sessions and for short JWTs? (3) What do you measure during stuffing when HTTP still looks healthy? → (1) encryption is reversible and the key sits with the server; use a salted slow one-way hash (2) delete the row or bump the version, versus short expiry plus revoking the refresh family (3) hash queue depth and login p99, not only the 5xx rate.
Practice next: Open Design a Basic Auth System on Practice System Design and run a timed attempt using clarifying questions and one login story, without peeking until you have a draft on the board.
Key Takeaways
- Login proves the password once, with a salted, slow, one-way hash; every later request checks a cheap proof (a session id or a short signed token) and never the password.
- Pick the proof from how fast revoke must be: opaque sessions for easy revoke, short JWTs plus rotating refresh tokens for edge validation, and a session version to sign out everywhere.
- The slow hash protects a leaked database, not the login form, so limit by address, device and hashed email before the hash, cap parallel password checks, and step up unknown devices under attack.
- Treat reset links and recovery codes as one-time bearer secrets: random, stored as a hash, short-lived, burned atomically, and followed by ending older sessions.
- Allow a short grace window on refresh-token reuse, so a lost response is not mistaken for theft.
- Use generic errors and equal response times for unknown emails, and keep passwords, tokens and secrets out of every log.
- Decide in advance what happens when the session store or the credentials database fails: fail closed on sensitive routes and say the revoke delay you accept.
Related Topics
- Rate Limiter System Design - Login and reset endpoint protection.
- Distributed Cache System Design - Session store sharding, hot keys, and failover.
- Notification Service System Design - Reset emails, security alerts, and async delivery.
- Logging System Design - Audit logs and safe security event storage.
- Design WhatsApp - Privacy and account security in messaging systems.
Quick revision notes
The problem in your own words. An authentication system proves who someone is once, at login, and then lets every later request show that proof cheaply. The hard parts are keeping passwords safe if the database leaks, ending a login for real, and stopping strangers who try leaked passwords from using up the slow password check.
The design in one breath. Signup stores a salted slow hash with its settings. Login passes address, email and risk limits, runs the hash on a capped pool of workers, asks for a second step if needed, and issues a session row or a short signed token plus a rotating refresh token. The gateway checks that proof and a version on every request. Sign-out deletes or revokes on the server, sign-out-everywhere adds one to a version, and reset is a one-time token stored as a hash.
The choices you must be able to defend. Opaque sessions when instant revoke matters, short JWTs plus rotating refresh tokens when edge validation matters. A hard lock after a few failures is a weakness, so use growing delays. Fail closed on sensitive routes when the session store is down, and name the revoke delay you accept elsewhere.
The numbers worth remembering. One password check is about 100 ms and about 10 a second per core, so 20,000 attacks a second would need about 2,000 cores. About 50,000 signed-in checks a second fits on a couple of store nodes, and the live logins for 10 million users are only a few gigabytes. Refresh grace windows are measured in tens of seconds, and access tokens in minutes.
The mistakes that cost points. Saying “we encrypt passwords,” hashing on every request, selling JWTs as free revoke, locking accounts after five tries, answering “email not found,” treating every refresh reuse as theft, letting a link scanner burn a reset token, and logging secrets.
Frequently asked follow-ups
- How do you store passwords?
- Signed ticket or a login remembered on the server?
- How do refresh tokens and ending a login work?
- How do you stop password guessing and bots with leaked passwords?
- How do password reset and a second step fit the login flow?
Deep-dive questions and strong answer outlines
How do you store passwords?
Store a per-user salt (a random value mixed into the scramble) and a slow one-way hash using Argon2id or bcrypt. Keep the algorithm and settings beside the hash so you can upgrade on the next successful login. Never store plaintext passwords, never log passwords, and do not "encrypt" passwords you need to verify, because encryption can be undone.
Signed ticket or a login remembered on the server?
A remembered login (opaque session) stores a random session id in an HttpOnly cookie (a cookie page scripts cannot read) and keeps the meaning of that id in Redis or a session database. Ending the login is deleting or invalidating that row. A signed ticket (JWT) can be checked without a lookup, which helps gateways, but ending it early needs a short life, rotating refresh tokens the server remembers, a block list, or a session-version check.
How does login work when bots try leaked passwords?
Limit attempts at the edge and by a hash of the email, return the same generic error for unknown emails and wrong passwords, run dummy hash work for unknown emails so timing does not leak, ask for a second step or a CAPTCHA when risk is high, and watch how deep the password-check waiting line gets. Do not let bots use up all slow-hash CPU while dashboards show only successful HTTP responses.
How does password reset work?
The reset request returns the same message whether the email exists. If it does, store a hash of a random token with a short life and email the raw token in an HTTPS link. On confirm, verify once, burn the token, store the new password hash, bump session version or end all logins, and notify the user.
Where does a second step (one-time code) fit?
The second step comes after the password check and before a full login is handed out. If the person turned on an authenticator code or hardware key, or if risk is high, return a short-lived challenge id rather than a full login. Recovery codes should be stored as hashes, and support should not be able to read them.
AI feedback on your design
After a practice session, InterviewCrafted summarizes strengths, gaps, and interviewer-style expectations—similar to a written debrief. See a static example report, then practice this problem to get feedback on your own answer.
FAQs
Q: Is OAuth a replacement for this design?
A: No. Signing in through another company can prove who someone is, but your product still needs to hand out its own login proof, check that proof on later requests, support sign-out, and keep its own security event record.
Q: Should signed tickets go in localStorage?
A: For browsers, prefer cookies marked HttpOnly, Secure, and SameSite so page scripts cannot read the proof after a cross-site scripting bug (a way for an attacker to run their own JavaScript on your page). Phone apps can keep bearer tokens in the phone’s secure storage instead.
Q: Should login say "email not found"?
A: Usually no. Use a generic "invalid email or password" response so attackers cannot build a list of registered emails. Keep detailed reasons in server logs for support and security investigation.
Q: What does sign out everywhere mean?
A: Either delete every remembered login for the user, or add one to a session version on the user record so every older login fails its next check. Designs that use signed tickets also need to end refresh tokens and keep access tickets short-lived.
Practice interactively
Open the practice session to use the canvas and stages, then review AI feedback.