diff --git a/.agents/skills/building-lambda-functions-with-powertools-python/references/circuit-breaker.md b/.agents/skills/building-lambda-functions-with-powertools-python/references/circuit-breaker.md index 928f243c17f..d5d5a155064 100644 --- a/.agents/skills/building-lambda-functions-with-powertools-python/references/circuit-breaker.md +++ b/.agents/skills/building-lambda-functions-with-powertools-python/references/circuit-breaker.md @@ -375,6 +375,8 @@ The consecutive-failure counter lives in memory per execution environment, so a If the utility cannot reach the persistence store when reading state, it treats the circuit as **closed**. A circuit breaker should never become the outage it is meant to prevent. +If the store fails while electing the prober after the recovery window, the call takes the open-circuit +path (`on_circuit_open` or `CircuitBreakerOpenError`) and a later call retries the election. ### Observability with metrics diff --git a/aws_lambda_powertools/utilities/circuit_breaker/base.py b/aws_lambda_powertools/utilities/circuit_breaker/base.py index 7f5b2dc1672..c141dd3bcbe 100644 --- a/aws_lambda_powertools/utilities/circuit_breaker/base.py +++ b/aws_lambda_powertools/utilities/circuit_breaker/base.py @@ -199,11 +199,10 @@ def _route_open(self, record: CircuitStateRecord) -> _Route: if self._now() < opened_at + self.config.recovery_timeout or not self._claim_probe(): return _Route.OPEN # Recovery window elapsed: try to become the single prober. - if self.persistence_store.try_acquire_half_open(self.name, _probe_owner_id(), opened_at): + if self._win_probe_election(opened_at): self._reset_probe_successes() self._notify(CircuitState.OPEN, CircuitState.HALF_OPEN, opened_at=opened_at) return _Route.PROBE - self._release_probe() return _Route.OPEN def _route_half_open(self, record: CircuitStateRecord) -> _Route: @@ -218,12 +217,31 @@ def _route_half_open(self, record: CircuitStateRecord) -> _Route: lease_expired = record.probe_lease_expiry is not None and self._now() >= record.probe_lease_expiry if lease_expired and self._claim_probe(): logger.debug("Circuit '%s' probe lease expired; attempting takeover.", self.name) - if self.persistence_store.try_acquire_half_open(self.name, _probe_owner_id(), record.opened_at or 0): + if self._win_probe_election(record.opened_at or 0): self._reset_probe_successes() return _Route.PROBE - self._release_probe() return _Route.OPEN + def _win_probe_election(self, opened_at: int) -> bool: + """ + Try to persist this worker as the prober; release the local probe slot when it doesn't win. + + A store error counts as a lost election: the call takes the open-circuit path and a + later call retries once the store recovers, matching the fail-open read policy. + """ + try: + won = self.persistence_store.try_acquire_half_open(self.name, _probe_owner_id(), opened_at) + except Exception: + logger.warning( + "Circuit '%s': probe election write failed; staying open until the store recovers.", + self.name, + exc_info=True, + ) + won = False + if not won: + self._release_probe() + return won + def _claim_probe(self) -> bool: """Mark a probe as in flight for this circuit; False when one is already running in this process.""" with _COUNTERS_LOCK: diff --git a/docs/utilities/circuit_breaker.md b/docs/utilities/circuit_breaker.md index 66b49744650..a1ee83e040f 100644 --- a/docs/utilities/circuit_breaker.md +++ b/docs/utilities/circuit_breaker.md @@ -209,6 +209,8 @@ The consecutive-failure counter lives in memory per execution environment, so a !!! note "Fail-open by design" If the utility cannot reach the persistence store when reading state, it treats the circuit as **closed**. A circuit breaker should never become the outage it is meant to prevent. + If the store fails while electing the prober after the recovery window, the call takes the open-circuit + path (`on_circuit_open` or `CircuitBreakerOpenError`) and a later call retries the election. ### Observability with metrics diff --git a/tests/functional/circuit_breaker/test_dynamodb_persistence.py b/tests/functional/circuit_breaker/test_dynamodb_persistence.py index ac67bfd0897..094259a1978 100644 --- a/tests/functional/circuit_breaker/test_dynamodb_persistence.py +++ b/tests/functional/circuit_breaker/test_dynamodb_persistence.py @@ -1,10 +1,13 @@ from __future__ import annotations +import time + import boto3 import pytest from botocore.config import Config from botocore.stub import Stubber +from aws_lambda_powertools.utilities.circuit_breaker import circuit_breaker from aws_lambda_powertools.utilities.circuit_breaker.config import CircuitBreakerConfig from aws_lambda_powertools.utilities.circuit_breaker.exceptions import CircuitBreakerConfigError from aws_lambda_powertools.utilities.circuit_breaker.persistence import ( @@ -100,6 +103,52 @@ def test_try_acquire_half_open_loses_on_conditional_failure(persistence): assert persistence.try_acquire_half_open("payment", "env-b", 1000) is False +@pytest.mark.parametrize( + "stored", + [ + pytest.param({"state": {"S": "OPEN"}}, id="open_recovery_window_elapsed"), + pytest.param( + { + "state": {"S": "HALF_OPEN"}, + "half_open_owner": {"S": "recycled-worker"}, + "probe_lease_expiry": {"N": "1"}, + }, + id="half_open_lease_expired", + ), + ], +) +def test_probe_election_store_error_falls_back_and_retries_after_recovery(stored): + # GIVEN a circuit past its recovery window and a DynamoDB table that throttles the probe election write + client = boto3.client("dynamodb", config=Config(region_name="us-east-1")) + store = CircuitBreakerDynamoDBPersistence(table_name=TABLE_NAME, boto3_client=client) + config = CircuitBreakerConfig(recovery_timeout=30, success_threshold=2, local_cache_max_age=0) + item = {"id": {"S": "payment"}, "failure_count": {"N": "3"}, "opened_at": {"N": str(int(time.time()) - 100)}} + item.update(stored) + protected_calls = [] + + @circuit_breaker(name="payment", persistence_store=store, config=config, on_circuit_open=lambda circuit: "fallback") + def charge(): + protected_calls.append(1) + return "charged" + + stubber = Stubber(client) + stubber.add_response("get_item", {"Item": item}) + stubber.add_client_error("put_item", service_error_code="ProvisionedThroughputExceededException") + stubber.add_response("get_item", {"Item": item}) + stubber.add_response("put_item", {}) + + with stubber: + # WHEN the election write fails, THEN the call is answered by the open-circuit fallback + assert charge() == "fallback" + assert protected_calls == [] + + # WHEN the store recovers, THEN the next call wins the election and probes the downstream + assert charge() == "charged" + assert protected_calls == [1] + + stubber.assert_no_pending_responses() + + def test_save_closed_updates_record(persistence): stubber = Stubber(persistence.client) stubber.add_response("update_item", {})