Session Management With Spring Reactive
Some web applications need to store state and this can be done by using a session.
The idea is that a user's experience is not determined by the choice of session management technique.
Web applications generally lie behind a load balancer which sends requests in a round robin manner (assuming all servers have the same capacity) to — as the name suggests — balance the load.
Below is a common approach to load balancing a web application.
Given the above, we will look into some ways of handling a user’s session.
Sticky Sessions
When a user accesses the web application, the load balancer will send the request to one of the servers at which point a session is created, which resides on the server itself.
So if the user’s first request was sent to Server 1, then the session is created on Server 1. If the second request is also sent to Server 1 then the user's session is found and they can continue with what they were doing, however, if the second request was instead sent to Server 2 then a new session is created resulting in the user starting all over. This results in the user having two different sessions (one on each server) with the load balancer sending requests to both servers causing a chaotic user experience.
Sticky sessions can be used to avoid this undesirable scenario by configuring the load balancer to always send a session to the exact same server where it was created.
Pros
- No application code is needed as the configuration is done on the load balancer.
Cons
- Causes uneven distribution of load across the servers.
- If a server goes down then all users on that particular server will lose their session and will have to start over again on the next available server.
Client-Side Session Management
In this scenario, the session state is stored on the client (your web browser) in a cookie.
Since the session does not reside on the server, then sticky sessions are not needed and it also does not matter which server you are sent to as each request will have the session available to it in the form of a cookie.
An example of client-side session management can be found in the Play framework where the session is stored in a signed cookie (JWT) and added unto each subsequent request.
Spring Session does not provide a client-side session management solution. See here for more info.
Pros
- No need to manage state on servers.
- No need to replicate state across servers.
- Simpler to scale.
Cons
- Limit to how much data you can store (up to 4KB).
- Need to make sure that the session data cannot be tampered with.
Server-Side Session Management
As stated previously, one way to manage a server-side session is to use sticky sessions.
The sticky session was needed because the session resides on the actual server.
A couple of alternatives to the sticky session approach:
- Store the session in a backing repository like Redis, Hazelcast, or a database. This way whichever server the request ends up at will go to the backing repository to get the session state. Spring Session is a good place to start to find out more about this approach.
- Replicate the session across your web servers. In this case, the session still resides on the server but if one server was to go down then the session could be picked up by another running server since it was replicated. Spring Session Hazelcast is a good place to find out about this approach.
Pros
- Only a session id is exposed to the client.
- No limit on session size.
- Can switch out session state implementation (for example from DB to Redis).
Cons
- More overhead to run a cluster or database.
Session Clustering in Spring Webflux
Spring Webflux provides a WebSession instead of an HttpSession.
The Spring Session documentation provides support for Redis, but what if you don’t want the overhead of maintaining a Redis cluster.
What if your web application would suffice with in-memory session clustering like that provided by Hazelcast web session clustering?
This would be fine if we were using a servlet container, but we are not (Netty being the default for Webflux), and Spring Session does not currently provide a Hazelcast implementation of ReactiveSessionRepository.
But all is not lost as we can use ReactiveMapSessionRepository passing in Hazelcast’s IMap.
In-Memory Session Clustering With Hazelcast
You can find all the code in the accompanying GitHub repository here.
- Configure Hazelcast
- Create a Config bean as Spring Boot uses it to auto configure a Hazelcast instance (see here for more details).
- Since we are creating the Hazelcast map ourselves it is important to configure it to evict expired sessions by setting a reasonable value for time to live (default value is 0 which means that the session will live infinitely).
- Configure spring session to use the Hazelcast map
- Make sure you add
@EnableSpringWebSession
. - Create a
ReactiveSessionRepository
bean which wraps the Hazelcast instance’s map.
- Make sure you add
- Test that it works
- Check out the GitHub repository and go to the root directory where build.gradle is and follow these steps:
- Open a terminal window and run the command:
SERVER_PORT=1234 ./gradlew bootRun
. - Wait for the server to start and then open another terminal window and run the command:
SERVER_PORT=6789 ./gradlew bootRun
. - Open a web browser and go to URL: http://localhost:1234
- Refresh the page several times and you should see the session id along with the hit count increasing incrementally.
- Open another tab in the same browser and go to URL: http://localhost:6789
- You should see that the session id is the same and the hit count has incremented.
- The time to live value is set to 30 seconds, so if the session is not accessed for 30 seconds then it will be evicted. You can see this outputted in the logs on the terminal, and that a new session is created when you access any of the URLs.
- Open a terminal window and run the command:
- Check out the GitHub repository and go to the root directory where build.gradle is and follow these steps: