Use Redis as a Session Store
Beginner8 min
Store and manage user sessions in Redis for fast, centralized session handling across multiple application instances.
Prerequisites
- -Redis installed and running
- -redis-cli available
Steps
1
Create a session key with user data
Store session data as a hash with a unique session ID and set a TTL for automatic expiration.
$ redis-cli HSET session:abc123 userId 1001 username alice role admin createdAt '2026-03-11T10:00:00Z'
2
Set session expiration
Automatically expire the session after 30 minutes of inactivity.
$ redis-cli EXPIRE session:abc123 1800
Call EXPIRE again on each request to implement sliding session windows.
3
Retrieve session data
Fetch all fields from a session hash to validate the user.
$ redis-cli HGETALL session:abc123
4
Destroy a session on logout
Remove the session key entirely when the user logs out.
$ redis-cli DEL session:abc123
5
Count active sessions
Use SCAN to count all active session keys without blocking.
$ redis-cli --scan --pattern 'session:*' | wc -l
Avoid KEYS in production as it blocks the server. Always use SCAN for pattern matching on live instances.
Full Script
FAQ
Discussion
Loading comments...