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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Resilience4j annotations let you add retries and a circuit breaker declaratively without cluttering the happy-path logic.
- 2Distinct fallback overloads matched by exception type let you react differently to an open circuit versus a genuine failure.
- 3Mapping 5xx responses to a custom exception turns transport errors into signals the resilience layer can act on.
Related explainers
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
java
public final class Slugifier { private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
Building a URL slugifier in Java
regex
unicode-normalization
string-processing
Intermediate
8 steps
java
@Repository public interface OrderRepository extends JpaRepository<Order, Long> { @Query("""
Keyset pagination with Spring Data JPA
pagination
cursor
jpa
Advanced
8 steps
java
public record FixedWidthField(String name, int start, int end) { public String extract(String line) { int from = Math.min(start, line.length());
Parsing fixed-width text in Java
records
parsing
streams
Intermediate
7 steps
java
@RestController @RequestMapping("/api/quotes") public class QuoteStreamController {
Streaming market quotes with Spring WebFlux
reactive-streams
backpressure
server-sent-events
Advanced
9 steps
java
@Controller public class BookController { private final BookService bookService;
Solving GraphQL N+1 with batch mapping in Spring
graphql
n+1-problem
batching
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/resilient-payment-calls-in-spring-explained-java-4a55/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.