Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

A Spring MVC application with server-side sessions must run on 10 instances with rolling deployments and limit each user to two concurrent sessions. How would you design session management?

Sessions move out of the JVM into a shared store with Spring Session, Redis or JDBC, so any of the 10 instances can serve any request and a rolling deploy loses nobody. Concurrent session control uses maximumSessions(2) with Spring Session's SpringSessionBackedSessionRegistry, which sees sessions from every instance. We decide whether a third login is refused or expires the oldest session, keep session contents small and serializable across versions, and set idle and absolute timeouts with invalidation on logout and password change.

Why this question is asked

An application that keeps sessions in each server's memory works perfectly on one instance and falls apart on ten: users get logged out when the load balancer picks a different node, every deployment signs everyone out, and a rule such as 'two sessions per user' cannot be enforced because no node sees the others. Interviewers ask this design question to see whether we know how Spring Session and Spring Security fit together, and which details break in production. In this answer, we will externalise the session store, enforce the two-session limit across instances, choose what happens on the third login, make the session survive rolling deployments, and set timeouts and invalidation.

1Why In-Memory Sessions Fail on 10 Instances

By default Tomcat keeps HttpSession objects in the memory of the JVM that created them. With 10 instances behind a load balancer, a user's second request may reach a node that has never heard of their session, so they appear logged out. Sticky sessions, where the load balancer always sends a user to the same node, hide the problem until that node is restarted, which in a rolling deployment happens to every node within minutes.

The concurrency rule has the same problem. Spring Security's default SessionRegistryImpl is an in-memory map on each node. Node 1 knows about the session it created and node 7 knows about its own, so a user can open two sessions on every node.

2Storing Sessions Outside the JVM With Spring Session

Spring Session replaces the container's session with one stored in an external store. It installs a filter, SessionRepositoryFilter, that wraps every request so request.getSession() reads from and writes to Redis or a database. Our code and Spring Security do not change; they still use HttpSession.

Redis is the common choice for speed and automatic expiry. JDBC works well when we already run a database and the login rate is moderate. For the concurrency rule we need a repository that can find all sessions of one user, which Spring Session calls FindByIndexNameSessionRepository. The JDBC repository and the indexed Redis repository support it; in Spring Boot 3 the Redis repository type is chosen with spring.session.redis.repository-type=indexed (check your version).

Properties
# application.properties
spring.session.redis.repository-type=indexed # needed to look up sessions by user
spring.session.timeout=30m # idle timeout
spring.data.redis.host=sessions.internal
server.servlet.session.cookie.secure=true
server.servlet.session.cookie.same-site=lax
Step throughWhere each part of the session lives
  1. Browsercookie with the session id
  2. Load balancerany node, no stickiness needed
  3. 10 application instancesSessionRepositoryFilter, Spring Security, no session state
  4. Redis or JDBC session storesession data, indexed by user name, expiry

4 layers, from the top down. Step through them one at a time.

Notice that the cookie still carries only a random id. The session data, including the security context, lives in Redis, keyed by that id, and every node reads the same data.

3Enforcing Two Sessions per User Across All Instances

Spring Security's concurrent session control counts a user's sessions in a SessionRegistry at login. We replace the in-memory registry with SpringSessionBackedSessionRegistry, which asks the session store for all sessions of the user, so the count is the same on every node.

Java
@Bean
SpringSessionBackedSessionRegistry<? extends Session> sessionRegistry(
FindByIndexNameSessionRepository<? extends Session> sessions) {
return new SpringSessionBackedSessionRegistry<>(sessions);
}
@Bean
SecurityFilterChain security(HttpSecurity http, SessionRegistry registry) throws Exception {
http.formLogin(Customizer.withDefaults())
.sessionManagement(s -> s
.maximumSessions(2)
.maxSessionsPreventsLogin(false) // third login expires the oldest session
.sessionRegistry(registry)
.expiredUrl("/login?expired"));
return http.build();
}
Step throughThird login with maximumSessions(2)
Browser CInstance 7Session store
POST /login
find sessions for user anna
2 sessions: A (oldest), B
mark session A expired
create session C
logged in, new cookie

6 messages in order. Play them, or step through them one at a time.

Session A's next request, on any instance, is redirected to /login?expired.

The behaviour on the third login is a product decision. With maxSessionsPreventsLogin(false), the default, the new login succeeds and the least recently used session is marked expired; its next request goes to /login?expired. With true, the third login is refused until the user logs out somewhere. Refusing is safer against shared accounts but frustrating for a user who closed a laptop without logging out, because that session stays alive until it times out. Most consumer applications choose to expire the oldest session and show the user where their sessions are.

4Surviving Rolling Deployments

During a rolling deployment, old and new versions of the application run at the same time and read the same sessions. Every attribute we store is serialized into Redis, by default with Java serialization. If version 2 changes a class that version 1 stored in the session, deserialization fails and the user is effectively logged out, or worse, a node throws errors on every request.

Three habits avoid this. Keep sessions small: the security context and a few ids, not whole entities or shopping carts with product objects. Store only types that change rarely, or simple values like strings and numbers. And consider a JSON serializer for the session store, configured with Spring Security's Jackson modules, so the stored form is readable and tolerant of added fields. Whatever we choose, a test that reads a session written by the previous version catches the problem before the release.

5Timeouts and Invalidation

An idle timeout, such as 30 minutes, ends sessions that are not used. An absolute timeout, such as 12 hours, ends every session after a fixed time even if it stays active, which limits how long a stolen session is useful. Spring Session gives us the idle timeout; the absolute one we add ourselves, for example with a filter that compares the session's creation time with the limit and invalidates it.

Logout must invalidate the session in the store, which Spring Security's logout does through the shared repository. On a password change we should go further and delete all the user's other sessions. Because the repository can find sessions by user name, that is a few lines: look up the sessions for the principal and delete every one except the current request's.

Java
Map<String, ? extends Session> all = sessions.findByPrincipalName(username);
all.keySet().stream()
.filter(id -> !id.equals(currentSessionId))
.forEach(sessions::deleteById); // every other device is signed out

6Follow-up questions

Why not keep sticky sessions and in-memory storage?

Sticky sessions lose every session on a node whenever it restarts, deploys or fails, and they still cannot enforce a per-user limit across nodes. An external store removes both problems and lets the load balancer spread traffic evenly.

What happens if Redis is down?

No one can log in or keep a session, so Redis becomes part of the login path's availability. We run it replicated, with sensible timeouts so a slow Redis fails fast, and monitor it like a database.

Do we still need HttpSessionEventPublisher?

With the in-memory registry it is needed so Spring Security learns about sessions that ended. With SpringSessionBackedSessionRegistry the registry reads the store directly, so it is not required for counting sessions.

7Conclusion

In this answer, we moved sessions out of the JVM with Spring Session so 10 instances share one store, used SpringSessionBackedSessionRegistry with maximumSessions(2) so the limit counts sessions on every node, chose between refusing the third login and expiring the oldest session, kept session contents small and serializable across versions for rolling deployments, and added idle and absolute timeouts with invalidation on logout and password change.

What to say in the interviewAbout 80 seconds aloud

Open with

With 10 instances and rolling deployments I would not keep sessions in the JVM. I would use Spring Session with Redis, or JDBC if we already have a database and modest traffic, so any instance can serve any request and restarts lose nobody; no sticky sessions needed.

Then, if they want more

For the two-session limit I would configure sessionManagement with maximumSessions(2), but replace the default in-memory registry with SpringSessionBackedSessionRegistry, which needs a repository that can find sessions by principal name, so the indexed Redis repository or the JDBC one. Then every node sees the same count.

I would agree with product what happens on the third login: by default it succeeds and expires the least recently used session, or with maxSessionsPreventsLogin(true) it is refused. I usually prefer expiring the oldest and showing users their active sessions.

For rolling deploys, old and new versions read the same sessions, so I keep session contents small and simple, ideally just the security context and some ids, consider a JSON serializer, and test reading a session written by the previous version.

Finally I would set an idle timeout of around 30 minutes, an absolute timeout with a small filter, invalidate on logout, and delete all other sessions of a user when their password changes.

About this answer

Last updated
12 November 2026
Versions it names
Spring Boot 3
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Security reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A Spring MVC application with server-side sessions must run on 10 instances with rolling...": https://scrivio-interview-library.netlify.app/spring-boot/authentication/dd1a083f14/