Scrivio Interview library
ScenarioAdvanced6 min read · updated 13 November 2026

A web application with 2 million active sessions sees Redis memory reach 300 GB and session saves taking 20 ms. Analysis shows an average session of 150 KB, mostly entity graphs and search results stored as attributes over the years.

How do you bring the session store back under control without logging everyone out, and which rules do you set for the future?

Sessions should hold identity and small state, so we set a budget of a few KB, find the largest attributes by sampling session hashes with HSTRLEN and MEMORY USAGE, and remove them in stages behind feature flags: stop writing them, read the data from its proper store, and let old copies expire with the session TTL so nobody is logged out. We check Spring Session's save mode, because always rewrites every attribute on each request while on-set-attribute writes only changes, move from JDK serialization to a compact versioned format such as JSON, and add guardrails: a session-size metric, a test that fails when an attribute exceeds the budget, and capacity alerts.

Why this question is asked

Session bloat is slow: one developer stores search results for convenience, another stores an entity graph to avoid a query, and years later 2 million sessions average 150 KB each. That is 300 GB of Redis memory and 20 ms saves on every request. Interviewers ask this scenario to see whether we can fix a live system gradually without hurting users, and then stop it from happening again. In this answer, we will confirm the arithmetic, find which attributes are responsible, remove them without logging anyone out, look at the save settings that make it worse, change serialization, and set rules for the future.

1Confirming Where the Memory Goes

The numbers agree with each other: 2 million sessions x 150 KB = 300 GB. And a 20 ms save is what we expect when each request writes a large share of 150 KB through the network and Redis's single thread. So the problem is not Redis; it is what the application puts into each session.

A session is meant to carry identity, such as the user id and security context, and small pieces of state, such as a cart id or the step of a wizard. Anything that can be reloaded from a database or a cache does not belong there. We set a budget, for example 4 KB per session, and work towards it.

2Finding the Largest Attributes

Spring Session's default repository stores each attribute as a field of the session hash named sessionAttr:<name>. So we can measure attributes directly. We sample a few thousand session keys from a replica, to keep load off the primary, and measure each field.

Text
SCAN 0 MATCH spring:session:sessions:* COUNT 1000 -- a batch of session keys
MEMORY USAGE spring:session:sessions:3f1c... -- (integer) 161220: about 157 KB
HKEYS spring:session:sessions:3f1c... -- creationTime, ..., sessionAttr:searchResults, ...
HSTRLEN spring:session:sessions:3f1c... sessionAttr:searchResults -- (integer) 88410
HSTRLEN spring:session:sessions:3f1c... sessionAttr:customerGraph -- (integer) 51207
HSTRLEN spring:session:sessions:3f1c... sessionAttr:SPRING_SECURITY_CONTEXT -- (integer) 2930
Attribute sizes in a sample of sessions
AttributeAverage sizeBelongs in session?
searchResults86 KBNo: rerun or cache by query
customerGraph50 KBNo: load from the database or cache
recentlyViewed9 KBIds only, about 0.3 KB
SPRING_SECURITY_CONTEXT3 KBYes
cartId, wizardStepunder 0.1 KBYes

Aggregating these per attribute name across the sample gives a ranking. Typically two or three attributes account for most of the size; here searchResults and customerGraph make up about 90 percent. That is where the work starts.

3Removing Attributes Without Logging Anyone Out

We must not delete sessions or rewrite them all at once. Instead we remove each large attribute in stages, behind a feature flag so each stage can be turned back. First, the code reads the data from its proper place when the attribute is missing: search results from a cache keyed by the query, customer data from the database or an entity cache. Then we stop writing the attribute. Sessions created from then on never get it, and existing sessions keep their old copy, unused, until they expire through the normal session TTL, or until we call removeAttribute when we touch them.

So within one session lifetime, say 30 minutes to a few hours depending on configuration, memory falls without any user noticing. We repeat for the next attribute and watch the memory graph come down step by step.

Step throughRemoving one attribute safely
  1. Read path falls back to the real storeFlag on, attribute optional
  2. Stop writing the attributeNew sessions never get it
  3. Old copies unusedOptionally removeAttribute on access
  4. Session TTL passesOld copies gone, memory falls
  5. Delete the old code pathFlag removed

5 steps in order. Play them, or step through them one at a time.

4Checking Spring Session's Save Behaviour

How much is written per request depends on two settings. SaveMode decides which attributes are written: ON_SET_ATTRIBUTE, the default, writes only attributes set with setAttribute during the request; ON_GET_ATTRIBUTE also writes attributes that were read; ALWAYS rewrites every attribute on every request. FlushMode decides when: ON_SAVE, the default, collects changes and writes them once at the end of the request, while IMMEDIATE writes each change as it happens.

A team that once found that mutating an object obtained from getAttribute was not saved, because ON_SET_ATTRIBUTE only notices setAttribute calls, often 'fixed' it by switching to ALWAYS. With 150 KB sessions, that means every request rewrites 150 KB, which matches our 20 ms saves. The correct fix is to call setAttribute after changing an object and to go back to the default.

Java
# application.properties (Spring Boot 3)
spring.session.redis.save-mode=on-set-attribute # default: write only attributes set this request
spring.session.redis.flush-mode=on-save # default: one write at the end of the request
cart.addItem(item);
session.setAttribute("cart", cart); # tells Spring Session the attribute changed

5Moving Off JDK Serialization

JDK serialization is large, because it writes class descriptors and field names in a verbose binary form, and fragile, because a change to a class's fields can make old sessions fail to deserialize after a deployment, which logs users out. A JSON serializer, registered as a RedisSerializer bean named springSessionDefaultRedisSerializer, produces smaller values for typical data and tolerates added fields. For a live system we switch with a serializer that writes JSON but can still read JDK bytes, so sessions created before the switch keep working until they expire.

6Rules and Guardrails for the Future

Rules only last if something checks them. We publish the budget, a few KB per session, with the rule that sessions hold identity and small state only. We add a metric, the distribution of session size at save time, with an alert if the p99 rises above the budget. We add a test that runs the main user journeys and fails if any single attribute exceeds, say, 1 KB, so a large attribute is caught in review rather than in production. And we set capacity alerts on the session store's used memory, with a forecast from active sessions times average size.

7Follow-up questions

How do you change the serialization format while sessions are live?

Use a transitional serializer. On write it always produces the new format, for example JSON. On read it looks at the first bytes: JDK serialization starts with the magic bytes 0xACED, so those values go to the JDK deserializer, and everything else goes to the JSON reader. Deploy that everywhere, and every session is converted as soon as its attributes are written again, while untouched old sessions expire naturally. After one maximum session lifetime, nothing in JDK format remains, and the fallback can be removed in a later release.

Why not just clear all sessions and start fresh?

Because every user would be logged out at once and lose carts and work in progress, which is the outcome the question asks us to avoid. The staged approach reaches the same memory level within one session lifetime without anyone noticing.

Does the default repository rewrite the whole hash on each request?

No. It writes only the changed fields with HSET, plus lastAccessedTime and the TTL. That is why large attributes cost most when they are set on every request or when save mode is always.

8Conclusion

In this answer, we saw that 300 GB and 20 ms saves came from 150 KB sessions full of data that belongs elsewhere. We found the largest attributes with HSTRLEN and MEMORY USAGE on sampled sessions, removed them in stages behind flags so old copies expired with the session TTL, restored the default save mode, moved to JSON with a transitional serializer, and added a size budget, a size metric, a failing test and capacity alerts so the bloat does not return.

What to say in the interviewAbout 90 seconds aloud

Open with

First I would confirm the arithmetic: 2 million sessions at 150 KB is the 300 GB, and saves are slow because each request writes large values. Sessions should hold identity and small state, so I would set a budget of a few KB.

Then, if they want more

To find the culprits I would sample session hashes on a replica with MEMORY USAGE and HSTRLEN per sessionAttr field, which usually shows two or three attributes, like search results and entity graphs, making up most of the size.

Then I remove them in stages behind feature flags: make the code read that data from its proper store when the attribute is missing, stop writing the attribute, and let the old copies expire with the session TTL. Nobody is logged out, and memory falls within one session lifetime. I would also check Spring Session's save mode.

The default, on-set-attribute, writes only changed attributes; if someone switched to always, every request rewrites all 150 KB, which explains the 20 ms. Flush mode on-save batches writes until the end of the request. I would move off JDK serialization to JSON with a serializer that can still read the old format.

And for the future: a session-size metric, a test that fails when an attribute exceeds the budget, and capacity alerts on the session store.

About this answer

Last updated
13 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
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 bring the session store back under control without logging everyone out, and...": https://scrivio-interview-library.netlify.app/databases/redis-patterns/30af08bde0/