Skip to content

Bug: Circuit breaker leaks _PROBES_IN_FLIGHT and crashes caller when try_acquire_half_open raises a store error #8954

Backlog

Description

@mayankcodes-dev

Expected Behaviour

The Circuit Breaker utility documents a strict fail-open guarantee: store errors on reads (get_state in aws_lambda_powertools/utilities/circuit_breaker/persistence/base.py) fail open cleanly, and store errors on state writes (_safe_persist in aws_lambda_powertools/utilities/circuit_breaker/base.py) are logged and swallowed so persistence outages never crash protected calls or strand recovery.

When try_acquire_half_open encounters a non-lock store error (such as DynamoDB throttling / ProvisionedThroughputExceededException or a network timeout during put_item):

  1. CircuitBreakerHandler._route_open() and CircuitBreakerHandler._route_half_open() should always release the in-process _PROBES_IN_FLIGHT[self.name] slot acquired by self._claim_probe(), so subsequent invocations in the warm Lambda execution environment can still probe once DynamoDB recovers.
  2. The store exception from try_acquire_half_open should be caught and logged (failing safe to _Route.OPEN so on_circuit_open or CircuitBreakerOpenError handles the call) instead of propagating raw DynamoDB exceptions out of @circuit_breaker.

Current Behaviour

Both CircuitBreakerHandler._route_open() (aws_lambda_powertools/utilities/circuit_breaker/base.py:199-207) and CircuitBreakerHandler._route_half_open() (base.py:219-225) call self._claim_probe() (which stores _PROBES_IN_FLIGHT[self.name] = os.getpid()) before calling self.persistence_store.try_acquire_half_open(...), and only call self._release_probe() afterwards if try_acquire_half_open returns False:

  • CircuitBreakerDynamoDBPersistence._put_record() (aws_lambda_powertools/utilities/circuit_breaker/persistence/dynamodb.py:247-252) only translates ConditionalCheckFailedException into CircuitBreakerExistingLockError and re-raises all other ClientErrors.
  • Neither CircuitBreakerPersistenceLayer.try_acquire_half_open() (persistence/base.py:254-259) nor _route_open() / _route_half_open() catches store exceptions or wraps _claim_probe() / _release_probe() in try...finally.

As a result, a single transient store error during probe election (either OPEN -> HALF_OPEN or expired-lease HALF_OPEN takeover):

  1. Leaks the raw store exception (e.g. ClientError) out of the @circuit_breaker-decorated call, bypassing on_circuit_open.
  2. Leaves _PROBES_IN_FLIGHT[self.name] permanently set in the process so every future call in that warm Lambda execution environment fails _claim_probe() and can never probe or recover the circuit even after the store recovers.

Code snippet

import datetime as dt

import boto3
from botocore.config import Config
from botocore.stub import Stubber

import aws_lambda_powertools.utilities.circuit_breaker.base as base_module
from aws_lambda_powertools.utilities.circuit_breaker import CircuitBreakerConfig, circuit_breaker
from aws_lambda_powertools.utilities.circuit_breaker.persistence import CircuitBreakerDynamoDBPersistence

client = boto3.client(
    "dynamodb",
    config=Config(region_name="us-east-1"),
    aws_access_key_id="test",
    aws_secret_access_key="test",
)
store = CircuitBreakerDynamoDBPersistence(table_name="CircuitBreakerState", boto3_client=client)
config = CircuitBreakerConfig(
    failure_threshold=2,
    recovery_timeout=10,
    success_threshold=1,
    local_cache_max_age=0,
)

fallback_calls = 0


def fallback(circuit):
    global fallback_calls
    fallback_calls += 1
    return f"fallback:{circuit.state}"


@circuit_breaker(name="payment", persistence_store=store, on_circuit_open=fallback, config=config)
def call_backend():
    return "ok"


now = int(dt.datetime.now().timestamp())
open_item = {
    "id": {"S": "payment"},
    "state": {"S": "OPEN"},
    "failure_count": {"N": "2"},
    "opened_at": {"N": str(now - 20)},
}

stubber = Stubber(client)
# Call 1: reads OPEN state past recovery_timeout, then put_item fails with DynamoDB throttling
stubber.add_response("get_item", {"Item": open_item})
stubber.add_client_error("put_item", service_error_code="ProvisionedThroughputExceededException")
# Call 2: DynamoDB recovers, get_item returns same OPEN item, but caller never probes or calls backend
stubber.add_response("get_item", {"Item": open_item})

with stubber:
    try:
        call_backend()
    except Exception as exc:
        print("Call 1 raised:", type(exc).__name__, "-", exc)
    print("Fallback calls during Call 1:", fallback_calls)
    print("_PROBES_IN_FLIGHT after Call 1:", dict(base_module._PROBES_IN_FLIGHT))

    res2 = call_backend()
    print("Call 2 (after DynamoDB recovers):", res2)
    print("Fallback calls after Call 2:", fallback_calls)
    print("_PROBES_IN_FLIGHT after Call 2:", dict(base_module._PROBES_IN_FLIGHT))

# Same leak occurs on expired HALF_OPEN lease takeover in _route_half_open
base_module._PROBES_IN_FLIGHT.clear()


@circuit_breaker(name="takeover", persistence_store=store, on_circuit_open=fallback, config=config)
def call_takeover():
    return "recovered"


expired_half_open_item = {
    "id": {"S": "takeover"},
    "state": {"S": "HALF_OPEN"},
    "failure_count": {"N": "2"},
    "opened_at": {"N": str(now - 100)},
    "half_open_owner": {"S": "dead-worker"},
    "probe_lease_expiry": {"N": str(now - 10)},
}

stubber2 = Stubber(client)
stubber2.add_response("get_item", {"Item": expired_half_open_item})
stubber2.add_client_error("put_item", service_error_code="ProvisionedThroughputExceededException")
stubber2.add_response("get_item", {"Item": expired_half_open_item})

with stubber2:
    try:
        call_takeover()
    except Exception as exc:
        print("Takeover Call 1 raised:", type(exc).__name__, "-", exc)
    print("_PROBES_IN_FLIGHT after Takeover Call 1:", dict(base_module._PROBES_IN_FLIGHT))

    res_takeover = call_takeover()
    print("Takeover Call 2 (after DynamoDB recovers):", res_takeover)

Possible Solution

Wrap probe election in a helper on CircuitBreakerHandler (used by both _route_open and _route_half_open) or guard try_acquire_half_open so that:

  1. If try_acquire_half_open(...) raises an exception, it logs a warning (consistent with _safe_persist and get_state) and treats the election as failed (return _Route.OPEN so on_circuit_open or CircuitBreakerOpenError runs safely).
  2. self._release_probe() is always executed whenever self._claim_probe() succeeded and _Route.PROBE is not returned (via try/except or try/finally freeing the slot on non-win or error).

I checked existing open/closed issues and PRs for circuit_breaker and found no duplicate report. I would be happy to submit a PR with regression tests once triaged.

Steps to Reproduce

  1. Check out develop (0bbc252, aws_lambda_powertools 3.41.0).
  2. Run the Stubber-based reproduction snippet above (no AWS account calls required).
  3. Observe ProvisionedThroughputExceededException escaping Call 1 with Fallback calls during Call 1: 0, _PROBES_IN_FLIGHT permanently retaining {'payment': <pid>}, and Call 2 returning fallback:OPEN after DynamoDB recovers instead of running a probe.

Did you run the reproduction yourself?

Yes, I ran it and saw the failure

Powertools for AWS Lambda (Python) version

develop @ 0bbc252 (3.41.0)

AWS Lambda function runtime

3.14

Packaging format used

PyPi

Debugging logs

Call 1 raised: ProvisionedThroughputExceededException - An error occurred (ProvisionedThroughputExceededException) when calling the PutItem operation: 
Fallback calls during Call 1: 0
_PROBES_IN_FLIGHT after Call 1: {'payment': 26700}
Call 2 (after DynamoDB recovers): fallback:OPEN
Fallback calls after Call 2: 1
_PROBES_IN_FLIGHT after Call 2: {'payment': 26700}
Takeover Call 1 raised: ProvisionedThroughputExceededException - An error occurred (ProvisionedThroughputExceededException) when calling the PutItem operation: 
_PROBES_IN_FLIGHT after Takeover Call 1: {'takeover': 26700}
Takeover Call 2 (after DynamoDB recovers): fallback:HALF_OPEN

Activity

  1. sumedh-aerram commented on Dec 5, 2026

    @sumedh-aerram
    Contributor

    I reproduced this on develop (0bbc252) with your script: the first call raises the raw ProvisionedThroughputExceededException and _PROBES_IN_FLIGHT stays set, in both the OPEN and expired-lease HALF_OPEN paths. I'd like to take it, and I have a fix ready that I'll open as a PR right after this comment. A store error during the probe election counts as a lost election: the local probe slot is released, the call takes the open-circuit path (on_circuit_open or CircuitBreakerOpenError), and the next call retries the election once the store recovers.

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

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions