What are RestClient, WebClient and OpenFeign, and how do they differ?

RestClient is Spring's synchronous HTTP client. Each call blocks the calling thread until the response arrives and returns a plain value such as Order or ResponseEntity<Order>. WebClient is non-blocking and returns Mono or Flux, so a thread can serve other work while the call is in flight. Both are imperative, fluent APIs.

OpenFeign and Spring's HTTP interfaces (methods annotated with @HttpExchange) are declarative. You write a Java interface and a proxy implements it. They are not separate transports. HTTP interfaces delegate to RestClient, WebClient or RestTemplate through an adapter. Feign is different: it uses its own feign.Client abstraction and does not go through RestClient at all.

Declarative contract   @HttpExchange interface           Feign interface
                              |                                |
High-level client      RestClient   |   WebClient          (Feign core)
                              |              |                 |
Adapter layer          ClientHttpRequestFactory |           feign.Client
                       ClientHttpConnector      |
                              |                                |
HTTP library           JDK HttpClient, Apache HttpComponents, Jetty, Reactor Netty

The declarative style is cosmetic compared with the execution model. That model decides your thread usage, return types and which Spring stack you pull in, so choose it first.

RestClient WebClient OpenFeign
Execution model Blocking Non-blocking Blocking by default
Return types Plain objects, ResponseEntity Mono, Flux Plain objects
Stack dependency spring-web spring-webflux Spring Cloud OpenFeign
Streaming / backpressure Stream reads, no backpressure Yes, via Reactive Streams Stream reads, no backpressure
Declarative support HTTP interfaces HTTP interfaces Native
Error handling onStatus, status handlers onStatus returning error signals ErrorDecoder
Testing MockRestServiceServer Stub HTTP server, StepVerifier Stub HTTP server
DECLARATIVE    +--------------------------+     +------------------+
CONTRACT       | @HttpExchange interface  |     | Feign interface  |
               +------------+-------------+     +--------+---------+
                            |  HttpServiceProxyFactory   |
                     +------+----------+                 |
                     v                 v                 v
HIGH-LEVEL    +--------------+  +--------------+  +--------------+
CLIENT        |  RestClient  |  |  WebClient   |  |  Feign core  |
              |   blocking   |  | non-blocking |  |   blocking   |
              | plain values |  |  Mono / Flux |  | plain values |
              +------+-------+  +------+-------+  +------+-------+
                     |                 |                 |
                     v                 v                 v
ADAPTER       +--------------+  +--------------+  +--------------+
LAYER         | ClientHttp-  |  | ClientHttp-  |  | feign.Client |
              | Request-     |  | Connector    |  |              |
              | Factory      |  |              |  |              |
              +------+-------+  +------+-------+  +------+-------+
                     |                 |                 |
                     v                 v                 v
HTTP          +----------------------------------------------------+
LIBRARY       | JDK HttpClient   Apache HttpComponents   Jetty     |
              | Reactor Netty    (each adapter supports a subset)  |
              +----------------------------------------------------+

An @HttpExchange interface is a proxy over RestClient or WebClient (RestTemplate is also supported), each of which reaches an HTTP library through its own adapter; Feign bypasses Spring's clients and uses its own feign.Client.

How does each client work under the hood?

All three clients follow the same path: build a request description, serialize the body, hand it to an HTTP library, then deserialize the response. They differ in who owns each step and when the request actually runs.

RestClient builds the request from the fluent chain, runs it through any registered ClientHttpRequestInterceptors, and executes it through a ClientHttpRequestFactory. The factory wraps a concrete HTTP library such as the JDK HttpClient, Apache HttpComponents, Jetty or Reactor Netty. Spring Boot picks a factory based on which of those libraries are on the classpath, unless you set one yourself. Bodies are written and read by HttpMessageConverters, for example the Jackson converter for JSON. The request runs on the calling thread, and retrieve() followed by body(...) returns only once the response has been read and converted.

WebClient assembles a reactive pipeline. Calling retrieve().bodyToMono(...) does not send anything. The request goes out only when something subscribes to the returned Mono or Flux, either your code or the WebFlux framework when it writes a response. Cross-cutting behaviour is added with ExchangeFilterFunctions, bodies are handled by reactive encoders and decoders, and I/O goes through a ClientHttpConnector, usually Reactor Netty's. Results arrive as signals on event-loop threads instead of return values on the caller's thread. Because nothing runs until subscription, subscribing twice sends the request twice.

HTTP interfaces are generated at startup. HttpServiceProxyFactory creates a JDK dynamic proxy for your interface. On each method call the proxy reads the @HttpExchange annotations and the method arguments (@PathVariable, @RequestParam, @RequestHeader, @RequestBody), builds a request description, and passes it to an adapter (RestClientAdapter, WebClientAdapter or RestTemplateAdapter). The adapter executes it with the underlying client. The method's return type decides how the result comes back: a plain object or ResponseEntity for blocking adapters, Mono or Flux for the WebClient adapter.

OpenFeign also builds a proxy, but with its own machinery. With Spring Cloud OpenFeign, @EnableFeignClients scans for @FeignClient interfaces and registers a proxy bean for each. A Contract parses the method annotations. Spring Cloud's contract understands Spring MVC annotations such as @GetMapping and @PathVariable. On each call Feign applies RequestInterceptors, serializes the body with an Encoder, executes the request through a feign.Client, and decodes the result with a Decoder. Non-2xx responses go to the ErrorDecoder. Each named client gets its own child application context, which is why Feign configuration is scoped per client.

Which HTTP client should a Spring Boot 3 service use by default?

For a servlet-stack service (Spring MVC, blocking I/O, one request per thread), use RestClient as the default, ideally behind a declarative HTTP interface. Callers then depend on a plain Java interface, while the client, base URL, interceptors and error handling stay in one configuration class.

Use WebClient only when the application is reactive end to end, meaning WebFlux controllers, reactive data access and no blocking calls on the request path. It also fits when you need what Reactor actually provides: Server-Sent Events, streaming large bodies without buffering them, or backpressure against a slow consumer.

The common middle ground, WebClient plus block() inside a servlet app, combines the costs of both models. You take on Reactor's operator semantics, harder-to-read stack traces and an extra dependency tree, but the request thread still waits for the response. In a WebFlux app the same call fails at runtime: Reactor refuses to block() on its non-blocking event-loop threads and throws an IllegalStateException, because a blocked event loop stalls every connection it serves.

Choose OpenFeign deliberately, typically in an existing Spring Cloud estate or where teams already publish shared Feign client libraries. In those cases, switching clients costs more than it gains.

For high fan-out, virtual threads remove much of the old reason to go reactive. When spring.threads.virtual.enabled is set, blocking RestClient calls park cheaply, so you can run many concurrent calls without reactive code. Throughput and memory still depend on your connection pool, payload sizes and downstream latency. Load-test your own workload before assuming RestClient matches WebClient.

Who should use each client?

  • RestClient (with or without HTTP interfaces) suits teams building Spring MVC services on Boot 3, teams moving off RestTemplate, and anyone who wants plain return values, linear stack traces and in-process tests with MockRestServiceServer. It is also the natural choice for services running on virtual threads, where blocking calls no longer tie up platform threads.
  • WebClient suits teams already running WebFlux end to end and fluent in Reactor, and services whose main job is streaming: proxying Server-Sent Events, relaying large bodies without buffering, or composing many concurrent calls with operators such as zip and flatMap while respecting backpressure.
  • OpenFeign suits organisations that already use Spring Cloud (service discovery, Spring Cloud LoadBalancer, per-client configuration properties) and teams that consume or publish shared Feign client libraries. For a new service with no such investment, HTTP interfaces give a similar declarative style without the extra dependency.
  • HTTP interfaces suit anyone who publishes a client for other teams or wants callers and tests to depend on a contract instead of a transport. Because the adapter is swappable, the same interface can move from RestClient to WebClient later without changing callers.

How do you implement RestClient behind a declarative HTTP interface?

Start by injecting the RestClient.Builder that Boot auto-configures rather than calling RestClient.create(). The static factory gives you a bare client. The injected builder already carries Boot's message converters, any RestClientCustomizer beans you have registered, and the observation hooks that feed metrics and tracing. Inject the builder into a configuration class, set a base URL and default headers, and call build(). Because the builder is a prototype-scoped bean, each client you build from it starts with a fresh copy and does not leak settings into other clients.

For one-off calls, the fluent chain is enough. Call get().uri(...) and then retrieve(). Use onStatus() to map status codes to your own exceptions, so a 404 from a downstream service becomes a domain-level "not found" instead of a generic client error. Finish with body(Type.class), or use toEntity() when you need headers.

For a stable contract, move to a declarative interface:

  1. Annotate the interface with @HttpExchange for the shared path prefix.
  2. Annotate each method with @GetExchange (or the matching variant for other verbs).
  3. Wrap the client with RestClientAdapter.create(restClient).
  4. Pass the adapter to HttpServiceProxyFactory.builderFor(adapter).build().
  5. Call createClient(YourApi.class) to get the proxy.

The interface has no dependency on the transport. WebClientAdapter and RestTemplateAdapter plug into the same factory, so callers and tests depend only on the contract.

Migrating from RestTemplate is mostly mechanical. RestClient.builder(restTemplate) reuses an existing template's request factory, interceptors and converters, so you can convert call sites one at a time. If a reactive stack later becomes justified, inject WebClient.Builder, switch to WebClientAdapter, and change the method return types to Mono or Flux.

@HttpExchange("/api/orders")
interface OrderApi {
    @GetExchange("/{id}")
    Order getOrder(@PathVariable String id);
}

record Order(String id, String status) {}

class OrderNotFoundException extends RuntimeException {
    OrderNotFoundException(String msg) { super(msg); }
}

@Configuration
class OrderClientConfig {

    // Inject Boot's prototype-scoped builder: it carries converters, customizers and observation hooks
    @Bean
    RestClient orderRestClient(RestClient.Builder builder) {
        return builder
            .baseUrl("")
            .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
            // Map a downstream 404 to a domain exception for every call, including proxy calls
            .defaultStatusHandler(status -> status.value() == 404,
                (request, response) -> { throw new OrderNotFoundException("Order not found: " + request.getURI()); })
            .build();
    }

    // The contract stays transport-agnostic; swap in WebClientAdapter or RestTemplateAdapter here
    @Bean
    OrderApi orderApi(RestClient orderRestClient) {
        HttpServiceProxyFactory factory = HttpServiceProxyFactory
            .builderFor(RestClientAdapter.create(orderRestClient))
            .build();
        return factory.createClient(OrderApi.class);
    }
}

// One-off fluent call: retrieve(), per-request onStatus(), then body conversion
// Order order = orderRestClient.get().uri("/api/orders/{id}", "ord-123").retrieve()
//     .onStatus(HttpStatusCode::is5xxServerError, (req, res) -> { throw new IllegalStateException("Orders service unavailable"); })
//     .body(Order.class);

A RestClient built from Boot's injected RestClient.Builder backs an @HttpExchange interface through RestClientAdapter and HttpServiceProxyFactory, with a 404 mapped to a domain exception and a one-off fluent call shown for comparison.

Where do you configure timeouts, connection pools and load balancing?

Timeouts and pool limits live on the transport underneath the client, not on the client's fluent API. The underlying library also sets the defaults, and some are long or unbounded. A plain JDK HttpURLConnection, for example, waits indefinitely unless you set a timeout. Leaving these unset means one slow downstream can hold threads and connections without limit.

Where each client takes its settings

  • RestClient: pass a ClientHttpRequestFactory to RestClient.builder().requestFactory(...). SimpleClientHttpRequestFactory exposes setConnectTimeout and setReadTimeout. For pooling, use HttpComponentsClientHttpRequestFactory backed by Apache HttpClient's PoolingHttpClientConnectionManager, where you set total and per-route limits.
  • WebClient: build a Reactor Netty HttpClient and wrap it in ReactorClientHttpConnector. Set the connect timeout with ChannelOption.CONNECT_TIMEOUT_MILLIS and the response timeout with responseTimeout(Duration). Pool limits go on a ConnectionProvider.
  • OpenFeign: connect and read timeouts go in Request.Options, either declared as a bean or set through per-client configuration properties. Pooling depends on which Feign client implementation you plug in.

Pools under virtual threads

Virtual threads remove the thread-count ceiling, so the connection pool becomes the real throttle. Size the pool from the traffic you expect, and set a timeout for acquiring a connection so callers fail fast instead of queuing.

Illustrative estimate (assumed numbers, not a benchmark): connections needed ≈ request rate × average latency. At an assumed 400 req/s and 150 ms, that is 400 × 0.15 = 60 connections per route.

Load balancing

When Spring Cloud LoadBalancer is on the classpath, Feign clients declared by service name are load-balanced automatically. To get the same behavior from RestClient or WebClient, annotate the RestClient.Builder or WebClient.Builder bean with @LoadBalanced. Miss this during a migration off Feign and calls to a service-name base URL fail DNS resolution.

@Configuration
class HttpClientConfig {

    // RestClient: timeouts live on the request factory, not the fluent API.
    // @LoadBalanced lets "" resolve via Spring Cloud LoadBalancer.
    @Bean
    @LoadBalanced
    RestClient.Builder restClientBuilder() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(2_000); // ms; the JDK default waits indefinitely
        factory.setReadTimeout(5_000);    // ms
        return RestClient.builder().requestFactory(factory);
    }

    // WebClient: timeouts and pool limits live on the Reactor Netty connector.
    @Bean
    @LoadBalanced
    WebClient.Builder webClientBuilder() {
        ConnectionProvider pool = ConnectionProvider.builder("inventory-pool")
                .maxConnections(60)                          // the real throttle under virtual threads
                .pendingAcquireTimeout(Duration.ofSeconds(2)) // fail fast instead of queuing
                .build();
        HttpClient httpClient = HttpClient.create(pool)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2_000)
                .responseTimeout(Duration.ofSeconds(5));
        return WebClient.builder().clientConnector(new ReactorClientHttpConnector(httpClient));
    }

    // OpenFeign: connect/read timeouts go in Request.Options
    // (connect, unit, read, unit, followRedirects).
    @Bean
    Request.Options feignOptions() {
        return new Request.Options(2, TimeUnit.SECONDS, 5, TimeUnit.SECONDS, true);
    }
}

Connect and read/response timeouts set on RestClient's request factory, WebClient's Reactor Netty connector with a bounded connection pool, and Feign's Request.Options, with both builders marked @LoadBalanced so service-name URLs resolve the way Feign clients do.

How should you handle errors and test each client?

Pick one mapping from upstream status codes to domain exceptions and apply it everywhere, whichever client sends the request. The mechanisms differ by client. With RestClient, retrieve() throws HttpClientErrorException or HttpServerErrorException for 4xx and 5xx by default, and onStatus lets you replace those with your own exceptions. WebClient works the same way, except its onStatus handler returns a Mono that emits the exception. Feign sends every non-2xx response through an ErrorDecoder, and the default decoder throws FeignException. An HTTP interface has no error handling of its own: it behaves like the RestClient or WebClient adapter behind it.

Here is a mapping that works for most services:

  • 404 becomes ResourceNotFoundException.
  • 409 becomes ConflictException.
  • Any other 4xx becomes UpstreamRejectedException, which is never retried.
  • 5xx becomes UpstreamUnavailableException, which is retryable.

Callers then branch on what the failure means for the business, and your retry and circuit-breaker rules can match on two exception types instead of status codes spread across the codebase. Put the mapping in one shared default status handler or ErrorDecoder so that individual call sites don't need to repeat it.

Client Error mechanism Usual test approach
RestClient onStatus, status-based exceptions MockRestServiceServer bound to the builder
WebClient onStatus returning Mono<Throwable> Local stub HTTP server
OpenFeign ErrorDecoder Local stub HTTP server, or mock the interface
HTTP interface Inherited from the backing client Same as the backing client, or mock the interface

MockRestServiceServer runs in-process and checks the outgoing request directly, so RestClient tests are fast. Tests for the other clients go through a real socket, which costs more time but also covers serialization and timeouts. If a test only needs the client's return value, mocking the interface is enough.

// One status-to-exception mapping, shared by RestClient (and any HTTP interface it backs) and Feign.
// The four exception types are plain RuntimeExceptions defined in your domain module.
public final class UpstreamErrors {
    private UpstreamErrors() {}

    public static RuntimeException map(int status, String detail) {
        return switch (status) {
            case 404 -> new ResourceNotFoundException(detail);
            case 409 -> new ConflictException(detail);
            // 5xx is retryable; any other 4xx is a permanent rejection and is never retried.
            default -> status >= 500
                    ? new UpstreamUnavailableException(detail)
                    : new UpstreamRejectedException(detail);
        };
    }
}

@Configuration
class InventoryClientConfig {
    @Bean
    RestClient inventoryRestClient(RestClient.Builder builder) {
        return builder
                .baseUrl("")
                // Default handler applies to every call, so call sites don't repeat onStatus.
                .defaultStatusHandler(HttpStatusCode::isError, (request, response) -> {
                    throw UpstreamErrors.map(response.getStatusCode().value(),
                            request.getMethod() + " " + request.getURI());
                })
                .build();
    }
}

// Feign routes every non-2xx response here instead of throwing FeignException.
class MappingErrorDecoder implements feign.codec.ErrorDecoder {
    @Override
    public Exception decode(String methodKey, feign.Response response) {
        return UpstreamErrors.map(response.status(), methodKey);
    }
}

A single status-to-domain-exception mapping, registered once as a RestClient default status handler and once as a Feign ErrorDecoder, so every client throws the same four exception types.

When should you avoid RestClient, WebClient or OpenFeign?

RestClient

RestClient blocks a thread for each call and has no backpressure model. That makes it a poor fit for server-sent events, long streams, or a reactive pipeline where a blocked thread stalls the event loop. You can read a stream from it, but you lose flow control, and slow producers hold threads open.

WebClient

WebClient costs you debuggability. Stack traces point into Reactor operators instead of your code. Thread-local state such as MDC and tracing context does not follow the chain unless you configure context propagation. Two Reactor bugs are common. Subscribing twice sends the request twice. An onErrorResume that is too broad silently swallows failures.

Mixed stacks

If both spring-web and spring-webflux are on the classpath, Spring Boot runs Spring MVC. If an app adds only webflux to get WebClient, it can start a reactive server unintentionally. Calling block() inside a reactive handler ties up event-loop threads and can deadlock under load.

OpenFeign

OpenFeign adds its own dependency and configuration model on top of Spring's. Check its current maintenance status before you adopt it for a new service.

Declarative clients in general

Declarative clients handle per-call customization, dynamic headers and partial response handling awkwardly. HTTP interfaces have no built-in fallback or circuit breaker. If you add retries, limit them to idempotent requests. Retrying a POST blindly can charge a customer twice.

Virtual threads

Virtual threads make blocking clients cheap, but they introduce two risks. On JDKs where synchronized pins the carrier thread, blocking I/O inside a synchronized block can exhaust carriers. Unbounded concurrency can also overwhelm downstream services, so cap concurrent calls explicitly, for example with a semaphore or bulkhead.

What are the alternatives to these three clients?

  • RestTemplate. Still part of Spring Framework and still works in Boot 3, but it is in maintenance mode: it receives fixes, not new features. Its template-method API (getForObject, exchange) has many overloads, and RestClient was introduced to replace it with a fluent API over the same request factories, interceptors and converters. Keep it in existing code until you migrate; don't pick it for new code. RestTemplateAdapter lets you put an HTTP interface in front of it in the meantime.
  • The JDK java.net.http.HttpClient used directly. No Spring dependency, supports HTTP/2 and offers both blocking send and CompletableFuture-based sendAsync. You give up Spring's message converters, observation hooks, status handlers and MockRestServiceServer, so you write serialization, error mapping and instrumentation yourself. It makes sense in small libraries that must not depend on Spring. In a Spring app it is usually better to use it as RestClient's transport through its request factory.
  • Apache HttpComponents, Jetty client or Reactor Netty used directly. These give full control over connection management, TLS and protocol details. The same trade-off applies: you lose Spring's conversion, error handling and observability. The usual pattern is to configure the library and plug it in underneath RestClient or WebClient, as in the timeout section above.
  • Generated clients from an API specification. If the downstream service publishes an OpenAPI description, a code generator can produce the client interface and model classes. Many generators can target Spring's HTTP clients, so the generated code sits on the same transports described here. This removes hand-written contracts but adds a build step, and the generated code is only as good as the specification.
  • Not using HTTP at all. For high-volume internal calls or event-driven flows, gRPC or a message broker may fit better than any HTTP client. That is an architectural decision, not a client choice, and it is outside the scope of this article.

How does your HTTP client choice affect development cost and engineering time?

Most of the cost of an HTTP client comes from how many patterns a team must learn, debug and test, not from writing the call itself. If RestClient plus HTTP interfaces is the default, a new engineer learns one declaration style, one way to stub responses (MockRestServiceServer bound to the builder) and one place where metrics and tracing are attached. That place is the auto-configured builder. Reactive stack traces and scheduler issues stop appearing in services that never needed them.

Factor RestClient + HTTP interface WebClient OpenFeign
Onboarding Imperative and familiar Requires reactive fluency Familiar, but needs a separate config model
Debugging Linear stack traces Async traces, operator chains Linear, extra proxy layer
Swapping transport Change the adapter, keep the interface Rewrite call sites Rewrite interfaces

Illustrative estimate (assumed numbers, not a benchmark): annual saving = engineers × incidents per engineer × hours saved per incident. With an assumed 10 × 2 × 3, that is 60 hours. Subtract the hours spent rewriting streaming services or shared Feign libraries. If the result is negative, don't force the migration.

Decision checklist:

  • Do you need streaming or backpressure? Use WebClient.
  • Do other teams consume a shared Feign client library? Keep Feign until the owners migrate.
  • Anything else: use RestClient behind an HTTP interface.

Migration path: start by injecting the Boot-managed RestClient.Builder so that observability carries over. Next, replace RestTemplate call sites one client at a time and move the error handling into status handlers. Then rewrite each Feign interface as an HTTP interface and keep the existing contract tests running against it.

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 .env by 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.