Member-only story
Memory Leak When Injecting Prototype Beans into Spring Singleton Beans — Full Case Study
Interactive Interview Theme:
*“You’re in a senior backend interview.The interviewer says:
‘We have a memory leak. AListin a base class keeps growing — even after we marked the beans as@Scope("prototype"). Why? And how do you fix it?’Can you explain with logs, source-level insight, and two production fixes — all while staying calm?”*
Let’s simulate the real incident — and turn it into a learning masterpiece.
Problem Background
A stateful abstract service accumulates 1 million characters per call in a List<String>.
Subclasses are injected into a singleton controller via List<SayService>.
Expectation:
Each HTTP request → new SayHello and SayBye instances → fresh data list.
Reality:data.size() keeps growing → OOM after 100+ requests.
The Code That Broke Production
// Stateful base class — DANGER!
public abstract class SayService {
List<String> data = new ArrayList<>(); // ← Shared per instance
public void say() {
data.add(IntStream.rangeClosed(1, 1_000_000)…