Scrivio Interview library
ScenarioAdvanced6 min read · updated 13 November 2026

A B2B application keeps Spring Session sessions in Redis. A customer tenant reports compromised credentials, and security wants all sessions of that tenant's 40,000 users ended within five minutes, and at most three concurrent sessions per user from now on.

How do you revoke the sessions now, and how would you design session storage so both requirements become routine?

With the default repository there is no index, so finding the tenant's sessions means a SCAN over every session key reading a tenant attribute, collecting ids on a replica and deleting in batches on the primary; it works but is slow. The quickest lever is a tenant revocation stamp, tenant:{t}:revokedBefore holding a timestamp, checked by a request filter that rejects any session created before it, which ends all 40,000 users' sessions with one write. For the future we use the indexed repository or our own user:{id}:sessions set with Spring Security's concurrent session control and SpringSessionBackedSessionRegistry to cap each user at three, combine revocation with credential resets and an audit, and exercise the revocation path regularly.

Why this question is asked

Revoking sessions is the kind of feature nobody builds until a security incident demands it within minutes, and then the team discovers that the session store cannot answer the question 'which sessions belong to this tenant?'. Interviewers ask this scenario to see whether we can act quickly with what exists and then design so the next request is routine. In this answer, we will see why the default repository makes this hard, look at the brute-force path, use a revocation stamp to meet the five-minute target, design per-user control and the three-session cap, and finish with the security and operational practices around it.

1Why the Default Repository Cannot Answer the Question

Spring Session's default RedisSessionRepository stores each session as one hash, spring:session:sessions:<id>, and nothing else. There is no index from tenant or user to session ids. The tenant id is probably stored as an attribute inside each session, or inside the serialized security context, so to find a tenant's sessions we would have to open every session in Redis and look.

That is possible, but with millions of sessions it is slow, and five minutes is tight.

2The Brute-Force Path: SCAN, Collect, Delete

If we must delete the sessions themselves, we walk the keyspace with SCAN on a replica, so the primary is not loaded, read the tenant attribute of each session, and collect matching ids. Then we delete them on the primary in batches with UNLINK, which frees memory in the background.

Java
SCAN 0 MATCH spring:session:sessions:* COUNT 1000 -- next cursor and up to ~1000 keys
HGET spring:session:sessions:3f1c... sessionAttr:tenantId -- "\"acme\"" with JSON values
-- matching ids collected; then on the primary, batches of 500:
UNLINK spring:session:sessions:3f1c... spring:session:sessions:9a7e... ... -- (integer) 500

With 5 million sessions, that is 5,000 SCAN steps and 5 million HGET calls, pipelined; it can finish in minutes, but if attributes are JDK-serialized the job must also deserialize values to read them, and it is a script written during an incident. It also misses sessions created by the attackers while it runs. So we use it as cleanup, not as the main lever.

3The Fast Lever: A Tenant Revocation Stamp

Instead of finding every session, we change the rule that decides whether a session is valid. We store one key, tenant:{acme}:revokedBefore, holding the current time. A filter that runs on every request reads the tenant's stamp and rejects any session whose creation time is earlier. One write ends every session of all 40,000 users at once, including ones we would not have found.

Java
// incident: one write ends all of the tenant's sessions
redis.opsForValue().set("tenant:{acme}:revokedBefore", String.valueOf(Instant.now().toEpochMilli()));
// filter, registered after Spring Session's filter
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) {
HttpSession session = req.getSession(false);
if (session != null) {
String tenant = (String) session.getAttribute("tenantId"); // "acme"
long revokedBefore = stamps.get(tenant); // cached 10 s; 1731400000000
if (session.getCreationTime() < revokedBefore) { // 1731398000000 < ...: true
session.invalidate(); // session deleted
res.sendError(HttpServletResponse.SC_UNAUTHORIZED); // user must log in again
return;
}
}
chain.doFilter(req, res);
}
Step throughRevocation with a stamp
Security teamRedisGateway filterUser's browser
SET tenant:{acme}:revokedBefore now
request with old session cookie
GET stamp (cached briefly)
revokedBefore
creationTime < revokedBefore: invalidate
401, log in again

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

One write; every old session fails on its next request.

Notice that sessions created after the stamp, after users log in again with reset credentials, pass the check. Each rejected session is invalidated as its owner returns, and the brute-force job or plain expiry cleans up the rest. Caching the stamp for a few seconds per instance keeps the cost negligible and still meets five minutes easily.

4Making Per-User Control and the Three-Session Cap Routine

For ending one user's sessions and limiting concurrent sessions, we need an index from user to sessions. The indexed repository provides it: findByPrincipalName returns all of a user's sessions. Spring Security's concurrent session control uses that through SpringSessionBackedSessionRegistry.

Java
@Bean
SpringSessionBackedSessionRegistry<? extends Session> sessionRegistry(
FindByIndexNameSessionRepository<? extends Session> sessions) {
return new SpringSessionBackedSessionRegistry<>(sessions); // needs the indexed repository
}
@Bean
SecurityFilterChain security(HttpSecurity http, SpringSessionBackedSessionRegistry<?> registry) throws Exception {
http.sessionManagement(s -> s
.maximumSessions(3) // a fourth login expires the oldest session
.sessionRegistry(registry));
return http.build();
}

maximumSessions(3) expires the least recently used session when a fourth login happens; adding maxSessionsPreventsLogin(true) would reject the new login instead, which locks out users who forget to log out. If the indexed repository's keyspace notifications and cleanup are unwelcome, we can maintain our own set, user:{id}:sessions, adding the id on login and removing it on logout, with care to prune expired ids. We keep the tenant stamp as well, since it is the fastest lever for an incident at tenant scale.

5Around the Sessions: Credentials, Audit and Practice

Ending sessions alone does not contain a credential compromise. Attackers who know the passwords simply log in again. So revocation is combined with forced password resets for the tenant's users, revocation of API tokens and refresh tokens issued to them, and an audit of what the compromised sessions accessed, using access logs keyed by session or user.

Finally, the revocation path is used only during incidents, which is exactly when an untested path turns out to be broken: the filter was not registered on a new service, or the stamp key format changed. We exercise it regularly, for example with a monthly drill against a test tenant that checks sessions end within the target time, and keep a runbook next to it.

6Follow-up questions

What does the revocation check cost per request?

One small GET per request if we read the stamp every time, about the cost of a round trip, typically well under a millisecond in the same zone. Caching each tenant's stamp in memory for 5 to 10 seconds makes it almost free and still meets a five-minute target by a wide margin. For instant effect we can also publish a message when a stamp changes so instances refresh their cache at once. A missing stamp means no revocation, which should be cached too so tenants without one do not cause repeated lookups.

Why compare creation time rather than delete the stamp after five minutes?

Because the comparison keeps working for sessions that were idle during the incident and come back hours later. The stamp stays for at least the maximum session lifetime, after which no session older than it can exist anyway.

Does the indexed repository index by tenant?

No, it indexes by principal name. For tenant-wide actions we either add our own tenant index, a set of session ids per tenant, or use the stamp, which needs no index at all.

7Conclusion

In this answer, we saw that the default repository has no index, so finding a tenant's sessions means scanning every session, which is slow during an incident. A tenant revocation stamp checked by a request filter ends all of the tenant's sessions with one write and meets the five-minute target. For routine control we use the indexed repository or our own per-user set, with Spring Security's concurrent session control and SpringSessionBackedSessionRegistry to cap users at three sessions, combine revocation with credential resets, token revocation and an audit, and drill the path regularly.

What to say in the interviewAbout 90 seconds aloud

Open with

With the default repository there is no index from tenant or user to sessions, so finding the tenant's sessions means a SCAN over all session keys, reading the tenant attribute of each one.

Then, if they want more

I could do that on a replica to collect the ids and delete them on the primary in batches, but it is slow and misses sessions created meanwhile.

So for the five-minute target I would use a tenant revocation stamp: write tenant acme revokedBefore with the current timestamp, and have a request filter reject and invalidate any session created before that stamp. One write ends all 40,000 users' sessions, and caching the stamp for a few seconds keeps the per-request cost tiny.

For the future, I would switch to the indexed repository, which gives findByPrincipalName, or keep my own set of session ids per user, and use Spring Security's concurrent session control with SpringSessionBackedSessionRegistry and maximumSessions of three, so a fourth login expires the oldest session.

I would also make sure revocation comes with forced password resets, revocation of API tokens and an audit of what was accessed, since ending sessions alone does not stop someone with the password. And I would drill the revocation path regularly, because it is only used during incidents and tends to be broken exactly when needed.

About this answer

Last updated
13 November 2026
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
Redis documentation
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 "How do you revoke the sessions now, and how would you design session storage so both...": https://scrivio-interview-library.netlify.app/databases/redis-patterns/190324e960/