java 36 lines · 7 steps

Resilient payment calls in Spring

A Spring service wraps an HTTP call to a payment gateway with retries, a circuit breaker, and typed fallbacks.

Explained by highlit
1@Service
2public class PaymentGatewayClient {
3 
4 private static final Logger log = LoggerFactory.getLogger(PaymentGatewayClient.class);
5 
6 private final RestClient restClient;
7 
8 public PaymentGatewayClient(RestClient.Builder builder,
9 @Value("${payment.gateway.base-url}") String baseUrl) {
10 this.restClient = builder.baseUrl(baseUrl).build();
11 }
12 
13 @CircuitBreaker(name = "paymentGateway", fallbackMethod = "chargeFallback")
14 @Retry(name = "paymentGateway")
15 public ChargeResult charge(ChargeRequest request) {
16 return restClient.post()
17 .uri("/v1/charges")
18 .contentType(MediaType.APPLICATION_JSON)
19 .body(request)
20 .retrieve()
21 .onStatus(HttpStatusCode::is5xxServerError, (req, res) -> {
22 throw new PaymentGatewayException("Gateway returned " + res.getStatusCode());
23 })
24 .body(ChargeResult.class);
25 }
26 
27 private ChargeResult chargeFallback(ChargeRequest request, CallNotPermittedException ex) {
28 log.warn("Circuit open for paymentGateway, rejecting charge for order {}", request.orderId());
29 return ChargeResult.deferred(request.orderId());
30 }
31 
32 private ChargeResult chargeFallback(ChargeRequest request, Throwable ex) {
33 log.error("Payment charge failed for order {}: {}", request.orderId(), ex.getMessage());
34 return ChargeResult.failed(request.orderId(), ex.getMessage());
35 }
36}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Resilience4j annotations let you add retries and a circuit breaker declaratively without cluttering the happy-path logic.
  2. 2Distinct fallback overloads matched by exception type let you react differently to an open circuit versus a genuine failure.
  3. 3Mapping 5xx responses to a custom exception turns transport errors into signals the resilience layer can act on.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Resilient payment calls in Spring — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code