Junior — Middle
How is the storage of user sessions implemented in your latest project?
sobes.tech AI
Answer from AI
In my last project, user sessions were stored using an application server and Redis as an external session storage.
Working mechanics:
- When a user authenticates, a unique session identifier (sessionId) is created.
- Session data (e.g., user ID, last activity time) is serialized and stored in Redis with the key sessionId.
- The web application retrieves the sessionId from cookies on each request and fetches session data from Redis.
- TTL (time-to-live) in Redis is used to manage session lifetime, allowing automatic removal of inactive sessions.
This approach ensures scalability (multiple application servers can access a single session store) and fast performance due to in-memory caching.
Example code for saving a session in Redis (using Jedis):
Jedis jedis = new Jedis("localhost");
String sessionId = UUID.randomUUID().toString();
Map<String, String> sessionData = new HashMap<>();
sessionData.put("userId", "12345");
// Save session with a TTL of 30 minutes
jedis.hmset(sessionId, sessionData);
jedis.expire(sessionId, 1800);