API & BACKEND ARCHITECTURE / SYSTEM CONCEPT BRIEF

Sessions

A session keeps a user logged in across stateless HTTP requests.

BeginnerPhase 02 / Topic 10 of 20RequirementsTrade-offsFailure modes
01

Overview

A session keeps a user logged in across stateless HTTP requests. After login, the server creates a session record (user ID, expiry, metadata) in a store and gives the browser a random, unguessable session ID in a cookie. Every later request sends the cookie, and the server looks up the session to identify the user.

Server-side sessions are simple and secure: revoking access is as easy as deleting the record. To scale horizontally, sessions must live in a shared store like Redis rather than in one server's memory, otherwise users are logged out whenever the load balancer sends them to another server.

A coat check ticket

You get a ticket with a random number. The ticket itself reveals nothing, but the attendant looks up the number to find your coat. If the attendant voids the ticket, it no longer works.

02

When to use it

  • Traditional web applications with browser clients.
  • When instant logout and revocation matter (banking, admin tools).
  • When you want minimal client-side token handling.
  • Behind-the-scenes backend-for-frontend patterns that hide tokens from browsers.
03

Where it shows up in interviews

Stateless app servers

Recognize it when: scale web servers horizontally without sticky sessions.

  • Design a scalable web app
  • Design an e-commerce checkout
Session management at scale

Recognize it when: millions of logged-in users, logout everywhere.

  • Design Netflix account sessions
  • Design device management for logins
04

Where it is used in real software

Redis session stores

Frameworks like express-session, Spring Session, and Django use Redis to share sessions across instances with TTL expiry.

'Log out of all devices'

Services like Google and Netflix list active sessions per user and can revoke them individually.

Session fixation fixes

Frameworks regenerate the session ID at login so an attacker cannot plant a known ID before the user signs in.

05

Key terms

Session ID
A long random identifier (128+ bits) stored in a cookie.
Session store
Where session data lives: Redis, database, or memory.
Idle timeout
Expire after inactivity (for example 30 minutes).
Absolute timeout
Expire after a maximum age regardless of activity.
Sticky sessions
Load balancer pins a user to one server; an alternative to a shared store with downsides.
06

How it works, step by step

  1. 1
    User logs in

    Credentials verified.

  2. 2
    Create the session

    Generate a random ID; store { userId, createdAt, lastSeen } in Redis with a TTL.

  3. 3
    Set the cookie

    Set-Cookie: sid=...; HttpOnly; Secure; SameSite=Lax.

  4. 4
    Each request

    Read the cookie, look up the session, attach the user, and refresh the idle TTL.

  5. 5
    Logout or expiry

    Delete the session record; the cookie becomes useless.

07

Where to store sessions

Choice affects scaling and availability

Step 1 / 4
StoreScales horizontallySurvives restartsNotes
Server memoryNo (needs sticky sessions)NoFine for a single server
RedisYesWith persistence / replicasMost common; TTL built in
Database tableYesYesSlower; cleanup jobs needed
Signed cookieYes (no store)YesSize limits; revocation is hard

NOWStore: Server memory | Scales horizontally: No (needs sticky sessions) | Survives restarts: No | Notes: Fine for a single server

Redis is the default: fast lookups, automatic TTL expiry, and shared by all app instances.

08

Implementation

import session from "express-session";import { RedisStore } from "connect-redis";import { createClient } from "redis"; const redis = createClient({ url: process.env.REDIS_URL });await redis.connect(); app.use(session({  store: new RedisStore({ client: redis, prefix: "sess:" }),  name: "sid",  secret: process.env.SESSION_SECRET!,  resave: false,  saveUninitialized: false,  rolling: true,                       // refresh idle expiry on activity  cookie: { httpOnly: true, secure: true, sameSite: "lax", maxAge: 30 * 60 * 1000 },})); app.post("/login", async (req, res, next) => {  const user = await verifyCredentials(req.body.email, req.body.password);  req.session.regenerate((err) => {    // new ID after login prevents session fixation    if (err) return next(err);    req.session.userId = user.id;    res.sendStatus(204);  });}); app.post("/logout", (req, res) => req.session.destroy(() => res.clearCookie("sid").sendStatus(204)));
09

Complexity and performance

Lookup~0.5-1 ms

Redis round trip.

Memory per session~200 B-2 KB

10M sessions = a few GB.

10

Trade-offs

Sessions vs JWT

Sessions give instant revocation and tiny cookies at the cost of a store lookup; JWTs avoid the lookup but are hard to revoke.

Sticky sessions vs shared store

Sticky sessions avoid a store but break balance and lose sessions when a server dies.

11

Variants and related techniques

Backend for frontend with sessions

The browser holds only a session cookie; the BFF stores OAuth tokens server-side and calls APIs.

Device sessions

Store device name and IP per session to show and revoke active logins.

12

Common mistakes

  • Predictable session IDs.

    Fix: Use a cryptographically secure random generator with at least 128 bits.

  • Not regenerating the ID at login.

    Fix: Prevents session fixation attacks.

  • Missing cookie flags.

    Fix: HttpOnly, Secure, and SameSite are required.

13

Interview questions

How do sessions work with multiple servers?

Store sessions in a shared store such as Redis so any server can look up any session ID; or use sticky sessions, which is simpler but hurts balancing and failover.

How would you implement 'log out of all devices'?

Index sessions by user ID (a Redis set of session IDs per user) and delete them all; for JWT-based systems, revoke all refresh tokens and bump a per-user token version checked on refresh.

14

Practice problems

ProblemDifficultyWhat it trains
Add Redis-backed sessions to a web appEasyShared store.
Design active session management for a streaming serviceMediumDevice list, limits, revocation.