Skip to content

Session Store

Application servers are stateless — sessions must live somewhere external. Redis is a natural fit: it is fast, supports key expiry natively, and its hash type maps cleanly onto a session object with named fields.

Each session is stored at key session:<id>. Fields such as userId, email, and role map directly to hash fields. An EXPIRE sets the idle timeout; refreshing that expiry on every authenticated request gives a sliding TTL.

127.0.0.1:6379> HSET session:abc123 userId 42 email "[email protected]" role "admin"
(integer) 3
127.0.0.1:6379> EXPIRE session:abc123 1800
(integer) 1
127.0.0.1:6379> HGETALL session:abc123
1) "userId"
2) "42"
3) "email"
5) "role"
6) "admin"
127.0.0.1:6379> HGET session:abc123 role
"admin"
127.0.0.1:6379> EXPIRE session:abc123 1800
(integer) 1
127.0.0.1:6379> TTL session:abc123
(integer) 1799

HSET with multiple field-value pairs creates the session in one round trip. HGETALL returns every field; HGET fetches a single field. Calling EXPIRE again resets the countdown, implementing the sliding idle timeout.

HSET session:abc123 userId 42 email "[email protected]" role "admin"
EXPIRE session:abc123 1800
HGETALL session:abc123
HGET session:abc123 role
EXPIRE session:abc123 1800
TTL session:abc123

Storing the session as a single JSON string is tempting but forces you to deserialise the entire blob just to read or change one field. With a hash, HGET fetches only the field you need and HSET updates only the field that changed — no round-trip of the full session value, and no risk of a write overwriting a concurrent update to a different field.

127.0.0.1:6379> HSET session:abc123 role "superadmin"
(integer) 0
127.0.0.1:6379> HGET session:abc123 role
"superadmin"

HSET returns 0 when it updates an existing field (no new field was added). Only the role field is touched; every other field remains unchanged.

HSET session:abc123 role "superadmin"
HGET session:abc123 role
Which command reads all fields and values of a hash?
How do you implement a sliding idle timeout for a session?
Why store a session as a hash rather than a JSON string?
What command deletes a session on logout?