Video in progress

Strong Middle 🧩 Microservices

What is the risk in this code where @Retry is put on a payment call?

@Retry(name = "payment")
public PaymentResponse charge(ChargeRequest req) {
    return restClient.post()
        .uri("/payments")
        .body(req)
        .retrieve()
        .body(PaymentResponse.class);
}

Creating a payment is not idempotent: if the first attempt actually went through and the response was lost to a timeout, the retry creates a second payment. Before retrying you need an idempotency key or a status check.

📖 Answer

The retry also fires on a ReadTimeout. But a read timeout does not mean "the request wasn't executed". It means "I didn't wait long enough for the response". The payment service may have already charged the money while the response got stuck in the network. The retry sends POST /payments again, and the customer is charged twice.

Ways to fix it:

public PaymentResponse charge(ChargeRequest req) {
    String key = req.orderId() + ":charge"; // a business key, not a random UUID
    return restClient.post()
        .uri("/payments")
        .header("Idempotency-Key", key)
        .body(req)
        .retrieve()
        .body(PaymentResponse.class);
}
  • The payment service stores the earlier result under this key and returns exactly the same response on a repeated request.
  • The key must be the same on every retry. If a new UUID.randomUUID() is created on each attempt, the protection doesn't work.
  • If the downstream doesn't support idempotency, limit the retry to ConnectException only: if no connection was made, the request never arrived.

People often slip up here in interviews: they say "we don't retry POST". In fact the rule is not about the HTTP method, it is about whether the operation is idempotent.