Home›Design›Accounts and sessions
Design doc · Accounts and sessions

User accounts, logins and sessions

Where should user accounts live, and where should sessions and tokens go?

Applications like this: any app with sign-in. This page is written the way I write a database design doc: the workload first, then where each kind of data goes and why, then how it grows, what breaks, and what I rejected.

The short answerAccounts in the main relational database. Sessions in Redis or Valkey with an expiry, or no server-side session at all if you use short-lived signed tokens.
1 · The workload

What the application asks of the database

DimensionThis application
WritesLow for accounts. High for sessions: every login, and often every request touches a session.
ReadsEvery authenticated request reads a session or validates a token.
Read to writeVery high on sessions.
ConsistencyStrict for accounts (a unique email). Loose for sessions: losing one means one more login.
LatencySession lookups must take about a millisecond, since every request pays it.
GrowthAccounts grow slowly. Sessions churn and expire.
Connected

Real failures behind this design

These incidents are why the choices below matter. Each one is written up with its numbers and sources.

2 · What goes where

Each kind of data, its store, and why

ApplicationAccounts, credentials, rolesPostgreSQL or MySQLSOURCE OF TRUTHSessions and refresh tokensRedis or Valkey with a TTL on each keyCAN BE LOSTLogin attempts and rate limitsRedis counters with a TTLCAN BE LOSTAudit of loginsAn append-only table or log, partitioned by timeSOURCE OF TRUTH

Solid arrows: the application writes there. Dashed arrows: a copy fed from the source of truth (change data capture, an outbox, or a cache fill), which can be rebuilt from it.

DataWhere it goesWhy
Accounts, credentials, rolesPostgreSQL or MySQLA unique constraint on email, and transactions for sign-up and role changes.
SessionsRedis or Valkey, 30-minute TTLLookups by key in memory, and expiry is built in. Losing them costs a login, not data.
Refresh tokensRedis or Valkey, 7-day TTL, rotated on useA refresh token outlives the session it renews, so it gets its own, longer TTL. Losing it costs a login, not data.
Login attempts and rate limitsRedis counters with a TTLA counter per user or per IP that expires on its own.
Audit of loginsAn append-only table or log, partitioned by timeKept for security reviews, rarely read.

How each family of store behaves under traffic: Database families.

3 · Data model

The core tables and the queries they serve

CREATE TABLE users (
  id            bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email         text   NOT NULL,
  password_hash text   NOT NULL,      -- argon2 or bcrypt, never the password
  created_at    timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX ON users (lower(email));

# Redis
SET session:9f2c... '{"user_id":42}' EX 1800
SET refresh:9f2c... '...' EX 604800   -- 7 days, rotated on use
SET login_fail:42 0 EX 900 NX
INCR login_fail:42
4 · How it grows

Start simple, change one thing at a time

  1. Everything in one databaseA sessions table with an expiry column works at small scale. Delete expired rows in a scheduled job.
  2. Session reads dominate the databaseMove sessions to Redis. Each login stops being a write to the primary.
  3. Many services need identityA dedicated identity service with its own database. Other services validate signed tokens without calling it.

Scale it: watch this design grow

Pick a stage, then throw something at it. The numbers are a model to show the shape of each change, not a measurement; the measured numbers are in the lab notebooks.

5 · What breaks first

The failures to plan for

What happensWhat you seeWhat I do
Sessions in the main databaseA delete job for expired sessions causes bloat and I/O spikesMove sessions to a store with built-in expiry.
Redis without a memory limitRedis runs out of memory, or swapsSet maxmemory and an eviction policy that removes keys with a TTL first (volatile-lru). If nothing has a TTL left, writes fail instead of evicting, so keep this Redis for sessions only.
Case-sensitive email lookupsDuplicate accounts for one personUnique index on lower(email).
6 · Alternatives

What I considered and did not pick

Cost. Sessions are small. A modest Redis node holds millions of them. The waste here is usually a large database instance sized for session traffic that a cache would absorb.

How this page was writtenFrom the engines' documentation and common practice. Measured on real servers: Redis keys that expire on their own, in the notebooks. Before you build: check the anti-patterns, size it with the capacity calculator, and write your own version from the design doc template. Want a second opinion? Submit it for review.
7 · Where to run it

On-prem, managed, EC2 or Kubernetes

StageWhere it runs
Where I would startManaged relational, plus managed Redis or Valkey
When it growsThe same

For a team without a dedicated database team. Who does which job in each option, and the full-cost comparison: Where to run the database.

8 · Estimate it

The numbers, worked live

The back-of-the-envelope numbers I would want before choosing anything. Move the assumptions to match your application. The link keeps your numbers, so a colleague sees the same ones.

Part 3 of 4 · Design · 24 pagesAll pages

Which database does my application need? What kind of application data goes in which database, and why, as design docs, plus the anti-patterns and the decisions behind them.