DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How Spring Security Concurrent Session Control Works: Part 1
  • Integrating Twilio Into My SaaS Solution In Heroku
  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  • How Spring and Hibernate Simplify Web and Database Management

Trending

  • How the Go Runtime Preempts Goroutines for Efficient Concurrency
  • Streamlining Event Data in Event-Driven Ansible
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  • What Is Plagiarism? How to Avoid It and Cite Sources
  1. DZone
  2. Coding
  3. Frameworks
  4. Session Management With Spring Reactive

Session Management With Spring Reactive

In this post, we examine the concepts behind session management in an application, and how to apply these ideas to your code.

By 
Mahan Hashemizadeh user avatar
Mahan Hashemizadeh
·
Sep. 25, 18 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
14.9K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Image title

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:

  1. 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.
  2. 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.
  • Test that it works
    • Check out the GitHub repository and go to the root directory where build.gradle is and follow these steps:
      1. Open a terminal window and run the command: SERVER_PORT=1234 ./gradlew bootRun. 
      2. Wait for the server to start and then open another terminal window and run the command: SERVER_PORT=6789 ./gradlew bootRun. 
      3. Open a web browser and go to URL: http://localhost:1234
      4. Refresh the page several times and you should see the session id along with the hit count increasing incrementally.
      5. Open another tab in the same browser and go to URL: http://localhost:6789
      6. You should see that the session id is the same and the hit count has incremented.
      7. 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.
Session (web analytics) Spring Framework

Opinions expressed by DZone contributors are their own.

Related

  • How Spring Security Concurrent Session Control Works: Part 1
  • Integrating Twilio Into My SaaS Solution In Heroku
  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  • How Spring and Hibernate Simplify Web and Database Management

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: