Quick revision
The short answer
Start the containers once per JVM instead of once per class, either with the singleton container pattern in a shared base class or by declaring them as beans with @ServiceConnection in a shared @TestConfiguration, so that cached Spring contexts reuse them. Keep tests independent through their data, with unique ids, cleanup, rollback, or separate schemas and topics, and keep context configuration uniform so Spring's context cache is actually reused. Testcontainers' reuse mode is a good speed-up on developer machines but should not be relied on in CI.
What to remember
In this answer, we saw that 120 classes with their own containers spend over 20 minutes starting PostgreSQL and Kafka and also defeat Spring's context cache. Sharing containers once per JVM, through a singleton base class or container beans with @ServiceConnection in a shared @TestConfiguration, reduces that to seconds. Uniform context configuration lets cached contexts be reused, isolation comes from data through rollback, unique ids, cleanup and separate topics, and reuse mode stays on developer machines rather than in CI.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Start the containers once per JVM instead of once per class, either with the singleton container pattern in a shared base class or by declaring them as beans with @ServiceConnection in a shared @TestConfiguration, so that cached Spring contexts reuse them. Keep tests independent through their data, with unique ids, cleanup, rollback, or separate schemas and topics, and keep context configuration uniform so Spring's context cache is actually reused. Testcontainers' reuse mode is a good speed-up on developer machines but should not be relied on in CI.
Why this question is asked
When every test class starts its own PostgreSQL and Kafka, the suite spends most of its time waiting for Docker rather than testing. The obvious fix, sharing containers, raises a fair concern: shared state is how tests start depending on each other and failing in random orders. Interviewers ask this design question to see whether we can get the speed without losing isolation. In this answer, we will measure where the time goes, share containers with two patterns, make the Spring context cache work with them, isolate tests through data, and finish with reuse mode and where it belongs.
1Where the Time Goes
Let us put numbers on the problem. A PostgreSQL container typically takes about 2 to 4 seconds to start and become ready, and a Kafka broker 5 to 10 seconds. If each of the 120 classes declares static containers with @Container, the @Testcontainers extension starts them before the class and stops them after it. That is roughly 120 x 11 seconds, about 22 minutes of container startup, before counting anything else.
There is a second cost hidden behind the first. Because each class has its own containers with their own random ports, each class also gets a different datasource URL and Kafka address, which makes its Spring context configuration different, so Spring cannot reuse a cached context either. Every class pays for a new context on top of new containers.
| Setup | Container starts | Startup time |
|---|---|---|
| Own containers in each of 120 classes | 240 | about 22 minutes |
| Singleton containers per JVM | 2 | about 11 seconds |
| Singleton, 4 parallel CI forks | 8 | about 11 seconds per fork |
2Pattern 1: Singleton Containers in a Base Class
The singleton container pattern starts the containers once, in a static initializer of an abstract base class, and never stops them explicitly. Every integration test class extends the base class, so they all see the same running containers. When the JVM exits, Testcontainers' cleanup container, called Ryuk, removes them.
Notice that the fields have no @Container annotation and the class has no @Testcontainers. That is deliberate: the extension would stop the containers after each class, which is exactly what we want to avoid. @ServiceConnection still works on these static fields in Spring Boot 3.1 and later, so no properties are needed. The Kafka container class and image name depend on the Testcontainers version; check your version.
3Pattern 2: Containers as Beans in a Test Configuration
Spring Boot offers a second pattern that fits its context cache naturally. We declare the containers as beans in a @TestConfiguration, annotate the bean methods with @ServiceConnection, and import that configuration into every integration test. Spring starts the containers when it creates the beans and stops them when the context is closed.
6 messages in order. Play them, or step through them one at a time.
The lifecycle is now tied to the context. As long as all test classes have the same context configuration, Spring builds the context once, starts the containers once, and every class reuses both. The same configuration can also be used to run the application locally against containers, through SpringApplication.from(App::main).with(ContainersConfig.class).
4Keeping Context Configuration Uniform
Both patterns depend on Spring reusing the context, and that only happens when the configuration is identical: same configuration classes, profiles, properties and bean overrides. If one class adds @MockitoBean PaymentGateway, another sets @TestPropertySource(properties = "feature.x=true"), and a third uses @DirtiesContext, each gets a separate context, and with pattern 2, separate containers as well.
So the design includes a convention: integration tests extend one base class or use one composed annotation with the shared configuration, overrides are standardised, and @DirtiesContext needs a reason. We can check this in CI by enabling debug logging for the context cache and watching the count of contexts created, which should be a small, stable number.
5Isolating Tests Through Data
Sharing containers means sharing state, so isolation must come from the data instead of fresh infrastructure. For the database there are a few options. Transactional tests that roll back, as in @DataJpaTest, leave no trace. Tests that commit, for example through a REST call, should create their own data with unique identifiers, such as a random customer id, and assert only on that data, or clean up the tables they used in an @AfterEach. For very independent suites, each test class can use its own schema.
Kafka needs the same thinking. Each test class, or each test, uses its own topic names, for example orders-<random suffix>, and its own consumer group, so messages from one test never reach another. A test that asserts 'exactly one message' on a shared topic will fail randomly once tests share a broker; a test that waits for its own message, keyed by its own id, will not.
- Does the test commit data?YesUse unique ids or clean up afterNoRoll back the transaction
- Does it read shared tables?YesFilter by its own idsNoNothing more needed
- Does it use Kafka?YesOwn topic or own key and consumer groupNoDone
3 steps in order. Play them, or step through them one at a time.
Notice that the assertion filters by the test's own customer id. That single habit removes most of the cross-test interference that people fear when they share containers.
6Reuse Mode: Useful Locally, Not in CI
Testcontainers also has a reuse mode. With testcontainers.reuse.enable=true in the developer's ~/.testcontainers.properties and .withReuse(true) on the container, Testcontainers keeps the container running after the JVM exits and attaches to it on the next run. For a developer running one test class twenty times an hour, that saves the startup every time.
It does not belong in CI. Reused containers survive between builds, so data from an earlier build can leak into the next, cleanup is not automatic, and parallel builds on the same agent could attach to the same container. CI should start clean containers once per JVM with the singleton or bean pattern, which already brings the cost down to seconds.
7Follow-up questions
Can tests run in parallel against shared containers?
Yes, if isolation comes from data, as described. Parallel forks in Maven or Gradle each have their own JVM, so each fork starts its own singleton containers, which also keeps forks apart.
Is the singleton pattern safe if one test breaks the database?
A test that drops tables or changes global settings would affect later tests, so such tests either restore what they changed or get their own container. They should be rare and clearly marked.
Which pattern would you choose?
For Spring Boot 3.1 and later, containers as beans in a shared @TestConfiguration fit the context cache and local development well. The base class singleton is simpler and also works for non-Spring tests. Both cut the startup to once per JVM.
8Conclusion
In this answer, we saw that 120 classes with their own containers spend over 20 minutes starting PostgreSQL and Kafka and also defeat Spring's context cache. Sharing containers once per JVM, through a singleton base class or container beans with @ServiceConnection in a shared @TestConfiguration, reduces that to seconds. Uniform context configuration lets cached contexts be reused, isolation comes from data through rollback, unique ids, cleanup and separate topics, and reuse mode stays on developer machines rather than in CI.
Open with
With 120 classes each starting PostgreSQL and Kafka, we pay maybe ten seconds of container startup per class, around twenty minutes, and because each class gets new random ports, Spring cannot reuse cached contexts either.
Then, if they want more
I would start the containers once per JVM. One way is the singleton pattern: an abstract base class with static containers started in a static initializer, without @Container so the extension does not stop them, and with @ServiceConnection so Boot wires them.
The other, which I prefer with Spring Boot 3.1 and later, is to declare the containers as beans with @ServiceConnection in a shared @TestConfiguration that every integration test imports, so they live as long as the cached context.
For that to work, the context configuration must be uniform: same base class, standardised bean overrides, no casual @DirtiesContext, and I would watch the context count in CI. Isolation then comes from data: transactions that roll back, unique ids in tests that commit and assertions filtered by those ids, cleanup where needed, and separate topics or consumer groups in Kafka.
Testcontainers' reuse mode is fine on developer machines, but not in CI, where leftover state and parallel builds make it unsafe.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Boot 3.1
- 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
- JUnit user guide, Mockito documentation
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 suite has 120 test classes each starting its own PostgreSQL and Kafka containers....": https://scrivio-interview-library.netlify.app/java/integration-testing/479f408d51/