Spring WebClient: non-blocking HTTP calls
WebClient is Spring's non-blocking HTTP client. It returns a Mono or a Flux instead of a value, which makes parallel calls, timeouts and retries a matter of composing operators. This page explains how it is built, then runs each important feature against a real server started in the same program, including the traps around error statuses and the in-memory buffer limit.
Contents
What WebClient is and how it is built Requests, URIs and bodies Error statuses: retrieve, onStatus and exchangeToMono Timeouts and retries Filters: headers, authentication and logging Parallel calls with Mono.zip and flatMap HTTP interface clients The 256 KB in-memory limit Choosing how to call HTTP services
What WebClient is and how it is built
WebClientMonoFlux
Underneath, a WebClient
- The fluent API:
,get() ,uri(...) ,retrieve() . Each step builds part of an immutable request description.bodyToMono(...) - Filters and codecs: an
chain wraps every request, for headers, logging or authentication, and the codecs convert bodies to and from JSON and other formats.ExchangeFilterFunction - A connector: the
does the network I/O. Reactor Netty is the default; the JDKClientHttpConnector , Jetty and Apache HttpComponents 5 connectors are alternatives.HttpClient
Spring has four ways to call HTTP services, and they share much of this machinery:
| Client | Since | Style | Best for |
|---|---|---|---|
RestTemplate | Spring 3.0 | Blocking, template methods | Existing code only: deprecated in Spring Boot 4.2 |
WebClient | Spring 5.0 | Non-blocking, fluent, MonoFlux | Reactive applications, streaming, many parallel calls |
HTTP interface clients (@HttpExchange | Spring 6.0 | A Java interface, implemented by a proxy | Typed clients for an API you call often |
RestClient | Spring 6.1 | Blocking, fluent, same API shape as WebClient | Spring MVC applications that do not need reactive types |
Every program on this page is a Spring Boot 4.1 application, on Spring Framework 7.0, that starts a small WebFlux server on a random port and calls it with WebClient in the same JVM. The output therefore shows both sides of each call. In Spring Boot 4, WebClient support has its own starter, spring-boot-starter-webclientspring-boot-starter-webfluxWebClient.Builder
Requests, URIs and bodies
The movie API below has one endpoint for a single movie, one search with a query parameter, and a POST that returns 201 with a Location
package demo.basics;
import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@SpringBootApplication
public class WebClientBasics {
record Movie(int id, String title, int year) { }
// The remote service this program calls, started in the same JVM
@RestController
static class MovieApi {
private final List<Movie> movies = List.of(new Movie(1, "Alien", 1979),
new Movie(2, "Heat", 1995), new Movie(3, "Up", 2009));
@GetMapping("/movies/{id}")
Movie one(@PathVariable int id) {
return movies.get(id - 1);
}
@GetMapping("/movies")
List<Movie> search(@RequestParam String q) {
System.out.println(" [server] q = \"" + q + "\"");
return movies.stream().filter(m -> m.year() < 2000).toList();
}
@PostMapping("/movies")
ResponseEntity<Movie> add(@RequestBody Movie movie) {
return ResponseEntity.status(201).header("Location", "/movies/4")
.body(new Movie(4, movie.title(), movie.year()));
}
}
public static void main(String[] args) {
SpringApplication app = new SpringApplication(WebClientBasics.class);
app.setDefaultProperties(Map.of("server.port", "0",
"spring.main.banner-mode", "off", "logging.level.root", "WARN"));
try (var context = app.run(args)) {
String port = context.getEnvironment().getProperty("local.server.port");
WebClient client = context.getBean(WebClient.Builder.class)
.baseUrl("http://localhost:" + port)
.defaultHeader("Accept", "application/json")
.build();
Mono<Movie> one = client.get().uri("/movies/{id}", 2)
.retrieve()
.bodyToMono(Movie.class);
System.out.println("Mono built, no request sent yet");
System.out.println("bodyToMono : " + one.block());
Flux<Movie> old = client.get()
.uri(b -> b.path("/movies").queryParam("q", "{q}").build("before 2000 & R"))
.retrieve()
.bodyToFlux(Movie.class);
System.out.println("bodyToFlux : " + old.map(Movie::title).collectList().block());
ResponseEntity<Movie> created = client.post().uri("/movies")
.bodyValue(new Movie(0, "Coco", 2017))
.retrieve()
.toEntity(Movie.class)
.block();
System.out.println("toEntity : " + created.getStatusCode() + ", Location "
+ created.getHeaders().getLocation() + ", body " + created.getBody());
}
}
}
Mono built, no request sent yet
bodyToMono : Movie[id=2, title=Heat, year=1995]
[server] q = "before 2000 & R"
bodyToFlux : [Alien, Heat]
toEntity : 201 CREATED, Location /movies/4, body Movie[id=4, title=Coco, year=2017]
- "Mono built, no request sent yet" came before any result. Like every Reactor pipeline, the call ran only when
subscribed.block() expanded the template variable, anduri("/movies/{id}", 2) decoded the JSON into the record.bodyToMono(Movie.class)- The server received
intact. The value was passed as a URI variable, so it was encoded as a whole. Concatenating it into the URI string would have split it at theq = "before 2000 & R" .& decoded the JSON array into abodyToFlux of two movies.Flux kept the status,toEntity , and the headers, alongside the body. Use it when the caller needs more than the body.201 CREATED
In an application, build the WebClientWebClient
Error statuses: retrieve, onStatus and exchangeToMono
A 404 or 503 is a normal HTTP response, so a client has to decide what it means. The inventory API returns 200 for one SKU, 404 for an unknown one, 400 with a JSON error body, and 503 during maintenance:
package demo.status;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;
@SpringBootApplication
public class StatusHandling {
record Item(String sku, int stock) { }
@RestController
static class InventoryApi {
@GetMapping("/items/{sku}")
ResponseEntity<?> item(@PathVariable String sku) {
return switch (sku) {
case "A1" -> ResponseEntity.ok(new Item("A1", 7));
case "BAD" -> ResponseEntity.badRequest().body(Map.of("error", "bad sku"));
case "DOWN" -> ResponseEntity.status(503).body("maintenance");
default -> ResponseEntity.notFound().build();
};
}
}
static class ItemNotFound extends RuntimeException {
ItemNotFound(String sku) {
super("no item " + sku);
}
}
public static void main(String[] args) {
SpringApplication app = new SpringApplication(StatusHandling.class);
app.setDefaultProperties(Map.of("server.port", "0",
"spring.main.banner-mode", "off", "logging.level.root", "WARN"));
try (var context = app.run(args)) {
WebClient client = context.getBean(WebClient.Builder.class)
.baseUrl("http://localhost:"
+ context.getEnvironment().getProperty("local.server.port"))
.build();
System.out.println("1. retrieve() turns 4xx and 5xx into exceptions:");
for (String sku : new String[] {"A1", "ZZ", "BAD", "DOWN"}) {
try {
Item item = client.get().uri("/items/{sku}", sku).retrieve()
.bodyToMono(Item.class).block();
System.out.println(" " + sku + ": " + item);
} catch (WebClientResponseException e) {
System.out.println(" " + sku + ": " + e.getClass().getSimpleName()
+ ", status " + e.getStatusCode().value()
+ ", body " + e.getResponseBodyAsString());
}
}
System.out.println("2. onStatus maps a status to your own exception or value:");
for (String sku : new String[] {"A1", "ZZ"}) {
Item item = client.get().uri("/items/{sku}", sku).retrieve()
.onStatus(s -> s.value() == 404,
response -> Mono.error(new ItemNotFound(sku)))
.bodyToMono(Item.class)
.onErrorResume(ItemNotFound.class, e -> Mono.just(new Item(sku, 0)))
.block();
System.out.println(" " + sku + ": " + item);
}
System.out.println("3. exchangeToMono hands you the status and body yourself:");
for (String sku : new String[] {"A1", "DOWN"}) {
String result = client.get().uri("/items/{sku}", sku)
.exchangeToMono(response -> {
HttpStatusCode status = response.statusCode();
if (status.is2xxSuccessful()) {
return response.bodyToMono(Item.class).map(Item::toString);
}
return response.bodyToMono(String.class)
.map(body -> "status " + status.value() + ", " + body);
})
.block();
System.out.println(" " + sku + ": " + result);
}
System.out.println("4. A 404 with bodyToMono and onStatus ignoring it is empty:");
Item missing = client.get().uri("/items/{sku}", "ZZ").retrieve()
.onStatus(s -> s == HttpStatus.NOT_FOUND, response -> Mono.empty())
.bodyToMono(Item.class)
.block();
System.out.println(" result: " + missing);
}
}
}
1. retrieve() turns 4xx and 5xx into exceptions:
A1: Item[sku=A1, stock=7]
ZZ: NotFound, status 404, body
BAD: BadRequest, status 400, body {"error":"bad sku"}
DOWN: ServiceUnavailable, status 503, body maintenance
2. onStatus maps a status to your own exception or value:
A1: Item[sku=A1, stock=7]
ZZ: Item[sku=ZZ, stock=0]
3. exchangeToMono hands you the status and body yourself:
A1: Item[sku=A1, stock=7]
DOWN: status 503, maintenance
4. A 404 with bodyToMono and onStatus ignoring it is empty:
result: null
- With
, every 4xx and 5xx status became a subclass ofretrieve() named after the status:WebClientResponseException ,NotFound ,BadRequest . The exception keeps the status and the response body, hereServiceUnavailable and{"error":"bad sku"} .maintenance replaced the 404 with anonStatus exception of our own, whichItemNotFound then turned into a default item with stock 0.onErrorResume handed the whole response to our function, which read the 503 body as a string. With exchange, you must consume or release the body in every branch;exchangeToMono releases it for you if the function does not.exchangeToMono- Part 4 is a trap: an
handler that returnsonStatus suppresses the error, and the body of the 404 then decodes to nothing, so the result wasMono.empty() . Only return an emptynull fromMono when an empty result is really what the caller expects.onStatus
Timeouts and retries
A remote call without a timeout can wait forever, and a call that fails once may succeed a moment later. The API below has a 2-second endpoint, an endpoint that returns 503 twice before succeeding, and one that always returns 400:
package demo.resilience;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;
import reactor.util.retry.Retry;
@SpringBootApplication
public class TimeoutsAndRetry {
static final AtomicInteger FLAKY_CALLS = new AtomicInteger();
static final AtomicInteger BAD_CALLS = new AtomicInteger();
@RestController
static class SlowApi {
@GetMapping("/fast")
String fast() {
return "fast";
}
@GetMapping("/slow")
Mono<String> slow() {
return Mono.just("finally").delayElement(Duration.ofSeconds(2));
}
@GetMapping("/flaky")
ResponseEntity<String> flaky() {
int call = FLAKY_CALLS.incrementAndGet();
System.out.println(" [server] /flaky call " + call);
return call < 3 ? ResponseEntity.status(503).body("busy")
: ResponseEntity.ok("served on call " + call);
}
@GetMapping("/bad")
ResponseEntity<String> bad() {
System.out.println(" [server] /bad call " + BAD_CALLS.incrementAndGet());
return ResponseEntity.badRequest().body("invalid");
}
}
static boolean isRetryable(Throwable e) {
return e instanceof WebClientResponseException w && w.getStatusCode().is5xxServerError();
}
public static void main(String[] args) {
SpringApplication app = new SpringApplication(TimeoutsAndRetry.class);
app.setDefaultProperties(Map.of("server.port", "0",
"spring.main.banner-mode", "off", "logging.level.root", "OFF"));
try (var context = app.run(args)) {
String base = "http://localhost:"
+ context.getEnvironment().getProperty("local.server.port");
HttpClient netty = HttpClient.create().responseTimeout(Duration.ofMillis(500));
WebClient client = context.getBean(WebClient.Builder.class).baseUrl(base)
.clientConnector(new ReactorClientHttpConnector(netty))
.build();
// one call first, so that class loading and connection setup are not timed
client.get().uri("/fast").retrieve().bodyToMono(String.class).block();
System.out.println("1. Netty responseTimeout(500 ms) on a 2 s endpoint:");
long start = System.nanoTime();
try {
client.get().uri("/slow").retrieve().bodyToMono(String.class).block();
} catch (RuntimeException e) {
System.out.println(" " + e.getClass().getSimpleName() + " caused by "
+ rootCause(e).getClass().getSimpleName() + " after about "
+ elapsed(start) + " ms");
}
System.out.println("2. Reactor timeout(300 ms) on the whole call:");
start = System.nanoTime();
String fallback = client.get().uri("/slow").retrieve().bodyToMono(String.class)
.timeout(Duration.ofMillis(300))
.onErrorReturn("cached value")
.block();
System.out.println(" " + fallback + " after about " + elapsed(start) + " ms");
System.out.println("3. Retry 5xx with backoff:");
String body = client.get().uri("/flaky").retrieve().bodyToMono(String.class)
.retryWhen(Retry.backoff(3, Duration.ofMillis(100))
.filter(TimeoutsAndRetry::isRetryable))
.block();
System.out.println(" " + body);
System.out.println("4. The same retry on a 400 does not retry:");
try {
client.get().uri("/bad").retrieve().bodyToMono(String.class)
.retryWhen(Retry.backoff(3, Duration.ofMillis(100))
.filter(TimeoutsAndRetry::isRetryable))
.block();
} catch (WebClientResponseException e) {
System.out.println(" " + e.getStatusCode().value() + " " +
e.getResponseBodyAsString());
}
}
}
static Throwable rootCause(Throwable e) {
while (e.getCause() != null) {
e = e.getCause();
}
return e;
}
static long elapsed(long start) {
return Math.round((System.nanoTime() - start) / 1000000 / 100.0) * 100;
}
}
1. Netty responseTimeout(500 ms) on a 2 s endpoint:
WebClientRequestException caused by ReadTimeoutException after about 600 ms
2. Reactor timeout(300 ms) on the whole call:
cached value after about 300 ms
3. Retry 5xx with backoff:
[server] /flaky call 1
[server] /flaky call 2
[server] /flaky call 3
served on call 3
4. The same retry on a 400 does not retry:
[server] /bad call 1
400 invalid
- Reactor Netty's
gave up long before the endpoint’s 2 seconds, after the 500 ms timeout plus some scheduling delay, withresponseTimeout(500 ms) , caused by Netty'sWebClientRequestException . It is a request exception, not aReadTimeoutException , because no response arrived.WebClientResponseException - Reactor's
limits the wholetimeout(300 ms) , including connecting and decoding, and is set per call.Mono then supplied a fallback value. The first call of the program was a warm-up, so that class loading did not count against the timeouts.onErrorReturn resubscribed after each 503. The server saw three calls and the third succeeded. Retrying works here because each subscription to a WebClientretryWhen(Retry.backoff(3, 100 ms)) sends a new request.Mono- The filter allowed retries only for 5xx statuses, so the 400 was not retried: the server saw one call. Retrying a client error only repeats the same failure.
In Spring Boot 4.1, the connect and read timeouts of the clients Boot builds can also be set with spring.http.clients.connect-timeoutspring.http.clients.read-timeoutspring.http.reactiveclient.*
Filters: headers, authentication and logging
An ExchangeFilterFunctionAuthorizationX-Request-Id
package demo.filters;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.ExchangeFilterFunctions;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
@SpringBootApplication
public class ExchangeFilters {
@RestController
static class EchoApi {
@GetMapping("/whoami")
String whoami(@RequestHeader(HttpHeaders.AUTHORIZATION) String auth,
@RequestHeader(value = "X-Request-Id", required = false) String id) {
return "auth=" + auth + ", requestId=" + id;
}
}
// Adds a fresh request id to every call, like a tracing or correlation filter
static ExchangeFilterFunction requestId() {
AtomicInteger counter = new AtomicInteger();
return (request, next) -> next.exchange(ClientRequest.from(request)
.header("X-Request-Id", "req-" + counter.incrementAndGet())
.build());
}
static ExchangeFilterFunction logging() {
return ExchangeFilterFunction.ofRequestProcessor(request -> {
System.out.println(" -> " + request.method() + " " + request.url().getPath()
+ " headers " + request.headers().headerNames());
return Mono.just(request);
}).andThen(ExchangeFilterFunction.ofResponseProcessor(response -> {
System.out.println(" <- " + response.statusCode().value());
return Mono.just(response);
}));
}
public static void main(String[] args) {
SpringApplication app = new SpringApplication(ExchangeFilters.class);
app.setDefaultProperties(Map.of("server.port", "0",
"spring.main.banner-mode", "off", "logging.level.root", "WARN"));
try (var context = app.run(args)) {
String base = "http://localhost:"
+ context.getEnvironment().getProperty("local.server.port");
WebClient bearer = context.getBean(WebClient.Builder.class).baseUrl(base)
.filter(requestId())
.filter((request, next) -> next.exchange(ClientRequest.from(request)
.headers(h -> h.setBearerAuth("token-123")).build()))
.filter(logging())
.build();
System.out.println("Bearer client:");
System.out.println(" " + bearer.get().uri("/whoami").retrieve()
.bodyToMono(String.class).block());
System.out.println(" " + bearer.get().uri("/whoami").retrieve()
.bodyToMono(String.class).block());
WebClient basic = bearer.mutate()
.filters(list -> list.removeIf(f -> f != list.get(0)))
.filter(ExchangeFilterFunctions.basicAuthentication("ann", "pw"))
.build();
System.out.println("Mutated copy with basic auth instead:");
System.out.println(" " + basic.get().uri("/whoami").retrieve()
.bodyToMono(String.class).block());
}
}
}
Bearer client:
-> GET /whoami headers [X-Request-Id, Authorization]
<- 200
auth=Bearer token-123, requestId=req-1
-> GET /whoami headers [X-Request-Id, Authorization]
<- 200
auth=Bearer token-123, requestId=req-2
Mutated copy with basic auth instead:
auth=Basic YW5uOnB3, requestId=req-3
- The request-id filter added
with a new value per call:X-Request-Id , thenreq-1 .req-2 - The second filter set a bearer token, and the server received
.Bearer token-123 - The logging filter ran last, so it saw both headers already added. Filters run in the order they were registered, each wrapping the next.
copied the client. The copy kept only the first filter, replaced the bearer token withmutate() , and sentExchangeFilterFunctions.basicAuthentication , the Base64 form ofBasic YW5uOnB3 . The original client was not changed.ann:pw
For OAuth 2 tokens, Spring Security provides ServerOAuth2AuthorizedClientExchangeFilterFunction
Parallel calls with Mono.zip and flatMap
The main practical gain of WebClient is that independent calls can run at the same time without extra threads. Every endpoint of this backend takes 200 ms, and the server counts how many calls overlap:
package demo.parallel;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@SpringBootApplication
public class ParallelCalls {
static final AtomicInteger IN_FLIGHT = new AtomicInteger();
static final AtomicInteger PEAK = new AtomicInteger();
@RestController
static class Backend {
// every endpoint takes 200 ms; the server records how many calls overlap
@GetMapping("/{what}/{id}")
Mono<String> get(@PathVariable String what, @PathVariable int id) {
return Mono.fromRunnable(() -> PEAK.accumulateAndGet(IN_FLIGHT.incrementAndGet(),
Math::max))
.then(Mono.delay(Duration.ofMillis(200)))
.thenReturn(what + id)
.doFinally(s -> IN_FLIGHT.decrementAndGet());
}
}
public static void main(String[] args) {
SpringApplication app = new SpringApplication(ParallelCalls.class);
app.setDefaultProperties(Map.of("server.port", "0",
"spring.main.banner-mode", "off", "logging.level.root", "WARN"));
try (var context = app.run(args)) {
WebClient client = context.getBean(WebClient.Builder.class)
.baseUrl("http://localhost:"
+ context.getEnvironment().getProperty("local.server.port"))
.build();
fetch(client, "warmup", 0).block();
System.out.println("Rough comparison, best of 3 runs, 200 ms per call:");
long best = Long.MAX_VALUE;
for (int run = 0; run < 3; run++) {
long start = System.nanoTime();
fetch(client, "user", 1).block();
fetch(client, "orders", 1).block();
fetch(client, "prefs", 1).block();
best = Math.min(best, elapsed(start));
}
System.out.println(" three block() calls in a row: about " + best + " ms");
best = Long.MAX_VALUE;
String joined = "";
for (int run = 0; run < 3; run++) {
long start = System.nanoTime();
var page = Mono.zip(fetch(client, "user", 1), fetch(client, "orders", 1),
fetch(client, "prefs", 1)).block();
best = Math.min(best, elapsed(start));
joined = List.of(page.getT1(), page.getT2(), page.getT3()).toString();
}
System.out.println(" Mono.zip of the same three : about " + best + " ms, " + joined);
for (int concurrency : new int[] {20, 4}) {
best = Long.MAX_VALUE;
int results = 0;
PEAK.set(0);
for (int run = 0; run < 3; run++) {
long start = System.nanoTime();
results = Flux.range(1, 20)
.flatMap(id -> fetch(client, "item", id), concurrency)
.collectList().block().size();
best = Math.min(best, elapsed(start));
}
System.out.println(" 20 items, flatMap concurrency " + concurrency + ": "
+ results + " results in about " + best + " ms, "
+ (concurrency == 4 ? "at most " + PEAK.get() + " calls at once"
: "more than 4 calls at once: " + (PEAK.get() > 4)));
}
}
}
static Mono<String> fetch(WebClient client, String what, int id) {
return client.get().uri("/{what}/{id}", what, id).retrieve().bodyToMono(String.class);
}
static long elapsed(long start) {
return Math.round((System.nanoTime() - start) / 1000000 / 100.0) * 100;
}
}
Rough comparison, best of 3 runs, 200 ms per call:
three block() calls in a row: about 600 ms
Mono.zip of the same three : about 200 ms, [user1, orders1, prefs1]
20 items, flatMap concurrency 20: 20 results in about 500 ms, more than 4 calls at once: true
20 items, flatMap concurrency 4: 20 results in about 1100 ms, at most 4 calls at once
- Three calls with
one after another took about three times 200 ms, the sum of their latencies.block() of the same three calls subscribed to all of them at once and took about 200 ms, the latency of the slowest.Mono.zip- With
and a concurrency of 20, the 20 item calls overlapped. They finished in well under a second, instead of the 4 seconds that 20 sequential calls would take.flatMap - With a concurrency of 4, the server never saw more than 4 calls at once, and the 20 calls took about five rounds of 200 ms. This limit protects a downstream service that cannot take the full load.
These timings are a rough comparison, best of 3 runs on a 2-core Linux container, rounded to 100 ms. The ratios are what matter. Reactor Netty's default connection pool also caps parallel connections per host, at 16 or twice the number of CPU cores, whichever is larger, and queues the rest.
HTTP interface clients
For an API you call in many places, writing the same get().uri(...).retrieve()@HttpExchange
package demo.httpinterface;
import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.support.WebClientAdapter;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;
import org.springframework.web.service.annotation.PostExchange;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@SpringBootApplication
public class HttpInterfaceClient {
record Task(int id, String text, boolean done) { }
@RestController
static class TaskApi {
@GetMapping("/tasks")
List<Task> list(@RequestParam boolean done) {
return List.of(new Task(1, "write tests", true), new Task(2, "ship", false))
.stream().filter(t -> t.done() == done).toList();
}
@GetMapping("/tasks/{id}")
Task one(@PathVariable int id) {
return new Task(id, "write tests", true);
}
@PostMapping("/tasks")
Task add(@RequestBody Task task) {
return new Task(3, task.text(), false);
}
}
// The client is only an interface; Spring generates the implementation
@HttpExchange("/tasks")
interface TaskClient {
@GetExchange
Flux<Task> list(@RequestParam boolean done);
@GetExchange("/{id}")
Mono<Task> one(@PathVariable int id);
@GetExchange("/{id}")
Task oneBlocking(@PathVariable int id);
@PostExchange
Mono<Task> add(@RequestBody Task task);
}
public static void main(String[] args) {
SpringApplication app = new SpringApplication(HttpInterfaceClient.class);
app.setDefaultProperties(Map.of("server.port", "0",
"spring.main.banner-mode", "off", "logging.level.root", "WARN"));
try (var context = app.run(args)) {
WebClient webClient = context.getBean(WebClient.Builder.class)
.baseUrl("http://localhost:"
+ context.getEnvironment().getProperty("local.server.port"))
.build();
TaskClient tasks = HttpServiceProxyFactory
.builderFor(WebClientAdapter.create(webClient))
.build()
.createClient(TaskClient.class);
System.out.println("proxy class is generated: "
+ tasks.getClass().getSimpleName().startsWith("$Proxy"));
System.out.println("list(done=false): " + tasks.list(false).collectList().block());
System.out.println("one(1) : " + tasks.one(1).block());
System.out.println("oneBlocking(1) : " + tasks.oneBlocking(1));
System.out.println("add(...) : "
+ tasks.add(new Task(0, "celebrate", false)).block());
}
}
}
proxy class is generated: true
list(done=false): [Task[id=2, text=ship, done=false]]
one(1) : Task[id=1, text=write tests, done=true]
oneBlocking(1) : Task[id=1, text=write tests, done=true]
add(...) : Task[id=3, text=celebrate, done=false]
created a JDK dynamic proxy forHttpServiceProxyFactory ; no implementation class was written.TaskClient- Methods that return
orFlux stay non-blocking.Mono sentlist(false) and returned only the unfinished item.GET /tasks?done=false returns a plainoneBlocking . The proxy blocks for it, which is fine in a Spring MVC application but must not happen on an event loop.Task with@PostExchange sent the record as JSON.@RequestBody
The same interface works over RestClientRestClientAdapter@ImportHttpServicesspring.http.serviceclient.*
The 256 KB in-memory limit
To protect the application from huge responses, the codecs refuse to buffer more than 256 KB when they decode a body into one object. The limit catches many developers the first time a response grows. This report endpoint returns 300 KB:
package demo.buffer;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
@SpringBootApplication
public class BufferLimit {
@RestController
static class ReportApi {
@GetMapping("/report")
String report() {
return "x".repeat(300 * 1024); // a 300 KB response
}
}
public static void main(String[] args) {
SpringApplication app = new SpringApplication(BufferLimit.class);
app.setDefaultProperties(Map.of("server.port", "0",
"spring.main.banner-mode", "off", "logging.level.root", "OFF"));
try (var context = app.run(args)) {
String base = "http://localhost:"
+ context.getEnvironment().getProperty("local.server.port");
WebClient.Builder builder = context.getBean(WebClient.Builder.class).baseUrl(base);
System.out.println("1. Default codecs, bodyToMono(String) of 300 KB:");
try {
builder.build().get().uri("/report").retrieve()
.bodyToMono(String.class).block();
} catch (RuntimeException e) {
Throwable cause = e.getCause() != null ? e.getCause() : e;
System.out.println(" " + cause.getClass().getSimpleName() + ": "
+ cause.getMessage());
}
System.out.println("2. maxInMemorySize raised to 1 MB:");
String body = builder.clone()
.codecs(c -> c.defaultCodecs().maxInMemorySize(1024 * 1024))
.build().get().uri("/report").retrieve()
.bodyToMono(String.class).block();
System.out.println(" read " + body.length() / 1024 + " KB");
System.out.println("3. Streaming the body as DataBuffers, no limit applies:");
long bytes = builder.build().get().uri("/report").retrieve()
.bodyToFlux(DataBuffer.class)
.map(buffer -> {
int n = buffer.readableByteCount();
DataBufferUtils.release(buffer);
return (long) n;
})
.reduce(0L, Long::sum)
.block();
System.out.println(" streamed " + bytes / 1024 + " KB");
}
}
}
1. Default codecs, bodyToMono(String) of 300 KB:
DataBufferLimitException: Exceeded limit on max bytes to buffer : 262144
2. maxInMemorySize raised to 1 MB:
read 300 KB
3. Streaming the body as DataBuffers, no limit applies:
streamed 300 KB
- With the default codecs,
failed withbodyToMono(String.class) , which is 256 KB.DataBufferLimitException: Exceeded limit on max bytes to buffer : 262144 raised the limit to 1 MB for this client, and the same call read all 300 KB. In Spring Boot,codecs(c -> c.defaultCodecs().maxInMemorySize(1024 * 1024)) sets it for every client and server codec at once.spring.http.codecs.max-in-memory-size- Reading the body as a
streamed it in chunks, with no limit, because nothing had to hold the whole body. Each buffer must be released after use, asFlux<DataBuffer> does here.DataBufferUtils.release
The limit applies to aggregated bodies. A JSON array decoded with bodyToFlux
Choosing how to call HTTP services
| Situation | Use |
|---|---|
| WebFlux application, or any reactive pipeline | WebClient |
| Spring MVC application, simple blocking calls | RestClient |
| Spring MVC application with several independent calls per request | WebClientMono.zipblock()RestClient |
| An API you call from many places | An @HttpExchange |
| Streaming responses, SSE or NDJSON | WebClientbodyToFlux |
Existing code on RestTemplate | It still works, but Spring Boot 4.2 deprecates it: use RestClient |
Whatever the client, set a timeout on every call, retry only idempotent requests and only on transient errors, and decide explicitly what a 404 means. For the operators used here, such as zipflatMapretryWhen