Overview

Mission-critical integration — payments, telecoms provisioning, insurance claims, logistics — connects systems that were built by different teams, different vendors, and sometimes different decades. Take payments, the worked example in this article: the RTGS or instant-scheme gateway, the legacy core, the open-API authorisation server, the fraud screening engine — each of these has its own availability profile, its own latency characteristics, and its own failure modes. When one of them degrades, the naive integration does exactly the wrong thing: it holds threads waiting for a response, exhausts connection pools, and eventually takes down services that had nothing to do with the failing backend.

Circuit breakers and bulkheads are the two patterns that interrupt this failure cascade. A circuit breaker monitors call outcomes and, when failures exceed a threshold, opens — refusing new calls to the failing backend and letting it recover. A bulkhead limits the concurrency any single downstream dependency can consume, so a slow backend cannot starve the thread pool that serves unrelated requests. Together, they form the fault-isolation layer that every production integration platform in a regulated enterprise needs before the first downstream goes slow.

Resilience4j over Hystrix

Netflix Hystrix is no longer maintained and its thread-pool model is heavyweight for modern reactive stacks. Resilience4j 2 is the production default for Spring Boot 3 applications: lighter, composable, native Micrometer integration, and compatible with both imperative and reactive Spring. The patterns in this article are Resilience4j 2 throughout; the principles apply to any implementation.

Why defaults fail in mission-critical integration

A standard Spring RestTemplate or Feign client configured with a 30-second connect timeout and a 60-second read timeout will hold a thread for up to 90 seconds waiting for a backend that has already stopped responding. A payment platform handling 500 concurrent payment initiations — each calling a legacy core that is silently timing out — will exhaust a thread pool of 200 in under 20 seconds. The result is not a graceful degradation. It is a full platform outage, visible to every channel including channels whose underlying requests never needed the legacy core at all.

Three failure modes are typical of transaction-heavy integration and absent from most general guidance.

  • Slow-response amplification. Payment-scheme gateways respond in milliseconds under normal load but can degrade to 5–15 seconds under settlement pressure at end-of-day; batch-heavy legacy cores show the same profile during overnight runs. The integration layer has no visibility into whether this is transient overload or a sustained outage. Without a circuit breaker, every active request ties up a thread waiting for the answer.
  • Partial failures in orchestrated flows. An ISO 20022 payment initiation may call fraud screening, currency conversion, beneficiary validation, and the payment gateway in sequence. If the third step starts timing out, the circuit breaker must trip on step 3 without affecting step 1, step 2, or the responses already returned. Correctly scoping the breaker to the individual downstream — not the whole flow — is the implementation detail that most first attempts get wrong.
  • Cascading failures across domain boundaries. An enterprise integration estate typically spans domains owned by different teams. A circuit breaker that trips silently — with no metrics, no alert, and no fallback log entry — makes incident diagnosis significantly harder. The open state of a breaker must be visible in the observability stack within seconds of the trip, not discovered retroactively in a post-incident review.

The circuit breaker pattern

A Resilience4j circuit breaker is a state machine with three primary states and two transitional ones. Understanding the transitions precisely matters for tuning — the defaults are almost always wrong for a high-stakes integration environment.

The CLOSED state is normal operation. Resilience4j maintains a sliding window — count-based or time-based — of recent outcomes. When the failure rate (or slow-call rate) exceeds the configured threshold within the window, the breaker transitions to OPEN. In the open state, calls fail fast with a CallNotPermittedException rather than being forwarded to the backend. After the configured waitDurationInOpenState, the breaker enters HALF_OPEN and allows a configurable number of probe calls through. If enough probe calls succeed, the breaker closes; if they fail, it reopens and the wait timer resets.

The slow-call threshold deserves explicit attention in transactional integration. A scheme-gateway call that consistently takes 8 seconds is a failure in practice even if it eventually returns a success response — it is holding a thread, blocking a saga step, and degrading end-user experience. Setting slowCallDurationThreshold to 5 seconds and slowCallRateThreshold to 80% catches this case, whereas a failure-rate-only configuration will not trip until the gateway starts returning errors rather than just being slow.

The bulkhead pattern

A circuit breaker controls whether calls are made. A bulkhead controls how many calls are made concurrently. The analogy is structural: a ship’s bulkhead prevents a hull breach in one compartment from flooding the whole vessel. In an integration platform, a bulkhead prevents a slow or stuck downstream from consuming the entire thread pool that serves every other downstream.

Resilience4j provides two bulkhead implementations with materially different operational characteristics.

Semaphore bulkhead. Limits concurrent calls using a counting semaphore. Lightweight, no additional threads. When the semaphore limit is reached, new calls fail immediately with BulkheadFullException. The caller’s thread is blocked only for the duration of the actual downstream call — the semaphore acquisition is non-blocking by default (configurable with maxWaitDuration). The right choice for reactive applications and for high-throughput paths where you can tolerate a fast fail rather than queue.

Thread-pool bulkhead. Executes calls in a dedicated thread pool and returns a CompletableFuture. Caller threads return immediately; the downstream call runs in a separate pool. When the pool is saturated, the call is rejected. The right choice for legacy blocking clients (JDBC, JMS, HttpClient with no async support) where you want caller-thread isolation. The cost is the additional thread pools — one per downstream — which adds memory and scheduling overhead. IBM ACE integration via Java Compute Nodes falls into this category.

Semaphore bulkhead does not isolate blocking callers

If your call to the downstream is blocking (synchronous JDBC, synchronous HTTP), a semaphore bulkhead limits concurrency but does not free the calling thread. A thread pool bulkhead submits the work to a separate pool, freeing the caller immediately. For IBM ACE Java Compute Nodes and any Spring service using JdbcTemplate, the thread-pool bulkhead is the correct choice.

Resilience4j 2 configuration

The canonical configuration for an integration service uses application.yml with Spring Boot’s auto-configuration. Each downstream gets its own named circuit breaker instance; shared configuration is defined in a default profile and overridden per instance where the backend has a distinct latency or reliability profile.

application.yml — Resilience4j circuit breakersyaml
resilience4j:
  circuitbreaker:
    configs:
      default:
        slidingWindowType: COUNT_BASED
        slidingWindowSize: 100
        minimumNumberOfCalls: 20
        failureRateThreshold: 50           # % failures to trip CLOSED → OPEN
        slowCallRateThreshold: 80           # % slow calls also trips breaker
        slowCallDurationThreshold: 5s       # >5s = counted as slow
        waitDurationInOpenState: 30s
        permittedNumberOfCallsInHalfOpenState: 5
        automaticTransitionFromOpenToHalfOpenEnabled: true
        registerHealthIndicator: true
        recordExceptions:
          - java.io.IOException
          - java.util.concurrent.TimeoutException
          - feign.FeignException$ServiceUnavailable   # nested class: binary name uses $
          - feign.FeignException$GatewayTimeout
        ignoreExceptions:
          - com.example.integration.exception.ValidationException  # business errors, not infra
          - com.example.integration.exception.InsufficientFundsException
    instances:
      scheme-gateway:
        baseConfig: default
        slowCallDurationThreshold: 8s    # scheme gateway can be legitimately slow
        waitDurationInOpenState: 60s   # longer recovery window for gateway
      legacy-core:
        baseConfig: default
        slidingWindowSize: 200          # higher volume, wider window
        failureRateThreshold: 30        # tighter threshold for the system of record
      fraud-engine:
        baseConfig: default
        slowCallDurationThreshold: 3s   # fraud must answer fast or not at all
        waitDurationInOpenState: 15s   # try to recover fraud quickly

  bulkhead:
    instances:
      scheme-gateway:
        maxConcurrentCalls: 25          # gateway licence concurrency limit
        maxWaitDuration: 0ms           # fast-fail if limit reached
      legacy-core:
        maxConcurrentCalls: 50
        maxWaitDuration: 100ms

  thread-pool-bulkhead:
    instances:
      fraud-engine:
        maxThreadPoolSize: 10
        coreThreadPoolSize: 5
        queueCapacity: 20
        keepAliveDuration: 20ms

The ignoreExceptions list is critical and is almost always omitted in first implementations. A ValidationException means the request was malformed — that is a client error, not an infrastructure failure. Counting it as a failure will trip the breaker during a period of legitimate high invalid-request volume, producing a false-positive open state that blocks all calls including valid ones. Separate infra exceptions from business exceptions explicitly.

PaymentGatewayClient.java — Resilience4j annotationsjava
@Component
public class PaymentGatewayClient {

  private final SchemeGatewayFeign feign;

  @CircuitBreaker(name = "scheme-gateway", fallbackMethod = "gatewayFallback")
  @Bulkhead(name = "scheme-gateway", type = Bulkhead.Type.SEMAPHORE)
  @TimeLimiter(name = "scheme-gateway")
  public CompletableFuture<PaymentResponse> submitPayment(PaymentRequest req) {
    return CompletableFuture.supplyAsync(() -> feign.submit(req));
  }

  private CompletableFuture<PaymentResponse> gatewayFallback(
      PaymentRequest req, CallNotPermittedException ex) {
    // breaker is OPEN: queue to local outbox, return accepted
    outboxService.enqueue(req);
    return CompletableFuture.completedFuture(
        PaymentResponse.queued(req.getIdempotencyKey())
    );
  }

  private CompletableFuture<PaymentResponse> gatewayFallback(
      PaymentRequest req, BulkheadFullException ex) {
    // concurrency cap: backpressure to caller, not silent drop
    throw new PaymentGatewayCapacityException("Scheme gateway concurrency limit reached");
  }
}
Annotation order matters

When stacking @CircuitBreaker, @Bulkhead, and @TimeLimiter, the outer-to-inner execution order follows the Spring AOP proxy chain. Resilience4j’s default is: TimeLimiter wraps CircuitBreaker wraps Bulkhead. Apply the annotations in the order you want the inner execution to be wrapped outward, or configure resilience4j.aspects-order explicitly to avoid subtle evaluation surprises.

IBM ACE flow hardening

IBM ACE 12 message flows call downstream services via HTTP Nodes, MQ Nodes, and Java Compute Nodes. The HTTP Request node has built-in timeout configuration but no circuit breaker semantics — a timed-out HTTP call is treated as a flow exception and triggers the flow’s failure terminal, but repeated timeouts do not open a breaker to prevent the next call from waiting again. Wrapping ACE flows with a Resilience4j-backed Java Compute Node is the standard approach for production hardening.

ResilientHttpNode.java — ACE Java Compute Node with circuit breakerjava
public class ResilientHttpNode extends JavaCompute {

  private static final CircuitBreaker breaker =
      CircuitBreakerRegistry.ofDefaults()
          .circuitBreaker("legacy-core", CircuitBreakerConfig.custom()
              .failureRateThreshold(50)
              .slowCallDurationThreshold(Duration.ofSeconds(5))
              .waitDurationInOpenState(Duration.ofSeconds(30))
              .build());

  @Override
  public void evaluate(MbMessageAssembly assembly) throws MbException {
    Supplier<MbMessage> call = Decorators
        .ofSupplier(() -> forwardToHttp(assembly))
        .withCircuitBreaker(breaker)
        .withBulkhead(coreBulkhead)
        .withFallback(List.of(
            CallNotPermittedException.class,
            BulkheadFullException.class),
            ex -> buildFallbackMessage(assembly, ex))
        .decorate();

    try {
      MbMessage response = call.get();
      propagateToOut(assembly, response);
    } catch (Exception e) {
      propagateToFailure(assembly, e);
    }
  }
}

The Java Compute Node approach gives ACE flows the same resilience properties as a Spring service, at the cost of maintaining a static CircuitBreakerRegistry shared across flow invocations on the same ACE instance. Use a static registry scoped to the node class — not instantiated per-message — so the state machine persists across messages rather than resetting on every invocation.

Fallback design for payment APIs

A circuit breaker without a fallback is an error changer, not a resilience mechanism. When the breaker opens on the scheme-gateway path, the API can: fail fast to the caller (which is appropriate for synchronous payment initiation), queue the payment to a local transactional outbox (which is appropriate for high-value transfers where eventual processing is acceptable), or return a cached last-known state (appropriate for read operations like balance checks).

The trade-offs for each are different and context-dependent. The decision to queue versus fail fast is not a technical one — it is a product and regulatory one. In most jurisdictions, a payment that an institution has accepted becomes its obligation to execute. Queuing and returning “accepted” binds the institution to a delivery commitment. Failing fast returns control to the customer to retry through another channel. Neither is universally correct; document the choice as an explicit business decision, not an engineering default.

Fallback strategy When to use Regulatory implication Implementation
Fail fast (503) Synchronous payment initiation where the customer can retry No liability created; customer retries via another channel Throw ServiceUnavailableException from fallback; caller sees 503
Transactional outbox queue High-value transfers; batch end-of-day settlement Institution accepts liability on the queued payment; must execute when gateway recovers Write to outbox table in same transaction; Debezium forwards when gateway recovers
Cached response Balance enquiries, statement previews, reference data Acceptable if staleness window is documented and disclosed Redis GET on the account key; annotate response with X-Cache-Age header
Degraded mode Fraud screening; AML pre-check Risk appetite decision: proceed without screening or hold for manual review Return a PROCEED_WITH_FLAG result; route to manual queue for post-hoc review
Silent success fallbacks for payment writes

Never return a success response for a payment that was not actually submitted — and then silently discard it when the queue fails or the outbox is not processed. A queued fallback requires an operational runbook for processing the queue when the gateway recovers, automated monitoring for queue depth, and an SLA for clearing it. Without those, the “queued” fallback is a hole in the payment audit trail that only surfaces during an audit, a regulatory examination or a customer complaint two weeks later.

Observability & Micrometer

Resilience4j publishes Micrometer metrics automatically when spring-boot-actuator and the Resilience4j Spring Boot starter are on the classpath. The metrics are prefixed resilience4j.circuitbreaker.* and resilience4j.bulkhead.*. Three dashboards are required for a production payment platform.

  • State transition gauge. resilience4j_circuitbreaker_state{name="scheme-gateway"} reports the current state as 0 (CLOSED), 1 (OPEN), 2 (HALF_OPEN). An alert on this gauge fires within 10 seconds of any breaker opening. This is the most important alert in the stack: an open breaker means the integration is actively degraded, not just slow.
  • Failure rate counter. resilience4j_circuitbreaker_failure_rate{name="..."} reports the current failure rate inside the sliding window. Track this on a 5-minute rolling average to distinguish a spike (tolerable) from a sustained elevated failure rate (investigate immediately).
  • Bulkhead available concurrent calls. resilience4j_bulkhead_available_concurrent_calls{name="..."} tells you how much headroom is left. When this metric approaches zero for more than 30 seconds, the bulkhead is consistently near capacity — either scale the downstream connection pool or reduce inbound call volume.
prometheus-alerts.yamlyaml
groups:
  - name: integration-resilience
    rules:
      - alert: CircuitBreakerOpen
        expr: resilience4j_circuitbreaker_state{state="open"} == 1
        for: 0m
        labels:
          severity: critical
        annotations:
          summary: "Circuit breaker OPEN: {{ $labels.name }}"
          description: "Breaker {{ $labels.name }} is OPEN. Fallbacks active. Payment platform degraded."

      - alert: BulkheadNearCapacity
        expr: resilience4j_bulkhead_available_concurrent_calls < 3
        for: 30s
        labels:
          severity: warning
        annotations:
          summary: "Bulkhead near capacity: {{ $labels.name }}"
          description: "{{ $labels.name }} has < 3 available slots. Imminent BulkheadFullException."

      - alert: CircuitBreakerFailureRateHigh
        expr: resilience4j_circuitbreaker_failure_rate > 30
        for: 2m
        labels:
          severity: warning
        annotations:
          summary: "High failure rate on {{ $labels.name }}: {{ $value }}%"

Pattern comparison

The table below summarises which pattern addresses which failure mode. Use it as a first-pass checklist when deciding which patterns to apply to a new downstream integration.

Failure mode Circuit Breaker Semaphore Bulkhead Thread-Pool Bulkhead Time Limiter
Downstream returns 5xx errors Yes — trips on failure rate No No No
Downstream responds slowly Yes — slow-call threshold No No Yes — cancels after timeout
Thread pool exhaustion No Yes — limits concurrency Yes — isolates to own pool No
Caller thread blocked by sync call No No — caller still blocks Yes — caller returns immediately Partial — with timeout interrupt
Cascading failure across services Yes — open state fast-fails Yes — caps blast radius Yes — pool isolation No
Downstream connection pool exhaustion No Yes — max concurrent = max connections Yes — pool size caps connections No

Production checklist

The order matters. Step 1 is non-negotiable before step 6; adding circuit breakers without observability is adding invisible protection that will silently fail when most needed.

  1. Identify every downstream dependency and its failure profile

    Map each downstream: what HTTP endpoints does it expose, what is its published SLA, what is its actual P99 latency in production, what does it return on degradation (5xx, timeout, partial response)? Score each one by impact if it fails or slows. The scheme gateway, the legacy core and the fraud engine are always in the top tier for a payments platform.

  2. Set per-dependency thresholds from observed baselines

    Do not use generic defaults. Query your existing APM or Prometheus for the actual P99 and failure rate baseline for each downstream over the last 30 days. Set slowCallDurationThreshold at 2× the observed P99, and failureRateThreshold at 3× the baseline failure rate. This prevents false-positive trips during normal load spikes.

  3. Implement and test fallback behaviour before enabling the circuit breaker

    The fallback is the hardest part. Test it in isolation first: mock the circuit breaker in an open state and verify that the fallback produces the correct response, logs the correct structured event, and increments the correct metric. A fallback that silently swallows exceptions is worse than no fallback.

  4. Deploy in shadow mode for one sprint

    Configure the circuit breaker with an extremely high threshold (e.g., 99% failure rate) and observe the failure rate metric without allowing it to actually trip. This validates that the metric collection is correct and that your threshold choices are calibrated before the breaker can cause production impact.

  5. Enable Prometheus alerts and verify delivery

    The CircuitBreakerOpen alert must fire and reach the on-call engineer within 60 seconds of the first trip. Test this in a non-production environment by deliberately misconfiguring a downstream and confirming end-to-end alert delivery through your paging tool or the NOC alerting channel.

  6. Add bulkheads after circuit breakers are stable

    Do not add both at the same time. Circuit breakers change observable behaviour (fast-fail responses); bulkheads add a concurrency limit that might start rejecting requests at peak load if sized incorrectly. Tune circuit breakers first over two to three weeks of production data, then introduce bulkheads with conservative (high) limits and tighten over time.

  7. Document the operational runbook for each open breaker

    Every circuit breaker instance needs a runbook entry: what does it protect, what is the fallback behaviour, how does an operator force the breaker back to CLOSED, and what downstream health check must return green before closing manually. In regulated industries this runbook is also an audit artefact for any critical third-party or network-connected integration.

Common pitfalls

Counting business errors as infrastructure failures

A 400 Bad Request from the legacy core is a client error, not an infrastructure failure. Counting it in the circuit breaker’s failure rate will trip the breaker during periods of high invalid-input volume — a spike in malformed payment requests from a third-party integrator, for example. Explicitly configure ignoreExceptions for every business exception class. When in doubt, check the HTTP status code in a custom RecordFailurePredicate and count only 5xx and network-level failures.

Scoping the circuit breaker too broadly

A single circuit breaker wrapping all calls to the legacy core — balance enquiries, payment initiation, account maintenance — will open when any subset of those calls degrades. A slow balance enquiry endpoint trips the breaker and blocks payment initiation, which is an unrelated and fully healthy path. Scope each breaker to a specific endpoint or flow, not to the downstream host. core-balance-check and core-payment-submit are separate instances with separate state machines.

No minimum call count before tripping

The minimumNumberOfCalls parameter prevents the breaker from tripping on a handful of failures at startup or after a deployment when traffic is low. Without it, the first two requests failing during a warm-up period will hit a 100% failure rate and open the breaker immediately. Set minimumNumberOfCalls to at least 20 for low-volume paths and at least 50 for high-volume ones.

When not to use circuit breakers

  • Synchronous database calls within a single service. The circuit breaker pattern is designed for remote calls across a network boundary. Database calls within a service should use connection pool timeouts and health indicators, not a circuit breaker. Adding a breaker to a DB call introduces complexity without addressing the actual failure mode (pool exhaustion), which is better addressed with a bulkhead sized to the connection pool.
  • Internal in-process calls. Method calls between beans in the same JVM process don’t traverse a network. A circuit breaker around them adds overhead and the latency-based trip conditions are meaningless — an in-process call that takes 5 seconds is a CPU-bound computation, not a network timeout.
  • Calls where the failure must be surfaced immediately. Real-time gross settlement (RTGS) notifications and some compliance-driven mandatory-check calls cannot be queued or degraded. An open circuit breaker on these paths must fail the entire transaction, not silently queue or fall back. Model the breaker as a fail-hard gate, not a resilience mechanism, for mandatory regulatory calls. Document the choice explicitly in the integration design.
  • Message consumers without retry infrastructure. A Kafka consumer protected by a circuit breaker that opens will stop processing messages and leave the consumer group lagging. This is only acceptable if there is a dead-letter queue and a replay mechanism. Without those, an open breaker on a consumer is a silent queue buildup that becomes a larger problem when the breaker eventually closes.