Patterncore
Server session state
Also called Server Session State, server-side session, session store, in-memory session, HTTP session.
Server session state keeps the data of each session on the server, in a serialized form under a session ID. The client holds only the ID.
- Family
- architectural
- Intent
- Keep the session state on a server system in a serialized form.
Intent
Server session state "Keeps the session state on a server system in a serialized form".1 The server keeps the data of each session, such as a cart, under a session ID. The client holds only the ID, usually in a cookie, and sends it with each request.
Problem
HTTP is stateless, but a user works through many requests. The application must keep the state of each session from one request to the next.
The client can hold the state, as in Client session state, but then each request carries all of it, the client can read it, and the server must check it each time. Large or secret state does not fit there. The state should stay where the client cannot see or change it.
Solution
Keep a store on the server from the session ID to the state of the session. The parts are:
- The session ID. A random value that no one can guess. The server makes it at the start of the session and sends it to the client in a cookie. OWASP says that "The meaning and business or application logic associated with the session ID must be stored on the server side, and specifically, in session objects or in a session management database or repository."2
- The store. A map in the memory of the server process, a set of files, or a cache. The state is often serialized, so that the server can write it to a file or move it to another server.3
- The load and the save. At the start of each request, the server finds the state from the ID. At the end, it saves the changed state.
- The timeout. A user can leave at any time and never come back, so the server ends a session after a time with no request. OWASP says that "All sessions should implement an idle or inactivity timeout."2
client server a
cookie: sid=a1 ---------> store: a1 -> "pen:2,ink:1" (last use 10:30)
a2 -> "ink:1" (last use 10:01)
<--------- page with the cart of a1
at 10:40 the server removes a2, which is idle for more than 30 minutes
In the following program, the store is a dictionary on the server. Each user has a random ID, and each ID has its own state.
import secrets
sessions = {} # on the server: session ID -> state; only the ID goes to the client
def start():
sid = secrets.token_urlsafe(16) # a random ID that no one can guess
sessions[sid] = {"cart": []}
return sid
ann, bob = start(), start()
sessions[ann]["cart"].append("pen")
sessions[bob]["cart"].append("ink")
print("ann:", sessions[ann]["cart"], "bob:", sessions[bob]["cart"])
print("length of the ID that the client keeps:", len(ann))
ann: ['pen'] bob: ['ink']
length of the ID that the client keeps: 22
Example
Each example file has two servers, a and b, each with its own store in memory, and a timeout of 30 minutes. Ann and Bob start sessions on server a, and their carts are separate. Then a load balancer sends one request of Ann to server b. Server b does not know the session a1, so it starts a new session with an empty cart. Ann's next request goes to server a again and finds the cart. At 10:40, server a removes the session of Bob, which has had no request for 39 minutes, and keeps the session of Ann.
class SessionStore:
"""One server's sessions, kept in its memory as serialized text, with the time of their last use."""
TIMEOUT = 30 # minutes with no request, then the session ends
def __init__(self, name):
self.name = name
self.sessions = {} # session ID -> [serialized state, minute of last use]
self.count = 0
def new_id(self):
# A real server makes a random ID with a secure generator, such as secrets.token_urlsafe(32).
self.count += 1
return f"{self.name}{self.count}"
def load(self, sid, now):
entry = self.sessions.get(sid)
if entry is None or now - entry[1] > self.TIMEOUT:
return None
return deserialize(entry[0])
def save(self, sid, cart, now):
self.sessions[sid] = [serialize(cart), now]
def sweep(self, now):
idle = sorted(s for s, (_, last) in self.sessions.items() if now - last > self.TIMEOUT)
for sid in idle:
del self.sessions[sid]
return idle
def serialize(cart):
return ",".join(f"{item}:{qty}" for item, qty in cart.items())
def deserialize(text):
cart = {}
for part in filter(None, text.split(",")):
item, qty = part.split(":")
cart[item] = int(qty)
return cart
def show(cart):
return ", ".join(f"{item} {qty}" for item, qty in cart.items())
def add(server, sid, who, item, now):
"""One request. The client sends only its session ID; the state is on the server."""
cart = server.load(sid, now) if sid else None
if cart is None:
status = f"session {sid} is unknown here, " if sid else ""
sid, cart = server.new_id(), {}
status += f"new session {sid}"
else:
status = f"session {sid}"
cart[item] = cart.get(item, 0) + 1
server.save(sid, cart, now)
print(f"10:{now:02d} {who} adds {item} on server {server.name}: {status}, cart {show(cart)}")
return sid
a, b = SessionStore("a"), SessionStore("b")
ann = add(a, None, "ann", "pen", 0)
bob = add(a, None, "bob", "ink", 1)
add(a, ann, "ann", "pen", 2)
add(b, ann, "ann", "ink", 3) # a load balancer sends this request to the other server
add(a, ann, "ann", "ink", 30)
print("10:40 server a removes idle sessions:", ", ".join(a.sweep(40)))
for sid, (text, last) in sorted(a.sessions.items()):
print(f"server a keeps {sid} = '{text}', last used at 10:{last:02d}")
10:00 ann adds pen on server a: new session a1, cart pen 1
10:01 bob adds ink on server a: new session a2, cart ink 1
10:02 ann adds pen on server a: session a1, cart pen 2
10:03 ann adds ink on server b: session a1 is unknown here, new session b1, cart ink 1
10:30 ann adds ink on server a: session a1, cart pen 2, ink 1
10:40 server a removes idle sessions: a2
server a keeps a1 = 'pen:2,ink:1', last used at 10:30
- Verdict: idiom.
SessionStoreis a dictionary from the session ID to the serialized cart and the minute of its last use.loadtreats a session that is idle for more thanTIMEOUTminutes as unknown, andsweepremoves such sessions. - The IDs
a1andb1keep the output stable. A real server makes them withsecrets.token_urlsafe, so that no one can guess the ID of another session.
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Main {
// One server's sessions, kept in its memory as serialized text, with the time of their last use.
static class SessionStore {
static final int TIMEOUT = 30; // minutes with no request, then the session ends
record Entry(String text, int lastUse) {}
final String name;
final Map<String, Entry> sessions = new TreeMap<>();
int count = 0;
SessionStore(String name) {
this.name = name;
}
String newId() {
// A real server makes a random ID with a secure generator, such as java.security.SecureRandom.
count++;
return name + count;
}
Map<String, Integer> load(String sid, int now) {
Entry e = sessions.get(sid);
if (e == null || now - e.lastUse() > TIMEOUT) {
return null;
}
return deserialize(e.text());
}
void save(String sid, Map<String, Integer> cart, int now) {
sessions.put(sid, new Entry(serialize(cart), now));
}
List<String> sweep(int now) {
List<String> idle = new ArrayList<>();
for (Map.Entry<String, Entry> e : sessions.entrySet()) {
if (now - e.getValue().lastUse() > TIMEOUT) {
idle.add(e.getKey());
}
}
idle.forEach(sessions::remove);
return idle;
}
}
static String serialize(Map<String, Integer> cart) {
List<String> parts = new ArrayList<>();
cart.forEach((item, qty) -> parts.add(item + ":" + qty));
return String.join(",", parts);
}
static Map<String, Integer> deserialize(String text) {
Map<String, Integer> cart = new LinkedHashMap<>();
for (String part : text.split(",")) {
if (!part.isEmpty()) {
String[] kv = part.split(":");
cart.put(kv[0], Integer.parseInt(kv[1]));
}
}
return cart;
}
static String show(Map<String, Integer> cart) {
List<String> parts = new ArrayList<>();
cart.forEach((item, qty) -> parts.add(item + " " + qty));
return String.join(", ", parts);
}
static String clock(int minute) {
return String.format("10:%02d", minute);
}
// One request. The client sends only its session ID; the state is on the server.
static String add(SessionStore server, String sid, String who, String item, int now) {
Map<String, Integer> cart = sid == null ? null : server.load(sid, now);
String status;
if (cart == null) {
status = sid == null ? "" : "session " + sid + " is unknown here, ";
sid = server.newId();
cart = new LinkedHashMap<>();
status += "new session " + sid;
} else {
status = "session " + sid;
}
cart.merge(item, 1, Integer::sum);
server.save(sid, cart, now);
System.out.println(clock(now) + " " + who + " adds " + item + " on server " + server.name + ": " + status + ", cart " + show(cart));
return sid;
}
public static void main(String[] args) {
SessionStore a = new SessionStore("a");
SessionStore b = new SessionStore("b");
String ann = add(a, null, "ann", "pen", 0);
add(a, null, "bob", "ink", 1);
add(a, ann, "ann", "pen", 2);
add(b, ann, "ann", "ink", 3); // a load balancer sends this request to the other server
add(a, ann, "ann", "ink", 30);
System.out.println("10:40 server a removes idle sessions: " + String.join(", ", a.sweep(40)));
a.sessions.forEach((sid, e) -> System.out.println("server a keeps " + sid + " = '" + e.text() + "', last used at " + clock(e.lastUse())));
}
}
10:00 ann adds pen on server a: new session a1, cart pen 1
10:01 bob adds ink on server a: new session a2, cart ink 1
10:02 ann adds pen on server a: session a1, cart pen 2
10:03 ann adds ink on server b: session a1 is unknown here, new session b1, cart ink 1
10:30 ann adds ink on server a: session a1, cart pen 2, ink 1
10:40 server a removes idle sessions: a2
server a keeps a1 = 'pen:2,ink:1', last used at 10:30
- Verdict: idiom. The store is a
TreeMapofEntryrecords (Java 16 and later). In a servlet container,HttpSessiongives the same store, and a server with many threads would use aConcurrentHashMap. sweepcollects the idle IDs first and removes them after the loop, because aTreeMapmust not change while a loop goes through it.
// One server's sessions, kept in its memory as serialized text, with the time of their last use.
class SessionStore {
static TIMEOUT = 30; // minutes with no request, then the session ends
constructor(name) {
this.name = name;
this.sessions = new Map(); // session ID -> [serialized state, minute of last use]
this.count = 0;
}
newId() {
// A real server makes a random ID with a secure generator, such as crypto.randomBytes(32).
this.count++;
return `${this.name}${this.count}`;
}
load(sid, now) {
const entry = this.sessions.get(sid);
if (entry === undefined || now - entry[1] > SessionStore.TIMEOUT) return null;
return deserialize(entry[0]);
}
save(sid, cart, now) {
this.sessions.set(sid, [serialize(cart), now]);
}
sweep(now) {
const idle = [...this.sessions].filter(([, [, last]]) => now - last > SessionStore.TIMEOUT).map(([sid]) => sid).sort();
for (const sid of idle) this.sessions.delete(sid);
return idle;
}
}
function serialize(cart) {
return [...cart].map(([item, qty]) => `${item}:${qty}`).join(",");
}
function deserialize(text) {
const cart = new Map();
for (const part of text.split(",").filter(Boolean)) {
const [item, qty] = part.split(":");
cart.set(item, Number(qty));
}
return cart;
}
const show = (cart) => [...cart].map(([item, qty]) => `${item} ${qty}`).join(", ");
const clock = (minute) => `10:${String(minute).padStart(2, "0")}`;
// One request. The client sends only its session ID; the state is on the server.
function add(server, sid, who, item, now) {
let cart = sid ? server.load(sid, now) : null;
let status;
if (cart === null) {
status = sid ? `session ${sid} is unknown here, ` : "";
sid = server.newId();
cart = new Map();
status += `new session ${sid}`;
} else {
status = `session ${sid}`;
}
cart.set(item, (cart.get(item) ?? 0) + 1);
server.save(sid, cart, now);
console.log(`${clock(now)} ${who} adds ${item} on server ${server.name}: ${status}, cart ${show(cart)}`);
return sid;
}
const a = new SessionStore("a");
const b = new SessionStore("b");
const ann = add(a, null, "ann", "pen", 0);
add(a, null, "bob", "ink", 1);
add(a, ann, "ann", "pen", 2);
add(b, ann, "ann", "ink", 3); // a load balancer sends this request to the other server
add(a, ann, "ann", "ink", 30);
console.log("10:40 server a removes idle sessions:", a.sweep(40).join(", "));
for (const [sid, [text, last]] of [...a.sessions].sort()) {
console.log(`server a keeps ${sid} = '${text}', last used at ${clock(last)}`);
}
10:00 ann adds pen on server a: new session a1, cart pen 1
10:01 bob adds ink on server a: new session a2, cart ink 1
10:02 ann adds pen on server a: session a1, cart pen 2
10:03 ann adds ink on server b: session a1 is unknown here, new session b1, cart ink 1
10:30 ann adds ink on server a: session a1, cart pen 2, ink 1
10:40 server a removes idle sessions: a2
server a keeps a1 = 'pen:2,ink:1', last used at 10:30
- Verdict: idiom. The store is a
Mapin the memory of one Node.js process. Node.js serves all the requests of the process on one thread, so two requests do not change the map at the same time. - Each server has its own store, so a request that goes to server
bdoes not find the session of servera.
package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
const timeout = 30 // minutes with no request, then the session ends
type entry struct {
text string
lastUse int
}
// sessionStore holds one server's sessions in its memory as serialized text, with the time of their last use.
type sessionStore struct {
name string
sessions map[string]entry
count int
}
func newStore(name string) *sessionStore {
return &sessionStore{name: name, sessions: map[string]entry{}}
}
func (s *sessionStore) newID() string {
// A real server makes a random ID with a secure generator, such as crypto/rand.
s.count++
return s.name + strconv.Itoa(s.count)
}
func (s *sessionStore) load(sid string, now int) ([]line, bool) {
e, ok := s.sessions[sid]
if !ok || now-e.lastUse > timeout {
return nil, false
}
return deserialize(e.text), true
}
func (s *sessionStore) save(sid string, cart []line, now int) {
s.sessions[sid] = entry{serialize(cart), now}
}
func (s *sessionStore) ids() []string {
ids := make([]string, 0, len(s.sessions))
for sid := range s.sessions {
ids = append(ids, sid)
}
sort.Strings(ids)
return ids
}
func (s *sessionStore) sweep(now int) []string {
var idle []string
for _, sid := range s.ids() {
if now-s.sessions[sid].lastUse > timeout {
idle = append(idle, sid)
delete(s.sessions, sid)
}
}
return idle
}
// line is one item of the cart. A slice keeps the order of the items.
type line struct {
item string
qty int
}
func serialize(cart []line) string {
parts := make([]string, len(cart))
for i, l := range cart {
parts[i] = l.item + ":" + strconv.Itoa(l.qty)
}
return strings.Join(parts, ",")
}
func deserialize(text string) []line {
var cart []line
for _, part := range strings.Split(text, ",") {
if item, qty, ok := strings.Cut(part, ":"); ok {
n, _ := strconv.Atoi(qty)
cart = append(cart, line{item, n})
}
}
return cart
}
func show(cart []line) string {
parts := make([]string, len(cart))
for i, l := range cart {
parts[i] = fmt.Sprintf("%s %d", l.item, l.qty)
}
return strings.Join(parts, ", ")
}
// add is one request. The client sends only its session ID; the state is on the server.
func add(server *sessionStore, sid, who, item string, now int) string {
cart, ok := server.load(sid, now)
var status string
if !ok {
if sid != "" {
status = "session " + sid + " is unknown here, "
}
sid = server.newID()
status += "new session " + sid
} else {
status = "session " + sid
}
found := false
for i := range cart {
if cart[i].item == item {
cart[i].qty++
found = true
}
}
if !found {
cart = append(cart, line{item, 1})
}
server.save(sid, cart, now)
fmt.Printf("10:%02d %s adds %s on server %s: %s, cart %s\n", now, who, item, server.name, status, show(cart))
return sid
}
func main() {
a, b := newStore("a"), newStore("b")
ann := add(a, "", "ann", "pen", 0)
add(a, "", "bob", "ink", 1)
add(a, ann, "ann", "pen", 2)
add(b, ann, "ann", "ink", 3) // a load balancer sends this request to the other server
add(a, ann, "ann", "ink", 30)
fmt.Println("10:40 server a removes idle sessions:", strings.Join(a.sweep(40), ", "))
for _, sid := range a.ids() {
e := a.sessions[sid]
fmt.Printf("server a keeps %s = '%s', last used at 10:%02d\n", sid, e.text, e.lastUse)
}
}
10:00 ann adds pen on server a: new session a1, cart pen 1
10:01 bob adds ink on server a: new session a2, cart ink 1
10:02 ann adds pen on server a: session a1, cart pen 2
10:03 ann adds ink on server b: session a1 is unknown here, new session b1, cart ink 1
10:30 ann adds ink on server a: session a1, cart pen 2, ink 1
10:40 server a removes idle sessions: a2
server a keeps a1 = 'pen:2,ink:1', last used at 10:30
- Verdict: idiom. The store is a map from the ID to an
entry. An HTTP server in Go runs each request in its own goroutine, so a real store needs async.Mutexaround the map. idssorts the keys, because the order of a range over a map is not defined.
use std::collections::BTreeMap;
const TIMEOUT: u32 = 30; // minutes with no request, then the session ends
type Cart = Vec<(String, u32)>;
// One server's sessions, kept in its memory as serialized text, with the time of their last use.
struct SessionStore {
name: String,
sessions: BTreeMap<String, (String, u32)>,
count: u32,
}
impl SessionStore {
fn new(name: &str) -> Self {
SessionStore { name: name.to_string(), sessions: BTreeMap::new(), count: 0 }
}
fn new_id(&mut self) -> String {
// A real server makes a random ID with a secure generator, such as the getrandom crate.
self.count += 1;
format!("{}{}", self.name, self.count)
}
fn load(&self, sid: &str, now: u32) -> Option<Cart> {
let (text, last) = self.sessions.get(sid)?;
if now - last > TIMEOUT {
return None;
}
Some(deserialize(text))
}
fn save(&mut self, sid: &str, cart: &Cart, now: u32) {
self.sessions.insert(sid.to_string(), (serialize(cart), now));
}
fn sweep(&mut self, now: u32) -> Vec<String> {
let idle: Vec<String> = self.sessions.iter().filter(|(_, (_, last))| now - last > TIMEOUT).map(|(sid, _)| sid.clone()).collect();
for sid in &idle {
self.sessions.remove(sid);
}
idle
}
}
fn serialize(cart: &Cart) -> String {
cart.iter().map(|(item, qty)| format!("{}:{}", item, qty)).collect::<Vec<_>>().join(",")
}
fn deserialize(text: &str) -> Cart {
text.split(',')
.filter_map(|part| part.split_once(':'))
.map(|(item, qty)| (item.to_string(), qty.parse().unwrap_or(0)))
.collect()
}
fn show(cart: &Cart) -> String {
cart.iter().map(|(item, qty)| format!("{} {}", item, qty)).collect::<Vec<_>>().join(", ")
}
// One request. The client sends only its session ID; the state is on the server.
fn add(server: &mut SessionStore, sid: Option<&str>, who: &str, item: &str, now: u32) -> String {
let (sid, mut cart, status) = match sid.and_then(|s| server.load(s, now).map(|c| (s, c))) {
Some((s, cart)) => (s.to_string(), cart, format!("session {}", s)),
None => {
let mut status = match sid {
Some(s) => format!("session {} is unknown here, ", s),
None => String::new(),
};
let id = server.new_id();
status += &format!("new session {}", id);
(id, Vec::new(), status)
}
};
match cart.iter_mut().find(|(i, _)| i == item) {
Some(line) => line.1 += 1,
None => cart.push((item.to_string(), 1)),
}
server.save(&sid, &cart, now);
println!("10:{:02} {} adds {} on server {}: {}, cart {}", now, who, item, server.name, status, show(&cart));
sid
}
fn main() {
let mut a = SessionStore::new("a");
let mut b = SessionStore::new("b");
let ann = add(&mut a, None, "ann", "pen", 0);
add(&mut a, None, "bob", "ink", 1);
add(&mut a, Some(&ann), "ann", "pen", 2);
add(&mut b, Some(&ann), "ann", "ink", 3); // a load balancer sends this request to the other server
add(&mut a, Some(&ann), "ann", "ink", 30);
println!("10:40 server a removes idle sessions: {}", a.sweep(40).join(", "));
for (sid, (text, last)) in &a.sessions {
println!("server a keeps {} = '{}', last used at 10:{:02}", sid, text, last);
}
}
10:00 ann adds pen on server a: new session a1, cart pen 1
10:01 bob adds ink on server a: new session a2, cart ink 1
10:02 ann adds pen on server a: session a1, cart pen 2
10:03 ann adds ink on server b: session a1 is unknown here, new session b1, cart ink 1
10:30 ann adds ink on server a: session a1, cart pen 2, ink 1
10:40 server a removes idle sessions: a2
server a keeps a1 = 'pen:2,ink:1', last used at 10:30
- Verdict: idiom. The store is a
BTreeMap, so the IDs come out in order.loaduses the?operator on theOptionfromget, so an unknown ID givesNone. - A server with many threads would put the store in an
Arc<Mutex<...>>.
Consequences
Benefits.
- Simple to program. The state is a normal object on the server, and most web frameworks give it to each request.
- Small requests. The client sends only the ID.
- The state stays on the server. The client cannot read or change it, so the server can trust it.
- The server can end a session. A logout or a timeout removes the state, and the ID is then worth nothing.
Liabilities.
State that is not keyed by the session is shared by all the users. In the following program, the cart is one variable in the server process. Bob adds an item and sees the item of Ann.
This code runs but gives a wrong answer on purpose.
cart = [] # Wrong: one variable in the server process, shared by all the users
def add(user, item):
cart.append(item)
return list(cart)
add("ann", "pen")
print("bob adds ink and sees:", add("bob", "ink"))
bob adds ink and sees: ['pen', 'ink']
Keep the state of each user in the store under the session ID of that user, and never in a global variable.
Many servers. A store in the memory of one server does not help the other servers, as the example shows. The usual answers are session affinity, where the load balancer sends all the requests of a session to the same server, or a shared store, such as a cache or a database.3 Django warns that "You should only use cache-based sessions if you’re using the Memcached or Redis cache backend."4 It says of its local-memory cache that it "is NOT multi-process safe, therefore probably not a good choice for production environments."4
Lost state on a restart. A store in memory loses all the sessions when the server stops. A store in files or in a cache survives a restart.
Memory. Each open session takes memory, also when its user has left. The timeout and a regular sweep keep the store small. Django notes that the cache backend does not grow without a limit, "because caches automatically delete stale data."4
A stolen ID gives the session. Anyone who has the ID can use the session, so the ID must be random, sent only over HTTPS, and changed at login.2
When not to use it
When the servers must be stateless. If any server must be able to handle any request, and there is no shared store, use Client session state.
When the state must survive for a long time. State that must last for days, or across restarts and deployments, is better as Database session state.
Variants and related patterns
Memory, files or a cache. PHP, by default, "saves session data on the server at the location specified by the session.save_path configuration directive."5 Django can keep sessions in the database, in files or in a cache.4
Serialized or live objects. The store can hold live objects, which is fast but ties the session to one process, or serialized data, which can move between servers. The serialized form can be a Serialized LOB in a shared table.3
Related patterns. Client session state holds the session ID. Database session state keeps the state in the database as committed data. The serialization is Serialization.
Known uses
- PHP sessions. "Sessions are a simple way to store data for individual users against a unique session ID."5 PHP serializes the session data at the end of each script and stores it with the session save handler.5
- Django, with the
cacheandfilesession engines.4
References
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Server Session State, pattern summary
- OWASP Cheat Sheet Series, Session Management Cheat Sheet, Session ID Content (or Value); Idle Timeout
- Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 6, Session State; Chapter 17, Session State Patterns, Server Session State
- Django 5.2 documentation, How to use sessions, Using cached sessions; Using file-based sessions; Clearing the session store
- PHP Manual, Sessions, Basic usage, introduction
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag K194TS Edit this page History Report an error Markdown