Skip to content
Commitwise
Menu
Java Backend

Microservices and resilience

Decide when microservices are worth it, draw service boundaries around business capabilities with their own data, choose synchronous calls or events, and keep one slow dependency from taking everything down with timeouts, retries with backoff, circuit breakers, bulkheads and fallbacks using Resilience4j in Spring Boot.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

On Black Friday the recommendations service slows down: responses that took 50 ms now take 20 seconds. The product page calls it synchronously, without a timeout. Within two minutes all 200 request threads of the product service are waiting on recommendations, the product service stops answering, checkout (which calls the product service for prices) stops too, and the whole shop is down, because of a “nice to have” widget.

Splitting a system into services gives teams independence, but it turns every function call into a network call that can be slow or fail. Resilience is the set of habits that keep one failing service from taking down the others: timeouts, careful retries, circuit breakers, bulkheads and fallbacks. This lesson covers when microservices pay off, how to draw their boundaries, and how to protect them.

New to some of these? Open what you need, or skip ahead.

Basics:What are clients and servers?

A server is a computer (usually many of them) that runs your backend: it stores data and answers requests. A client is whatever sends the requests: your mobile app, a website, another server.

Big systems put many identical servers behind one address, with a load balancer in front that spreads requests between them. Data lives in a database, and frequently used data is often kept in a fast cache (in memory) so the database isn’t asked every time.

Basics:What is a thread pool?

A server handles each request on a thread. Threads are limited (Tomcat’s default is 200), so they’re kept in a pool and reused. A thread waiting for a slow network call can’t serve anyone else. If every thread is waiting, new requests queue up and eventually fail, even though the CPU is idle.

Part Not started

When to split, and where

A monolith is one application that does everything: products, orders, payments. A microservice architecture splits it into separate applications that talk over the network, each deployed on its own.

Microservices help when:

  • Many teams work on the system and keep getting in each other’s way.
  • Parts need to scale differently, like search under heavy load while invoicing runs once a night.
  • Parts change at different speeds, so one team can release ten times a day without waiting for the others.

They also cost a lot: every call can fail, data is spread out, testing and debugging are harder. That’s why many teams start with a modular monolith: one deployable application, but split inside into modules with clear boundaries. Splitting it later is much easier.

When you do split, two rules matter most:

  • Split by business capability: catalog, ordering, payments, shipping. Not by technical layer (“the database service”).
  • Each service owns its data. Other services ask it through its API or listen to its events. They never read its tables directly.

Microservices buy independent deployability, team autonomy and independent scaling at the price of distributed-systems problems: partial failure, latency, eventual consistency, versioned contracts and harder observability. A modular monolith with enforced module boundaries (packages or Gradle modules, ArchUnit or Spring Modulith checks) captures most of the design benefit and leaves the option to extract services when team or scaling pressure is real. Boundaries follow business capabilities / bounded contexts: a service owns a cohesive set of rules and its data, exposes them via an API and events, and can change its schema freely. Choose synchronous calls (REST, gRPC) when the caller needs the result to proceed, asynchronous events when other services just react; prefer events for cross-service side effects, which removes temporal coupling. Warning signs of a distributed monolith: shared databases, chains of synchronous calls per request, services that must deploy together, and changes that always touch several services. Gateways or backend-for-frontends aggregate APIs for clients (especially mobile) rather than making clients call many services.

@Service
class CheckoutService(
    private val inventory: InventoryClient,          // synchronous: checkout can't continue without it
    private val orders: OrderRepository,
    private val outbox: OutboxRepository,
) {
    @Transactional
    fun placeOrder(cart: Cart): Order {
        if (!inventory.reserve(cart.items)) throw OutOfStockException()
        val order = orders.save(Order.from(cart))
        // asynchronous: email, loyalty and analytics react to the event at their own pace
        outbox.save(OutboxEvent.of("OrderPlaced", order.id, OrderPlaced.from(order)))
        return order
    }
}
@Service
class CheckoutService {
    private final InventoryClient inventory;         // synchronous: checkout can't continue without it
    private final OrderRepository orders;
    private final OutboxRepository outbox;

    CheckoutService(InventoryClient inventory, OrderRepository orders, OutboxRepository outbox) {
        this.inventory = inventory;
        this.orders = orders;
        this.outbox = outbox;
    }

    @Transactional
    public Order placeOrder(Cart cart) {
        if (!inventory.reserve(cart.items())) throw new OutOfStockException();
        Order order = orders.save(Order.from(cart));
        // asynchronous: email, loyalty and analytics react to the event at their own pace
        outbox.save(OutboxEvent.of("OrderPlaced", order.id(), OrderPlaced.from(order)));
        return order;
    }
}
  • Inventory is called directly, because checkout must know whether the items are available before it can continue.
  • Email, loyalty points and analytics don’t need to answer checkout. They read the OrderPlaced event later. If the email service is down for an hour, checkout keeps working.
  • The event is saved in an outbox table in the same transaction as the order, then published to Kafka by a separate process, so an order is never saved without its event. The Kafka lesson shows the details.

Predict the output

The orders service reads the customers table of the customer service's database directly, to save an HTTP call. The customer team renames the column phone to phone_number and deploys. What happens?

Spot the bugA product list that takes ten seconds

Tap the line with the bug.

fun listProducts(products: List<Product>): List<ProductView> {
    val views = mutableListOf<ProductView>()
    for (p in products) {
        val price = pricingClient.priceFor(p.id)
        val stock = inventoryClient.stockFor(p.id)
        views += ProductView(p, price, stock)
    }
    return views
}
List<ProductView> listProducts(List<Product> products) {
    List<ProductView> views = new ArrayList<>();
    for (Product p : products) {
        Price price = pricingClient.priceFor(p.id());
        Stock stock = inventoryClient.stockFor(p.id());
        views.add(new ProductView(p, price, stock));
    }
    return views;
}

Contracts between services

  • Version APIs and events: additive changes only within a version; consumers ignore unknown fields; breaking changes get a new version and a deprecation period.
  • Consumer-driven contract tests (Pact, Spring Cloud Contract) catch breaking changes in the provider’s CI, before deployment.
  • Schemas for events (Avro or Protobuf with a schema registry, or JSON Schema) with compatibility rules enforced on publish.
  • Correlation: propagate trace context (W3C traceparent) and a request id through calls and events, so one user action can be followed across services.
  • Microservices = independent deploy and scale, paid for with partial failure, latency, eventual consistency, contracts. Start with a modular monolith (Spring Modulith, ArchUnit) and extract under real pressure.
  • Boundaries by business capability; each service owns its data; no shared database.
  • Sync (REST/gRPC) when the caller needs the answer; events (with an outbox) for side effects.
  • Distributed monolith signs: shared tables, chatty per-item calls, lockstep deploys, cross-service changes for every feature.
  • Versioned APIs and event schemas, contract tests, trace propagation; BFF/gateway for mobile clients.

Check this part

  1. How should microservices be split?

  2. Checkout must also send a confirmation email. Call the email service synchronously, or publish an event?

  3. Which is a sign of a distributed monolith?

  4. What usually captures most of the benefit with less risk early on?

Microservices trade simplicity for independent deployment and scaling, so start with a modular monolith and split when teams or load demand it. Draw boundaries around business capabilities, each service owning its data; never share a database. Use synchronous calls when the caller needs the answer now, events when others only need to know something happened. Chatty calls, shared tables and lockstep deploys mean a distributed monolith.

Part Not started

Keeping one failure from spreading

The Black Friday outage from the start of the lesson is called a cascading failure: one slow service makes its callers slow, which makes their callers slow, until everything is down. Five tools stop it:

  • Timeout: never wait forever. If inventory doesn’t answer in 2 seconds, give up. A slow answer is often worse than a fast error.
  • Retry: try again, but only for errors that might go away (a dropped connection), only for operations that are safe to repeat, and with growing pauses between attempts (backoff) plus a bit of randomness (jitter), so thousands of clients don’t retry at the same instant.
  • Circuit breakerCircuit breakerA guard around calls to a dependency that stops calling it for a while when most recent calls fail, and fails fast instead.Open in glossary →: like the fuse in your house. If most recent calls failed, stop calling for a while (the circuit is open) and fail immediately. After a pause, let a few test calls through (half-open); if they work, close the circuit again.
  • Bulkhead: named after the walls that divide a ship into compartments. Limit how many calls to one service can run at once, so a slow dependency can use up at most, say, 20 threads, not all 200.
  • Fallback: what to show when the call fails: no recommendations, cached prices, “stock unknown”.

Resilience4j is the library Spring Boot apps use for all of these.

Failure handling is layered: timeouts on every remote call (connect and read; budgeted from the caller’s own SLA, ideally propagating a deadline), retries only for transient errors on idempotent operations (or with idempotency keys), with exponential backoff and jitter, a small attempt count and a single retrying layer; circuit breakers (Resilience4j: count- or time-based sliding windows, failure-rate and slow-call-rate thresholds, open/half-open/closed) to fail fast and give the dependency room to recover; bulkheads (semaphore or thread-pool) to cap concurrency per dependency; and fallbacks that degrade explicitly (cached data, default values, hiding a feature) rather than lying. Resilience4j decorators apply in a fixed order: Retry(CircuitBreaker(RateLimiter(TimeLimiter(Bulkhead(call))))), so each retry attempt is counted by the breaker. Watch the interplay: retries multiply load (3 attempts at each of 3 layers is 27 calls), and an open breaker should short-circuit retries. Expose breaker states and bulkhead saturation as metrics, and alert on them. With virtual threads, thread exhaustion moves elsewhere (connection pools, downstream capacity), so bulkheads and timeouts still matter.

@Component
class InventoryClient(builder: RestClient.Builder) {
    private val restClient = builder
        .baseUrl("http://inventory")
        .requestFactory(SimpleClientHttpRequestFactory().apply {
            setConnectTimeout(Duration.ofMillis(500))
            setReadTimeout(Duration.ofSeconds(2))                   // never wait forever
        })
        .build()

    @Retry(name = "inventory")
    @CircuitBreaker(name = "inventory", fallbackMethod = "stockUnknown")
    @Bulkhead(name = "inventory")
    fun stockFor(sku: String): Stock =                              // a GET: safe to retry
        restClient.get().uri("/stock/{sku}", sku).retrieve().body<Stock>()!!

    private fun stockUnknown(sku: String, cause: Throwable): Stock =
        Stock.unknown(sku)                                          // the page shows "check availability"
}
@Component
class InventoryClient {
    private final RestClient restClient;

    InventoryClient(RestClient.Builder builder) {
        var requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(Duration.ofMillis(500));
        requestFactory.setReadTimeout(Duration.ofSeconds(2));       // never wait forever
        this.restClient = builder.baseUrl("http://inventory").requestFactory(requestFactory).build();
    }

    @Retry(name = "inventory")
    @CircuitBreaker(name = "inventory", fallbackMethod = "stockUnknown")
    @Bulkhead(name = "inventory")
    public Stock stockFor(String sku) {                             // a GET: safe to retry
        return restClient.get().uri("/stock/{sku}", sku).retrieve().body(Stock.class);
    }

    private Stock stockUnknown(String sku, Throwable cause) {
        return Stock.unknown(sku);                                  // the page shows "check availability"
    }
}
# application.yml
resilience4j:
  circuitbreaker:
    instances:
      inventory:
        sliding-window-type: COUNT_BASED
        sliding-window-size: 50
        failure-rate-threshold: 50          # open when half of the last 50 calls failed...
        slow-call-duration-threshold: 2s
        slow-call-rate-threshold: 50        # ...or half were slower than 2 s
        wait-duration-in-open-state: 30s
        permitted-number-of-calls-in-half-open-state: 5
  retry:
    instances:
      inventory:
        max-attempts: 3
        wait-duration: 200ms
        enable-exponential-backoff: true    # 200 ms, 400 ms
        retry-exceptions:
          - org.springframework.web.client.ResourceAccessException   # I/O errors and timeouts
  bulkhead:
    instances:
      inventory:
        max-concurrent-calls: 20            # at most 20 threads waiting on inventory
        max-wait-duration: 0                # reject immediately when full
  • setReadTimeout(2 s): after 2 seconds without an answer, the call fails instead of holding the thread.
  • retry: up to 3 attempts, only for connection problems and timeouts, waiting 200 ms and then 400 ms.
  • circuitbreaker: if half of the last 50 calls failed or were slow, stop calling inventory for 30 seconds; calls fail at once and go to the fallback.
  • bulkhead: at most 20 calls to inventory at the same time; the 21st is rejected immediately, so 180 threads stay free for everything else.
  • stockUnknown is the fallback: the product page still loads, with “check availability” instead of a stock count.
Spot the bugA client that waits forever

Tap the line with the bug.

@Component
class RecommendationsClient {
    private val restTemplate = RestTemplate()

    fun forUser(userId: String): List<Product> =
        restTemplate.getForObject(
            "http://recommendations/users/{id}", ProductList::class.java, userId)!!.items
}
@Component
class RecommendationsClient {
    private final RestTemplate restTemplate = new RestTemplate();

    List<Product> forUser(String userId) {
        return restTemplate.getForObject(
            "http://recommendations/users/{id}", ProductList.class, userId).items();
    }
}

Production puzzles

Predict the output

The API gateway retries failed requests 3 times. It calls orders, which retries inventory calls 3 times, and inventory retries its database query 3 times. The database starts timing out. How many database queries can one client request cause?

Spot the bugRetrying an order

Tap the line with the bug.

@Retry(name = "payments")
fun charge(orderId: String, amount: Money): PaymentResult =
    restClient.post()
        .uri("/payments")
        .body(ChargeRequest(orderId, amount))
        .retrieve()
        .body<PaymentResult>()!!
@Retry(name = "payments")
public PaymentResult charge(String orderId, Money amount) {
    return restClient.post()
        .uri("/payments")
        .body(new ChargeRequest(orderId, amount))
        .retrieve()
        .body(PaymentResult.class);
}

Exercisehard

Protect the product page

The product page calls catalog (required), pricing (required), inventory (important, has a sensible fallback) and recommendations (optional). The page’s own target is p99 under 800 ms. Design timeouts, retries, breakers, bulkheads and fallbacks for each call.

›

Start from the 800 ms budget and work backwards; decide which calls can run in parallel and which can fail without failing the page.

SolutionTry it yourself first
  • Run calls in parallel (structured concurrency or CompletableFutures on virtual threads) so the budget isn’t the sum of all calls.
  • Catalog and pricing (required): timeouts around 300 ms each, one retry for connection errors only (they’re GETs), circuit breakers that fail the page fast with a clear error when open; pricing could fall back to a short-lived cached price if the business accepts it.
  • Inventory (important): 250 ms timeout, no retry (the fallback is good enough), breaker with fallback “check availability”.
  • Recommendations (optional): 150 ms timeout, no retry, small bulkhead (for example 10 concurrent calls), breaker with an empty-list fallback; or load it asynchronously from the client after the page renders.
  • Everywhere: separate bulkheads per dependency, metrics and alerts on breaker state and fallback rate, and load tests that inject slowness (fault injection) to prove the page stays under budget when any one dependency is slow.

Predict the output

The inventory circuit breaker is open. A user opens a product page. What happens to the inventory call?

  • Timeouts on every remote call (connect and read), budgeted from the caller’s SLA. new RestTemplate() has none.
  • Retry: transient errors, idempotent operations (or idempotency keys), exponential backoff + jitter, few attempts, one layer; retries multiply across layers.
  • Circuit breaker: failure-rate and slow-call thresholds, open → half-open → closed; fail fast with fallbacks. Bulkhead per dependency.
  • Resilience4j order: Retry(CircuitBreaker(RateLimiter(TimeLimiter(Bulkhead(call))))). Metrics and alerts on breaker states and fallback rates.
  • Parallelize independent calls; fault-inject slowness in load tests.

Check this part

  1. What does a circuit breaker do when it is open?

  2. Why add jitter to retry delays?

  3. Which call is unsafe to retry automatically?

  4. What does a bulkhead protect against?

Every remote call needs a timeout. Retry only transient failures of idempotent operations, with exponential backoff and jitter, and only at one layer. A circuit breaker stops calling a failing dependency for a while and fails fast; a bulkhead caps concurrent calls so one dependency can't take all threads; fallbacks degrade gracefully. Resilience4j provides all of them for Spring Boot.

Key takeaways

  • Microservices give teams independence but make every call a network call; start with a modular monolith.
  • Split by business capability, and let each service own its data.
  • Call synchronously only when you need the answer; publish events for everything else.
  • Every remote call needs a timeout; retry carefully; use circuit breakers, bulkheads and fallbacks.
  • Watch for distributed-monolith signs and fix boundaries, not just symptoms.
  • Budget timeouts from SLAs, retry at one layer with idempotency, and parallelize independent calls.
  • Make degradation explicit and observable; test it with fault injection.
  • Contracts, versioning and tracing are part of the architecture, not afterthoughts.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.