Quick revision
The short answer
We run PostgreSQL and Toxiproxy as Testcontainers on one network, create a proxy from port 8666 to postgres:5432, and point spring.datasource.url at Toxiproxy's mapped port through @DynamicPropertySource. The test warms the cache, adds a 3,000 ms latency toxic, calls GET /products/42 while timing it, asserts status 200 with the fallback body in under 1 second, and removes the toxic in @AfterEach. It only passes if the code puts a time limit on the database call and has a fallback, and it should also cover dropped connections and recovery.
What to remember
In this answer, we wrote a Spring Boot integration test that reaches PostgreSQL through Toxiproxy, adds 3 seconds of downstream latency and asserts that GET /products/42 returns 200 with the stale cached product in under a second. We saw that it passes only with a client-side time limit and a fallback, that it should cover dropped and stuck connections and recovery without a restart, and that short limits in a test profile with generous margins keep it stable.
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.
We run PostgreSQL and Toxiproxy as Testcontainers on one network, create a proxy from port 8666 to postgres:5432, and point spring.datasource.url at Toxiproxy's mapped port through @DynamicPropertySource. The test warms the cache, adds a 3,000 ms latency toxic, calls GET /products/42 while timing it, asserts status 200 with the fallback body in under 1 second, and removes the toxic in @AfterEach. It only passes if the code puts a time limit on the database call and has a fallback, and it should also cover dropped connections and recovery.
Why this question is asked
We all write code that is supposed to survive a slow database, with timeouts and fallbacks, but very few teams check that it really does. Usually the first real test is a production incident. Interviewers ask this question to see whether we can turn a resilience claim into a repeatable test, and whether we know what makes such a test meaningful rather than flaky. In this answer, we will set up the containers, write the test, look at the application code it needs to pass, add the other faults worth covering, and finish with how to keep it stable on a build server.
1A Quick Recap of Toxiproxy and Testcontainers
Testcontainers starts real Docker containers from a JUnit test and stops them afterwards. Toxiproxy is a TCP proxy that sits between our application and a dependency. It has a control API, on port 8474, that lets the test add toxics: latency, limited bandwidth, timeouts that hold data, or a disabled proxy that refuses connections.
So the plan is: the application connects to Toxiproxy instead of PostgreSQL, Toxiproxy forwards to PostgreSQL over a shared Docker network, and the test tells Toxiproxy when to misbehave.
- JUnit test with MockMvccalls GET /products/42 and times it
- Spring Boot applicationJDBC URL points at Toxiproxy's mapped port
- Toxiproxy containerproxy pg: 0.0.0.0:8666 -> postgres:5432, toxics added by the test
- PostgreSQL containeralias postgres on the shared network
4 layers, from the top down. Step through them one at a time.
2Setting Up the Containers
Both containers join one Testcontainers Network, and PostgreSQL gets the alias postgres so Toxiproxy can reach it by name. The proxy is created through the Toxiproxy Java client, and the datasource URL uses the host port that Docker mapped to Toxiproxy's port 8666.
Notice that the application never learns PostgreSQL's real address; every byte goes through the proxy. The class names shown are from Testcontainers 1.x and the eu.rekawek toxiproxy-java client; Testcontainers 2 moved the container classes into per-module packages, so check your version for the imports.
3Writing the Test
The test first calls the endpoint once with a healthy database, so the cache holds product 42. Then it adds the latency toxic, calls again, and checks both the result and the time.
Asserting both behaviour and time is the heart of it. A test that only checks status 200 would pass if the endpoint waited 3 seconds and then answered, which is exactly the failure we want to prevent. A test that only checks the time would pass if the endpoint failed fast with a 500.
4What the Application Needs for the Test to Pass
Run against a typical service, this test fails, and that is its first value. To pass, the database call needs a time limit and the code needs a fallback. But there is a catch in choosing the limit. A server-side statement timeout cancels slow queries, but here the database is fast and the network is slow; even the error reply comes back through the 3-second toxic. So the limit must be on the client side.
A Resilience4j TimeLimiter around the repository call does this: after, say, 500 ms it stops waiting and the fallback returns the cached product marked as stale. The PostgreSQL driver's socketTimeout setting is a coarser second line of defence, measured in whole seconds. Notice that a time-limited call still holds its pooled connection until the slow reply arrives, so the connection pool must have room for that under load.
5Covering Other Faults and Recovery
Latency is only one way a database fails. proxy.disable() makes Toxiproxy refuse and drop connections, which tests what happens when the database disappears; a timeout toxic holds data without replying, which tests stuck connections. Each gets its own test with its own expected behaviour.
Recovery deserves a test too. After removing the toxic or re-enabling the proxy, the next requests should succeed with fresh data, without restarting the application. This checks that the connection pool, HikariCP by default, discards the broken connections and opens new ones, and that a circuit breaker, if we have one, closes again.
| Fault | Toxiproxy call | Expected behaviour |
|---|---|---|
| Slow database | latency DOWNSTREAM 3000 ms | 200 from cache within 1 s |
| Database gone | proxy.disable() | fast fallback or clear 503, no hang |
| Stuck connection | timeout toxic | time limit fires, pool recovers |
| Recovery | remove toxic, proxy.enable() | fresh data again, no restart |
6Keeping the Test Stable
Resilience tests easily become flaky. Two habits help. First, use a test profile with short, explicit limits, for example a 300 ms time limit and a 3,000 ms toxic, so the gap between the expected and the failing time is large. Second, leave sensible margins: asserting under 1 second when the limit is 300 ms tolerates a slow build machine, while a regression to 3 seconds still fails clearly. Then the test fails on real regressions, not on a busy CI agent.
7Follow-up questions
How would you inject the same fault into a running staging environment?
With a fault injection tool that works on the network of real pods, such as Chaos Mesh NetworkChaos, LitmusChaos or AWS Fault Injection Service, targeting the traffic from the product service's pods to the database with 3 seconds of delay. Alternatively a Toxiproxy sidecar can sit in front of the database in staging. We would define steady state, a small blast radius and abort conditions as for any chaos experiment, and watch the same assertion: product pages stay fast and marked stale.
Why add the toxic downstream rather than upstream?
Downstream latency delays the data coming back from PostgreSQL to the application, which is what a slow database or network looks like to the client. Upstream latency delays requests going to the database. Both are valid, but downstream reproduces slow replies directly and affects every query result.
Why not mock the repository to sleep for 3 seconds instead?
A mock tests our fallback logic but skips the real driver, connection pool and network. Toxiproxy exercises the real stack, so it catches problems such as a time limit that does not interrupt the driver, or a pool that never recovers.
8Conclusion
In this answer, we wrote a Spring Boot integration test that reaches PostgreSQL through Toxiproxy, adds 3 seconds of downstream latency and asserts that GET /products/42 returns 200 with the stale cached product in under a second. We saw that it passes only with a client-side time limit and a fallback, that it should cover dropped and stuck connections and recovery without a restart, and that short limits in a test profile with generous margins keep it stable.
Open with
I would start PostgreSQL and Toxiproxy as Testcontainers on one network, give PostgreSQL the alias postgres, and in a DynamicPropertySource create a proxy with the Toxiproxy client from 0.0.0.0:8666 to postgres:5432, then point spring.datasource.url at Toxiproxy's mapped port 8666.
Then, if they want more
In the test I call GET /products/42 once to warm the cache, add a latency toxic of 3,000 ms downstream, call it again with MockMvc while timing it, and assert status 200, the stale fallback body and a duration under one second. An AfterEach removes all toxics and re-enables the proxy.
The important point is that the test asserts both behaviour and time; otherwise a slow 200 or a fast 500 would pass. It only passes if the application has a client-side time limit, like a Resilience4j TimeLimiter, and a fallback, because a server-side statement timeout cannot help when the network itself is slow.
I would add tests for proxy.disable(), a timeout toxic and recovery after removing the toxic, checking the pool heals without a restart. To keep it stable, I use short limits in a test profile and generous margins, so it fails on real regressions, not slow CI machines.
About this answer
- Last updated
- 13 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
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 "Write a Spring Boot integration test in which PostgreSQL is reached through Toxiproxy...": https://scrivio-interview-library.netlify.app/architecture/high-availability/4b733c1456/