Tech Interview RoomStudy guides

Spring Microservices

Call another microservice reliably. Compare RestTemplate, WebClient, RestClient and declarative HTTP interfaces with Resilience4j.

Advanced · 2 min read · Lesson 3 of 5 in Spring Microservices

Problem

The Order Service must call the Inventory Service (GET /inventory/{sku}) with timeouts, error mapping, propagation of the caller's token, retries for transient failures and a circuit breaker with a fallback.

Caller
Order Service (InventoryGateway)
↓1. circuit breaker + retry
Client
RestClient or HTTP interface proxy (timeoutstoken interceptor)
↓2. GET /inventory/{sku} with Bearer token
Callee
Inventory Service
↓fallback when open or failing
Fallback
⚡ Last known availability
java
record Availability(String sku, int available, boolean known) {
    static Availability unknown(String sku) { return new Availability(sku, 0, false); }
}

class InventoryUnavailableException extends RuntimeException {
    InventoryUnavailableException(String message) { super(message); }
}

Approach 1: RestTemplate (classic, in maintenance mode)

Blocking and still common in older services; configure timeouts explicitly (the default is to wait forever).

java
import java.time.Duration;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.web.client.RestTemplate;

class InventoryRestTemplateClient {
    private final RestTemplate restTemplate;

    InventoryRestTemplateClient(RestTemplateBuilder builder) {
        this.restTemplate = builder
            .rootUri("http://inventory-service")
            .setConnectTimeout(Duration.ofSeconds(1))
            .setReadTimeout(Duration.ofSeconds(2))
            .build();
    }

    Availability availability(String sku) {
        return restTemplate.getForObject("/inventory/{sku}", Availability.class, sku);
    }
}

Approach 2: WebClient (reactive; non-blocking end to end only in WebFlux apps)

Great for streaming and high fan-out in reactive services. In a Spring MVC service, calling .block() gives you no advantage over a blocking client.

java
import java.time.Duration;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

class InventoryWebClient {
    private final WebClient webClient = WebClient.builder().baseUrl("http://inventory-service").build();

    Mono<Availability> availability(String sku) {
        return webClient.get().uri("/inventory/{sku}", sku)
            .retrieve()
            .bodyToMono(Availability.class)
            .timeout(Duration.ofSeconds(2));
    }
}

Approach 3: RestClient (Spring Boot 3.2+), the modern blocking client

Fluent API like WebClient, synchronous like RestTemplate; ideal with virtual threads. Configure timeouts, map 5xx to a domain exception, and propagate the caller's JWT with an interceptor.

java
import java.net.http.HttpClient;
import java.time.Duration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.web.client.RestClient;

@Configuration
class InventoryClientConfig {
    @Bean
    RestClient inventoryRestClient(RestClient.Builder builder) {
        JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(
            HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(1)).build());
        factory.setReadTimeout(Duration.ofSeconds(2));
        return builder
            .baseUrl("http://inventory-service")
            .requestFactory(factory)
            .requestInterceptor(propagateBearerToken())
            .defaultStatusHandler(HttpStatusCode::is5xxServerError, (request, response) -> {
                throw new InventoryUnavailableException("Inventory returned " + response.getStatusCode());
            })
            .build();
    }

    static ClientHttpRequestInterceptor propagateBearerToken() {
        return (request, body, execution) -> {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (auth instanceof JwtAuthenticationToken jwt) request.getHeaders().setBearerAuth(jwt.getToken().getTokenValue());
            return execution.execute(request, body);
        };
    }
}

class InventoryRestClient {
    private final RestClient restClient;
    InventoryRestClient(RestClient inventoryRestClient) { this.restClient = inventoryRestClient; }

    Availability availability(String sku) {
        return restClient.get().uri("/inventory/{sku}", sku).retrieve().body(Availability.class);
    }
}

Approach 4: Declarative HTTP interface + Resilience4j (optimal)

An annotated interface (built into Spring 6, like OpenFeign without the extra dependency) backed by the configured RestClient. A gateway bean adds a circuit breaker, retries and a fallback; configuration lives in application.yml (resilience4j.circuitbreaker.instances.inventory..., resilience4j.retry.instances.inventory...).

java
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.retry.annotation.Retry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;

@HttpExchange("/inventory")
interface InventoryHttpClient {
    @GetExchange("/{sku}")
    Availability availability(@PathVariable String sku);
}

@Configuration
class InventoryHttpInterfaceConfig {
    @Bean
    InventoryHttpClient inventoryHttpClient(RestClient inventoryRestClient) {
        return HttpServiceProxyFactory.builderFor(RestClientAdapter.create(inventoryRestClient))
            .build()
            .createClient(InventoryHttpClient.class);
    }
}

@Service
class InventoryGateway {
    private final InventoryHttpClient client;
    InventoryGateway(InventoryHttpClient client) { this.client = client; }

    @CircuitBreaker(name = "inventory", fallbackMethod = "fallback")
    @Retry(name = "inventory")
    public Availability availability(String sku) {
        return client.availability(sku);
    }

    Availability fallback(String sku, Throwable cause) {
        return Availability.unknown(sku);                         // degrade: UI shows "availability unknown"
    }
}

Feasible → optimal

  • RestTemplate: works, verbose, maintenance mode.
  • WebClient: best inside reactive applications; pointless with .block() in MVC.
  • RestClient: the modern blocking client for MVC services (pairs perfectly with virtual threads).
  • HTTP interface + Resilience4j: least code at the call site, centralised timeouts, token propagation, retries, circuit breaking and fallbacks: the production answer.

Follow-up questions interviewers ask

Try answering each one before you open it.

Related: how do you call several services in parallel from a Spring MVC endpoint?

With virtual threads enabled (spring.threads.virtual.enabled=true), submit each blocking RestClient call to Executors.newVirtualThreadPerTaskExecutor() (or CompletableFuture.supplyAsync(..., executor)) and join; latency becomes the slowest call. Propagate the security and tracing context (Spring's DelegatingSecurityContextExecutor and Micrometer's context propagation).

Related: OpenFeign or HTTP interfaces?

Both are declarative clients. OpenFeign (Spring Cloud) has a large ecosystem (encoders, Spring Cloud LoadBalancer integration) but is in maintenance mode; Spring's own HTTP interfaces are built into the framework since 6.0, work with RestClient and WebClient, and are the recommended choice for new code.

Related: which calls are safe to retry?

Idempotent ones (GET, PUT, DELETE by id) on transient errors (timeouts, connection resets, 502/503/504, 429 with Retry-After). For POST, retry only with an idempotency key the server honours (see the idempotent POST question). Cap attempts (2–3), use exponential backoff with jitter, and retry at one layer only to avoid retry storms.