0
0
Redisquery~5 mins

Session storage pattern in Redis

Choose your learning style9 modes available
Introduction

We use session storage to keep user data temporarily while they use a website or app. It helps remember who they are and what they did without saving forever.

When a user logs into a website and you want to remember their login during their visit.
When you want to store a shopping cart for a user before they check out.
When you need to save temporary preferences like language or theme while the user browses.
When you want to track user activity during a session without saving it permanently.
When you want fast access to user data that expires after some time.
Syntax
Redis
SET session:<session_id> <data> EX <seconds>
Use a unique session ID to store each user's data separately.
The EX option sets how long the session data stays before it expires automatically.
Examples
This saves session data for user 42 with a cart of 3 items, expiring in 1 hour.
Redis
SET session:12345 "user_id=42;cart=3" EX 3600
This retrieves the stored session data for session ID 12345.
Redis
GET session:12345
This deletes the session data when the user logs out or the session ends.
Redis
DEL session:12345
Sample Program

This example stores session data for user 'alice' with a dark theme for 30 minutes, then retrieves it.

Redis
SET session:abc123 "user=alice;theme=dark" EX 1800
GET session:abc123
OutputSuccess
Important Notes

Always use a unique session ID to avoid overwriting other users' data.

Set an expiration time to automatically clear old sessions and save memory.

Session data should be small and simple for fast access.

Summary

Session storage keeps temporary user data during their visit.

Use Redis SET with an expiration to save session info.

Retrieve with GET and delete with DEL when done.