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:

  1. Static analysis. Custom rules in ErrorProne or Sonar: Executors.new* forbidden, a warning for new ConcurrentHashMap in a static field, a class with ThreadLocal.set but no remove. Keep the rules few and precise, otherwise teams will turn them off.

  2. Shared primitives. In the platform library the right way should be the easiest way: a ready cache builder, a bounded executor, a context facade.

  3. 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.

  4. 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.

  5. 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.