Persist HTTP session using AWS ElastiCache

Over the time, we have presented many use cases where AWS ElastiCache in general (and Redis to be very specific) it’s a good choice: it could be used for throttling (here), for caching (here), for sending messages (here), for jobs scheduling (here) or for acquire a lock (here).

Even you probably get bored to see new and new topics about Redis, we want to discuss today another use case where this data store is good choice.

Anybody knows that HTTP is a stateless protocol. Consequently, a HTTP server cannot determine if a call is done by a new or an existing visitor. But if we really want to track the client’s activity across multiple calls, we can use HTTP sessions.

Spring framework offers a transparent integration with the classical HttpSession, but enhances this with a RESTful API and with support to share data across multiple hosts. Basically, your application is not tight to a single container, but it can be distributed across a cluster of nodes.

One way to achieve that is by adding a persistence layer. One solution is to do that using Redis. And you probably know that we prefer to use Redis from AWS ElastiCache instead of managing our own cluster.

We created a simple (and stupid) Spring Boot application to demo that. This is more a microservice and not at all a web application. But the whole idea is to see how simple is the configuration. The entire implementation is available here. The README file contains all steps to run it. If you want to connect to your ElastiCache Redis endpoint, here is described how to do that.

After making some calls – preferably using different browsers, you can check the redis key space and you’ll notice that some session details are stored there.

redis-cli KEYS spring:*
1) "spring:session:sessions:expires:f099544b-b4fa-40c9-b4da-3c6b2ed8cc29"
2) "spring:session:expirations:1558029540000"

Many other details about this topic can be found on SpringSession page (here).

Feel free to share your thoughts with us and to distribute this post to anyone may benefit from it.