Video in progress
How do you test retry and idempotency logic when the error only shows up on a network failure?
I inject the failure on purpose: in WireMock, Fault.CONNECTION_RESET_BY_PEER, delays, and the "request was executed but the response got lost" case; with Toxiproxy, cutting the database or broker connection. Then I check: was the operation executed once, is the number of retries right, is the result consistent.
📖 Answer
The most dangerous case is "succeeded, but the response never came". The provider charged the money, the response got lost on the way, your client gets a timeout and retries. Without an idempotency key, it's charged twice.
With WireMock:
stubFor(post("/charge").inScenario("lost-response")
.whenScenarioStateIs(STARTED)
.willReturn(aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER))
.willSetStateTo("second"));
stubFor(post("/charge").inScenario("lost-response")
.whenScenarioStateIs("second")
.willReturn(okJson("{\"status\":\"PAID\",\"id\":\"ch_1\"}")));
paymentService.pay(orderId);
verify(2, postRequestedFor(urlEqualTo("/charge")));
List<LoggedRequest> calls = findAll(postRequestedFor(urlEqualTo("/charge")));
assertThat(calls).extracting(r -> r.getHeader("Idempotency-Key")).containsOnly(calls.get(0).getHeader("Idempotency-Key"));
assertThat(paymentRepo.findByOrderId(orderId)).hasSize(1);
For database-related cases there's Toxiproxy (available as a Testcontainers module): in the middle of a test it cuts the Postgres or Kafka connection, adds latency, then restores it. That's how you see how the connection pool recovers, whether the outbox resends the message, and whether the consumer handles the duplicate idempotently.
The simplest way to check your own consumer's idempotency: send the same message twice and check that one record remains. This test should be written for almost every Kafka listener, because with at-least-once delivery, duplicates are the norm.
Check the retry count too: retries that are unbounded or have no exponential backoff can "kill" the provider in prod.
Sign up to mark studied questions and save your progress.