Redis Sessions
When a user logs in, the web application creates a session: a random session ID sent to the browser in a cookie, and server-side data (user ID, roles, cart, CSRF token) stored under that ID. If you run several web servers, the session data must live somewhere they can all reach, quickly, on every request. Redis is the classic session store: fast, shared, and with built-in expiry for idle sessions.
One hash per session
The session ID is the key, the session data a hash, and the idle timeout a TTL:
HSET session:8f14e45f user_id 17 name Grace role admin csrf 9c2d
EXPIRE session:8f14e45f 1800
HGETALL session:8f14e45f
TTL session:8f14e45fredis> HSET session:8f14e45f user_id 17 name Grace role admin csrf 9c2d
(integer) 4
redis> EXPIRE session:8f14e45f 1800
(integer) 1
redis> HGETALL session:8f14e45f
1) "user_id"
2) "17"
3) "name"
4) "Grace"
5) "role"
6) "admin"
7) "csrf"
8) "9c2d"
redis> TTL session:8f14e45f
(integer) 1800
The ID must be long and random, generated by a cryptographically secure generator (secrets.token_urlsafe(32) in Python, crypto.randomUUID() in JavaScript). The short IDs here are just for readability.
Sliding expiration
Users should stay logged in while they are active and be logged out after 30 minutes of inactivity. So on every request, the application reads the session and refreshes the TTL:
HSET session:8f14e45f user_id 17 role admin
EXPIRE session:8f14e45f 1800
EXPIRE session:8f14e45f 1800
HGET session:8f14e45f user_id
GETEX missing-key EX 1800redis> HSET session:8f14e45f user_id 17 role admin
(integer) 2
redis> EXPIRE session:8f14e45f 1800
(integer) 1
redis> EXPIRE session:8f14e45f 1800
(integer) 1
redis> HGET session:8f14e45f user_id
"17"
redis> GETEX missing-key EX 1800
(nil)
For sessions stored as strings, GETEX key EX 1800 reads and refreshes in one command. Hashes can use a pipeline of HGETALL + EXPIRE (or HGETEX for per-field expiries).
Add an absolute limit as well, so that a stolen session cannot be kept alive forever: store created in the hash and reject sessions older than, say, 12 hours.
Logging out everywhere
To log a user out of all devices you need to know their sessions. Keep a set of session IDs per user:
HSET session:aaa user_id 17
HSET session:bbb user_id 17
HSET session:ccc user_id 42
SADD user:17:sessions aaa bbb
SADD user:42:sessions ccc
SCARD user:17:sessions
DEL session:aaa session:bbb user:17:sessions
EXISTS session:aaa session:bbb session:cccredis> HSET session:aaa user_id 17
(integer) 1
redis> HSET session:bbb user_id 17
(integer) 1
redis> HSET session:ccc user_id 42
(integer) 1
redis> SADD user:17:sessions aaa bbb
(integer) 2
redis> SADD user:42:sessions ccc
(integer) 1
redis> SCARD user:17:sessions
(integer) 2
redis> DEL session:aaa session:bbb user:17:sessions
(integer) 3
redis> EXISTS session:aaa session:bbb session:ccc
(integer) 1
In application code you read the set with SMEMBERS, then delete those session keys and the set together. Because the session keys expire on their own, the set can contain IDs of sessions that are already gone; that is harmless, and you can tidy it when you read it.
Flash messages and per-field expiry
Some session data should vanish sooner than the session itself, such as a "Profile saved!" message or a one-time password. With hash field expiration (Redis 7.4+) the field can expire alone:
HSET session:8f14e45f user_id 17
EXPIRE session:8f14e45f 1800
HSETEX session:8f14e45f EX 60 FIELDS 1 otp 731904
HTTL session:8f14e45f FIELDS 2 otp user_id
HGETDEL session:8f14e45f FIELDS 1 otp
HEXISTS session:8f14e45f otpredis> HSET session:8f14e45f user_id 17
(integer) 1
redis> EXPIRE session:8f14e45f 1800
(integer) 1
redis> HSETEX session:8f14e45f EX 60 FIELDS 1 otp 731904
(integer) 1
redis> HTTL session:8f14e45f FIELDS 2 otp user_id
1) (integer) 60
2) (integer) -1
redis> HGETDEL session:8f14e45f FIELDS 1 otp
1) "731904"
redis> HEXISTS session:8f14e45f otp
(integer) 0
HGETDEL reads the one-time password and removes it, so it cannot be used twice.
A session store in Python
Here is the logic of a small session store using sliding and absolute expiry, written against a minimal in-memory imitation of Redis with a fake clock so that the output is deterministic:
IDLE_TTL, MAX_AGE = 1800, 2 * 3600 # 30 min idle, 2 h absolute (short for the demo)
class MiniRedis:
def __init__(self): self.h, self.exp, self.now = {}, {}, 0
def _alive(self, k):
if k in self.exp and self.exp[k] <= self.now:
self.h.pop(k, None); self.exp.pop(k, None)
return k in self.h
def hset(self, k, mapping): self.h.setdefault(k, {}).update(mapping)
def hgetall(self, k): return dict(self.h[k]) if self._alive(k) else {}
def expire(self, k, s):
if self._alive(k): self.exp[k] = self.now + s
def delete(self, k): self.h.pop(k, None); self.exp.pop(k, None)
r = MiniRedis()
def create_session(sid, user_id):
r.hset(f"session:{sid}", {"user_id": str(user_id), "created": str(r.now)})
r.expire(f"session:{sid}", IDLE_TTL)
def load_session(sid):
key = f"session:{sid}"
data = r.hgetall(key)
if not data:
return None, "expired or unknown"
if r.now - int(data["created"]) > MAX_AGE:
r.delete(key)
return None, "too old, log in again"
r.expire(key, IDLE_TTL) # sliding expiration
return data, "ok"
create_session("s1", 17)
for t in [600, 2000, 3700, 5400, 7000, 7300]:
r.now = t
data, status = load_session("s1")
print(f"t={t:>5}s {status}")
create_session("s2", 42) # created at t=7300
r.now = 7300 + 1801
print(f"t={r.now}s s2: {load_session('s2')[1]}")t= 600s ok
t= 2000s ok
t= 3700s ok
t= 5400s ok
t= 7000s ok
t= 7300s too old, log in again
t=9101s s2: expired or unknown
The session survives while requests keep coming within 30 minutes of each other, and is refused once it is older than the 2-hour absolute limit, even though it is still active. The second session, never used after it was created, expires after 1801 idle seconds. Real applications use longer limits, such as 12 hours or a few days.
Framework support
You rarely write this by hand. Popular integrations:
| Framework | Package |
|---|---|
| Express (Node.js) | express-session + connect-redis |
| Django | SESSION_ENGINE = "django.contrib.sessions.backends.cache" with django.core.cache.backends.redis.RedisCache |
| Flask | Flask-Session with SESSION_TYPE = "redis" |
| Spring Boot | Spring Session Data Redis |
| ASP.NET Core | AddStackExchangeRedisCache + AddSession |
Tip: Sessions are data users would miss: configure persistence (AOF) or replication for the session store, and use the
noevictionorvolatile-lrupolicy so that memory pressure does not silently log people out.
Test yourself
How do you implement 'log out after 30 minutes of inactivity'?
- Set EXPIRE 1800 once at login
- Refresh the session key's TTL to 1800 on every request
- Use PERSIST
- Run a cron job that deletes all sessions every 30 minutes
Which structure helps you log a user out of all devices?
- A set of session IDs per user
- A HyperLogLog of sessions
- A bitmap of users
- A single global session hash
Which command reads a string value and resets its expiry in one step?
- GETDEL
- GETEX key EX seconds
- GETSET
- PERSIST