Scrivio Interview library
DebuggingFoundations7 min read · updated 12 November 2026

This singleton controller returns wrong results under load. Explain the bug:

Java
@RestController
class PriceController {
private BigDecimal total;
@GetMapping("/sum")
BigDecimal sum(@RequestParam List<BigDecimal> items) {
total = BigDecimal.ZERO;
for (var i : items) total = total.add(i);
return total;
}
}

PriceController is a singleton, so one instance serves every request thread at the same time, and total is a field on that one instance. Two concurrent requests reset and add to the same field, so each can return a sum that includes the other request's items. The fix is to make total a local variable inside sum(), because Spring does not make singletons thread-safe; the class itself has to be stateless or protect its shared state.

Why this question is asked

This bug looks harmless in a code review and passes every unit test, because a test calls the method once on one thread. It only shows up under load, where it produces wrong numbers that are hard to reproduce. Interviewers ask it because it checks whether we know how Spring creates beans and how a web server runs requests, two facts that together decide whether a field is safe. In this answer, we will recap the singleton scope and the request threads, reproduce the wrong result step by step, fix it with a local variable, and then look at the general rule Spring leaves to us.

1A Quick Recap of Singletons and Request Threads

A bean is an object that Spring creates and manages for us. Every bean has a scope, which says how many instances Spring creates. The default scope is singleton: Spring creates one instance of the class for the whole application context and hands that same instance to everyone who needs it. A @RestController is a bean like any other, so by default there is exactly one PriceController object in the application.

The web server, Tomcat by default in Spring Boot, handles requests with a pool of threads. A thread is an independent path of execution; with the default Tomcat settings there can be up to 200 of them running requests at once. When ten clients call /sum at the same moment, ten threads call sum() on the same PriceController object at the same moment.

Here is the important part. Local variables and method parameters live on each thread's own stack, so every call gets its own copy. Fields live on the object, which lives on the shared heap, so every thread that uses the object sees the same field. A singleton with a mutable field is therefore one variable shared by every request in flight.

2Reproducing the Wrong Result

Let us follow two requests that arrive together. Request A asks for the sum of 10 and 20, and request B asks for the sum of 1 and 2. Both threads run the same code against the same total field.

Java
// Thread A: /sum?items=10,20 Thread B: /sum?items=1,2
// A: total = ZERO total is 0
// A: total = total.add(10) total is 10
// B: total = ZERO total is 0 (B wiped A's work)
// B: total = total.add(1) total is 1
// A: total = total.add(20) total is 21 (A adds to B's value)
// B: total = total.add(2) total is 23
// A: return total A returns 23, expected 30
// B: return total B returns 23, expected 3
Step throughTwo requests sharing one total field
Thread APriceController.totalThread B
total = 0
total = 10
total = 0, wipes A's 10
total = 1
total = 21
total = 23
A reads 23, expected 30
B reads 23, expected 3

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

Both threads write the same field on the one shared controller, so each sees the other's work.

Notice that neither request gets its own answer. The exact wrong numbers depend on how the operating system schedules the two threads, which is why the bug is intermittent: on a quiet test machine the threads rarely overlap, and in production with hundreds of requests per second they overlap all the time.

There is a second, quieter problem. Even without overlapping steps, the Java memory model does not promise that one thread sees another thread's write to a plain field right away, or in order. A field with no synchronisation and no volatile has no visibility guarantee at all. So the code is wrong for two reasons: the steps interleave, and the writes are not published safely between threads.

3The Fix: Keep the Sum in a Local Variable

The total only needs to exist for the duration of one call. That is exactly what a local variable is for. Each thread gets its own copy on its own stack, so no other thread can see or change it.

Java
@RestController
class PriceController {
@GetMapping("/sum")
BigDecimal sum(@RequestParam List<BigDecimal> items) {
BigDecimal total = BigDecimal.ZERO; // local: one copy per call, per thread
for (var i : items) total = total.add(i);
return total;
}
}
// Thread A: /sum?items=10,20 -> 30
// Thread B: /sum?items=1,2 -> 3
// Even shorter, with no variable at all:
// return items.stream().reduce(BigDecimal.ZERO, BigDecimal::add);

So the controller now has no fields that change after construction. It is stateless, and a stateless object is thread-safe without any locking: there is nothing shared to fight over. BigDecimal itself is immutable, which helps too; add() returns a new object instead of changing the old one, so nothing about the numbers is shared either.

It is worth saying why we do not fix it with synchronized. Marking sum() as synchronized would make the answers correct, but it would allow only one request at a time to compute a sum, turning 200 request threads into a queue. Locking is for state that really must be shared. Here the state never needed to be shared in the first place.

4What Spring Does and Does Not Promise

A common misunderstanding is that Spring somehow protects singletons because it manages them. It does not. Spring guarantees that it creates the bean once, injects its dependencies, and publishes the fully built object safely to the threads that use it. After that, every call is plain Java. Spring adds no locks and makes no copies.

So the responsibility sits with the class. The usual rule is that controllers, services and repositories are stateless: they hold only final references to other beans and configuration values that never change after startup. If a singleton truly needs shared mutable state, such as a counter or a cache, it must use a thread-safe type like AtomicLong or ConcurrentHashMap, or guard the state with a lock. Data that belongs to one request belongs in parameters and local variables, or in a request-scoped bean if it has to travel across several beans.

Where a value lives and who can see it
Kind of variableWhere it livesShared between requests?
Method parameterthe calling thread's stackNo
Local variablethe calling thread's stackNo
Field of a singleton beanthe heap, on the one instanceYes, by every thread
Field of a request-scoped beanthe heap, one instance per requestNo
static fieldthe heap, on the classYes, by every thread

5How to Spot This in a Review

The pattern to look for is simple: a field in a singleton bean that is assigned anywhere other than the constructor. In PriceController, the line total = BigDecimal.ZERO inside a request method is the giveaway. Marking injected fields final makes the pattern stand out, because any field that cannot be final is immediately suspicious. A quick load test, for example firing a few hundred concurrent requests with known inputs and checking every response, turns the bug from intermittent into obvious, and it is a good habit for any controller that someone suspects of holding state.

6Follow-up questions

Would changing the scope to prototype fix it?

Not for a controller in the usual way. A prototype bean is created fresh each time it is requested from the container, but a controller is looked up once when Spring builds its request mappings, so the same instance would still serve every request. Request scope would give one instance per HTTP request, but it is heavier and hides the real problem. The right fix is to remove the field.

Would making total volatile fix it?

No. volatile guarantees that each read sees the latest write, but it does not make the sequence of reset, add and return atomic. Two threads can still interleave their steps exactly as before, so the results would still be mixed up. volatile solves visibility, not the race between steps.

Is BigDecimal the problem here?

No. BigDecimal is immutable and safe to share. The problem is the field that holds a reference to it, which every thread reassigns. If total had been a mutable type, the bug would be the same or worse.

7Conclusion

In this answer, we saw that PriceController is a singleton, so every request thread runs sum() on the same object and shares its total field. Concurrent requests reset and add to that one field, so they return each other's sums, and the plain field also has no visibility guarantee between threads. Moving total into a local variable gives each call its own copy and makes the controller stateless and thread-safe without locks. Spring does not make singletons thread-safe; keeping them stateless, or using thread-safe types for the rare shared state, is our job.

What to say in the interviewAbout 90 seconds aloud

Open with

The bug is shared mutable state in a singleton. A RestController has singleton scope by default, so there is one PriceController instance, and Tomcat calls sum on it from many request threads at the same time.

Then, if they want more

The total field lives on that one instance, so every thread is reading and writing the same variable. If one request sums 10 and 20 while another sums 1 and 2, the second one resets total to zero in the middle of the first, and both can come back with 23 or some other mixed value.

It is intermittent because it depends on thread scheduling, which is why it only shows up under load. On top of the race, a plain field has no visibility guarantee between threads under the Java memory model.

The fix is to make total a local variable, or just reduce the stream of items, so each call has its own copy on its own stack and the controller is stateless. I would not use synchronized, because that serialises every request for state that never needed to be shared.

The general point is that Spring creates singletons once and publishes them safely, but it does nothing to make them thread-safe. Controllers and services should only hold final references to collaborators and immutable configuration, and anything per request belongs in parameters or locals.

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 "This singleton controller returns wrong results under load. Explain the bug:": https://scrivio-interview-library.netlify.app/spring-boot/bean-scopes/7a5d75c1f4/