Video in progress
Memory leaks keep repeating across several teams. What patterns do you identify, and what team rules and guardrails do you set up to prevent them?
Most leaks come from a few patterns: unbounded caches and collections, listeners that were never unregistered, ThreadLocal, metrics with unbounded cardinality, unbounded queues and unclosed resources. I collect them from postmortems and close them with static analysis rules, shared library primitives, and automatic signals in tests and prod.
📖 Answer
If you review a year's postmortems, the leaks look alike. A typical list:
| Pattern | Example | Guardrail |
|---|---|---|
| Unbounded cache | static Map<Long, X> CACHE = new ConcurrentHashMap<>() |
only Caffeine, maximumSize/Weight mandatory |
| Listener / callback | eventBus.register(this), no unregister |
registration returns an AutoCloseable |
| ThreadLocal | set without remove |
a lint rule, ScopedValue or a facade |
| Metric cardinality | userId or url with path parameters in a tag |
a limit on the number of tags with Micrometer's MeterFilter |
| Unbounded queue | newFixedThreadPool, LinkedBlockingQueue() |
a shared BoundedExecutors factory |
| Unclosed resource | a stream, an HTTP response body, a Session |
try-with-resources, ErrorProne/Sonar rules |
The guardrail layers:
-
Static analysis. Custom rules in ErrorProne or Sonar:
Executors.new*forbidden, a warning fornew ConcurrentHashMapin a static field, a class withThreadLocal.setbut noremove. Keep the rules few and precise, otherwise teams will turn them off. -
Shared primitives. In the platform library the right way should be the easiest way: a ready cache builder, a bounded executor, a context facade.
-
Tests. A long integration test (a soak test): the same load for 2-4 hours, with automatic evaluation of the "Old after GC" trend. Monotonic growth means the build goes red.
-
A prod signal. The same trend alert in all services and an automatic JFR OldObjectSample recording, so the evidence is ready when a leak appears.
-
Education. Every leak postmortem turns into a one-page "pattern card" that goes into onboarding.
The measure of success: the number of leak-related incidents and the time it took to find them. If a pattern keeps repeating, a rule or a primitive is missing: we fix the system, not the team.
Sign up to mark studied questions and save your progress.