Sub topic 11
Calling other services with WebClient
This chapter assumes you can read Mono and Flux pipelines and use map, flatMap, and switchIfEmpty. It also assumes you know basic Spring Boot dependency injection and HTTP status codes. Timeouts and retries get a short treatment here, and the next chapter covers them in more depth.
Why WebClient
A WebFlux handler runs on a small number of event-loop threads. If it calls another service with a blocking client, such as RestTemplate, the thread waits for the response and cannot serve other requests. WebClient is Spring's non-blocking HTTP client. It returns a Mono or Flux immediately and releases the thread while the network does its work.
WebClient is part of spring-webflux. By default it runs on Reactor Netty, the same library that powers the server side.
Creating a client
You can create a client with WebClient.create(baseUrl), but in a Spring Boot application it is better to inject the auto-configured WebClient.Builder. Boot's builder already has the codecs and the Jackson settings of your application. Build one client per remote service and reuse it. Each client holds a connection pool, so creating one per request wastes connections.
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
record User(String id, String name) {}
@Component
public class UserClient {
private final WebClient client;
public UserClient(WebClient.Builder builder) {
this.client = builder
.baseUrl("https://api.example.com")
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.build();
}
public Mono<User> find(String id) {
return client.get()
.uri("/users/{id}", id)
.retrieve()
.bodyToMono(User.class);
}
}Use URI template variables, as in /users/{id}, instead of concatenating strings. The client encodes the values for you.
The request lifecycle
A call has three stages: describe the request, choose how to read the response, and subscribe.
- Describe the request with
get(),post(),uri(...),header(...), andbodyValue(...). - Call
retrieve()and pickbodyToMonofor one value orbodyToFluxfor many. - Subscribe. Nothing is sent until something subscribes. In a controller, returning the
Monois enough, because the framework subscribes.
Sending a body
Use bodyValue for a plain object. Use body(publisher, Type.class) when the body is itself a Mono or Flux.
record NewUser(String name) {}
public Mono<User> create(String name) {
return client.post()
.uri("/users")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(new NewUser(name))
.retrieve()
.bodyToMono(User.class);
}Add this method to UserClient from the previous example.
Handling error statuses
retrieve() treats any 4xx or 5xx response as an error. The Mono fails with a WebClientResponseException. It has subclasses such as WebClientResponseException.NotFound, so you can handle one status without inspecting numbers.
public Mono<User> findOrEmpty(String id) {
return client.get()
.uri("/users/{id}", id)
.retrieve()
.bodyToMono(User.class)
.onErrorResume(WebClientResponseException.NotFound.class,
ex -> Mono.empty());
}You need import org.springframework.web.reactive.function.client.WebClientResponseException;. Here a remote 404 becomes an empty Mono, so the caller can use switchIfEmpty as it does for a local lookup.
To translate a status into your own exception, use onStatus. It runs before the body is decoded.
public Mono<User> findStrict(String id) {
return client.get()
.uri("/users/{id}", id)
.retrieve()
.onStatus(status -> status.value() == 404,
response -> Mono.error(new IllegalArgumentException("No user " + id)))
.bodyToMono(User.class);
}The function you pass to onStatus must return a Mono<? extends Throwable>. It does not throw.
Timeouts and retries
The spine's standard pattern puts a timeout and a retry with backoff on the pipeline:
WebClient client = WebClient.create("https://api.example.com");
Mono<User> user = client.get()
.uri("/users/{id}", id)
.retrieve()
.bodyToMono(User.class)
.timeout(Duration.ofSeconds(2))
.retryWhen(Retry.backoff(3, Duration.ofMillis(200)));Operator order matters. timeout placed before retryWhen limits each attempt to two seconds, and a timeout triggers a retry. If you place timeout after retryWhen, it limits the whole operation, retries included.
Retry.backoff(3, ...) retries every error by default, including a 404 that will never succeed. Restrict it to failures that can recover, and unwrap the exception when retries run out:
Retry retry = Retry.backoff(3, Duration.ofMillis(200))
.filter(ex -> ex instanceof WebClientResponseException w
&& w.getStatusCode().is5xxServerError())
.onRetryExhaustedThrow((spec, signal) -> signal.failure());Without onRetryExhaustedThrow, callers receive a RetryExhaustedException that wraps the real cause. Use the filter to avoid retrying POST requests that are not idempotent. A retried POST /users can create a user twice.
Configuring the connection
The timeout operator knows nothing about connecting or reading. Set those limits on the Reactor Netty HttpClient and pass it to the builder.
import io.netty.channel.ChannelOption;
import java.time.Duration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
HttpClient httpClient = HttpClient.create()
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000)
.responseTimeout(Duration.ofSeconds(2));
WebClient client = WebClient.builder()
.baseUrl("https://api.example.com")
.clientConnector(new ReactorClientHttpConnector(httpClient))
.codecs(c -> c.defaultCodecs().maxInMemorySize(2 * 1024 * 1024))
.build();The maxInMemorySize line addresses a common surprise. The default buffer limit is 256 KB, and larger bodies fail with a DataBufferLimitException. Raise the limit for endpoints that return big JSON documents. For very large payloads, use bodyToFlux(DataBuffer.class) and process the data in chunks.
Composing several calls
Because every call is a Mono, you can combine calls with the operators from earlier chapters.
- Use
flatMapwhen the second call needs a value from the first. - Use
Mono.zipwhen the calls are independent and should run at the same time.
record Profile(User user, List<Order> orders) {}
record Order(String id) {}
public Mono<Profile> profile(String id) {
Mono<User> user = userClient.find(id);
Mono<List<Order>> orders = orderClient.forUser(id).collectList();
return Mono.zip(user, orders)
.map(t -> new Profile(t.getT1(), t.getT2()));
}This example assumes userClient.find returns Mono<User> and orderClient.forUser returns Flux<Order>. Both requests start together, so the total latency is close to the slower call instead of the sum of both. If either call fails, zip fails and cancels the other.
Streaming responses
bodyToFlux works for a JSON array and for a stream. When the remote service returns text/event-stream, each event arrives as an element as soon as it is sent. This lets you consume a Server-Sent Events source and pass the elements on to your own clients without collecting them first.
Reading the full response
retrieve() covers most cases. When you need headers or the status together with the body, use toEntity or exchangeToMono.
public Mono<ResponseEntity<User>> findWithHeaders(String id) {
return client.get()
.uri("/users/{id}", id)
.retrieve()
.toEntity(User.class);
}With exchangeToMono you must consume or release the body yourself in every branch. If you skip it, the connection can leak from the pool.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Calling `.block()` inside a handler | Stalls an event-loop thread, and Reactor may throw an error | Return the `Mono` and compose with `flatMap` |
| Building a new `WebClient` per request | Connection pools are not reused | Create one client per remote service |
| Building a pipeline and never subscribing | No request is sent | Return the `Mono` or `Flux`, or subscribe |
| Retrying every error | Wasted retries on 4xx, duplicate `POST` effects | Use `filter` on the `Retry` spec |
| Ignoring the 256 KB buffer limit | `DataBufferLimitException` on large bodies | Raise `maxInMemorySize` or stream |
Exercises
Exercise
A WebClient pipeline ends with .retryWhen(Retry.backoff(3, Duration.ofMillis(200))) and the remote service answers 404. What happens, and how do you change it so only 5xx responses are retried?
Show answer
By default the 404 raises a WebClientResponseException.NotFound, and the retry spec retries every error, so the request is sent four times before failing with a RetryExhaustedException. Add .filter(ex -> ex instanceof WebClientResponseException w && w.getStatusCode().is5xxServerError()) to the Retry spec. Optionally add .onRetryExhaustedThrow((spec, signal) -> signal.failure()) to surface the original exception.
Exercise
You write client.get().uri("/users/1").retrieve().bodyToMono(User.class); as a statement in a method and ignore the result. No request reaches the server. Why?
Show answer
A WebClient pipeline is lazy. The request is sent only when something subscribes to the returned Mono. Because the Mono is discarded, nothing subscribes. Return it from the handler or controller, or subscribe to it.