java 38 lines · 7 steps

Resilient payment calls with Spring Retry

A Spring service retries transient payment failures with exponential backoff and falls back gracefully when retries run out.

Explained by highlit
1@Service
2public class PaymentGatewayClient {
3 
4 private static final Logger log = LoggerFactory.getLogger(PaymentGatewayClient.class);
5 
6 private final RestTemplate restTemplate;
7 
8 public PaymentGatewayClient(RestTemplate restTemplate) {
9 this.restTemplate = restTemplate;
10 }
11 
12 @Retryable(
13 retryFor = { ResourceAccessException.class, HttpServerErrorException.class },
14 noRetryFor = HttpClientErrorException.class,
15 maxAttempts = 4,
16 backoff = @Backoff(delay = 500, multiplier = 2.0, maxDelay = 5000, random = true)
17 )
18 public ChargeResult charge(ChargeRequest request) {
19 log.debug("Submitting charge for order {}", request.orderId());
20 ResponseEntity<ChargeResult> response = restTemplate.postForEntity(
21 "/v1/charges", request, ChargeResult.class);
22 return response.getBody();
23 }
24 
25 @Recover
26 public ChargeResult recoverCharge(RemoteAccessException ex, ChargeRequest request) {
27 log.error("Charge for order {} failed after retries: {}", request.orderId(), ex.getMessage());
28 return ChargeResult.pending(request.orderId(),
29 "Gateway unavailable, charge queued for reconciliation");
30 }
31 
32 @Recover
33 public ChargeResult recoverCharge(HttpServerErrorException ex, ChargeRequest request) {
34 log.error("Gateway returned {} for order {}", ex.getStatusCode(), request.orderId());
35 throw new PaymentProcessingException(
36 "Payment gateway rejected charge for order " + request.orderId(), ex);
37 }
38}
01 / 01
STEP 01

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1Retry only errors that might succeed next time — server and network faults — and never client errors like 4xx that will always fail.
  2. 2Randomized exponential backoff spreads retries out and prevents a thundering herd against a struggling downstream service.
  3. 3Distinct @Recover methods let you shape different outcomes — a safe fallback versus a rethrown exception — based on which failure exhausted the retries.

Related explainers

java
@Component
@Converter
public class EncryptedStringConverter implements AttributeConverter<String, String> {
 

Transparent column encryption in Spring & JPA

encryption aes-gcm jpa-converter
Advanced 10 steps
java
package com.acme.billing.config;
 
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;

Feature-flagged beans with Spring @ConditionalOnProperty

feature-flags conditional-beans strategy-pattern
Intermediate 5 steps
java
public static Map<String, String> parseCookieHeader(String header) {
    Map<String, String> cookies = new LinkedHashMap<>();
    if (header == null || header.isBlank()) {
        return cookies;

Parsing an HTTP Cookie header in Java

string-parsing http url-decoding
Intermediate 6 steps
java
public class TimedSocketReader {
 
    private static final int READ_TIMEOUT_MS = 5_000;
    private static final int CONNECT_TIMEOUT_MS = 3_000;

Reading a socket with connect and read timeouts

sockets timeouts io
Intermediate 8 steps
java
public final class EncodingDetector {
 
    public enum Encoding {
        UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN

Detecting text encoding from raw bytes in Java

byte-manipulation encoding-detection bitwise-operations
Intermediate 8 steps
java
public final class ImportOrganizer {
 
    private static final Pattern IMPORT_LINE =
            Pattern.compile("^import\\s+(static\\s+)?([\\w.]+(?:\\.\\*)?)\\s*;\\s*$");

Sorting Java imports with a regex pass

regex sorting text-processing
Intermediate 8 steps

Share this explainer

Here's the card — post it anywhere.

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