java
68 lines · 9 steps
Building a resilient RestClient in Spring
A Spring @Configuration bean assembles a RestClient with timeouts and a retry interceptor that backs off on transient failures.
Explained by
highlit
1@Configuration
2public class PaymentGatewayClientConfig {
3
4 @Bean
5 RestClient paymentGatewayClient(RestClient.Builder builder,
6 @Value("${payment.gateway.base-url}") String baseUrl) {
7 var requestFactory = new SimpleClientHttpRequestFactory();
8 requestFactory.setConnectTimeout(Duration.ofSeconds(2));
9 requestFactory.setReadTimeout(Duration.ofSeconds(5));
10
11 return builder
12 .baseUrl(baseUrl)
13 .requestFactory(new BufferingClientHttpRequestFactory(requestFactory))
14 .requestInterceptor(new RetryInterceptor(3, Duration.ofMillis(200)))
15 .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
16 .build();
17 }
18
19 static class RetryInterceptor implements ClientHttpRequestInterceptor {
20
21 private static final Logger log = LoggerFactory.getLogger(RetryInterceptor.class);
22 private static final Set<Integer> RETRYABLE = Set.of(429, 502, 503, 504);
23
24 private final int maxAttempts;
25 private final Duration backoff;
26
27 RetryInterceptor(int maxAttempts, Duration backoff) {
28 this.maxAttempts = maxAttempts;
29 this.backoff = backoff;
30 }
31
32 @Override
33 public ClientHttpResponse intercept(HttpRequest request, byte[] body,
34 ClientHttpRequestExecution execution) throws IOException {
35 IOException lastError = null;
36 for (int attempt = 1; attempt <= maxAttempts; attempt++) {
37 try {
38 ClientHttpResponse response = execution.execute(request, body);
39 if (attempt == maxAttempts || !RETRYABLE.contains(response.getStatusCode().value())) {
40 return response;
41 }
42 log.warn("Retrying {} {} after status {} (attempt {}/{})",
43 request.getMethod(), request.getURI(), response.getStatusCode(), attempt, maxAttempts);
44 response.close();
45 } catch (IOException ex) {
46 lastError = ex;
47 if (attempt == maxAttempts) {
48 throw ex;
49 }
50 log.warn("Retrying {} {} after I/O error (attempt {}/{}): {}",
51 request.getMethod(), request.getURI(), attempt, maxAttempts, ex.getMessage());
52 }
53 sleep(backoff.multipliedBy(attempt));
54 }
55 throw Objects.requireNonNullElseGet(lastError,
56 () -> new IOException("Exhausted retries for " + request.getURI()));
57 }
58
59 private void sleep(Duration duration) throws IOException {
60 try {
61 Thread.sleep(duration.toMillis());
62 } catch (InterruptedException ex) {
63 Thread.currentThread().interrupt();
64 throw new IOException("Retry interrupted", ex);
65 }
66 }
67 }
68}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Centralizing HTTP client setup in a @Bean makes timeouts, headers, and retries consistent across every caller.
- 2A request interceptor is the right seam for cross-cutting concerns like retry, since it wraps the actual execution.
- 3Only retry idempotent-safe transient statuses with backoff, and always surface the last error when attempts are exhausted.
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.
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/building-a-resilient-restclient-in-spring-explained-java-e060/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.