Scrivio Interview library
ScenarioIntermediate5 min read · updated 12 November 2026

Your CI runs out of memory and database connections during tests. You find 40 cached application contexts, each with its own Hikari pool and Kafka consumers. What would you do?

Each cached context is a running application with its own Hikari pool and Kafka consumers, so 40 of them exhaust memory and database connections. The main fix is to reduce the number of distinct context configurations by standardising profiles, properties and mocks. Around it, we lower spring.test.context.cache.maxSize so evicted contexts are closed, shrink pool sizes in the test profile, split runs into forks with smaller caches, and on Spring Framework 7 rely on its pausing of inactive cached contexts to stop background work; check your version.

Why this question is asked

Out-of-memory errors and 'too many connections' failures in a test run look like infrastructure problems, and the first instinct is to give CI a bigger machine. Here the numbers point elsewhere: 40 cached contexts means 40 copies of the application alive at once in one JVM. Interviewers ask this to see whether we connect the symptom to the context cache and fix the cause rather than the machine. In this answer, we will do the arithmetic that explains the failure, then go through the fixes from the most effective to the supporting ones.

1A Quick Recap: What a Cached Context Holds

The Spring TestContext framework caches each application context it starts and keeps it running, so a later test class with the same configuration can reuse it. A cached context is not a description of the application; it is the application, with every singleton bean alive. That includes a HikariCP connection pool, the pool of open database connections Spring Boot creates for the DataSource, Kafka listener containers with consumer threads polling the broker, scheduled tasks, and caches.

A context leaves the cache only when it is evicted, because the cache is full, or removed by @DirtiesContext, or when the JVM ends. Until then, all of that keeps running.

2Doing the Arithmetic

With Spring Boot's default Hikari pool of 10 connections, 40 contexts can hold up to 400 connections to the test database. PostgreSQL's default max_connections is 100, so somewhere around the tenth context, new connections are refused with an error saying there are too many clients. Memory follows the same pattern: if one context with its caches, threads and Kafka buffers uses 150 MB, 40 of them need about 6 GB of heap, more than a typical CI runner's JVM is given.

Resource use as contexts accumulate
Contexts cachedDB connections (10 each)Heap (150 MB each)Kafka consumer threads
1100.15 GB3
10100, at PostgreSQL's default limit1.5 GB30
32 (default maxSize)3204.8 GB96
404006 GB120

3Fix 1: Reduce Distinct Configurations

Every distinct combination of profiles, properties and @MockitoBean overrides is a separate context. Forty contexts usually means test classes have drifted: one adds a property, another mocks one extra bean. We turn on cache statistics logging to see the configurations, then standardise on a few base classes with fixed profiles, properties and mock sets.

Properties
logging.level.org.springframework.test.context.cache=DEBUG
# before: size = 32, maxSize = 32, hitCount = 310, missCount = 58 (evicting and reloading)
# after: size = 4, maxSize = 32, hitCount = 364, missCount = 4

This is the fix that solves the problem rather than containing it. Going from 40 configurations to 4 cuts connections, memory and startup time by the same factor. Moving tests that do not need a full context to unit tests or slices reduces the count further.

4Fix 2: Bound the Cache Size

The default maximum is 32 contexts. If the suite genuinely needs many configurations, we can lower the limit so the cache never holds more than the machine can afford. When a context is evicted, it is closed: its pool returns connections to the database and its consumers stop.

Properties
# src/test/resources/spring.properties (or -Dspring.test.context.cache.maxSize=8)
spring.test.context.cache.maxSize=8
# at most 8 live contexts: 80 connections, about 1.2 GB

The trade-off is time. If evicted configurations are needed again later, they are rebuilt, so a small limit with many configurations makes the suite slower. That is why bounding the cache supports Fix 1 rather than replacing it.

5Fix 3: Smaller Pools and Quieter Background Work in Tests

Tests rarely need 10 database connections per context. In the test profile we shrink the pool, and we stop background work that tests do not use, such as listeners that start polling as soon as the context starts.

YAML
# application-test.yml
spring:
datasource:
hikari:
maximum-pool-size: 2 # 40 contexts -> 80 connections instead of 400
minimum-idle: 0 # idle contexts release connections
kafka:
listener:
auto-startup: false # only tests that need consumers start them

Spring Framework 7 adds help here: it can pause cached contexts that are not currently in use, stopping their lifecycle components such as listener containers and schedulers, and restart them when a test class reuses the context. That stops idle contexts from consuming threads and polling the broker, though their memory remains. Check your version for the exact behaviour.

6Fix 4: Split Runs Into Forks

Because the cache is per JVM, running the suite in several forks, each with a share of the test classes, means each JVM holds fewer contexts and less heap. With Gradle we set maxParallelForks, with Maven Surefire forkCount. The catch is that forks can repeat configurations; four forks that each need the same 4 contexts start 16 in total, and use connections in parallel. So forking works best after Fix 1, and with the smaller pools from Fix 3.

Step throughOrder of fixes
  1. Measure contextscache statistics, heap, connections
  2. Standardise configurationsfewer distinct keys
  3. Shrink pools, stop idle consumerstest profile
  4. Bound maxSizeevicted contexts are closed
  5. Fork the runsmaller cache per JVM

5 steps in order. Play them, or step through them one at a time.

7Follow-up questions

Why not just raise PostgreSQL's max_connections on CI?

It hides the cause and costs memory on the database side, since each connection is a backend process. The suite would still start 40 applications and stay slow, and the limit would be hit again when more tests arrive.

Does closing an evicted context really release connections?

Yes. Closing the context destroys its beans, and Hikari closes its pool on shutdown. Contexts that stay cached, however, keep their idle connections, which is why minimum-idle of 0 helps.

Can @DirtiesContext help here?

It closes contexts sooner, which lowers peak use, but every later class with that configuration starts it again. Used broadly, it turns a memory problem into a time problem.

8Conclusion

In this answer, we saw that every cached context is a running application with its own connection pool and consumers, so 40 of them can need 400 connections and several gigabytes of heap. The real fix is fewer distinct configurations through standard profiles, properties and mocks. Supporting fixes are a lower spring.test.context.cache.maxSize, smaller pools and stopped consumers in the test profile, Spring Framework 7's pausing of idle contexts, and forks with smaller caches per JVM.

What to say in the interviewAbout 80 seconds aloud

Open with

Forty cached contexts means forty copies of the application running in one JVM, each with its own Hikari pool and Kafka consumers. With the default pool of 10, that can be 400 database connections against PostgreSQL's default limit of 100, and if each context takes around 150 megabytes, about 6 gigabytes of heap.

Then, if they want more

So I would not start with a bigger CI machine. First I would turn on cache statistics logging and reduce the number of distinct configurations, because each different set of profiles, properties or @MockitoBean overrides creates a new context. A few shared base classes usually bring 40 down to a handful.

Then I would bound the cache by lowering spring.test.context.cache.maxSize, knowing that evicted contexts are closed and release their connections, but may be rebuilt later. In the test profile I would shrink the Hikari pool to one or two connections with minimum idle zero, and turn off Kafka listener auto-startup for tests that do not need it.

On Spring Framework 7, idle cached contexts can be paused so their consumers and schedulers stop, which I would check for our version. Finally, I would split the run into forks so each JVM has a smaller cache, doing that after the earlier steps so forks do not multiply the problem.

About this answer

Last updated
12 November 2026
Versions it names
Spring Framework 7
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.
Official documentation
Spring Boot reference, Testing
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 "Your CI runs out of memory and database connections during tests. You find 40 cached...": https://scrivio-interview-library.netlify.app/spring-boot/spring-boot-test/4d28d08def/