Session Store
Why Redis for sessions?
Section titled “Why Redis for sessions?”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.
Storing a session as a hash
Section titled “Storing a session as a hash”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.
Redis CLI demo
Section titled “Redis CLI demo”127.0.0.1:6379> HSET session:abc123 userId 42 email "[email protected]" role "admin"(integer) 3127.0.0.1:6379> EXPIRE session:abc123 1800(integer) 1127.0.0.1:6379> HGETALL session:abc1231) "userId"2) "42"3) "email"4) "[email protected]"5) "role"6) "admin"127.0.0.1:6379> HGET session:abc123 role"admin"127.0.0.1:6379> EXPIRE session:abc123 1800(integer) 1127.0.0.1:6379> TTL session:abc123(integer) 1799HSET 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:abc123Hashes vs. serialised JSON
Section titled “Hashes vs. serialised JSON”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.
Updating a single field
Section titled “Updating a single field”127.0.0.1:6379> HSET session:abc123 role "superadmin"(integer) 0127.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