Scrivio Interview library
DesignAdvanced6 min read · updated 12 November 2026

A web application stores a shopping cart in a session-scoped bean. You need to scale to many instances. What do you consider?

A session-scoped cart lives inside the HttpSession of one server, so with many instances we need either sticky sessions, which route a user to the same instance but lose carts when it dies, or a shared session store such as Redis or a database through Spring Session, which requires the cart and everything it references to be serialisable and adds serialisation cost per request. Often the better design is to store the cart in a database keyed by user or by a cart id cookie, which survives restarts, logouts and different devices.

Background to this question

A session-scoped bean is the quickest way to build a shopping cart: the cart follows the user from request to request without any storage code. That works perfectly on one server. Once we run ten or fifty instances behind a load balancer, the cart's location becomes a real design question, and the answer affects availability, performance and user experience. In this answer, we will recap where a session-scoped bean really lives, look at sticky sessions and shared session stores with their costs, and then compare them with storing the cart as ordinary data.

1Where a Session-Scoped Bean Really Lives

When we mark a bean @SessionScope, Spring stores its instance as an attribute of the HttpSession, under a name such as scopedTarget.cart. The HttpSession is the servlet container's server-side storage for one user, found through the JSESSIONID cookie the browser sends. By default, Tomcat keeps sessions in the memory of the server process that created them.

Java
@Component
@SessionScope
public class Cart implements Serializable {
private final List<CartLine> lines = new ArrayList<>();
public void add(String sku, int qty) { lines.add(new CartLine(sku, qty)); }
public List<CartLine> lines() { return List.copyOf(lines); }
}
// Instance 1 handles POST /cart/add -> cart stored in instance 1's memory
// Load balancer sends GET /cart to instance 2 -> new empty session, cart is empty

Notice the consequence. The cart is in the memory of one process. If the next request goes to another instance, that instance has no such session and creates an empty one, so the user's cart seems to vanish.

2Option 1: Sticky Sessions

The load balancer can route each user to the same instance every time, usually by the session cookie. This needs no code changes, and in-memory sessions stay fast. But it has real costs. When an instance is restarted for a deployment, crashes, or is removed by autoscaling, every cart on it is lost, and with deployments several times a day that happens often. Load also spreads unevenly, because users stay pinned to an instance even when it is busy, and draining an instance for a deployment takes as long as its longest session.

Sticky sessions are a reasonable short-term step, but they make instances stateful, which works against the reason we scaled out in the first place.

3Option 2: A Shared Session Store With Spring Session

Spring Session replaces the container's session storage with an external store, such as Redis, a relational database through JDBC, Hazelcast or MongoDB. A filter wraps every request so that HttpSession reads and writes go to the store, and any instance can serve any user. Session-scoped beans keep working unchanged, because they are just session attributes.

XML
<!-- pom.xml -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
# application.properties
spring.session.timeout=30m
spring.data.redis.host=redis.internal
# Request on instance 2 now finds the cart that instance 1 saved

There is a catch: everything in the session must be serialisable, because it is written to Redis as bytes. The Cart and all its fields must implement Serializable, or use a JSON serialiser configured for Spring Session. If the cart holds a reference to an injected service, that service would be serialised too, so session beans should hold only data. Changes to attributes must also reach the store; Spring writes session-scoped bean instances back to the session at the end of each request so that the store sees the updated cart, but other mutable objects taken from the session may need to be set again explicitly.

The other cost is size. Each request reads the session from the store and writes back what changed. A cart of 20 KB with 200,000 active sessions means 4 GB in Redis, and every request moves those bytes over the network and spends CPU serialising them. If teams add more to the session over time, such as recently viewed items and cached product data, it gets slower for every request, so we must keep sessions small and watch their size.

4Option 3: Store the Cart as Data

The third option is to stop treating the cart as session state at all. A cart is business data: it has value after the session ends, people expect it on their phone and laptop, and marketing wants to remind them of abandoned carts. So we store it in a database table, or in a document store, keyed by the user id for signed-in users and by a cart id kept in a cookie for anonymous users. When an anonymous user signs in, we merge the anonymous cart into their account cart.

Java
@Service
class CartService {
private final CartRepository carts;
CartService(CartRepository carts) { this.carts = carts; }
@Transactional
void add(CartKey key, String sku, int qty) {
Cart cart = carts.findByKey(key).orElseGet(() -> Cart.empty(key));
cart.add(sku, qty);
carts.save(cart); // any instance, any device, survives restarts
}
}
Where to keep a cart when scaling out
OptionSurvives restartCross-deviceMain cost
In-memory session + stickynonolost carts on deploys, uneven load
Spring Session (Redis/JDBC)yesnoserialisation per request, size limits
Cart table keyed by user/cart idyesyesa DB read/write per change, merge logic
For carts, storing them as data usually wins.

Now the services are stateless singletons, any instance can serve any request, deployments lose nothing, and the session, if we still need one, carries only small things such as authentication. The cost is a database read and write per cart change, which is cheap for typical cart traffic, and a little more design work for merging and expiring carts.

5Follow-up questions

Is session scope ever the right choice after scaling out?

Yes, for small, short-lived, per-user state that has no value after the session ends, such as a multi-step form's progress or a flash message. With Spring Session the beans keep working across instances. The rule is to keep such state small and to put anything with business value in proper storage.

What goes wrong if a session-scoped bean holds a reference to a singleton service?

When the session is serialised, Java tries to serialise the service too, which usually fails with NotSerializableException or drags a large object graph into the store. Spring's scoped proxies can serialise themselves by bean name, but a plain injected singleton cannot. Session beans should hold only data, or mark service fields transient and look them up again.

How would you migrate from session carts to stored carts without losing carts?

Deploy the stored cart service first and write to both places for a while. On each request, if the session has a cart but the store does not, copy it to the store. After a period longer than the session timeout, every active cart has been migrated, and the session-scoped bean can be removed.

6Conclusion

In this answer, we saw that a session-scoped bean is an attribute of the HttpSession, which by default lives in one server's memory. To scale out we can use sticky sessions, which keep it simple but lose carts on every restart, or Spring Session with Redis or a database, which shares sessions but needs serialisable beans and costs serialisation and memory per request. For a shopping cart, storing it as data keyed by user or cart id is usually best, because it survives restarts, logouts and devices.

What to say in the interviewAbout 80 seconds aloud

Open with

First I would recognise that a session-scoped bean is just an attribute of the HttpSession, and by default the session lives in the memory of the instance that created it.

Then, if they want more

With many instances, a request that lands elsewhere gets an empty cart. One option is sticky sessions at the load balancer: no code change, but every deployment, crash or scale-in loses the carts on that instance, and load spreads unevenly. The second option is Spring Session with Redis or JDBC, so any instance can read the session.

Session-scoped beans keep working, but the cart and everything it references must be serialisable, so it should hold only data, not injected services, and every request pays to read and write the session. Size matters: 20 KB times 200,000 sessions is 4 GB in Redis, so sessions must stay small.

For a cart specifically, I would usually store it as business data instead: a table keyed by the user id, or by a cart id cookie for anonymous users, merged at login. That survives restarts and logouts, works across devices, supports abandoned-cart features, and keeps the services stateless. I would keep the session only for small things like authentication.

About this answer

Last updated
12 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.
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 web application stores a shopping cart in a session-scoped bean. You need to scale to...": https://scrivio-interview-library.netlify.app/spring-boot/bean-scopes/3af9475681/