What are RestClient and WebClient, and where does each one sit in Spring?
RestClient is a synchronous HTTP client with a fluent, chained API. It lives in spring-web, the same module as RestTemplate, and reuses that client's infrastructure: HttpMessageConverters for serialization, ClientHttpRequestFactory for the transport, and ClientHttpRequestInterceptors for cross-cutting concerns. You can build one from an existing RestTemplate and keep its converters and interceptors. Spring presents it as the modern successor to RestTemplate's template-method API, and the calling thread still blocks until the response arrives.
WebClient is a non-blocking client built on Project Reactor. It returns Mono and Flux, and it ships in spring-webflux. Adding the WebFlux starter to a servlet application puts Reactor and, by default, Reactor Netty on the classpath, even if you only want the client. It has no relationship to RestTemplate's infrastructure. It uses codecs instead of message converters and ExchangeFilterFunctions instead of interceptors.
Neither client opens sockets itself. Both delegate to an underlying library, such as the JDK HttpClient, Apache HttpClient, Jetty or Reactor Netty. Each library has its own defaults for connect and read timeouts, pool sizing and idle eviction. Those defaults, not Spring's, determine how the client behaves under load unless you override them.
| Aspect | RestClient | WebClient |
|---|---|---|
| Execution model | Blocking, thread-per-request | Non-blocking, event loop |
| Return types | Plain objects, ResponseEntity<T> |
Mono<T>, Flux<T> |
| Module / dependencies | spring-web only |
spring-webflux, Reactor, usually Reactor Netty |
| Extension points | ClientHttpRequestInterceptor |
ExchangeFilterFunction |
| Streaming | InputStream-based, blocking |
Flux with backpressure |
| Typical use | Servlet apps, imperative code | WebFlux apps, high fan-out, streaming |
+-------------------------------+ +-------------------------------+
| spring-web | | spring-webflux |
| +-------------------------+ | | +-------------------------+ |
| | RestTemplate | | | | WebClient, non-blocking | |
| +-----------+-------------+ | | | returns Mono<T>/Flux<T> | |
| | shares infra | | +-----------+-------------+ |
| v | | v |
| +-------------------------+ | | +-------------------------+ |
| | RestClient (blocking) | | | | ExchangeFilterFunction | |
| | returns T, ResponseEnt. | | | | codecs | |
| +-----------+-------------+ | | +-----------+-------------+ |
| v | | v |
| +-------------------------+ | | +-------------------------+ |
| | ClientHttpRequest- | | | | ClientHttpConnector | |
| | Interceptor | | | | Reactor event loop | |
| | HttpMessageConverter | | | +-----------+-------------+ |
| | ClientHttpRequest- | | | | |
| | Factory | | | | |
| +-----------+-------------+ | | | |
| | | | | |
+--------------+----------------+ +--------------+----------------+
v v
+-------------------------------------------------------------------+
| Underlying HTTP library (does the actual socket I/O) |
| JDK HttpClient, Apache HttpClient, Jetty, Reactor Netty |
| Its own defaults: connect/read timeouts, pool size, idle eviction |
+-------------------------------------------------------------------+
RestClient reuses RestTemplate's spring-web infrastructure while WebClient uses its own reactive filter, codec and connector stack in spring-webflux, and both delegate to an underlying HTTP library whose defaults govern timeouts and pooling.
Why is the execution model, not the API style, the real decision?
Put the two versions of the same call next to each other and the code looks almost identical. Both fetch an order by ID, map a 404 to a domain exception, and treat any 5xx as a retryable upstream failure. RestClient chains get(), uri(), retrieve() and onStatus(...), then calls body(Order.class). WebClient uses the same verbs, ends in bodyToMono(Order.class), and then calls block() because the calling code runs on a servlet request thread and needs a value. The visible difference is one method call. The difference in how the code runs is much larger.
The block() version is still blocking. The Tomcat thread waits until the response arrives, just as it does with RestClient. You get none of the throughput benefit of non-blocking I/O, and you take on several costs:
- Reactor on the classpath. Your MVC service now depends on a reactive runtime, and the Netty connector or another reactive HTTP connector comes with it.
- Harder stack traces. An exception raised in
onStatussurfaces through Reactor's operator chain instead of your controller's call stack. Readable traces need checkpoints or debug hooks. - Broken context propagation. The response is processed on a Netty event-loop thread, not on the thread that made the call. Anything stored in a
ThreadLocalis missing there: the logging MDC, Spring Security'sSecurityContextHolder, and tracing context. Error-mapping code that logs a request ID or reads the current principal fails silently unless you set up context propagation explicitly.
So the choice is not about which API you prefer. It is about whether your request path is reactive from end to end. For Spring MVC services, which run on a thread per request, it is not, and RestClient is the right default.
// Same call, two clients. Order, OrderNotFoundException and
// UpstreamUnavailableException are placeholder domain types.
// RestClient: blocking by design, runs on the calling Tomcat thread.
Order fetchWithRestClient(String id) {
return restClient.get()
.uri("/orders/{id}", id)
.retrieve()
// Map 404 to a domain exception.
.onStatus(status -> status.value() == 404,
(request, response) -> { throw new OrderNotFoundException(id); })
// Treat any 5xx as a retryable upstream failure.
.onStatus(HttpStatusCode::is5xxServerError,
(request, response) -> {
throw new UpstreamUnavailableException(response.getStatusCode());
})
.body(Order.class);
}
// WebClient + block(): same verbs, same blocking on the Tomcat thread,
// plus Reactor on the classpath and a reactive connector underneath.
Order fetchWithWebClient(String id) {
return webClient.get()
.uri("/orders/{id}", id)
.retrieve()
// These lambdas may run on a connector event-loop thread, so
// ThreadLocal state (MDC, SecurityContextHolder, trace context)
// can be missing here unless context propagation is configured.
.onStatus(status -> status.value() == 404,
response -> Mono.error(new OrderNotFoundException(id)))
.onStatus(HttpStatusCode::is5xxServerError,
response -> Mono.error(
new UpstreamUnavailableException(response.statusCode())))
.bodyToMono(Order.class)
// The request thread waits here, just as it does with RestClient.
.block();
}
The same GET with 404 and 5xx handling in RestClient and in WebClient with block(): the code differs by one call, but both block the servlet thread, and only the WebClient version adds Reactor and thread-hopping error handlers.
How do you configure a shared client with timeouts and connection pools?
Whichever client you pick, build it once and inject it. Spring Boot exposes an auto-configured RestClient.Builder and WebClient.Builder that already carry the observation instrumentation, message converters or codecs, and any customizers your platform registers. If you call RestClient.create() or WebClient.create() at a call site, you bypass all of that. You lose traces and metrics, and serialization can diverge from the rest of the service. Define one bean per downstream service from the injected builder. Set the base URL, default headers and authentication there, so call sites only describe the request.
Timeouts do not belong on the fluent API. They belong one layer down. For RestClient, that layer is the ClientHttpRequestFactory and the HTTP library it wraps, such as the JDK HttpClient, Apache HttpComponents or Reactor Netty. For WebClient, it is the ClientHttpConnector, typically a Reactor Netty HttpClient with its ConnectionProvider.
Set four values explicitly:
- Connect timeout
- Read or response timeout
- Maximum pool size
- Pool acquisition timeout
Library defaults are tuned for general use, and some are unbounded. One slow dependency can then hold threads or connections indefinitely, and the failure cascades upstream.
Treat the request factory or connector as a behavioral dependency, not a detail. Swapping it can silently change:
- timeout semantics
- whether connections are pooled and reused
- whether HTTP/2 is negotiated
Configure these settings in code. Cover them with a test that points the client at a deliberately slow stub and asserts that the call fails within the expected time.
Publishing these configured builders as a shared platform module saves engineering time in a mixed RestTemplate, RestClient and WebClient estate. Each team stops rediscovering safe settings, and drift between services shrinks.
// Imports omitted: Spring Web, Apache HttpClient 5 (hc.client5/hc.core5), Reactor Netty, Netty ChannelOption
@Configuration
class DownstreamClients {
// Inject Boot's builder so observation, converters and platform customizers are kept
@Bean
RestClient inventoryClient(RestClient.Builder builder) {
var pool = PoolingHttpClientConnectionManagerBuilder.create()
.setMaxConnTotal(50).setMaxConnPerRoute(50) // bounded pool size
.setDefaultConnectionConfig(ConnectionConfig.custom()
.setConnectTimeout(Timeout.ofSeconds(2)) // connect timeout
.setSocketTimeout(Timeout.ofSeconds(5)).build())
.build();
var http = HttpClients.custom().setConnectionManager(pool)
.setDefaultRequestConfig(RequestConfig.custom()
.setConnectionRequestTimeout(Timeout.ofMillis(500)) // pool acquisition timeout
.setResponseTimeout(Timeout.ofSeconds(5)).build()) // response timeout
.build();
return builder
.requestFactory(new HttpComponentsClientHttpRequestFactory(http)) // explicit, not auto-detected
.baseUrl("")
.defaultHeader("X-Caller", "orders-service")
.build();
}
@Bean
WebClient pricingClient(WebClient.Builder builder) {
var pool = ConnectionProvider.builder("pricing")
.maxConnections(50) // bounded pool size
.pendingAcquireTimeout(Duration.ofMillis(500)) // pool acquisition timeout
.build();
var http = HttpClient.create(pool)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000) // connect timeout
.responseTimeout(Duration.ofSeconds(5)); // response timeout
return builder
.clientConnector(new ReactorClientHttpConnector(http)) // explicit connector
.baseUrl("")
.build();
}
}
Defines one RestClient bean and one WebClient bean from the Spring Boot-provided builders, and sets connect timeout, response timeout, pool size and pool acquisition timeout explicitly on the underlying Apache HttpClient 5 and Reactor Netty clients.
How does error handling differ between RestClient and WebClient?
Error handling is where the two clients diverge most in practice, because the exception model follows the execution model.
With RestClient, retrieve() throws by default when it sees a 4xx or 5xx response: HttpClientErrorException or HttpServerErrorException, both subtypes of RestClientResponseException. An onStatus handler replaces that default for the statuses its predicate matches. The handler receives the request and the response, so you can read the error body and throw a domain exception such as PaymentDeclinedException. That exception surfaces at the call site, where a normal try/catch or a controller advice can handle it.
WebClient's onStatus handler returns a Mono<Throwable>, not a thrown exception. The client turns that throwable into an error signal that travels down the pipeline. You then reshape it with operators such as onErrorMap and onErrorResume. Mapping the body is itself asynchronous, because the error payload arrives as a publisher you have to transform. If nothing subscribes, the request never runs. If a fire-and-forget subscribe() has no error consumer, the failure only reaches the logs.
| Aspect | RestClient | WebClient |
|---|---|---|
| Default on 4xx/5xx | Throws RestClientResponseException subtype |
Emits WebClientResponseException as error signal |
| Domain mapping | Throw from onStatus handler |
Return Mono<Throwable> from onStatus |
| Where it surfaces | Call site | Downstream operators or subscriber |
| Failure if ignored | Propagates up the stack | Can be dropped silently |
Neither client handles resilience for you. Reactor's retry(n) resubscribes immediately with no delay, so attaching it to a non-idempotent POST can duplicate side effects. If thousands of callers retry the same failing dependency in lockstep, a short outage becomes a retry storm. Blocking code needs a resilience library or hand-written retry logic, and that logic has the same pitfalls: retry only idempotent calls, use backoff with jitter, and cap the total number of attempts.
// RestClient: the handler throws, and the exception surfaces at the call site.
Payment fetchBlocking(RestClient client, String id) {
return client.get().uri("/payments/{id}", id)
.retrieve()
.onStatus(HttpStatusCode::is4xxClientError, (request, response) -> {
// Read the error body synchronously and throw a domain exception
String body = new String(response.getBody().readAllBytes(), StandardCharsets.UTF_8);
throw new PaymentDeclinedException(body);
})
.body(Payment.class); // 5xx still throws HttpServerErrorException by default
}
// WebClient: the handler returns Mono<Throwable>, which becomes an error signal.
Mono<Payment> fetchReactive(WebClient client, String id) {
return client.get().uri("/payments/{id}", id)
.retrieve()
.onStatus(HttpStatusCode::is4xxClientError, response ->
response.bodyToMono(String.class)
.defaultIfEmpty("") // an empty Mono here would suppress the error
.map(PaymentDeclinedException::new))
.bodyToMono(Payment.class)
// Retry only this idempotent GET, only on 5xx, with backoff and jitter
.retryWhen(Retry.backoff(3, Duration.ofMillis(200))
.jitter(0.5)
.filter(ex -> ex instanceof WebClientResponseException wce
&& wce.getStatusCode().is5xxServerError()));
}
// Nothing runs until something subscribes, and the error must be handled there.
void caller(WebClient client) {
fetchReactive(client, "pay_123")
.subscribe(
payment -> log.info("paid {}", payment),
error -> log.warn("payment lookup failed", error)); // without this, the failure only reaches the logs
}
Both clients map a 4xx error body into a PaymentDeclinedException. RestClient throws it at the call site, while WebClient emits it as an error signal that a subscriber must handle, and the WebClient call retries only 5xx failures on an idempotent GET with jittered backoff.
Can HTTP interfaces make the transport choice swappable?
An HTTP interface is a plain Java interface whose methods describe requests. You annotate methods with @GetExchange, @PostExchange, @PutExchange or @DeleteExchange, and bind parameters with @PathVariable, @RequestParam, @RequestHeader and @RequestBody. A shared @HttpExchange on the type sets a common path prefix. HttpServiceProxyFactory then builds an implementation at runtime from an adapter. RestClientAdapter wraps a RestClient, and WebClientAdapter wraps a WebClient. The timeouts, pools and status handlers you configured on that client carry over unchanged.
The time saved is real. You no longer write a hand-rolled wrapper class per downstream service, with URI building, body conversion and response extraction repeated in every method. Each endpoint becomes one annotated signature, which is easy to review and to stub in tests.
Portability stops at the return type. A method returning Order blocks the caller. A method returning Mono<Order> returns immediately and does nothing until it is subscribed. Moving from one adapter to the other therefore means changing the signatures and every call site, not just the wiring.
The proxy also hides the request. A per-call header works if you add a @RequestHeader parameter, but that leaks transport concerns into the interface. A timeout on one request has no clean place to go. Error mapping that needs the request URI or body is also harder, because only the underlying client's status handlers can see those details.
Use HTTP interfaces for many uniform endpoints. Use the client directly for the few calls that need special handling.
When does WebClient earn its place, and when should you avoid it?
WebClient justifies its cost when the non-blocking model is doing real work:
- Reactive end-to-end WebFlux applications. On a small, shared event-loop pool, a blocking client call would stall every request scheduled on that thread.
- High fan-out. Many concurrent downstream calls can be in flight without a dedicated thread waiting on each one.
- Streaming. Server-sent events, or large bodies consumed incrementally as a
Flux, avoid buffering the whole payload in memory. - Backpressure-aware pipelines. A slow consumer can throttle the producer instead of letting data queue without bound.
Avoid WebClient in blocking Spring MVC applications that adopt it only for the fluent API. Calling block() on every request gives you RestClient's semantics plus a Reactor dependency and fragmented stack traces. RestClient already offers the same fluent style. Also avoid it for teams unfamiliar with Reactor. Count the learning curve, review effort and on-call debugging as development cost, not just the code you write.
The common failure modes are silent and often appear only under load:
- Blocking on event-loop threads. JDBC calls or
block()on an event loop starve unrelated requests. - Forgetting to subscribe. The request is assembled but never sent, and nothing reports an error.
- Unbounded
flatMapconcurrency. It can flood a downstream service or exhaust the connection pool. - Swallowed errors. Broad fallbacks or fire-and-forget
subscribe()calls without an error handler hide failures.
| Scenario | Recommended client |
|---|---|
| Spring MVC, request/response calls | RestClient |
| MVC on virtual threads with moderate fan-out | RestClient |
| WebFlux, reactive end to end | WebClient |
| Large fan-out with bounded concurrency | WebClient |
| SSE or streamed large bodies | WebClient |
| Team new to Reactor, no streaming needs | RestClient |
How do virtual threads change the RestClient vs WebClient choice?
The table assumes that each blocked call holds an expensive platform thread. On Java versions with virtual threads, that assumption no longer holds. When a RestClient call blocks on a socket read, the JVM parks the virtual thread and frees its carrier thread for other work. You can therefore write fan-out as plain imperative code: submit each downstream call to an executor that starts one virtual thread per task, then wait for the results in order. You get no Mono, no operator chains, and stack traces stay readable.
Compare the same code on platform threads. Suppose a handler fans out to ten downstream calls and runs them on the servlet request pool or a shared unbounded pool. A moderate burst of traffic can then occupy every worker thread while the CPU sits idle, and new requests queue behind them. The usual fix is a separate, carefully sized executor, which you then have to tune and monitor.
Illustrative estimate. Assume 100 incoming requests per second. Each one fans out to 10 calls, and each call takes 100 ms. That gives about 100 concurrent in-flight calls (100 × 10 × 0.1 s). Virtual threads handle this trivially. A platform pool of 200 threads that also serves inbound requests will be under real pressure.
Some caveats still apply:
- Pinning: On some JDK versions, blocking inside
synchronizedblocks pins the carrier thread. Native code paths also pin it. - Connection pools: The bottleneck moves to the HTTP client's pool size, so calls wait for a connection instead of a thread.
- Rate limits: Downstream quotas do not grow because your threads got cheaper.
- Explicit bounds: Cap concurrency yourself, for example with a semaphore around each call. Virtual threads will not limit it for you.
How do you migrate from RestTemplate and test both clients?
RestTemplate is in maintenance mode and receives no new features, so RestClient is the natural successor for blocking code. Because both share the same underlying abstractions, you can migrate mechanically rather than redesign.
Start from the configuration you already trust
RestClient.builder(restTemplate) creates a builder from an existing RestTemplate. It reuses the request factory, message converters and interceptors. You keep the connection pool sizing, timeouts and auth or tracing interceptors that production has already validated, and you don't re-derive them under pressure. Use the shared RestTemplate bean as the source, adjust the builder where needed, and expose the RestClient as its own bean.
Migrate behind service boundaries
Don't swap clients across the codebase in one change. Your service classes already hide HTTP from callers, so convert one method at a time inside them. Each change is small and reviewable, a regression points to a single call site, and both clients can run against the same connection pool during the transition. Tests at the service boundary stay unchanged and act as the safety net.
Test the failure paths
MockRestServiceServer can bind to a RestClient.Builder, which works well for fast tests of request shape and response mapping. It replaces the request factory, though, so it cannot show whether your timeouts actually fire. For that, run a local mock HTTP server that works with either client, and script these cases against it:
- A response slower than the read timeout.
- A refused connection.
- A dropped connection.
- 4xx and 5xx responses, checked against your exception mapping.
These tests confirm that the request factory defaults behave the way you configured them.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to spring restclient vs webclient, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.