Store user sessions in Redis with automatic expiration using TTL, choosing between Hashes (field-level access), Strings (serialized), or JSON (nested data) based on access patterns.
Redis is ideal for session storage due to its speed, built-in TTL support, and flexible data structures. This guide covers storage strategies, sliding expiration, and multi-server session sharing.
Hashes allow storing multiple session attributes with individual field access:
HSET session:abc123 user_id "1" created_at "1706648400" last_access "1706648400"
EXPIRE session:abc123 1800
Retrieve the full session:
HGETALL session:abc123
Update a single field:
HSET session:abc123 last_access "1706648500"
Sessions should typically expire after a period of inactivity, not from creation time. Reset the TTL on each access:
HGETALL session:abc123
EXPIRE session:abc123 1800
This creates a "sliding window" where active users stay logged in, while inactive sessions automatically expire.
For complex session data with nested structures, serialize to JSON:
SET session:abc123 '{"user_id":1,"cart":["item1","item2"],"prefs":{"theme":"dark"}}' EX 1800
This approach requires reading and writing the entire session on each update, but simplifies handling complex nested data.
The session ID should be cryptographically random to prevent guessing attacks.
To support "logout from all devices" or "see active sessions":
Track all sessions for a user in a Set:
HSET session:abc123 user_id "1" device "iPhone"
SADD user:1:sessions "abc123"
EXPIRE user:1:sessions 7200
List all sessions for a user:
SMEMBERS user:1:sessions
For each session ID, fetch details:
HGETALL session:abc123
Logout single session:
DEL session:abc123
SREM user:1:sessions "abc123"
Logout from all devices:
SMEMBERS user:1:sessions
For each session ID returned, delete the session key, then delete the set:
DEL session:abc123 session:def456 ...
DEL user:1:sessions
When a user logs out or an admin revokes access, all application servers must immediately stop accepting the session. Use Pub/Sub to broadcast invalidation:
Publisher (on logout):
PUBLISH session:invalidate abc123
Subscribers (all app servers):
SUBSCRIBE session:invalidate
When a message arrives, remove the session from any local cache.
Expired sessions are automatically removed by Redis, but the session ID references in user Sets may become stale. Periodically clean these:
user:*:sessions keyssession:{id} existsThis can run as a background job during low-traffic periods.
Sessions can consume significant memory at scale. Strategies to reduce footprint: