All systems
Identity

Authentication System Design

Proving who the caller is, on every request, without asking them for a password more than once.

internal/handlersinternal/passwordinternal/middlewareinternal/crypto

Questions this page answers

"Design an authentication system" is one of the most common system design interview prompts, and the follow-up questions are remarkably consistent between companies. Here are the ones that come up, each with a short answer. Every one of them is worked through somewhere below, so if you can follow this page you can answer the question.

What is authentication?

Proving that somebody is who they say they are. It is the step that turns an anonymous request into a request from a known person, usually by checking something only they should have: a password, a code from their phone, a key on their laptop. It answers one question and only one, which is who is calling. What they are then allowed to do is a separate system, and keeping the two apart matters more than it sounds.

Worked through in Problem statement →
Design a login system. Where do you start?

With requirements, not with tokens. Ask who is signing in (people in a browser, a mobile app, another service), whether you need to sign somebody out instantly, whether a second factor is required, and roughly how many users there are. Those four answers decide almost everything else. Only then write the functional list: register, sign in, stay signed in, sign out, reset a forgotten password. Jumping straight to "I would use JWTs" is the mistake interviewers are watching for, because it answers a question nobody asked yet.

Worked through in System requirements →
How do you store passwords?

Never as text, and never with a fast hash like SHA-256. You use a function built to be slow, such as bcrypt, scrypt or Argon2. Slow is the feature: a function that takes 60 milliseconds instead of a microsecond makes guessing a stolen hash roughly 60,000 times more expensive. The function also mixes in a salt, a random value stored next to the hash, so two people with the same password get different hashes and an attacker cannot crack them all at once with a precomputed table. bcrypt generates and stores the salt inside its own output, so there is no separate column to manage.

Worked through in Data model →
Sessions or JWTs? Which would you pick and why?

This is a trade-off question, and naming a winner is the wrong answer. A session is a row in your database; the client holds a meaningless id, and you look it up on every request. That costs a database read per request and makes signing somebody out instant, because you delete the row. A JWT is a self-contained token the server can check with mathematics alone, so there is no lookup, but you cannot un-issue it before it expires. The design here uses both, deliberately: a short-lived JWT for the per-request check, and a session row behind the long-lived token so revocation still works. You get stateless verification and instant sign-out, at the cost of one database write when a token is renewed.

Worked through in Problem statement →
A JWT cannot be cancelled once issued. So how do you log someone out?

You make the uncancellable thing short-lived, and put the cancellable thing behind it. The access token lives 15 minutes and nothing can stop it inside that window. The refresh token lives 7 days, and it only works if a matching session row exists in the database. Signing out marks that row revoked, so the next renewal fails and the user is out within at most 15 minutes. If a product truly needs instant revocation of the access token too, the usual answer is a deny list of token ids in Redis checked on every request, which trades the per-request lookup back in.

Worked through in High level design →
Users should stay signed in for a week, but be signed out after a period of inactivity. How?

Two separate clocks on the same session row, which is a question people often get half right. The idle timeout moves forward every time the session is used, so a person who keeps working never gets kicked out. The absolute timeout never moves, so a session dies at a fixed point no matter how active it is. Here the idle timeout is 7 days and the absolute timeout is 30. An unused sign-in dies in a week; a constantly used one still dies in a month. Without the absolute clock a session that is touched often enough lives forever.

Worked through in Data model →
Where should a browser keep the token? localStorage or a cookie?

A cookie with the HttpOnly flag, which means JavaScript cannot read it. Anything in localStorage is readable by any script on the page, so one cross-site scripting bug hands over every token. The cookie approach has its own weakness, cross-site request forgery, where another site makes the browser send your cookie along with a request you did not intend; the defence is the SameSite attribute plus checking the origin. Here the refresh token is an HttpOnly cookie scoped to the /api/auth path, so it is not even attached to ordinary API calls, and the access token is sent in the Authorization header where no browser attaches it automatically.

Worked through in High level design →
How do you stop someone guessing passwords?

Count failures per account and bar it temporarily once there are too many: here ten failures inside a window bars the account for fifteen minutes. The important detail is that the check runs before the password is hashed. If you hash first and check the limit afterwards, an attacker can still force you to burn 60 milliseconds of processor time per guess, which is a denial of service rather than a break-in but takes you down just the same.

Worked through in High level design →
What if the attacker spreads the guesses across a thousand different IP addresses?

Then a limit counted per address does nothing, because no single address reaches it, which is why the lockout counts failures per account. The mirror-image mistake is to bar the address instead, and it is worth naming because it is so easy to make: behind an office, a university or a mobile carrier, one address is hundreds of people, so barring it bars all of them, and anybody who can guess your egress address can do it on purpose. The shape that avoids both is to bar the (address, account) pair, and to keep a separate, looser address control that counts failures rather than attempts.

Worked through in High level design →
Slow hashing protects the database after a breach. What protects the login endpoint before one?

A different set of defences entirely, layered in front. bcrypt makes a stolen hash expensive to crack, and does nothing about somebody hammering your endpoint ten thousand times a minute: in fact it makes that worse, because you are now paying 60 milliseconds of processor time per guess. The layers that matter at the request level are an address rate limit at the edge, tighter flood limits on the credential routes, a shield that counts failed sign-ins per (address, account) pair, and a per-account lockout. Each catches an attack shape the others miss, and the two that do the real work count failures rather than attempts, so a busy shared address is not punished for signing in successfully.

Worked through in High level design →
Walk through the layers. What does each one actually catch?

An address limit, 100 requests a minute, stops a crude flood from one machine. Per-route limits on the credential endpoints are tighter, because those are the ones worth attacking, and they are flood control rather than guess control: they count every request including the successful ones, so they have to leave room for a shared office address. The guessing is caught by counting failures instead. The sign-in shield bars the (address, account) pair after 5 failures and refuses an address outright once it accumulates about four times that many, and the account lockout bars an account after 10 failures wherever they come from. Remove any one and a specific attack shape walks through.

Worked through in Technology stack →
Is a hard account lockout actually a good idea?

It is the part of this design most open to challenge, because the key is an email address anybody can guess, so ten deliberate failures lock a known user out. What makes it survivable is the recovery: the owner is emailed when it happens, and a password reset clears the lock immediately. Without that the victim is refused with the same "invalid email or password" as everybody else, having no idea why, with no way back except waiting or an administrator. A graduated delay is the stronger answer and it has its own trap, which is the next question.

Worked through in Bottlenecks and improvements →
Why not use progressive delays instead of locking?

Because the obvious way to do it leaks. If the delay grows with that account failure count, then a slow response means the address exists and a fast one means it does not, and you have built a timing oracle into the thing that was carefully made uniform. It has to be keyed on the caller instead, which an attacker evades by rotating addresses. So a delay is a good complement and a poor replacement: it slows a single attacker, and the per-account lockout is still what catches a distributed one.

Worked through in Bottlenecks and improvements →
Where do CAPTCHAs fit, and are they worth it?

As a middle tier between no friction and a hard bar: after a couple of failures ask for a challenge, and only start barring if that also fails. Interactive puzzles are weak now, since solving services and vision models are cheap, and they annoy exactly the people who are not attacking. An invisible challenge that scores the request from its telemetry is the version worth having. Here the tier is wired to a provider through configuration, and if no provider is set it stays dormant rather than silently pretending to be a defence.

Worked through in Technology stack →
What should you return when you refuse a sign-in, and does it matter?

On the sign-in route, nothing that distinguishes the refusal: a locked account answers exactly like a wrong password, because a 429 saying "too many attempts" confirms the address exists and turns the form into a lookup service. You give up Retry-After to keep that uniform, which is the right trade. Once the password has been checked, on the second-factor route, the caller already knows the account exists, so naming the wait leaks nothing and Retry-After is sent there.

Worked through in API design →
Your rules accept "Summer2024!". Is that a strong password?

It passes every local rule and it is in every credential-stuffing list in existence, which is the point. Length and character variety measure shape, and shape is a weak proxy for compromise. Credential stuffing is not guessing, it is replaying known passwords, so the question that matters is whether this exact password already appears in a breach corpus. That check uses k-anonymity: the password is hashed locally and only the first five characters of the hash are sent, so the service never learns which password was asked about.

Worked through in System requirements →
That check calls a third party on your registration path. What if it is down?

It answers false and the registration proceeds, which is a deliberate choice about which failure is worse. Failing closed means somebody else outage stops every registration and every password change here, a self-inflicted incident caused by an advisory check. Failing open means that during the outage passwords are judged by the local rules alone, which is exactly where you started. It is also off by default and bounded by a short timeout, for the same reason.

Worked through in System requirements →
How do you avoid telling an attacker which email addresses are registered?

By making "no such account" and "wrong password" indistinguishable, in both the message and the time taken. Returning different errors turns the login form into a lookup service for valid addresses. Timing matters as much as wording: if an unknown address returns instantly while a real one takes 60 milliseconds because a hash was computed, the difference is measurable, so the unknown-address path does the same wasted work. The same rule applies to the forgotten-password endpoint, which answers identically whether or not the address exists.

Worked through in System requirements →
What is refresh token rotation, and how would you detect a stolen token?

Rotation means every renewal issues a new refresh token and invalidates the one presented, so any given token is usable exactly once. Detection falls out of that for free: the session row remembers the hash of the token it just replaced, so if the old token is presented again you know there are two copies in the world. One of them is a thief. The system cannot tell which, so the safe response is to revoke the whole session and make the real user sign in again. The subtlety worth raising in an interview is the false alarm: a client that retries after a dropped response looks exactly like a replay, which is why a short grace window for an immediate retry is a common refinement.

Worked through in Data model →
How do other services check the token without calling your auth service?

That is the property a JWT is bought for. The token carries its claims (who the user is, their role, when it expires) and a signature over them. Any service holding the key can recompute that signature and know the contents were not altered, using only processor time and the clock. Nothing is called and nothing is looked up.

Worked through in High level design →
With a shared secret, every service that can verify can also mint. Is that not a problem?

It is the reason asymmetric signing exists. HMAC verification needs the same key that signs, so in an estate of a dozen services each one holds something that can forge an administrator token, and the blast radius of the least important one being compromised is all of them. Signing with a private key and verifying with the public half fixes it: a verifier holds something that provably cannot sign. Here a shared secret is the default, because for one service it is one environment variable and nothing to distribute, and setting a private key switches to RS256.

Worked through in Technology stack →
How do services get the public key, and how do you rotate it?

From a published key set, at /.well-known/jwks.json. Hardcoding the key into every service turns rotation into a synchronised redeploy of the whole estate, which in practice means it never happens. Services fetch the set, cache it, and refetch when a token names a key id they have not seen, so a new key propagates on its own. The key id is derived from the key itself rather than configured, so the id in a token and the id in the published set cannot disagree.

Worked through in Technology stack →
During a rotation, what happens to tokens signed with the old key?

They keep working until they expire, because the previous public key stays in the published set and stays accepted. Without that, the moment you switch keys every token in circulation becomes invalid and everybody is signed out. You drop the old key once one refresh lifetime has passed, which is the point at which nothing signed by it can still be live.

Worked through in Technology stack →
What is the algorithm confusion attack?

You publish a public key on purpose. An attacker takes it, signs a token using it as an HMAC secret, and sets the header to HS256. A verifier that reads the algorithm out of the token and picks its key accordingly then verifies an attacker-minted token with a key it was handed publicly. The defence is to pin the accepted algorithm to what you actually sign with rather than trusting the header, which is one line and the difference between a working system and a forgeable one.

Worked through in Low level design →
What stops a token minted for staging working on production?

The issuer and audience claims, when they are set. Without them a token is valid anywhere that holds the same key, which is exactly what happens when a secret is copied between environments or two products share a signing key. They are written when configured and checked only when the token carries them, so switching them on does not invalidate tokens already in circulation.

Worked through in System requirements →
What is the difference between authentication and authorization?

Authentication is who you are; authorization is what you may do. They are different systems and conflating them is a classic source of real breaches: a token can be perfectly valid and still not entitle its holder to the invoice they just requested. Here the auth middleware does exactly one job, turning a token into an identity on the request context, and it deliberately makes no decision about permission. The next layer reads that identity and decides. Keeping them apart is why an ownership check cannot be accidentally satisfied by the mere fact that somebody is signed in.

Worked through in Low level design →
What happens to signed-in users when the database goes down?

They keep working, for up to 15 minutes. This is the quiet benefit of stateless verification: checking an access token touches no storage, so every already-authenticated read keeps succeeding through a database outage. What stops is anything needing a write: new sign-ins, renewals, and sign-outs. The failure is therefore gradual rather than instant, and the window is exactly the access token lifetime, which is a useful thing to be able to state precisely when an interviewer asks what breaks first.

Worked through in Scalability and performance →
How do you rotate the signing secret without signing everybody out?

With one key you cannot, which is the point of the question. Changing it invalidates every token in existence at once. The fix is to verify against two keys while signing with only one: add the new key as an accepted verifier, switch signing over to it, and once one access token lifetime has passed, nothing signed with the old key is still valid and it can be dropped. Rotation then takes 15 minutes instead of logging out every user.

Worked through in Bottlenecks and improvements →
How does multi-factor authentication fit into the login flow?

Sign-in stops halfway. Instead of returning tokens, a correct password returns a short-lived pending token that proves the first factor passed and nothing else. The client sends that back along with the code from the authenticator app, and only then are real tokens issued. The important part is that the pending token carries no authority: it cannot be used on any other endpoint, so an attacker holding a correct password is still holding nothing useful.

Worked through in API design →
How do you handle a forgotten password safely?

Email a single-use token, store only its hash, and expire it in minutes rather than days. Single-use means it stops working the moment it is used, so an emailed link sitting in a mailbox is not a permanent key to the account. Storing only the hash means a database leak does not hand over working reset links. And the endpoint answers identically whether or not the address exists, for the same enumeration reason as the login form.

Worked through in API design →
How would you size this? How many servers, how much storage?

Work from active users rather than registered ones, because dormant accounts cost storage and nothing else. Multiply through to get requests per second, then check the two expensive operations separately: password hashing, which is deliberately slow and therefore caps sign-ins, and token verification, which is nearly free and therefore does not cap anything. Every figure in the capacity section below shows where it came from, so you can change one assumption and redo the arithmetic.

Worked through in Capacity estimation →

1.Problem statement

Every endpoint past the public ones needs to know which user is calling. The obvious answer is to send the password with every request, which means the client has to store it and hand it over a thousand times a day. That is wrong for a reason worth stating plainly: a password is a long-lived secret, and the more places and times it travels, the more chances there are to lose it.

The second answer is a session: the server keeps a row for each signed-in person, the client holds a meaningless identifier, and the server looks it up on every request. This works, and plenty of large systems do exactly this. The cost is that it puts a database read in front of every single thing the application does.

The third answer is a token that carries its own proof. A JSON Web Token (JWT) is a small piece of JSON, such as "user 123, role editor, expires at 09:15", with a signature over it. Any server holding the key can recompute that signature and know nobody tampered with the contents, without looking anything up. Verification becomes arithmetic instead of a query.

That buys speed and gives up control. Once a token is issued it is valid until it expires, and there is no way to take it back. If somebody steals it, or a user signs out, or an account is suspended, the token carries on working regardless.

So this design uses both, and the split is the central idea of the page. A short-lived access token (15 minutes) does the per-request work with no lookup. A long-lived refresh token (7 days) renews it, and that one is backed by a row in the database, so it can be revoked. You get stateless verification on the hot path and real revocation where it matters, at the cost of one database write each time a token is renewed.

The hard parts are not the signing, which is a library call. They are what happens when a token is stolen, what happens when a user signs out on one device but not another, and what happens when somebody tries ten thousand passwords against one account from a thousand different addresses.

The system has to be able to:

  • Register a user, hash the password with a function that is slow on purpose, and never store the plain text.
  • Issue a credential a request can carry, and verify it without reading the database.
  • Renew that credential without a second sign-in, and notice when a renewal is a replay of an old one.
  • Revoke one device without signing the user out everywhere, and revoke everywhere when a password changes.
  • Resist password guessing spread across many addresses, without letting an attacker lock out a user whose address they can guess.
  • Hand the caller to the authorization system as an identity, so that layer never has to parse a token.

2.System requirements

Functional requirements

  • Registration with email and password, and an optional requirement that the address be confirmed before the first sign-in.
  • Sign-in returning an access token and a refresh token, with the refresh token also set as an HttpOnly cookie scoped to /api/auth.
  • Token refresh that rotates the refresh token and invalidates the one presented.
  • Sign-out for the current device, and sign-out for every device.
  • Password reset by emailed single-use token, and password change for a signed-in user.
  • Social sign-in through Google and GitHub, landing on the same user record.
  • A context-level identity every handler and service reads, rather than each one parsing the Authorization header.

Non-functional requirements

  • Verification cost. checking an access token must not touch the database. It is a signature check and a clock comparison, both of which take microseconds, and that is what makes it affordable to do on every single request.
  • Blast radius. this is the question of how much damage one stolen thing can do. A stolen access token expires in 15 minutes. A stolen refresh token is usable once, and using it after the real client already has tells the server something is wrong.
  • Storage safety. somebody who steals a copy of the database must not be able to sign in with it. Passwords are stored as bcrypt hashes and refresh tokens as SHA-256 digests, so neither column contains anything that can be replayed.
  • Availability. signing in may depend on the database. Verifying a token may not. An application therefore stays readable through a database outage for as long as its access tokens live.
  • No membership oracle. an oracle here means anything that answers a question an attacker should not get to ask. A wrong password, an unknown address and a locked account all answer the same way, in the same time, so the login form cannot be used to discover which addresses are registered or what state they are in.
  • Every lockout has a way out. a lock keyed on something anybody can guess must not be a dead end. The owner is told it happened and given a link that clears it, through the mailbox, which is the one channel where saying so reveals nothing to whoever caused it.
  • Advisory checks fail open. the breach check calls a service this application does not run. If it is slow, broken or unreachable the password is allowed, because an outage elsewhere must not stop people registering or changing a password here.

3.Capacity estimation

Numbers for a mid-sized deployment. They are here to size the thing, not to predict your traffic: change an assumption and the sums below move with it.

Assumptions

ParameterValue
Registered users1,000,000 (a successful mid-market product; pick your own number and every sum below rescales with it)
Daily active users200,000 (20% of registered, a normal ratio for a tool people use on working days; a consumer social app would be higher, a tax product far lower)
Sign-ins per active user per day1.2 (most people are already signed in and never see the form; the 0.2 covers a second device or a session that expired overnight)
API requests per active user per day400 (one screen typically makes 5 to 15 API calls, and an engaged user opens 30 to 80 screens in a working day)
Access token lifetime15 minutes (short enough that a stolen token is nearly worthless, long enough that renewals stay rare; the industry norm is 5 to 60 minutes)
Refresh token lifetime168 hours, which is 7 days (how long somebody can close the laptop and come back without signing in again; a product decision, not a technical one)
Session row~400 bytes (two 32-byte hashes, two timestamps, a user agent string of around 200 bytes, an address, and row overhead)
User row~1.2 KB with profile fields (identifier, email, a 60-byte bcrypt hash, name, role, timestamps, and whatever the product adds)

Sign-in rate: how often the expensive path runs

200,000 daily active users x 1.2 sign-ins = 240,000 sign-ins/day
240,000 / 86,400 = 2.8 sign-ins/second average (86,400 is the number of seconds in a day)
peak = 2.8 x 5 = 14 sign-ins/second (5x is the usual ratio of the busiest hour to the daily average when an audience shares working hours; a global consumer app is flatter, nearer 2x)

This matters because sign-in is the one deliberately slow operation. bcrypt at cost 10 takes roughly 60 milliseconds of processor time, so 14 a second is 14 x 0.06 = 0.84 seconds of work per second, which is under one processor core. That is the number that tells you the cost factor can stay where it is.

Token verification rate: how often the cheap path runs

200,000 daily active users x 400 requests = 80,000,000 requests/day
80,000,000 / 86,400 = 926 verifications/second average
peak = 926 x 5 = 4,630 verifications/second (same 5x peaking factor as above)

Verifying a signature takes a few microseconds, so 4,630 a second is roughly 0.02 seconds of work per second: effectively nothing. Compare it with the session approach, where these same 4,630 requests a second would each be a database read. That gap is the entire argument for stateless access tokens.

Refresh rate: the part that is not free

an 8 hour working day / a 15 minute token = 32 renewals per active session
200,000 daily active users x 32 = 6,400,000 renewals/day
6,400,000 / 86,400 = 74 renewals/second average, and 370/second at the same 5x peak

Every renewal is a database write, because rotation replaces the stored hash. This is the only part of the hot path with state, so it is the number to watch. Note how it moves: halving the access token lifetime to 7 minutes doubles this to 148 and 740. Lengthening it to an hour cuts it to 18. That single assumption is the main lever on write load.

Session storage: how big the revocation table gets

200,000 daily active users x 3 devices = 600,000 live sessions (laptop, phone, and one more: a tablet, a work machine, a second browser)
600,000 x 400 bytes = 240 MB
plus indexes on token_hash, user_id and expires_at = ~400 MB (indexes commonly add 50 to 100% on a table this narrow)

Under a gigabyte, so it stays in the primary database and needs no separate store. It stays that size only because expired rows are swept on a schedule; left alone the table would grow with every sign-in ever made rather than with devices currently signed in.

User storage: the part that grows with signups, not usage

1,000,000 users x 1.2 KB = 1.2 GB
with indexes and audit columns = ~2 GB

Small enough that it never drives a design decision, which is worth saying out loud: dormant accounts cost storage and nothing else. This is why the sums above start from active users rather than registered ones.

4.High level design

Sign-in is a write path that ends in two tokens. Everything after it is a read path that touches no storage at all until the access token expires.

Core components

  • Auth handlers. the HTTP surface. Register, login, refresh, logout, forgot and reset. They are thin on purpose: they read the request, call a service, and shape the response, holding no logic that would have to be tested through HTTP.
  • Password service. bcrypt hashing and comparison, plus the strength rules. The only place in the system that ever sees a plain text password, and it never returns one.
  • JWT service. signs and verifies. Every token carries a user id, a role, a type, an expiry and a jti, which is a unique id for that individual token, so two tokens issued in the same second are still distinguishable from each other.
  • Session store. one row per signed-in device, found by the SHA-256 hash of the current refresh token. This single table is what turns a stateless token into a revocable one, and it is the reason this design is not purely stateless.
  • Auth middleware. runs before your handler. It reads the Authorization header or the access cookie, verifies the token, and puts an identity on the request context so everything downstream reads a value instead of parsing a header. It decides who you are and nothing about what you may do.
  • Lockout counter. failed attempts counted per account rather than per address, so an attack spread across a thousand machines still trips it. Ten failures bar the account for fifteen minutes, and the count resets on any successful sign-in.
  • Edge rate limiter. the layer in front of all of it, from the security library mounted at the edge of the router. A general ceiling of 100 requests a minute per address, and much tighter limits on the routes that take a password or a code: 5 sign-ins per 15 minutes, 3 registrations, 3 forgotten-password requests, 5 code verifications per 5 minutes. Counted in Redis when it is configured, so the limit means the same thing behind every replica.
  • Sign-in shield. a failed-login counter that bars the (address, account) pair after 5 failures, so one account under attack is protected without touching anybody else behind the same address. An address that accumulates roughly four times that many failures is refused outright for a minute, which is the one machine working through many accounts. Known shared egress ranges can be exempted from address-level barring and are still counted.

Request flow

Sign-in and the first authenticated request

123456789ClientWeb / MobileAuth MiddlewareAuth HandlerPassword ServiceLockout CounterJWT ServiceSession StoreDatabaseAudit Log
  1. 1The client posts an email and password to /api/v1/auth/login. The middleware lets it straight through, because this route is public: it is the route you use when you have nothing to prove yet.
  2. 2The handler reads the request and asks the lockout counter whether this account is currently barred. A barred account is refused right here, before any password hashing is paid for, which is what stops a guessing attack from costing processor time.
  3. 3The password service compares the submitted password against the stored bcrypt hash. A wrong password and an unknown email take the same path and the same amount of time, so the response cannot be used to find out which addresses exist.
  4. 4A failed comparison increments the counter for that account. Ten failures inside the window bar it for fifteen minutes. An unknown address increments nothing, because otherwise an attacker could deliberately lock out any address they can guess.
  5. 5On success the JWT service mints two tokens: an access token good for 15 minutes, and a refresh token good for 7 days. Each carries its own jti, the unique per-token id, so they can be told apart later.
  6. 6The session store records the device: the SHA-256 hash of the refresh token, the browser or app it came from, the address, and the two expiry timestamps.
  7. 7The row is written. Note what is not written: the refresh token itself. Only its hash is stored, so even somebody holding a dump of this table cannot produce a working token from it.
  8. 8The response carries both tokens, and also sets the refresh token as a cookie marked HttpOnly, so JavaScript cannot read it, and scoped to the /api/auth path, so the browser does not attach it to ordinary API calls.
  9. 9The sign-in is written to the audit log, outside the response path so it cannot slow the user down. From here on, each request carries the access token and the middleware verifies it with no storage read at all, which is the whole point of the arrangement.

Data flow

  • Passwords travel over TLS, are hashed the moment they arrive, and are never written to a log, a trace or an error message. A password in a log file is a password in your log search tool, your backups and your screenshots.
  • Access tokens are stored nowhere on the server. Their validity is entirely a property of the signature and the clock, which is exactly why no server has to be asked about them and why they cannot be cancelled early.
  • Refresh tokens are stored only as SHA-256 hashes. The server can recognise a token it issued without being able to produce one, the same trick used for passwords and for the same reason.
  • The hash of the previous refresh token is kept alongside the current one. That one extra column is what makes replay detection possible: it is how the server can tell that a token it already replaced has just been presented again.
  • The identity placed on the request context is a plain value, not a database handle. A service that needs the user id gets the user id, and does not get the ability to run queries as that user.
  • Browsers and mobile apps are not the same problem. A mobile app has no cross-site request forgery risk and no JavaScript injection surface, so it holds tokens in the platform keychain and sends them in the Authorization header. The cookie machinery exists for browsers.

5.Technology stack

ComponentWhat it is
Token formatJWT, HS256 on a shared secret by default
Multi-service signingRS256 with a private key, opt-in; the public half published at /.well-known/jwks.json
Key rotationa kid per key derived from the key itself, with the previous public key accepted while tokens age out
Issuer and audiencewritten when configured, checked when present
Password hashingbcrypt, cost 10 (about 60 ms per hash)
Session storagethe primary database, one row per device
TransportAuthorization: Bearer, plus HttpOnly cookies for browsers
Social sign-inOAuth2 against Google and GitHub
Address rate limit100 requests/minute in production, 1,000 in development
Sign-in route limit30 attempts per 5 minutes, per address: flood control, counting every attempt
Other credential routesregister 10/15min, forgot-password 10/15min, reset 10/15min, code verify 20/5min
Sign-in shield5 failures bars the (address, account) pair; roughly 20 failures refuses the address briefly
Per-account lockout10 failed sign-ins bars the account for 15 minutes, database-backed so it survives a restart
Lockout recoverythe owner is emailed a reset link, and a completed reset clears the lock
Challenge tierTurnstile, hCaptcha or reCAPTCHA, by configuration; dormant when none is set
Breach checkingoptional, off by default: the chosen password checked against the public corpus by k-anonymity, failing open
Shared countersRedis when configured, so limits hold across replicas
Client addressthe forwarded chain walked from the right, past configured trusted proxies
Reset tokenssingle-use, hashed at rest, short expiry

6.Data model

Three tables carry the whole system: a user, a session per device, and a short-lived token for the password reset flow.

users

There is no salt column, which surprises people. bcrypt generates a random salt per password and stores it inside the hash string, so the single column holds the algorithm, the cost, the salt and the hash together.

ColumnHolds
idUUIDv7, which sorts by creation time so the index stays compact as rows are added
emailunique, and the identifier somebody signs in with
password_hashthe bcrypt output, which contains the salt and the cost inside it; never the password
roleADMIN, EDITOR or USER
email_verified_atnull until confirmed; gates sign-in when verification is required
totp_secretencrypted at rest, null until two-factor is enrolled
created_at, updated_ataudit columns

sessions

One row per signed-in device. This table is the thing that turns a stateless token into a revocable one, and the two timestamp columns are how one session can have both an idle timeout and an absolute one.

ColumnHolds
idUUIDv7
user_idthe owner, indexed
token_hashSHA-256 of the current refresh token, unique
prev_token_hashSHA-256 of the token this one replaced; the entire replay detection mechanism is this column
user_agent, ipwhat the device list shows a user, so they can recognise their own sessions
last_seen_atmoved forward on every renewal, which is what drives the idle timeout
expires_atthe absolute deadline, which never moves no matter how active the session is
revoked_atset on sign-out; the row is kept rather than deleted, so a later replay can still be recognised

password_reset_tokens

ColumnHolds
token_hashthe emailed token, hashed, so a database leak yields no working links
user_idwho it is for
expires_atshort, measured in minutes rather than days
used_atset on first use, which is what makes the link work exactly once

Where it lives

  • Everything is in the primary relational database. There is no second store to keep consistent, and a session lookup is a single indexed read.
  • Sessions are swept on a schedule: rows past their absolute expiry are deleted, and revoked rows go once they are older than the retention window. Without the sweep this table grows with every sign-in ever made.
  • The idle timeout is 7 days and the absolute timeout is 30. An unused sign-in dies in a week; one that is used every day still dies in a month. Two clocks, because one cannot express both rules.

7.API design

Authentication

MethodEndpointWhat it does
POST/api/v1/auth/registerCreate an account and sign in
POST/api/v1/auth/loginExchange credentials for tokens
POST/api/v1/auth/refreshRotate the refresh token, issue a new access token
POST/api/v1/auth/logoutRevoke the current session
GET/api/v1/auth/meThe signed-in user

Passwords

MethodEndpointWhat it does
POST/api/v1/auth/forgot-passwordEmail a single-use reset link, answering the same way whether or not the address exists
POST/api/v1/auth/reset-passwordSet a new password from that link
POST/api/v1/auth/change-passwordChange it while signed in, ending every other session

Sessions

MethodEndpointWhat it does
GET/api/v1/auth/sessionsEvery device currently signed in
DELETE/api/v1/auth/sessions/:idSign one device out
POST/api/v1/auth/sessions/revoke-allSign every device out

Sign-in request

{
"email": "ada@example.com",
"password": "correct horse battery staple"
}

Sign-in response. expires_in is 900 seconds, which is the 15 minute access token

{
"data": {
"user": {
"id": "01a11e82-d0bc-7367-9c39-5e9873953dde",
"email": "ada@example.com",
"first_name": "Ada",
"role": "USER"
},
"tokens": {
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"expires_in": 900
}
},
"message": "Signed in"
}

When two-factor is enrolled, sign-in stops halfway and no real token is issued

{
"data": {
"mfa_required": true,
"pending_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"methods": ["totp", "backup_code"]
},
"message": "A second factor is required"
}

8.Low level design

Core types

AuthHandlerinternal/handlers/auth.go

Reads and validates the request, calls the services, shapes the response. Holds no logic that would be worth testing through HTTP.

RegisterLoginRefreshLogoutMeForgotPasswordResetPassword
JWTServiceinternal/services/jwt.go

The only thing in the system that signs or verifies. Issuing and verifying are separate methods, so a service that only needs to verify can exist without ever holding the ability to mint tokens.

GenerateTokenPairValidateAccessTokenValidateRefreshToken
SessionStoreinternal/session/session.go

Creates, rotates and revokes device sessions, and decides whether a presented refresh token belongs to a live one.

CreateSessionRotateSessionRevokeRevokeAllForUserListForUser
PasswordServiceinternal/password/password.go

Hash, compare, and judge strength. Comparison takes the same time whether or not the user exists, which is a correctness requirement rather than an optimisation.

HashCompareStrength
AuthMiddlewareinternal/middleware/auth.go

Turns a token into an identity on the request context, or returns a 401. It does not decide what that identity is allowed to do, and keeping that line clean is what stops "is signed in" from being mistaken for "is allowed".

RequireAuthOptionalAuth

Design principles applied

  • Single responsibility. the handler does HTTP, the JWT service does cryptography, the session store does revocation. No one of them knows about two of those three.
  • Authentication is not authorization. the middleware answers who, and stops. A separate layer answers what they may touch. These are different questions, and the breaches that come from merging them look like a valid token being treated as permission for a record it was never entitled to.
  • Dependency inversion. services take interfaces for the clock and the store, which is a plain way of saying the expiry tests can move time forward instead of sleeping for 15 minutes.
  • Open for extension. password, social and passkey sign-in all end at the same point, issuing a token pair for an existing user record, so adding one never required changing the token layer.
  • Fail closed. an unparseable token, an unknown session and a revoked session all produce the same 401. There is no path through the code where an error leaves the request authenticated.

Patterns

PatternWhere it is used
Strategypassword, social and passkey sign-in, each ending at the same token issuance
Chain of responsibilitythe middleware stack: request id, then auth, then rate limit, then the handler
Token rotationevery renewal replaces the stored hash and remembers the old one
Context carrierthe identity rides on context.Context, so a background job started by a request keeps it

9.Scalability and performance

  • Verification is stateless, so the API scales horizontally with no shared session store and no sticky sessions. Adding a replica adds capacity immediately, because a replica needs nothing from the others to check a token.
  • A database outage degrades this system gradually rather than instantly. Already-signed-in users keep reading for up to one access token lifetime, 15 minutes, because verification reads no storage. What stops is sign-ins, renewals and sign-outs, all of which write.
  • The refresh endpoint is the only part of the hot path that writes. At 370 writes a second it is comfortable on one primary, and it is the first thing to watch if the access token lifetime is ever shortened.
  • That trade is worth stating as a rule: shortening the access token lifetime buys a smaller window of damage from a stolen token, and pays for it in writes. Halving it to 7 minutes doubles the write rate on that one endpoint.
  • Session reads are a single lookup on a unique index. The table stays small because it holds devices currently signed in, not a history of every sign-in.
  • Bcrypt cost is a deliberate ceiling on sign-in throughput. It is sized so a peak hour fits in a fraction of a core, which means raising it is a capacity decision as much as a security one.
  • Social sign-in depends on somebody else being up. It sits on its own route with its own timeout, so a slow provider cannot consume the connection pool that ordinary password sign-in needs.

10.Bottlenecks and improvements

What breaks first

  • Refresh storms. every client with a 15 minute token renews on roughly the same cadence. A deploy that restarts every client at once converts a steady 74 writes a second into a single spike.
  • Bcrypt under credential stuffing. an attacker sending ten thousand sign-ins a second is asking for ten thousand slow hashes a second. That is a denial of service aimed at the processor rather than the database, and it is caused by the very thing that makes passwords safe.
  • The sessions table growing. without a sweep, revoked and expired rows accumulate forever, and the unique index on token_hash grows along with them.
  • Rotating a shared secret signs everybody out. changing JWT_SECRET invalidates every token at once, so in practice it never gets rotated. Asymmetric signing has an answer, since the previous public key can stay accepted while tokens age out, and a shared secret does not: there is only one value and it both signs and verifies.
  • Clock skew. token expiry is a comparison against the local clock. A replica whose clock has drifted will reject valid tokens or accept dead ones, and nothing in the logs will say so.
  • The lockout can still be aimed at somebody. the per-account lockout is keyed on an email address, which anybody can guess, so ten deliberate failures bar that person for fifteen minutes. Recovery is now immediate rather than a dead end, because the owner is emailed and a password reset clears the lock, but the nuisance is real: an attacker can still make somebody reset a password they did not want to change. A graduated delay would remove it entirely, at the cost of a timing signal that has to be keyed carefully.
  • The sign-in route cannot say why it refused. a locked account answers exactly like a wrong password, because saying "locked" would confirm the address exists. That is the right call and it has a cost: no status code, no Retry-After, and nothing a client can back off against. The mailbox carries the explanation instead, which is the only channel where saying it leaks nothing.
  • Local password rules measure the wrong thing. length, variety and a list of a few hundred obvious passwords all judge shape. "Summer2024!" passes every one of them and is in every credential-stuffing list there is. Shape is a weak proxy for whether a password is actually compromised, and the breach check that closes the gap is off by default because it calls a third party.
  • Nothing escalates on an unusual sign-in. a correct password from a new device in a new country is treated exactly like one from the usual laptop. The pieces for a risk score exist, since the device is already recognised for the second factor and the address is already geolocated, but nothing combines them into a decision to ask for more.

What to do about it

  • Jitter the renewal. clients renew at a random point inside the last third of the token lifetime rather than at a fixed offset. The same number of renewals, spread across minutes instead of arriving together.
  • Cost the attack before hashing. the rate limiter and the account lockout both run before the password service, so a stuffing attack is refused without the server paying for a hash.
  • Sweep on a schedule. a scheduled job deletes sessions past their absolute expiry and revoked rows past the retention window, keeping the table proportional to live devices rather than to history.
  • Two signing keys. verify against both the current and the previous key, but sign only with the current one. Rotation then takes one access token lifetime instead of signing out every user, which is the difference between a secret that can be rotated and one that cannot.
  • A small leeway on expiry. allowing a few seconds of clock skew on the expiry comparison removes a whole class of failure that is otherwise invisible until a replica drifts.
  • Delay before you lock. make each failure slower rather than jumping from no friction to a fifteen minute wall. A script is stopped just as well, because the attack rate collapses, and a person who mistyped twice barely notices. The subtlety that decides whether it is safe: keyed on the account it is a timing oracle, since a delay that only happens for real addresses announces which addresses are real. It has to be keyed on the caller, where it costs an attacker nothing to evade by rotating addresses, which is why it is a complement to the lockout rather than a replacement for it.
  • Risk-based step-up rather than a uniform challenge. score the sign-in from what is already known, which is the recognised device, the address and its location, and the velocity of attempts, then ask for more only when the score is poor. A correct password from a new device in a new country is the case worth interrupting. Everything needed is already collected for other reasons; nothing currently combines it.
  • Tell the owner, through the one channel that leaks nothing. the sign-in response must stay uniform, so the explanation goes to the mailbox: somebody has been trying, here is a link that lets you back in now. The attacker cannot read it and the owner learns both facts at once. This is what turns a lockout from a wall into an event with a remedy.

Read next