Skip to content

DefaultCircuitBreakerProvider registers a new onError listener on every call, leaking listeners and causing GC storms #1317

Open

Description

@ricardomoreirabc

Describe the Bug

DefaultCircuitBreakerProvider.getCircuitBreaker() adds a new onError listener to the circuit breaker every time it decorates a call:

val circuitBreaker = circuitBreakerRegistry.circuitBreaker(identifier, customCircuitBreakerConfig);

circuitBreaker
    .getEventPublisher()
    .onError(event -> lastExceptions.put(circuitBreaker.getName(), event.getThrowable()));

CircuitBreakerRegistry.circuitBreaker(...) returns the same cached instance for an identifier, so the listeners accumulate without bound for the lifetime of the JVM.
resilience4j keeps event consumers in a CopyOnWriteArraySet, so each new registration scans all existing listeners for duplicates and then copies the whole backing array.
Per-call cost and allocation therefore grow linearly with uptime, and total CPU grows with request rate × uptime.

This affects every call that goes through ResilienceDecorator with the circuit breaker enabled.
That includes OAuth2Service.retrieveAccessToken(), which runs on every request through an OAuth2 destination even when the token is cached.

The listener was introduced in #942 (4bf241a8, "fix: CircuitBreaker stack-trace") and is still on main.

A secondary issue in the same class: lastExceptions is a plain HashMap, but it is written from event callbacks on arbitrary threads.

Impact in production

A Spring Boot service on Cloud Foundry sends every outbound request through an OAuth2 client-credentials HttpDestination (OAuth2HeaderProvider → OAuth2Service → ResilienceDecorator).
Its CPU climbed with instance uptime under the same traffic: instances up about 3 days ran at 210–318% of their CPU entitlement, instances up 1–6 hours at 26–65%.
Restarting an instance reset it.

Measurements on one instance up 3.1 days (SDK 5.35.0, resilience4j 2.4.0, SapMachine 25, Spring Boot 4.1.2):

Measurement Value
Reachable DefaultCircuitBreakerProvider$$Lambda instances (jcmd GC.class_histogram, i.e. after a Full GC) 5,611,791 (16 bytes each, matching the onError lambda)
Object[] retained on the heap ~505 MB
Heap 2.59 of 2.65 GB committed
New listeners vs. requests served, same 122 s window 3,530 / 3,568 (0.99 per request)
Allocation per request from the array copy ~22 MB
Java CPU samples in listener registration (JFR, 60 s) 56% (33% duplicate scan in CopyOnWriteArraySet, 23% in EventProcessor.registerConsumer)
GCs in 60 s 114, including 16 Full GCs; 91 triggered by "G1 Humongous Allocation"
GC pause time ~4.4 s per minute across 43 parallel GC threads, roughly 3 cores

A thread dump shows request threads going from OAuth2Service.retrieveAccessToken through DefaultCircuitBreakerProvider.getCircuitBreaker (line 66) into Arrays.copyOf.
One request thread had allocated 159 GB over its lifetime.

The lambda count grew at a steady 22–32 per second on both old and freshly started instances, so the count tracks uptime, and CPU tracks the count.

Steps to Reproduce

  1. Use the default Resilience4jDecorationStrategy with the circuit breaker enabled (the default ResilienceConfiguration).
  2. Call ResilienceDecorator.executeSupplier(...) repeatedly with the same configuration identifier.
  3. Count the consumers registered on the breaker's event publisher: it grows by one per call.

Minimal check (reflection only to read the consumer count):

ResilienceConfiguration config = ResilienceConfiguration.of("leak-test");
DefaultCircuitBreakerProvider provider = new DefaultCircuitBreakerProvider();

for( int i = 0; i < 100; i++ ) {
    provider.decorateCallable(() -> "token", config).call();
}

CircuitBreaker breaker = provider.getCircuitBreaker(config);
Field field = EventProcessor.class.getDeclaredField("eventConsumerMap");
field.setAccessible(true);
Map<?, ? extends Collection<?>> consumers = (Map) field.get(breaker.getEventPublisher());
int listeners = consumers.values().stream().mapToInt(Collection::size).sum();
// listeners > 100; expected 1

A local reproduction with SDK 5.35.0 and resilience4j 2.4.0 on the full HTTP path (Apache HttpClient5 → OAuth2HeaderProvider → OAuth2Service → ResilienceDecorator, local token endpoint and downstream server, 8 threads, 240,000 requests, token endpoint hit only 8 times) gave:

Requests Listeners ms/request GC time per 30k requests
30k 30,000 0.33 30 ms
120k 120,000 0.30 62 ms
150k 150,000 0.73 1,331 ms
240k 240,000 1.32 2,801 ms

The jump at about 150k listeners is where the copied array becomes a humongous allocation for that heap, the same pattern as in production.
With the listener registered once per breaker (see below), the same run stays at 1 listener, ~0.14 ms/request and ~7 ms GC per 30k requests.

Expected Behavior

The onError listener is registered once per circuit breaker, so the cost of a decorated call does not depend on how many calls came before it.

A possible fix is to register the listener when the registry creates the breaker:

private CircuitBreakerRegistry getCircuitBreakerRegistry( @Nonnull final ResilienceIsolationKey isolationKey )
{
    return circuitBreakerRegistries.computeIfAbsent(isolationKey, k -> {
        final CircuitBreakerRegistry registry = CircuitBreakerRegistry.of(DEFAULT_CIRCUIT_BREAKER_CONFIG);
        registry.getEventPublisher().onEntryAdded(added -> {
            final CircuitBreaker breaker = added.getAddedEntry();
            breaker.getEventPublisher().onError(e -> lastExceptions.put(breaker.getName(), e.getThrowable()));
        });
        return registry;
    });
}

and to remove the onError registration from getCircuitBreaker(), making lastExceptions a ConcurrentHashMap.

Used Versions

  • SAP Cloud SDK version: 5.35.0 (present since fix: CircuitBreaker stack-trace #942, still on main)
  • resilience4j: 2.4.0 (2.3.0 behaves the same)
  • Java: SapMachine 25 (Cloud Foundry Java buildpack)
  • Spring Boot: 4.1.2

Code Examples

Workaround we run in production: a provider identical to DefaultCircuitBreakerProvider except that the listener is registered in onEntryAdded and lastExceptions is a ConcurrentHashMap.
We install it with the default decorators in their default order, swapping only the circuit breaker provider:

ResilienceDecorator.setDecorationStrategy(
    Resilience4jDecorationStrategy.builder()
        .decorators(List.of(
            new DefaultBulkheadProvider(),
            new DefaultTimeLimiterProvider(),
            new DefaultRateLimiterProvider(),
            new SingleListenerCircuitBreakerProvider(),
            new DefaultCachingDecorator(),
            new DefaultRetryProvider()))
        .build());

Behaviour when the token endpoint fails is unchanged: with the token endpoint returning 500, calls 1–10 fail with DestinationAccessException → ResilienceRuntimeException → TokenRequestFailedException, and calls 11–14 get CircuitBreaker '…' is OPEN and does not permit further calls. Triggered by … with CallNotPermittedException suppressed, identical to the SDK default.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      ⌂ Proxy