Design a server-side session store

Design a session store with 256-bit random ids stored only as hashes, idle and absolute timeouts, id rotation at login to stop fixation, cheap revocation of one or all sessions, and a cookie configured so scripts and other sites cannot misuse it.

● MediumFREEBy ·Design problem·16 min read·Beginner → Intermediate
sessionssession fixationcookies__Host- prefixidle timeoutrevocation

01Understand the problem

✓What you will learn
  • Generate session ids an attacker cannot guess and store only their hashes
  • Enforce idle and absolute timeouts without a write on every request
  • Rotate the id at login and privilege change to stop session fixation
  • Configure the cookie: __Host- prefix, Secure, HttpOnly, SameSite
◎Interview radar

What they probe: why server-side sessions instead of JWTs here, what is stored and under which key, how you log out everywhere, what fixation is, and which cookie attributes matter. Where candidates slip: the raw session id as the database key, a sliding expiry with no absolute limit, keeping the same id after login, localStorage for the token, and SameSite=None without a reason.

A server-side session is a random id in a cookie that points at state held by the server. Unlike a self-contained token, it can be revoked instantly by deleting the record, and the state never leaves the server. The design questions are how the id is made and stored, when the session expires, and how the cookie is protected in the browser.

  1. create(userId, meta) returns a fresh session and its id; the id is shown once, to be set in the cookie.
  2. get(id) returns the session if it exists, has not idled out and is within its absolute lifetime.
  3. rotate(id) issues a new id for the same session and kills the old one.
  4. destroy(id) and destroyAllFor(userId) revoke immediately.
  5. Activity extends the idle timeout, but writes happen at most once a minute per session.
SettingTypical valueWhy
Id size32 random bytes (256 bits)Unguessable; OWASP asks for at least 64 bits of entropy, more is free
Idle timeout30 minutes (15 for high-value apps)Limits an abandoned unlocked screen
Absolute timeout12 hours to 7 daysLimits a stolen cookie no matter how active
Touch interval60 secondsBounds write load from sliding expiry

02Interfaces first

The contractts
export interface Session {
  userId: string;
  createdAt: number;        // epoch ms; drives the absolute timeout
  lastSeenAt: number;       // epoch ms; drives the idle timeout
  authLevel: "password" | "mfa";
  userAgent: string;        // for the "your devices" page, not for security decisions
}

export interface SessionBackend {
  put(idHash: string, s: Session, ttlMs: number): Promise<void>;
  get(idHash: string): Promise<Session | undefined>;
  delete(idHash: string): Promise<void>;
  /** All id hashes for a user, maintained as a secondary index (a Redis set or an indexed column). */
  listFor(userId: string): Promise<string[]>;
}

export interface SessionPolicy { idleMs: number; absoluteMs: number; touchEveryMs: number }
iWhy store a hash of the id

If the session table leaks through a backup, a read replica or SQL injection, raw ids are live credentials for every logged-in user. SHA-256 of a 256-bit random id cannot be reversed, and because the id has full entropy no salt or slow hash is needed. Lookup stays a single indexed read.

03The session manager

SessionManagerts
import { createHash, randomBytes } from "node:crypto";

const ID_RE = /^[A-Za-z0-9_-]{43}$/;                 // 32 bytes as base64url
const hashId = (id: string) => createHash("sha256").update(id).digest("hex");

export class SessionManager {
  constructor(private readonly backend: SessionBackend, private readonly policy: SessionPolicy,
              private readonly now: () => number = Date.now) {
    if (policy.idleMs <= 0 || policy.absoluteMs < policy.idleMs) throw new RangeError("need 0 < idle <= absolute");
  }

  private ttl(s: Session, now: number): number {
    return Math.min(s.lastSeenAt + this.policy.idleMs, s.createdAt + this.policy.absoluteMs) - now;
  }

  async create(userId: string, authLevel: Session["authLevel"], userAgent: string): Promise<{ id: string; session: Session }> {
    const now = this.now();
    const id = randomBytes(32).toString("base64url");
    const session: Session = { userId, createdAt: now, lastSeenAt: now, authLevel, userAgent: userAgent.slice(0, 256) };
    await this.backend.put(hashId(id), session, this.ttl(session, now));
    return { id, session };
  }

  async get(id: string | undefined): Promise<Session | undefined> {
    if (!id || !ID_RE.test(id)) return undefined;     // cheap rejection of junk cookies
    const h = hashId(id);
    const s = await this.backend.get(h);
    if (!s) return undefined;
    const now = this.now();
    if (this.ttl(s, now) <= 0) { await this.backend.delete(h); return undefined; }   // do not trust the backend TTL alone
    if (now - s.lastSeenAt >= this.policy.touchEveryMs) {
      const touched = { ...s, lastSeenAt: now };
      await this.backend.put(h, touched, this.ttl(touched, now));
      return touched;
    }
    return s;
  }

  /** Call at login, MFA step-up and any privilege change. The old id stops working immediately. */
  async rotate(oldId: string, changes: Partial<Pick<Session, "userId" | "authLevel">> = {}): Promise<{ id: string; session: Session } | undefined> {
    const s = await this.get(oldId);
    if (!s) return undefined;
    await this.backend.delete(hashId(oldId));
    const now = this.now();
    const id = randomBytes(32).toString("base64url");
    const session: Session = { ...s, ...changes, lastSeenAt: now, createdAt: changes.userId ? now : s.createdAt };
    await this.backend.put(hashId(id), session, this.ttl(session, now));
    return { id, session };
  }

  async destroy(id: string): Promise<void> {
    if (ID_RE.test(id)) await this.backend.delete(hashId(id));
  }

  async destroyAllFor(userId: string, exceptId?: string): Promise<number> {
    const keep = exceptId ? hashId(exceptId) : undefined;
    const all = await this.backend.listFor(userId);
    const doomed = all.filter((h) => h !== keep);
    await Promise.all(doomed.map((h) => this.backend.delete(h)));
    return doomed.length;
  }
}
Cookiets
export const COOKIE = "__Host-sid";

/** __Host- forces Secure, Path=/ and no Domain, so a sibling subdomain cannot set or overwrite it. */
export function sessionCookie(id: string, maxAgeSec: number): string {
  return COOKIE + "=" + id + "; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=" + Math.max(0, Math.floor(maxAgeSec));
}

export const clearCookie = () => COOKIE + "=; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=0";
▭On the whiteboard · Design choices4 points
01
id
32 bytes from the CSPRNG, base64url; only SHA-256(id) is stored
02
expiry
min(lastSeen + idle, created + absolute), checked in code and mirrored as backend TTL
03
fixation
rotate at login and privilege change; old id deleted at once
04
cookie
__Host-sid, Secure, HttpOnly, SameSite=Lax

04Edge cases and tests

Threat or edgeWhat goes wrongDefence
Session fixationAttacker plants a known id before the victim logs inRotate at login; never accept ids from URLs
XSS reading the cookieScript exfiltrates the idHttpOnly; and fix the XSS, which can still act as the user
Subdomain cookie tossingevil.example.com sets a cookie for example.com__Host- prefix
Password changeOld sessions elsewhere stay validdestroyAllFor(userId, currentId)
Concurrent rotateTwo tabs log in together; one gets a dead idAcceptable: it re-authenticates; or allow a few seconds of grace for the old id
Backend TTL driftA record outlives its policyExpiry is checked in get(), not only by the store
!SameSite is defence in depth, not CSRF protection

SameSite=Lax stops the cookie on cross-site POSTs in current browsers, but same-site attacks (a vulnerable sibling subdomain) and older clients remain. Pair it with a CSRF token or Fetch Metadata checks, which is the next lesson.

vitestts
import { describe, it, expect } from "vitest";

class MemBackend implements SessionBackend {
  rows = new Map<string, Session>();
  async put(h: string, s: Session) { this.rows.set(h, { ...s }); }
  async get(h: string) { const s = this.rows.get(h); return s && { ...s }; }
  async delete(h: string) { this.rows.delete(h); }
  async listFor(u: string) { return [...this.rows].filter(([, s]) => s.userId === u).map(([h]) => h); }
}

const MIN = 60_000;
function setup() {
  let t = 0;
  const backend = new MemBackend();
  const sm = new SessionManager(backend, { idleMs: 30 * MIN, absoluteMs: 8 * 60 * MIN, touchEveryMs: MIN }, () => t);
  return { sm, backend, advance: (ms: number) => { t += ms; } };
}

describe("SessionManager", () => {
  it("never stores the raw id", async () => {
    const { sm, backend } = setup();
    const { id } = await sm.create("u1", "password", "test");
    expect([...backend.rows.keys()]).not.toContain(id);
  });
  it("expires after idle time, and after the absolute limit even when active", async () => {
    const { sm, advance } = setup();
    const a = await sm.create("u1", "password", "t");
    advance(31 * MIN);
    expect(await sm.get(a.id)).toBeUndefined();
    const b = await sm.create("u1", "password", "t");
    for (let i = 0; i < 20; i++) { advance(25 * MIN); await sm.get(b.id); }   // 500 minutes of activity
    expect(await sm.get(b.id)).toBeUndefined();
  });
  it("rotation kills the old id", async () => {
    const { sm } = setup();
    const a = await sm.create("anon", "password", "t");
    const b = await sm.rotate(a.id, { userId: "u1" });
    expect(await sm.get(a.id)).toBeUndefined();
    expect((await sm.get(b!.id))?.userId).toBe("u1");
  });
  it("logs out everywhere except the current device", async () => {
    const { sm } = setup();
    const keep = await sm.create("u1", "mfa", "laptop");
    await sm.create("u1", "mfa", "phone");
    expect(await sm.destroyAllFor("u1", keep.id)).toBe(1);
    expect(await sm.get(keep.id)).toBeDefined();
  });
});

05Extensions, follow-ups, how to say it

  • Step-up freshness: store mfaAt and require it within the last few minutes for sensitive actions, even inside a valid session.
  • Device list: show created time, last seen and a coarse location per session, with a revoke button that calls destroy.
  • Anomaly signals: a session suddenly used from a new country or ASN can be challenged; do not bind hard to IP, which breaks mobile users.
  • Redis layout: sess:<hash> with PEXPIRE plus a per-user set user-sess:<userId>; prune dead members from the set lazily.
Q1Why not just use a JWT?+

A JWT cannot be revoked before it expires without a server-side denylist, which is a session store anyway. For a first-party web app, an opaque id in an HttpOnly cookie is simpler and revocable.

Q2Is a 30-minute sliding expiry enough on its own?+

No. An attacker with a stolen cookie can keep it alive forever by making a request every 29 minutes. The absolute timeout bounds that.

Q3Why reject ids that do not match the format before hashing?+

It is cheap, blocks junk and oversized cookies before any store lookup, and keeps logs and metrics clean. Security still comes from the hash lookup.

“How to say it in the room

"The id is 32 random bytes, base64url, in a __Host- cookie that is Secure, HttpOnly and SameSite=Lax; the store only ever sees its SHA-256. A session is valid until the earlier of last seen plus idle and created plus absolute, checked in code and mirrored as the record TTL, and I touch last seen at most once a minute. At login and any privilege change I rotate the id, deleting the old record, which stops fixation. A per-user index makes 'log out everywhere' one call, used on password change."

Test yourself

An attacker gets a victim to visit the site with a session cookie the attacker created. The victim then logs in. With which design does the attacker end up logged in as the victim?

Finished this one?
Tick it and it shows as done on the roadmap and the course.