Repository navigation
Description
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):
CircuitBreakerHandler._route_open()andCircuitBreakerHandler._route_half_open()should always release the in-process_PROBES_IN_FLIGHT[self.name]slot acquired byself._claim_probe(), so subsequent invocations in the warm Lambda execution environment can still probe once DynamoDB recovers.- The store exception from
try_acquire_half_openshould be caught and logged (failing safe to_Route.OPENsoon_circuit_openorCircuitBreakerOpenErrorhandles 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 translatesConditionalCheckFailedExceptionintoCircuitBreakerExistingLockErrorand re-raises all otherClientErrors.- 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()intry...finally.
As a result, a single transient store error during probe election (either OPEN -> HALF_OPEN or expired-lease HALF_OPEN takeover):
- Leaks the raw store exception (e.g.
ClientError) out of the@circuit_breaker-decorated call, bypassingon_circuit_open. - 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:
- If
try_acquire_half_open(...)raises an exception, it logs a warning (consistent with_safe_persistandget_state) and treats the election as failed (return _Route.OPENsoon_circuit_openorCircuitBreakerOpenErrorruns safely). self._release_probe()is always executed wheneverself._claim_probe()succeeded and_Route.PROBEis not returned (viatry/exceptortry/finallyfreeing 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
- Check out
develop(0bbc252,aws_lambda_powertools3.41.0). - Run the
Stubber-based reproduction snippet above (no AWS account calls required). - Observe
ProvisionedThroughputExceededExceptionescaping Call 1 withFallback calls during Call 1: 0,_PROBES_IN_FLIGHTpermanently retaining{'payment': <pid>}, and Call 2 returningfallback:OPENafter 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
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsTriage
Activity
sumedh-aerram commentedon Dec 5, 2026
I reproduced this on
develop(0bbc252) with your script: the first call raises the rawProvisionedThroughputExceededExceptionand_PROBES_IN_FLIGHTstays set, in both theOPENand expired-leaseHALF_OPENpaths. 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_openorCircuitBreakerOpenError), and the next call retries the election once the store recovers.