Programming Search⌘K

Patternadvanced

Database session state

Also called Database Session State, database-backed session, session table, JDBC session store.

Database session state keeps the data of each session in the database as committed rows, apart from the business data, so that any server can handle the next request.

Family
architectural
Intent
Store session data as committed data in the database.

Intent

Database session state stores "session data as committed data in the database."1 Each request reads the state of its session from the database and writes the changed state back before the request ends. No server keeps the state between requests, so any server can handle the next request.

Problem

An application with many servers must keep the state of each session from one request to the next. With Server session state in the memory of one server, the next request must go to the same server, and the state is lost when that server stops. With Client session state, each request carries all the state, and large state does not fit.

The database is already shared by all the servers and survives a restart. But session data is not business data. A cart that the user never checks out is not an order, and no report may count it.

Solution

Keep the session data in the database, apart from the business data. The parts are:

  • The session ID. The client keeps only a random ID, usually in a cookie, as in Server session state.
  • The session tables. One row for each session, with the ID, the user and the time of the last request, and rows for the data of the session. The data can be separate rows, or one serialized value in a Serialized LOB.
  • Pending data apart from committed business data. Session data must not look like business data to the rest of the system. Fowler describes two ways: a field that marks the pending rows, or separate tables for the pending data.2
  • The commit step. When the user finishes, for example with a checkout, one transaction turns the pending data into business data.
  • The purge. A user can leave at any time, so a job deletes the sessions that are idle for too long, with their data.
  request -> any server -> reads the session rows -> does the work -> writes them back
  sessions:    s1 ann 10:25     s2 bob 10:01
  cart_lines:  s1 pen 2, s1 ink 1, s2 ink 1      (pending session data)
  checkout s1: one transaction moves the lines of s1 into orders and order_lines
  purge:       deletes s2 and its cart lines, because s2 is idle for 39 minutes

In the following program, server a commits the state of a session and stops. Server b reads the same rows from the database.

import sqlite3

URI = "file:sessions?mode=memory&cache=shared"
server_a = sqlite3.connect(URI, uri=True)
server_b = sqlite3.connect(URI, uri=True)
server_a.execute("""CREATE TABLE session_data (
    session_id TEXT, name TEXT, value TEXT, PRIMARY KEY (session_id, name))""")

# Request 1 goes to server a, which commits the state of the session.
server_a.execute("INSERT INTO session_data VALUES ('s1', 'step', '2'), ('s1', 'plan', 'basic')")
server_a.commit()
server_a.close()  # server a stops

# Request 2 goes to server b, which reads the same committed rows.
rows = server_b.execute(
    "SELECT name, value FROM session_data WHERE session_id = 's1' ORDER BY name").fetchall()
print("server b reads s1:", dict(rows))
Output
server b reads s1: {'plan': 'basic', 'step': '2'}

Example

Each example file has two servers that share one database. In the Python file, the database is SQLite in memory, and the other files keep the tables in shared collections. Ann and Bob each put items in a cart. A request of Ann goes to server b, which reads the cart that server a wrote. Ann then checks out, and one transaction moves the pending cart lines of Ann into the order tables. The sales report reads only the order tables. At 10:40, the purge deletes the session of Bob, who has had no request for 39 minutes, with the pending cart line of that session. The ink of Bob is never counted as a sale.

PythonGitHub
import sqlite3

TIMEOUT = 30  # minutes with no request before a session ends
URI = "file:shop?mode=memory&cache=shared"


def connect():
    # Each server opens its own connection to the same database.
    return sqlite3.connect(URI, uri=True, isolation_level=None)


def setup(db):
    db.executescript("""
        CREATE TABLE sessions (id TEXT PRIMARY KEY, user TEXT, last_used INTEGER);
        CREATE TABLE cart_lines (session_id TEXT, item TEXT, qty INTEGER,
                                 PRIMARY KEY (session_id, item));
        CREATE TABLE orders (id INTEGER PRIMARY KEY, user TEXT);
        CREATE TABLE order_lines (order_id INTEGER, item TEXT, qty INTEGER);
    """)


def hhmm(t):
    return f"{t // 60}:{t % 60:02d}"


def start(db, sid, user, now):
    db.execute("INSERT INTO sessions VALUES (?, ?, ?)", (sid, user, now))


def touch(db, sid, now):
    # Return the user of the session, or None if it is unknown or idle.
    row = db.execute("SELECT user, last_used FROM sessions WHERE id = ?", (sid,)).fetchone()
    if row is None or now - row[1] > TIMEOUT:
        return None
    db.execute("UPDATE sessions SET last_used = ? WHERE id = ?", (now, sid))
    return row[0]


def cart(db, sid):
    rows = db.execute(
        "SELECT item, qty FROM cart_lines WHERE session_id = ? ORDER BY rowid", (sid,))
    return ", ".join(f"{item} {qty}" for item, qty in rows)


def add(db, server, sid, item, now):
    user = touch(db, sid, now)
    db.execute("""INSERT INTO cart_lines VALUES (?, ?, 1)
                  ON CONFLICT (session_id, item) DO UPDATE SET qty = qty + 1""", (sid, item))
    print(f"{hhmm(now)} {user} adds {item} on server {server}: cart {cart(db, sid)}")


def checkout(db, server, sid, now):
    user = touch(db, sid, now)
    lines = cart(db, sid)
    # The pending cart lines become an order in one transaction.
    db.execute("BEGIN")
    oid = db.execute("INSERT INTO orders (user) VALUES (?)", (user,)).lastrowid
    db.execute("""INSERT INTO order_lines SELECT ?, item, qty FROM cart_lines
                  WHERE session_id = ? ORDER BY rowid""", (oid, sid))
    db.execute("DELETE FROM cart_lines WHERE session_id = ?", (sid,))
    db.execute("COMMIT")
    print(f"{hhmm(now)} {user} checks out on server {server}: order {oid} with {lines}")


def report(db):
    rows = db.execute("SELECT item, SUM(qty) FROM order_lines GROUP BY item ORDER BY item")
    print("sales:", ", ".join(f"{item} {qty}" for item, qty in rows))


def purge(db, now):
    idle = "SELECT id FROM sessions WHERE ? - last_used > ?"
    ids = [r[0] for r in db.execute(idle + " ORDER BY id", (now, TIMEOUT))]
    db.execute("BEGIN")
    db.execute(f"DELETE FROM cart_lines WHERE session_id IN ({idle})", (now, TIMEOUT))
    db.execute("DELETE FROM sessions WHERE ? - last_used > ?", (now, TIMEOUT))
    db.execute("COMMIT")
    print(f"{hhmm(now)} purge sessions idle for more than {TIMEOUT} minutes: {', '.join(ids)}")


def count(db, table):
    return db.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]


a, b = connect(), connect()
setup(a)
start(a, "s1", "ann", 600)
start(a, "s2", "bob", 601)
add(a, "a", "s1", "pen", 600)
add(a, "a", "s2", "ink", 601)
add(b, "b", "s1", "pen", 603)  # server b reads the rows that server a wrote
add(a, "a", "s1", "ink", 604)
checkout(b, "b", "s1", 625)
report(a)
purge(a, 640)
print(f"rows left: sessions {count(a, 'sessions')}, cart lines {count(a, 'cart_lines')}, "
      f"orders {count(a, 'orders')}, order lines {count(a, 'order_lines')}")
Output
10:00 ann adds pen on server a: cart pen 1
10:01 bob adds ink on server a: cart ink 1
10:03 ann adds pen on server b: cart pen 2
10:04 ann adds ink on server a: cart pen 2, ink 1
10:25 ann checks out on server b: order 1 with pen 2, ink 1
sales: ink 1, pen 2
10:40 purge sessions idle for more than 30 minutes: s2
rows left: sessions 1, cart lines 0, orders 1, order lines 2
  • Verdict: stdlib. The sqlite3 module is part of the Python standard library. The two connections a and b stand for two servers that share one database. The URI file:shop?mode=memory&cache=shared keeps the database in memory, so the example writes no file.
  • The session data is in its own tables, sessions and cart_lines. The checkout moves the pending lines into orders and order_lines in one transaction, so the sales report never sees a cart that is not an order.
  • purge removes the sessions that are idle for more than TIMEOUT minutes, with their cart lines. A real server runs it on a schedule.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.TreeMap;

// The "database" is a set of tables that every server shares.
// A real system keeps these tables in a database server and uses JDBC.
public class Main {
    static final int TIMEOUT = 30; // minutes with no request before a session ends

    static class Session {
        final String user;
        int lastUsed;
        Session(String user, int lastUsed) { this.user = user; this.lastUsed = lastUsed; }
    }

    static class Line {
        final String key; // the session ID for a cart line, the order ID for an order line
        final String item;
        int qty;
        Line(String key, String item, int qty) { this.key = key; this.item = item; this.qty = qty; }
    }

    static final Map<String, Session> sessions = new TreeMap<>();
    static List<Line> cartLines = new ArrayList<>(); // the pending data
    static final List<String> orders = new ArrayList<>();
    static final List<Line> orderLines = new ArrayList<>(); // the committed business data

    static String hhmm(int t) { return String.format("%d:%02d", t / 60, t % 60); }

    static void start(String sid, String user, int now) { sessions.put(sid, new Session(user, now)); }

    // Return the user of the session, or null if it is unknown or idle.
    static String touch(String sid, int now) {
        Session s = sessions.get(sid);
        if (s == null || now - s.lastUsed > TIMEOUT) return null;
        s.lastUsed = now;
        return s.user;
    }

    static String cart(String sid) {
        StringJoiner j = new StringJoiner(", ");
        for (Line l : cartLines) if (l.key.equals(sid)) j.add(l.item + " " + l.qty);
        return j.toString();
    }

    static void add(String server, String sid, String item, int now) {
        String user = touch(sid, now);
        Line found = null;
        for (Line l : cartLines) if (l.key.equals(sid) && l.item.equals(item)) found = l;
        if (found != null) found.qty += 1;
        else cartLines.add(new Line(sid, item, 1));
        System.out.println(hhmm(now) + " " + user + " adds " + item + " on server " + server + ": cart " + cart(sid));
    }

    // The pending cart lines become an order. A database does this in one transaction.
    static void checkout(String server, String sid, int now) {
        String user = touch(sid, now);
        String lines = cart(sid);
        orders.add(user);
        String oid = String.valueOf(orders.size());
        List<Line> rest = new ArrayList<>();
        for (Line l : cartLines) {
            if (l.key.equals(sid)) orderLines.add(new Line(oid, l.item, l.qty));
            else rest.add(l);
        }
        cartLines = rest;
        System.out.println(hhmm(now) + " " + user + " checks out on server " + server + ": order " + oid + " with " + lines);
    }

    static void report() {
        Map<String, Integer> sums = new TreeMap<>();
        for (Line l : orderLines) sums.merge(l.item, l.qty, Integer::sum);
        StringJoiner j = new StringJoiner(", ");
        sums.forEach((item, qty) -> j.add(item + " " + qty));
        System.out.println("sales: " + j);
    }

    static void purge(int now) {
        List<String> ids = new ArrayList<>();
        for (Map.Entry<String, Session> e : sessions.entrySet())
            if (now - e.getValue().lastUsed > TIMEOUT) ids.add(e.getKey());
        cartLines.removeIf(l -> ids.contains(l.key));
        for (String id : ids) sessions.remove(id);
        System.out.println(hhmm(now) + " purge sessions idle for more than " + TIMEOUT + " minutes: " + String.join(", ", ids));
    }

    public static void main(String[] args) {
        start("s1", "ann", 600);
        start("s2", "bob", 601);
        add("a", "s1", "pen", 600);
        add("a", "s2", "ink", 601);
        add("b", "s1", "pen", 603); // server b reads the rows that server a wrote
        add("a", "s1", "ink", 604);
        checkout("b", "s1", 625);
        report();
        purge(640);
        System.out.println("rows left: sessions " + sessions.size() + ", cart lines " + cartLines.size()
            + ", orders " + orders.size() + ", order lines " + orderLines.size());
    }
}
Output
10:00 ann adds pen on server a: cart pen 1
10:01 bob adds ink on server a: cart ink 1
10:03 ann adds pen on server b: cart pen 2
10:04 ann adds ink on server a: cart pen 2, ink 1
10:25 ann checks out on server b: order 1 with pen 2, ink 1
sales: ink 1, pen 2
10:40 purge sessions idle for more than 30 minutes: s2
rows left: sessions 1, cart lines 0, orders 1, order lines 2
  • Verdict: stdlib. JDBC, in the java.sql package, is part of the standard library, but a real server also needs the driver of its database. The example keeps the tables in shared collections, so it runs with no driver.
  • A TreeMap keeps the session IDs in order, so purge lists the idle sessions in a stable order.
JavaScriptGitHub
// The "database" is a set of tables that every server shares.
// A real system keeps these tables in a database server.
const TIMEOUT = 30; // minutes with no request before a session ends

const db = {
  sessions: new Map(), // id -> { user, lastUsed }
  cartLines: [], // { sessionId, item, qty }, the pending data
  orders: [], // { id, user }
  orderLines: [], // { orderId, item, qty }, the committed business data
};

const hhmm = (t) => `${Math.floor(t / 60)}:${String(t % 60).padStart(2, "0")}`;

function start(sid, user, now) {
  db.sessions.set(sid, { user, lastUsed: now });
}

// Return the user of the session, or null if it is unknown or idle.
function touch(sid, now) {
  const s = db.sessions.get(sid);
  if (s === undefined || now - s.lastUsed > TIMEOUT) return null;
  s.lastUsed = now;
  return s.user;
}

function cart(sid) {
  return db.cartLines
    .filter((l) => l.sessionId === sid)
    .map((l) => `${l.item} ${l.qty}`)
    .join(", ");
}

function add(server, sid, item, now) {
  const user = touch(sid, now);
  const line = db.cartLines.find((l) => l.sessionId === sid && l.item === item);
  if (line) line.qty += 1;
  else db.cartLines.push({ sessionId: sid, item, qty: 1 });
  console.log(`${hhmm(now)} ${user} adds ${item} on server ${server}: cart ${cart(sid)}`);
}

// The pending cart lines become an order. A database does this in one transaction.
function checkout(server, sid, now) {
  const user = touch(sid, now);
  const lines = cart(sid);
  const oid = db.orders.length + 1;
  db.orders.push({ id: oid, user });
  for (const l of db.cartLines.filter((l) => l.sessionId === sid)) {
    db.orderLines.push({ orderId: oid, item: l.item, qty: l.qty });
  }
  db.cartLines = db.cartLines.filter((l) => l.sessionId !== sid);
  console.log(`${hhmm(now)} ${user} checks out on server ${server}: order ${oid} with ${lines}`);
}

function report() {
  const sums = new Map();
  for (const l of db.orderLines) sums.set(l.item, (sums.get(l.item) ?? 0) + l.qty);
  const items = [...sums.keys()].sort();
  console.log("sales:", items.map((i) => `${i} ${sums.get(i)}`).join(", "));
}

function purge(now) {
  const ids = [...db.sessions.keys()]
    .filter((id) => now - db.sessions.get(id).lastUsed > TIMEOUT)
    .sort();
  db.cartLines = db.cartLines.filter((l) => !ids.includes(l.sessionId));
  for (const id of ids) db.sessions.delete(id);
  console.log(`${hhmm(now)} purge sessions idle for more than ${TIMEOUT} minutes: ${ids.join(", ")}`);
}

start("s1", "ann", 600);
start("s2", "bob", 601);
add("a", "s1", "pen", 600);
add("a", "s2", "ink", 601);
add("b", "s1", "pen", 603); // server b reads the rows that server a wrote
add("a", "s1", "ink", 604);
checkout("b", "s1", 625);
report();
purge(640);
console.log(
  `rows left: sessions ${db.sessions.size}, cart lines ${db.cartLines.length}, ` +
    `orders ${db.orders.length}, order lines ${db.orderLines.length}`,
);
Output
10:00 ann adds pen on server a: cart pen 1
10:01 bob adds ink on server a: cart ink 1
10:03 ann adds pen on server b: cart pen 2
10:04 ann adds ink on server a: cart pen 2, ink 1
10:25 ann checks out on server b: order 1 with pen 2, ink 1
sales: ink 1, pen 2
10:40 purge sessions idle for more than 30 minutes: s2
rows left: sessions 1, cart lines 0, orders 1, order lines 2
  • Verdict: library. Node.js has no database in its stable standard library, so a real server uses a database driver. The example keeps the tables in a shared object, so it runs with no package. All the servers use the same object, as they would use the same database.
  • cartLines is the pending data and orderLines is the committed business data. The checkout moves the lines of one session from the first to the second.
package main

import (
	"fmt"
	"sort"
	"strings"
)

// The "database" is a set of tables that every server shares.
// A real system keeps these tables in a database server and uses database/sql.

const timeout = 30 // minutes with no request before a session ends

type session struct {
	user     string
	lastUsed int
}

type line struct {
	key  string // the session ID for a cart line, the order ID for an order line
	item string
	qty  int
}

var (
	sessions   = map[string]*session{}
	cartLines  []*line // the pending data
	orders     []string
	orderLines []*line // the committed business data
)

func hhmm(t int) string { return fmt.Sprintf("%d:%02d", t/60, t%60) }

func start(sid, user string, now int) { sessions[sid] = &session{user, now} }

// touch returns the user of the session, or "" if it is unknown or idle.
func touch(sid string, now int) string {
	s, ok := sessions[sid]
	if !ok || now-s.lastUsed > timeout {
		return ""
	}
	s.lastUsed = now
	return s.user
}

func cart(sid string) string {
	var parts []string
	for _, l := range cartLines {
		if l.key == sid {
			parts = append(parts, fmt.Sprintf("%s %d", l.item, l.qty))
		}
	}
	return strings.Join(parts, ", ")
}

func add(server, sid, item string, now int) {
	user := touch(sid, now)
	var found *line
	for _, l := range cartLines {
		if l.key == sid && l.item == item {
			found = l
		}
	}
	if found != nil {
		found.qty++
	} else {
		cartLines = append(cartLines, &line{sid, item, 1})
	}
	fmt.Printf("%s %s adds %s on server %s: cart %s\n", hhmm(now), user, item, server, cart(sid))
}

// checkout turns the pending cart lines into an order.
// A database does this in one transaction.
func checkout(server, sid string, now int) {
	user := touch(sid, now)
	lines := cart(sid)
	orders = append(orders, user)
	oid := fmt.Sprint(len(orders))
	var rest []*line
	for _, l := range cartLines {
		if l.key == sid {
			orderLines = append(orderLines, &line{oid, l.item, l.qty})
		} else {
			rest = append(rest, l)
		}
	}
	cartLines = rest
	fmt.Printf("%s %s checks out on server %s: order %s with %s\n", hhmm(now), user, server, oid, lines)
}

func report() {
	sums := map[string]int{}
	var items []string
	for _, l := range orderLines {
		if _, ok := sums[l.item]; !ok {
			items = append(items, l.item)
		}
		sums[l.item] += l.qty
	}
	sort.Strings(items)
	var parts []string
	for _, i := range items {
		parts = append(parts, fmt.Sprintf("%s %d", i, sums[i]))
	}
	fmt.Println("sales:", strings.Join(parts, ", "))
}

func purge(now int) {
	var ids []string
	for id, s := range sessions {
		if now-s.lastUsed > timeout {
			ids = append(ids, id)
		}
	}
	sort.Strings(ids)
	idle := map[string]bool{}
	for _, id := range ids {
		idle[id] = true
		delete(sessions, id)
	}
	var rest []*line
	for _, l := range cartLines {
		if !idle[l.key] {
			rest = append(rest, l)
		}
	}
	cartLines = rest
	fmt.Printf("%s purge sessions idle for more than %d minutes: %s\n", hhmm(now), timeout, strings.Join(ids, ", "))
}

func main() {
	start("s1", "ann", 600)
	start("s2", "bob", 601)
	add("a", "s1", "pen", 600)
	add("a", "s2", "ink", 601)
	add("b", "s1", "pen", 603) // server b reads the rows that server a wrote
	add("a", "s1", "ink", 604)
	checkout("b", "s1", 625)
	report()
	purge(640)
	fmt.Printf("rows left: sessions %d, cart lines %d, orders %d, order lines %d\n",
		len(sessions), len(cartLines), len(orders), len(orderLines))
}
Output
10:00 ann adds pen on server a: cart pen 1
10:01 bob adds ink on server a: cart ink 1
10:03 ann adds pen on server b: cart pen 2
10:04 ann adds ink on server a: cart pen 2, ink 1
10:25 ann checks out on server b: order 1 with pen 2, ink 1
sales: ink 1, pen 2
10:40 purge sessions idle for more than 30 minutes: s2
rows left: sessions 1, cart lines 0, orders 1, order lines 2
  • Verdict: stdlib. The database/sql package is part of the standard library, but a real server also needs the driver of its database. The example keeps the tables in package variables, so it runs with no driver.
  • touch returns an empty string for a session that is unknown or idle. The example sorts the idle IDs, because the order of a Go map is not fixed.
RustGitHub
use std::collections::BTreeMap;

// The "database" is a set of tables that every server shares.
// A real system keeps these tables in a database server.

const TIMEOUT: u32 = 30; // minutes with no request before a session ends

struct Session {
    user: String,
    last_used: u32,
}

struct Line {
    key: String, // the session ID for a cart line, the order ID for an order line
    item: String,
    qty: u32,
}

#[derive(Default)]
struct Db {
    sessions: BTreeMap<String, Session>,
    cart_lines: Vec<Line>, // the pending data
    orders: Vec<String>,
    order_lines: Vec<Line>, // the committed business data
}

fn hhmm(t: u32) -> String {
    format!("{}:{:02}", t / 60, t % 60)
}

impl Db {
    fn start(&mut self, sid: &str, user: &str, now: u32) {
        let s = Session { user: user.to_string(), last_used: now };
        self.sessions.insert(sid.to_string(), s);
    }

    // Return the user of the session, or None if it is unknown or idle.
    fn touch(&mut self, sid: &str, now: u32) -> Option<String> {
        let s = self.sessions.get_mut(sid)?;
        if now - s.last_used > TIMEOUT {
            return None;
        }
        s.last_used = now;
        Some(s.user.clone())
    }

    fn cart(&self, sid: &str) -> String {
        let parts: Vec<String> = self
            .cart_lines
            .iter()
            .filter(|l| l.key == sid)
            .map(|l| format!("{} {}", l.item, l.qty))
            .collect();
        parts.join(", ")
    }

    fn add(&mut self, server: &str, sid: &str, item: &str, now: u32) {
        let user = self.touch(sid, now).unwrap_or_default();
        match self.cart_lines.iter_mut().find(|l| l.key == sid && l.item == item) {
            Some(l) => l.qty += 1,
            None => self.cart_lines.push(Line { key: sid.to_string(), item: item.to_string(), qty: 1 }),
        }
        println!("{} {} adds {} on server {}: cart {}", hhmm(now), user, item, server, self.cart(sid));
    }

    // The pending cart lines become an order. A database does this in one transaction.
    fn checkout(&mut self, server: &str, sid: &str, now: u32) {
        let user = self.touch(sid, now).unwrap_or_default();
        let lines = self.cart(sid);
        self.orders.push(user.clone());
        let oid = self.orders.len().to_string();
        let (mine, rest): (Vec<Line>, Vec<Line>) =
            std::mem::take(&mut self.cart_lines).into_iter().partition(|l| l.key == sid);
        for l in mine {
            self.order_lines.push(Line { key: oid.clone(), item: l.item, qty: l.qty });
        }
        self.cart_lines = rest;
        println!("{} {} checks out on server {}: order {} with {}", hhmm(now), user, server, oid, lines);
    }

    fn report(&self) {
        let mut sums: BTreeMap<&str, u32> = BTreeMap::new();
        for l in &self.order_lines {
            *sums.entry(l.item.as_str()).or_insert(0) += l.qty;
        }
        let parts: Vec<String> = sums.iter().map(|(i, q)| format!("{} {}", i, q)).collect();
        println!("sales: {}", parts.join(", "));
    }

    fn purge(&mut self, now: u32) {
        let ids: Vec<String> = self
            .sessions
            .iter()
            .filter(|(_, s)| now - s.last_used > TIMEOUT)
            .map(|(id, _)| id.clone())
            .collect();
        self.cart_lines.retain(|l| !ids.contains(&l.key));
        for id in &ids {
            self.sessions.remove(id);
        }
        println!("{} purge sessions idle for more than {} minutes: {}", hhmm(now), TIMEOUT, ids.join(", "));
    }
}

fn main() {
    let mut db = Db::default();
    db.start("s1", "ann", 600);
    db.start("s2", "bob", 601);
    db.add("a", "s1", "pen", 600);
    db.add("a", "s2", "ink", 601);
    db.add("b", "s1", "pen", 603); // server b reads the rows that server a wrote
    db.add("a", "s1", "ink", 604);
    db.checkout("b", "s1", 625);
    db.report();
    db.purge(640);
    println!(
        "rows left: sessions {}, cart lines {}, orders {}, order lines {}",
        db.sessions.len(),
        db.cart_lines.len(),
        db.orders.len(),
        db.order_lines.len()
    );
}
Output
10:00 ann adds pen on server a: cart pen 1
10:01 bob adds ink on server a: cart ink 1
10:03 ann adds pen on server b: cart pen 2
10:04 ann adds ink on server a: cart pen 2, ink 1
10:25 ann checks out on server b: order 1 with pen 2, ink 1
sales: ink 1, pen 2
10:40 purge sessions idle for more than 30 minutes: s2
rows left: sessions 1, cart lines 0, orders 1, order lines 2
  • Verdict: library. The Rust standard library has no database access, so a real server uses a crate for its database. The example keeps the tables in a Db value, so it runs with no crate.
  • touch returns None for a session that is unknown or idle. partition splits the cart lines into the lines of the session and the rest.

Consequences

Benefits.

  • Any server can handle any request. The servers keep no state between requests, so a load balancer can send each request anywhere, and a server can stop at any time.
  • The state survives a restart. The session data is committed, so a crash or a deployment does not lose it.
  • One store. The application uses the database that it already has, with its backups and its tools.

Liabilities.

Session data mixed with business data. In the following program, each request writes the cart line straight into the table of real order lines. Bob never checks out, but the sales report counts the ink of Bob.

This code runs but gives a wrong answer on purpose.

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE order_lines (session_id TEXT, item TEXT, qty INTEGER)")

# Each request saves the cart line straight into the table of real order lines.
db.execute("INSERT INTO order_lines VALUES ('s1', 'pen', 2)")  # ann checks out
db.execute("INSERT INTO order_lines VALUES ('s2', 'ink', 1)")  # bob leaves without checking out

sold = db.execute("SELECT SUM(qty) FROM order_lines WHERE item = 'ink'").fetchone()[0]
print("ink sold according to the sales report:", sold)
Output
ink sold according to the sales report: 1

Keep the pending data in separate tables, or mark it with a field that every query of the business data checks. Turn it into business data only at the commit step.

A database access on each request. Each request reads and writes the session rows, which is slower than memory. A cache in front of the database helps, and Django has a cached_db backend that writes to both the database and a cache, and reads from the cache first.3

Old sessions stay. Django explains: "When a user logs in, Django adds a row to the django_session database table." If the user does not log out, "the row never gets deleted."3 It also says: "Django does not provide automatic purging of expired sessions." It recommends the clearsessions command, "for example as a daily cron job".3 Spring Session JDBC, in contrast, "executes a clean-up job every minute that deletes the expired sessions (and its attributes)."4 OWASP says that "All sessions should implement an idle or inactivity timeout."5

Concurrent requests. Two requests of the same session, for example from two browser tabs, can read the same rows and overwrite the writes of each other. An Optimistic offline lock on the session row finds the conflict.

When not to use it

When the state is small. A few values fit in a signed cookie with Client session state, with no database access.

When the state is large and short-lived, and requests can stay on one server. Server session state in memory is faster.

Rows or one serialized value. The data of a session can be normal rows in tables, which queries can read, or one serialized value in a column, which is simpler to save. Spring Session JDBC uses a table for the sessions and a table for the attributes: "By default, the implementation uses SPRING_SESSION and SPRING_SESSION_ATTRIBUTES tables to store sessions."4

Related patterns. Server session state with a shared store is close to this pattern, but it keeps the data in a serialized form that the database does not understand. The serialized form is Serialization or a Serialized LOB. A Unit of Work can collect the changes of one request and write them in one transaction.

Known uses

  • Django keeps sessions in the database by default: "By default, Django stores sessions in your database".3
  • Spring Session JDBC keeps the sessions of a Java web application in a relational database.4

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Database Session State, pattern summary
  2. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 6, Session State; Chapter 17, Session State Patterns, Database Session State
  3. Django 5.2 documentation, How to use sessions, Configuring the session engine; Clearing the session store
  4. Spring Session reference, JDBC, Understanding the Session Storage Details; Customizing the Expired Sessions Clean-Up Job
  5. OWASP Cheat Sheet Series, Session Management Cheat Sheet, Idle Timeout

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/9YAYMG/text.yaml