October 12, 2026

Authentication System Design

Authentication System Design

This post follows the flow of the Authentication System Design page from the Grit docs. Same order, same numbers, but told with an office building and its reception desk so anyone (and a tired developer) can follow it.

Jump to the design if you already know the questions.

backstory

If you only want the technical part, skip to the problem statement

"Design an authentication system" is one of the most common system design interview questions. The follow-ups are almost always the same: sessions or JWTs, how do you store passwords, how do you stop guessing, how do you log someone out.

Authentication sounds scary, but the whole idea fits in one sentence:

Prove who is walking in, on every request, without asking them for the password more than once.

To make it easy, we will use one story the whole way through.

the office building

Imagine a company office building. Only people who have been checked at reception can go up to the floors.

  • The security guards on every floor are your server.
  • The secret PIN you tell reception is the password.
  • The visitor badge clipped to your shirt is the access token. It lasts 15 minutes.
  • The renewal pass in your pocket is the refresh token. It lasts 7 days, and you take it back to reception to swap for a fresh badge.
  • The reception logbook is the session table in the database.
  • The scrambling machine is bcrypt, the slow machine that turns your PIN into scrambled nonsense that nobody can turn back into the PIN.

Keep these in your head. Everything below is just this story, with numbers.

questions this post answers

Every one of these is worked through in the sections after this. If you can follow the post, you can answer the question in an interview.

01. What is authentication?

Showing that you are really you. Reception says "who are you?" and you give your secret PIN. It only answers "who is at the desk". What you are allowed to do inside, like which floors you can enter, is a different job (authorization), and keeping the two apart matters a lot. (section 1)

02. Design a login system. Where do you start?

With questions, not tools. Who is coming in: people walking in through the front door (a browser), people using the staff entrance (a phone app), or delivery robots (other services)? Must we remove someone instantly? Do we need a second check? How many people are there? Then write the list: sign up, sign in, stay in, sign out, forgot the PIN. Shouting "I'll use JWTs!" first is the mistake interviewers look for. (section 2)

03. How do you store passwords?

You never write the PIN down. You put it through a slow scrambling machine (bcrypt, scrypt or Argon2) that makes scrambled output nobody can turn back into the PIN. Slow is the point: 60 milliseconds instead of a blink makes guessing against a stolen scramble about 60,000 times more work. You also add a few random extra digits (a salt) before scrambling, so two people with the same PIN get different results. bcrypt hides those extra digits inside its own output, so you need no extra column. (section 6)

04. Sessions or JWTs? Which one?

Both, on purpose. A session is the reception logbook: you hold a number, reception looks you up every time, and can cross you out instantly. A JWT is a badge with a tamper-proof hologram: the guard checks the hologram with no logbook, but cannot take the badge back. So we use a short badge for every request and a long renewal pass backed by the logbook. (section 1)

05. A JWT cannot be cancelled. So how do you log someone out?

Make the uncancellable thing short and put a cancellable thing behind it. The badge lasts 15 minutes and nothing can stop it. The renewal pass lasts 7 days but only works if the logbook still has your name. Logging out crosses you off, so you are out within 15 minutes at most. If you need it instant, keep a "cancelled badges" list in Redis, but then the guards are looking things up again. (section 4)

06. Stay signed in for a week, but get signed out when inactive. How?

Two clocks on the same row. The idle clock moves forward every time you use it (7 days). The hard clock never moves (30 days). Without the hard clock, someone who keeps using the session could stay in forever. (section 6)

07. Where should a browser keep the token? localStorage or a cookie?

A cookie marked HttpOnly, which JavaScript cannot peek into. Anything in localStorage can be read by any script on the page, so one cross-site scripting bug hands over everything. Cookies have their own weakness (another site tricking your browser into sending them), fixed with SameSite and an origin check. The renewal-pass cookie is only sent to the /api/auth path, and the badge travels in the Authorization header. (section 4)

08. How do you stop someone guessing passwords?

Count the wrong guesses per account. Ten failures in a window and reception locks that account for 15 minutes. And check this before scrambling the PIN. If you scramble first, the attacker still makes you waste 60 milliseconds per guess, which can knock your server over. (section 4)

09. What if the attacker guesses from a thousand different addresses?

Counting per address does nothing, because no single address gets caught. That is why we count per account. The opposite mistake is barring the address: a school, an office or a phone company is hundreds of people behind one address. So bar the pair (address, account) and keep a separate, looser address control that counts failures. (section 4)

10. Slow hashing protects after a breach. What protects before one?

A set of layers in front of the desk. bcrypt makes a stolen scramble expensive, but does nothing against someone walking up 10,000 times a minute. In fact it makes it worse, because every visit costs you 60 ms. So you add an address rate limit, tighter limits on the sign-in routes, a shield that counts failures per pair, and a per-account lockout. (section 4)

11. Walk through the layers. What does each one catch?

A limit of 100 requests a minute per address stops a crude flood. Tighter limits on credential routes are flood control (they count every request, so they must leave room for shared addresses). The shield bars the (address, account) pair after 5 failures, and refuses an address after about four times that many. The account lockout bars an account after 10 failures from anywhere. Remove one layer and one kind of attack walks right in. (section 5)

12. Is a hard account lockout a good idea?

It is the part most open to challenge. The key is an email address anyone can guess, so ten bad guesses lock a real person out. It is survivable only because there is a way back: the owner gets an email, and a password reset clears the lock immediately. (section 10)

13. Why not use growing delays instead of locking?

Because the obvious version leaks. If the delay grows with that account's failures, a slow answer means "this address exists" and a fast one means "it does not". Keyed on the caller instead, an attacker simply rotates addresses. So a delay is a good helper but not a replacement for the lockout. (section 10)

14. Where do CAPTCHAs fit?

As a middle step between "no friction" and "locked": after a couple of failures, ask for a challenge. Puzzle-style ones are weak now because solving services are cheap, and they annoy honest visitors. An invisible challenge that scores the request is better. If no provider is configured, this tier stays asleep instead of pretending to protect you. (section 5)

15. What should you return when you refuse a sign-in?

Nothing that tells the refusal apart. A locked account must answer exactly like a wrong password. A "429 too many attempts" confirms the account exists. So on sign-in we give up Retry-After to stay uniform. On the second-factor route, the caller has already proven the password, so naming the wait leaks nothing and Retry-After is sent. (section 7)

16. Your rules accept "Summer2024!". Is that strong?

It passes every rule and it is in every stolen-password list on earth. Length and symbols only measure shape. Credential stuffing replays known passwords, so the real question is whether this exact password was already leaked. That check uses k-anonymity: hash it locally and send only the first five characters, so the service never learns which password you asked about. (section 2)

17. That check calls a third party. What if it is down?

It answers "not leaked" and registration continues (fail open). If we failed closed, someone else's outage would stop every sign up here, which is an incident we caused ourselves for an advisory check. It is off by default and has a short timeout. (section 2)

18. How do you avoid revealing which emails are registered?

Make "no such account" and "wrong password" look identical, in words and in time. If an unknown email answers instantly and a real one takes 60 ms (because a hash was computed), the gap is measurable. So the unknown path does the same wasted work. The forgot-password endpoint answers the same way for every address. (section 2)

19. What is refresh token rotation, and how do you detect a stolen token?

Every renewal hands you a new renewal pass and destroys the old one, so each pass works exactly once. The session row remembers the hash of the pass it just replaced. If the old pass shows up again, there are two copies in the world and one belongs to a thief. We cannot tell which, so we revoke the whole session and make the real person sign in again. A short grace window for an immediate retry avoids false alarms from dropped responses. (section 6)

20. How do other services check the token without calling your auth service?

The badge carries the facts (who, role, expiry) and a signature. Any service holding the key can recompute the signature and know nothing was changed. No calls, no lookups, just math and a clock. (section 4)

21. With a shared secret, every verifier can also mint tokens. Is that bad?

Yes, and it is why asymmetric signing exists. With a shared secret, a dozen services each hold something that can forge an admin badge. With a private key that signs and a public key that verifies, verifiers hold something that cannot sign. The default here is a shared secret (one environment variable). Setting a private key switches to RS256. (section 5)

22. How do services get the public key, and how do you rotate it?

From a published key set at /.well-known/jwks.json. Services cache it and refetch when a token names a key id they have not seen, so new keys spread by themselves. The key id is derived from the key, so the token and the published set cannot disagree. (section 5)

23. During a rotation, what happens to tokens signed with the old key?

They keep working until they expire, because the previous public key stays accepted. Drop it after one refresh lifetime, when nothing signed by it can still be alive. (section 5)

24. What is the algorithm confusion attack?

The public key is public on purpose. An attacker uses it as an HMAC secret, signs a token, and writes HS256 in the header. A verifier that trusts the header will accept it. The fix is one line: pin the accepted algorithm to what you really sign with. (section 8)

25. What stops a staging token working on production?

The issuer and audience claims. Without them, a token is valid anywhere with the same key. They are written when configured and checked only when present, so switching them on does not break tokens already out there. (section 2)

26. Authentication vs authorization?

Authentication is who you are. Authorization is what you may touch. The auth middleware only turns a token into an identity on the request, and the next layer decides permission. That is why "is signed in" can never accidentally count as "is allowed". (section 8)

27. What happens to signed-in users when the database goes down?

They keep working for up to 15 minutes, because checking a badge touches no storage. What stops is anything that writes: new sign-ins, renewals and sign-outs. The failure is gradual, and the window is exactly the access token lifetime. (section 9)

28. How do you rotate the signing secret without signing everybody out?

With one key you cannot. The fix is to verify with two keys and sign with one. Add the new key, switch signing to it, wait one access token lifetime, then drop the old one. Rotation takes 15 minutes instead of logging out everyone. (section 10)

29. How does multi-factor authentication fit in?

Sign-in stops halfway. A correct password returns a short-lived pending token that proves only that step one passed. The client sends it back with the code from the authenticator app, and only then do real tokens come out. The pending token has no power anywhere else. (section 7)

30. How do you handle a forgotten password safely?

Email a single-use token, store only its hash, and expire it in minutes. Single-use means it stops working the moment it is used. Storing the hash means a database leak gives no working links. And the endpoint answers the same whether or not the address exists. (section 7)

31. How would you size this?

Work from active users, not registered ones. Multiply through to requests per second, then check the two expensive things separately: password hashing (slow on purpose, so it caps sign-ins) and token verification (nearly free, so it caps nothing). (section 3)

1. problem statement

the office building version

Every floor in the building needs to know who is walking in. How do the guards know?

Idea 1: say the secret PIN every time. The visitor has to remember the PIN and say it out loud at every floor, every door, a thousand times a day. The more places and times it travels, the more chances someone overhears it. A password is a long-lived secret, so this is wrong.

Idea 2: the reception logbook (a session). Reception writes your name in the logbook and gives you a number. Every time you reach a door, the guard phones reception to check the logbook. It works, and many big systems do exactly this. The cost: a database read in front of everything the app does.

Idea 3: a badge with a hologram (a JWT). A JSON Web Token is a small piece of JSON, like "user 123, role editor, expires at 09:15", with a signature over it. Any guard holding the key can recompute the signature and know nobody changed it, with no phone call. Checking becomes math instead of a query.

That buys speed and gives up control. Once a badge is handed out, it is valid until it expires. If it is stolen, or the visitor signs out, or the account is suspended, the badge carries on working.

So we use both. This is the central idea of the whole design:

  • A short-lived access token (the badge, 15 minutes) does the work on every request, with no lookup.
  • A long-lived refresh token (the renewal pass, 7 days) renews it, and it is backed by a row in the database, so it can be revoked.

You get stateless checking on the hot path and real revocation where it matters, at the cost of one database write each time a badge is renewed.

The hard parts are not the signing (that is a library call). They are:

  • what happens when a token is stolen,
  • what happens when you sign out on one device but not another,
  • what happens when someone tries ten thousand passwords on one account from a thousand addresses.

The system has to be able to:

  • Register a user, scramble the password with a function that is slow on purpose, and never store the plain text.
  • Hand out 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 from 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

the office building version

Before building the front desk, decide what it must do, and how good it must be at it.

functional requirements (what it does)

  • Sign up with email and password, with an optional rule that the email must be confirmed before the first sign-in.
  • Sign in and get an access token and a refresh token. The refresh token is also set as an HttpOnly cookie scoped to /api/auth.
  • Refresh: rotate the refresh token and invalidate the one you presented.
  • Sign out the current device, or every device.
  • Reset password by an emailed single-use token, and change password while signed in.
  • Social sign-in with Google and GitHub, landing on the same user record.
  • One identity on the request context that every handler reads, so nobody parses the Authorization header by hand.

non-functional requirements (how well it does it)

  • Verification cost. Checking an access token must not touch the database. It is a signature check and a clock comparison, both microseconds. That is what makes it affordable on every single request.
  • Blast radius. How much damage can one stolen thing do? A stolen access token dies in 15 minutes. A stolen refresh token works once, and using it after the real client has already used it tells the server something is wrong.
  • Storage safety. Someone 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 holds anything replayable.
  • Availability. Signing in may depend on the database. Verifying a token may not. The app stays readable through a database outage for as long as access tokens live.
  • No membership oracle. An oracle is 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 form cannot be used to find out who is registered.
  • Every lockout has a way out. A lock keyed on something guessable must not be a dead end. The owner is emailed and given a link that clears it, the one channel where saying so leaks nothing.
  • Advisory checks fail open. The breach check calls a service we do not run. If it is slow or down, the password is allowed, because someone else's outage must not stop people registering.

3. capacity estimation

the office building version

How many people come to the building, and how hard do reception and the guards have to work? These are numbers for a mid-sized app. Change one assumption and every sum moves with it.

assumptions

ParameterValue
Registered users1,000,000 (pick your own number and every sum rescales)
Daily active users200,000 (20% of registered, a normal ratio for a tool used on working days)
Sign-ins per active user per day1.2 (most people are already signed in; the 0.2 is a second device or an overnight expiry)
API requests per active user per day400 (one screen makes 5 to 15 API calls, and a busy user opens 30 to 80 screens a day)
Access token lifetime15 minutes (short enough that a stolen token is nearly worthless; the norm is 5 to 60 minutes)
Refresh token lifetime168 hours, which is 7 days (a product decision, not a technical one)
Session row~400 bytes (two 32-byte hashes, two timestamps, a user agent, an address, row overhead)
User row~1.2 KB with profile fields

sign-in rate: how often the slow path runs

200,000 daily active users x 1.2 sign-ins = 240,000 sign-ins/day
240,000 / 86,400 seconds in a day         = 2.8 sign-ins/second average
peak = 2.8 x 5                            = 14 sign-ins/second

(5x is the usual ratio of the busiest hour to the daily average. A global app is flatter, nearer 2x.)

Sign-in is the one deliberately slow thing. bcrypt at cost 10 takes about 60 ms of processor time, so 14 a second is 14 x 0.06 = 0.84 seconds of work per second. That is under one processor core, which tells you the cost factor can stay where it is.

token verification rate: how often the cheap path runs

200,000 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

A signature check takes a few microseconds, so 4,630 a second is roughly 0.02 seconds of work per second: effectively nothing. With sessions, those same 4,630 requests would each be a database read. That gap is the whole argument for stateless access tokens.

refresh rate: the part that is not free

8 hour working day / 15 minute token = 32 renewals per active session
200,000 x 32                         = 6,400,000 renewals/day
6,400,000 / 86,400                   = 74 renewals/second average, 370/second at 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. Halve the access token lifetime to 7 minutes and it doubles to 148 and 740. Stretch it to an hour and it drops to 18. That one 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
600,000 x 400 bytes                    = 240 MB
plus indexes (token_hash, user_id, expires_at) = ~400 MB

Under a gigabyte, so it stays in the main database with no separate store. It stays that size only because expired rows are swept on a schedule.

user storage: 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. Dormant accounts cost storage and nothing else, which is why every sum above starts from active users.

4. high level design

the office building version

Signing in is a write path that ends with two things in your hands: a badge and a renewal pass. Everything after that is a read path that touches no storage at all, until the badge expires.

core components

  • Auth handlers. The HTTP surface: register, login, refresh, logout, forgot, reset. They are thin on purpose. They read the request, call a service, and shape the response. (the reception clerks)
  • Password service. bcrypt hashing and comparison, plus the strength rules. The only place that ever sees a plain password, and it never returns one. (the scrambling machine)
  • JWT service. Signs and verifies. Every token carries a user id, a role, a type, an expiry and a jti, a unique id for that one token, so two tokens issued in the same second can still be told apart. (the badge printer)
  • Session store. One row per signed-in device, found by the SHA-256 hash of the current refresh token. This table is what makes a stateless token revocable. (the reception logbook)
  • 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. It decides who you are and nothing about what you may do. (the guard on each floor)
  • Lockout counter. Counts failed attempts per account rather than per address, so an attack from a thousand machines still trips it. Ten failures bar the account for fifteen minutes. A successful sign-in resets it.
  • Edge rate limiter. The layer in front of everything. A general ceiling of 100 requests a minute per address, and much tighter limits on routes that take a password or code: 5 sign-ins per 15 minutes, 3 registrations, 3 forgot-password requests, 5 code checks per 5 minutes. Counted in Redis when configured, so the limit means the same 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 anyone else behind the same address. An address that piles up about four times that many failures is refused for a minute, which catches one machine working through many accounts. Known shared ranges can be exempted from address-level barring and are still counted.

request flow: sign-in and the first authenticated request

Client -> Auth middleware -> Auth handler -> Lockout counter -> Password service
       -> JWT service -> Session store -> Database -> Audit log
  1. The 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. The handler asks the lockout counter whether this account is currently barred. A barred account is refused right here, before any hashing is paid for. That is what stops a guessing attack from costing processor time.
  3. The password service compares the submitted password to the stored bcrypt hash. A wrong password and an unknown email take the same path and the same time, so the response cannot reveal which addresses exist.
  4. A failed comparison increments the counter for that account. Ten failures in 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. On 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.
  6. The session store records the device: the SHA-256 hash of the refresh token, the browser or app, the address, and the two expiry timestamps.
  7. The row is written. Note what is not written: the refresh token itself. Only its hash, so someone holding a dump of this table cannot produce a working token.
  8. The response carries both tokens and also sets the refresh token as an HttpOnly cookie, so JavaScript cannot read it, scoped to /api/auth, so the browser does not attach it to ordinary API calls.
  9. The 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.

data flow

  • Passwords travel over TLS, are scrambled 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 only the signature and the clock, which is 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 hash of the previous refresh token is kept next to the current one. That one extra column is what makes replay detection possible.
  • The identity on the request context is a plain value, not a database handle. A service that needs the user id gets the user id, not the ability to run queries as that user.
  • Browsers and mobile apps are different problems. A mobile app has no cross-site request forgery risk and no script injection surface, so it keeps tokens in the platform keychain and sends them in the Authorization header. The cookie machinery exists for browsers.

5. technology stack

the office building version

These are the tools we picked to build the front desk.

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 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

the office building version

Three notebooks run the whole front desk: one for the staff and members (users), one for who is inside right now, one line per device (sessions), and one for forgot-my-PIN requests (reset tokens).

users

There is no salt column, which surprises people. bcrypt makes a random salt (the random extra digits) per password and stores it inside the hash string, so one 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 you sign in with
password_hashthe bcrypt output, which contains the salt and the cost; 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 is the table that turns a stateless token into a revocable one, and its two timestamps are how one session has 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 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, not 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. 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, the 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 used daily still dies in a month. Two clocks, because one cannot express both rules.

7. api design

the office building version

These are the counters at reception that visitors can walk up to.

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 on, sign-in stops halfway

No real token is issued yet. The pending token proves only that step one passed.

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

8. low level design

the office building version

Now we look at the staff members working inside the building. Each one does exactly one job.

core types

TypeFileJobMethods
AuthHandlerinternal/handlers/auth.goReads and validates the request, calls the services, shapes the response. No logic worth testing through HTTP.Register, Login, Refresh, Logout, Me, ForgotPassword, ResetPassword
JWTServiceinternal/services/jwt.goThe only thing that signs or verifies. Issuing and verifying are separate methods, so a verify-only service never holds the power to mint tokens.GenerateTokenPair, ValidateAccessToken, ValidateRefreshToken
SessionStoreinternal/session/session.goCreates, rotates and revokes device sessions, and decides whether a presented refresh token belongs to a live one.CreateSession, RotateSession, Revoke, RevokeAllForUser, ListForUser
PasswordServiceinternal/password/password.goHash, compare, and judge strength. Comparison takes the same time whether or not the user exists, which is a correctness requirement, not an optimisation.Hash, Compare, Strength
AuthMiddlewareinternal/middleware/auth.goTurns a token into an identity on the request context, or returns a 401. It does not decide what that identity may do.RequireAuth, OptionalAuth

design principles applied

  • Single responsibility. The handler does HTTP, the JWT service does cryptography, the session store does revocation. None of them knows about two of the three.
  • Authentication is not authorization. The middleware answers "who" and stops. A separate layer answers "what may they touch". Breaches from mixing them look like a valid token 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 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. 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. No path through the code leaves a request authenticated by accident.

the algorithm confusion trap

The public key is public on purpose. If the verifier reads the algorithm out of the token header and picks its key from that, an attacker can sign a token with the public key as an HMAC secret and write HS256. The verifier accepts a forged token. The defence is one line: pin the accepted algorithm to what you actually sign with, and never trust the header.

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

the office building version

What if a million visitors show up?

  • Checking is stateless, so the API scales sideways. No shared session store, no sticky sessions. Adding a replica adds capacity immediately, because a replica needs nothing from the others to check a badge.
  • A database outage fades out slowly instead of crashing. Already-signed-in users keep reading for up to 15 minutes. What stops is sign-ins, renewals and sign-outs, all of which write.
  • Refresh is the only hot write. At 370 writes a second it is comfortable on one primary, and it is the first thing to watch if you ever shorten the access token lifetime.
  • A rule worth remembering. Shorter access tokens mean a smaller window of damage from a stolen token, and you pay for it in writes. Halve it to 7 minutes and the write rate on that endpoint doubles.
  • Session reads are one 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, so 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 eat the connection pool that password sign-in needs.

10. bottlenecks and improvements

the office building version

Where does the front desk break first, and how do we fix it?

what breaks first

  • Refresh storms. Every client with a 15 minute token renews on about the same cadence. A deploy that restarts every client at once turns a steady 74 writes a second into one big 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, caused by the very thing that makes passwords safe.
  • The sessions table growing. Without a sweep, revoked and expired rows pile up forever, and the unique index on token_hash grows with them.
  • Rotating a shared secret signs everybody out. Changing JWT_SECRET invalidates every token at once, so in practice it never gets rotated. There is only one value and it both signs and verifies.
  • Clock skew. 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. It is keyed on an email address anyone can guess, so ten deliberate failures bar that person for fifteen minutes. Recovery is immediate (the owner is emailed, and a reset clears the lock), but an attacker can still make someone reset a password they did not want to change.
  • 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. The cost: no status code, no Retry-After, nothing a client can back off against. The mailbox carries the explanation instead.
  • Local password rules measure the wrong thing. Length, variety and a short list of obvious passwords all judge shape. "Summer2024!" passes all of them and is in every stuffing list. The breach check closes the gap but 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 like one from the usual laptop. The pieces for a risk score exist (the device is already recognised, the address is already located), but nothing combines them.

what to do about it

  • Jitter the renewal. Clients renew at a random point in the last third of the token lifetime, not at a fixed offset. 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 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.
  • Two signing keys. Verify against the current and the previous key, but sign only with the current one. Rotation then takes one access token lifetime instead of logging out every user.
  • A small leeway on expiry. Allowing a few seconds of clock skew removes a whole class of failure that is otherwise invisible until a replica drifts.
  • Delay before you lock. Make each failure slower instead of jumping from no friction to a fifteen minute wall. A script is stopped just as well, because its attack rate collapses, and a person who mistyped twice barely notices. It must be keyed on the caller, not the account. Keyed on the account it is a timing oracle that announces which addresses are real. Keyed on the caller, an attacker can dodge it by rotating addresses, which is why it complements the lockout and does not replace it.
  • Risk-based step-up instead of a uniform challenge. Score the sign-in from what is already known (recognised device, address and location, velocity of attempts) and ask for more only when the score is poor.
  • Tell the owner through the one channel that leaks nothing. The sign-in response stays 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. That turns a lockout from a wall into an event with a remedy.

lesson learned

Do not start with "I'll use JWTs". Start with who is signing in and what must happen when something goes wrong. The design that survives is not purely stateless or purely sessions. It is a short-lived token for speed and a revocable session behind it for control.

Slow things protect you in one place and hurt you in another. bcrypt saves you after a breach and costs you during an attack, so always make the cheap checks (rate limit, lockout) run before the expensive one (hashing).

conclusion

Authentication looks like one big scary box, but it is really a few small ideas stacked together:

  1. Never keep the secret PIN. Keep slow, salted scrambles.
  2. Hand out a short badge for speed and a revocable renewal pass for control.
  3. Swap the pass on every use, so a copied pass gives itself away.
  4. Put cheap guards in front of the expensive scrambling machine.
  5. Never let the front desk tell strangers anything useful, not even how long it took to say no.
  6. Keep "who are you" and "what may you do" as two separate jobs.

Next up in the series: sessions and devices, then authorization.

Until next time, happy hacking! 🚀

read next