Beyond "It Works in Staging": Operationalizing Production Reliability on AWS
Beyond "It Works in Staging": Operationalizing Production Reliability on AWS

Beyond "It Works in Staging": Operationalizing Production Reliability on AWS
Category: Architecture | Reliability & Availability
There is a class of production failure that no amount of code review catches. It lives in the gap between what your system does under controlled conditions and what it does under real traffic, partial degradation, and failover pressure.
I've watched IAM policies that passed every review lock out a service account during a regional failover because nobody had validated the assumed-role chain in a degraded topology. I've watched Kubernetes clusters that passed every chaos test surprise an on-call team when an actual AZ went dark because simulated failure and real failure have different characteristics, especially around timing and partial state.
This post is about closing that gap systematically, using three concrete AWS-native patterns. All examples use the
agentsre library (open source, linked below) and target production fintech-grade reliability requirements.
The Three Gaps That Cause Most AWS Production Incidents
Gap 1: IAM policy validation assumes steady-state topology.
Your
aws iam simulate-principal-policy call works in the primary region. It doesn't test what happens when the trust policy assumption chain changes shape during a failover event.Gap 2: Database migrations are tested at staging data volumes, not production concurrency.
A migration that succeeds in 4 minutes in staging can create lock contention that cascades across your connection pool in production, especially when legacy data stores have type inconsistencies that only appear at scale.
Gap 3: Chaos testing validates recovery, not degraded-state behavior.
Most chaos test frameworks inject failure and measure MTTR. They don't measure how your service behaves when a dependency is slow but not down the brownout case that produces the worst cascade failures.
Pattern 1: Failover-Aware IAM Policy Validator
The standard IAM simulation API validates permissions against a single principal in a single region. This doesn't model cross-region assume-role chains under failover conditions.
Here's a validator that constructs the assumed-role chain for both primary and failover topologies, then diffs the effective permissions:
python
import boto3import jsonfrom dataclasses import dataclass, fieldfrom typing import Optionalimport logging
logger = logging.getLogger(__name__)
@dataclassclass IAMFailoverContext: primary_region: str failover_region: str service_account_arn: str role_arns: list[str] actions_to_validate: list[str] resource_arns: list[str]
@dataclassclass FailoverPolicyDiff: primary_allowed: set[str] = field(default_factory=set) failover_allowed: set[str] = field(default_factory=set) primary_only: set[str] = field(default_factory=set) failover_only: set[str] = field(default_factory=set) gap_detected: bool = False gap_detail: str = ""
def simulate_role_chain( iam_client, role_arns: list[str], actions: list[str], resources: list[str], source_arn: str,) -> set[str]: """ Simulate IAM permissions through a chain of assumed roles. Returns the set of allowed actions at the end of the chain. """ allowed_actions = set() current_principal = source_arn
for role_arn in role_arns: try: response = iam_client.simulate_principal_policy( PolicySourceArn=current_principal, ActionNames=actions, ResourceArns=resources, CallerArn=current_principal, ) for result in response.get("EvaluationResults", []): if result["EvalDecision"] == "allowed": allowed_actions.add(result["EvalActionName"]) current_principal = role_arn except iam_client.exceptions.NoSuchEntityException: logger.warning( "Role not found in simulation chain", extra={"role_arn": role_arn, "principal": current_principal}, ) break
return allowed_actions
def validate_iam_failover_gap(ctx: IAMFailoverContext) -> FailoverPolicyDiff: """ Detect IAM permission gaps that only manifest during regional failover.
This catches the class of incident where a policy that looks correct in steady state locks out a service account during a failover event because the assume-role chain changes shape. """ primary_iam = boto3.client("iam", region_name=ctx.primary_region) failover_iam = boto3.client("iam", region_name=ctx.failover_region)
primary_allowed = simulate_role_chain( primary_iam, ctx.role_arns, ctx.actions_to_validate, ctx.resource_arns, ctx.service_account_arn, )
# In failover, the role ARN region segments may differ — reconstruct chain failover_role_arns = [ arn.replace(ctx.primary_region, ctx.failover_region) for arn in ctx.role_arns ]
failover_allowed = simulate_role_chain( failover_iam, failover_role_arns, ctx.actions_to_validate, ctx.resource_arns, ctx.service_account_arn, )
diff = FailoverPolicyDiff( primary_allowed=primary_allowed, failover_allowed=failover_allowed, primary_only=primary_allowed - failover_allowed, failover_only=failover_allowed - primary_allowed, )
if diff.primary_only: diff.gap_detected = True diff.gap_detail = ( f"Actions allowed in primary but NOT in failover: {sorted(diff.primary_only)}. " f"These will break during a regional failover event." ) logger.error( "IAM failover gap detected", extra={ "primary_region": ctx.primary_region, "failover_region": ctx.failover_region, "blocked_actions": sorted(diff.primary_only), }, )
return diff
# Example usageif __name__ == "__main__": ctx = IAMFailoverContext( primary_region="us-east-1", failover_region="us-west-2", service_account_arn="arn:aws:iam::123456789012:role/payment-processor", role_arns=[ "arn:aws:iam::123456789012:role/data-access-us-east-1", "arn:aws:iam::123456789012:role/rds-read-us-east-1", ], actions_to_validate=[ "rds:DescribeDBInstances", "rds:DescribeDBClusters", "secretsmanager:GetSecretValue", "s3:GetObject", ], resource_arns=["*"], )
result = validate_iam_failover_gap(ctx)
if result.gap_detected: print(f"POLICY GAP DETECTED: {result.gap_detail}") else: print("IAM permissions are symmetric across primary and failover regions.")Run this as part of your pre-failover validation pipeline, not as a one-time audit. The permissions landscape drifts.
Pattern 2: Production-Aware Migration Checkpointer
This is the pattern I reach for any time a migration touches a table that's being read or written by live traffic during the window.
The core idea: divide the migration into checkpointed batches, validate row counts at each checkpoint, and expose a pause mechanism that the on-call engineer can trigger without rolling back the entire migration.
python
import timeimport boto3import loggingfrom dataclasses import dataclassfrom typing import Callable, Optionalfrom enum import Enum
logger = logging.getLogger(__name__)
class MigrationStatus(str, Enum): RUNNING = "RUNNING" PAUSED = "PAUSED" COMPLETED = "COMPLETED" FAILED = "FAILED" ROLLED_BACK = "ROLLED_BACK"
@dataclassclass MigrationCheckpoint: checkpoint_id: str rows_processed: int rows_expected: int elapsed_seconds: float status: MigrationStatus error: Optional[str] = None
class ProductionMigrationRunner: """ Runs a database migration in checkpointed batches with: - Row-count validation at each checkpoint - Pause/resume capability via SSM Parameter Store flag - CloudWatch metrics for migration progress - Automatic rollback on validation failure """
def __init__( self, migration_id: str, batch_size: int = 1000, pause_check_interval: int = 30, ssm_pause_flag_path: Optional[str] = None, cloudwatch_namespace: str = "SRE/Migrations", ): self.migration_id = migration_id self.batch_size = batch_size self.pause_check_interval = pause_check_interval self.ssm_pause_flag_path = ssm_pause_flag_path or f"/migrations/{migration_id}/pause" self.cloudwatch_namespace = cloudwatch_namespace self.ssm = boto3.client("ssm") self.cw = boto3.client("cloudwatch") self.total_processed = 0
def _is_paused(self) -> bool: try: response = self.ssm.get_parameter(Name=self.ssm_pause_flag_path) return response["Parameter"]["Value"].lower() == "true" except self.ssm.exceptions.ParameterNotFound: return False
def _emit_metric(self, metric_name: str, value: float, unit: str = "Count"): self.cw.put_metric_data( Namespace=self.cloudwatch_namespace, MetricData=[ { "MetricName": metric_name, "Dimensions": [{"Name": "MigrationId", "Value": self.migration_id}], "Value": value, "Unit": unit, } ], )
def run( self, get_batch: Callable[[int, int], list], process_batch: Callable[[list], int], validate_checkpoint: Callable[[int, int], bool], total_rows_expected: int, rollback_fn: Optional[Callable[[], None]] = None, ) -> MigrationCheckpoint: """ Execute a migration with full checkpoint governance.
Args: get_batch: fn(offset, limit) -> list of rows to process process_batch: fn(rows) -> count of rows actually processed validate_checkpoint: fn(processed_so_far, expected_total) -> bool total_rows_expected: expected total rows for validation rollback_fn: optional fn() to call on validation failure """ start_time = time.time() offset = 0 checkpoint_num = 0
logger.info( "Migration starting", extra={ "migration_id": self.migration_id, "total_rows_expected": total_rows_expected, "batch_size": self.batch_size, }, )
while True: # Pause check while self._is_paused(): logger.warning( "Migration paused via SSM flag", extra={"migration_id": self.migration_id, "offset": offset}, ) time.sleep(self.pause_check_interval)
batch = get_batch(offset, self.batch_size) if not batch: break
try: processed = process_batch(batch) self.total_processed += processed offset += len(batch) checkpoint_num += 1 except Exception as e: logger.error( "Batch processing failed", extra={"migration_id": self.migration_id, "offset": offset, "error": str(e)}, ) if rollback_fn: rollback_fn() return MigrationCheckpoint( checkpoint_id=f"{self.migration_id}-cp-{checkpoint_num}", rows_processed=self.total_processed, rows_expected=total_rows_expected, elapsed_seconds=time.time() - start_time, status=MigrationStatus.ROLLED_BACK, error=str(e), )
# Checkpoint validation if not validate_checkpoint(self.total_processed, total_rows_expected): logger.error( "Checkpoint validation failed — triggering rollback", extra={ "migration_id": self.migration_id, "processed": self.total_processed, "expected": total_rows_expected, }, ) self._emit_metric("ValidationFailure", 1) if rollback_fn: rollback_fn() return MigrationCheckpoint( checkpoint_id=f"{self.migration_id}-cp-{checkpoint_num}", rows_processed=self.total_processed, rows_expected=total_rows_expected, elapsed_seconds=time.time() - start_time, status=MigrationStatus.ROLLED_BACK, error="Checkpoint validation failed", )
self._emit_metric("RowsProcessed", self.total_processed) self._emit_metric("BatchDurationSeconds", time.time() - start_time, unit="Seconds")
logger.info( "Checkpoint passed", extra={ "migration_id": self.migration_id, "checkpoint": checkpoint_num, "rows_processed": self.total_processed, "progress_pct": round((self.total_processed / total_rows_expected) * 100, 1), }, )
elapsed = time.time() - start_time self._emit_metric("MigrationDurationSeconds", elapsed, unit="Seconds")
return MigrationCheckpoint( checkpoint_id=f"{self.migration_id}-final", rows_processed=self.total_processed, rows_expected=total_rows_expected, elapsed_seconds=elapsed, status=MigrationStatus.COMPLETED, )The SSM pause flag is the part I've found most useful in real incidents. You can pause a running migration without rolling it back — useful when you see connection pool pressure building and want to give the database a breather before continuing.
Pattern 3: Brownout-Aware Circuit Breaker
The cascade failure pattern nobody talks about enough: your dependency doesn't go down. It gets slow. Your thread pool fills up waiting for it. Your service starts timing out from the perspective of your callers. The incident scope doubles.
This circuit breaker tracks latency, not just error rate:
python
import timeimport threadingimport loggingfrom dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Callable, TypeVar, Optionalimport boto3
logger = logging.getLogger(__name__)
T = TypeVar("T")
class CircuitState(str, Enum): CLOSED = "CLOSED" # Normal operation OPEN = "OPEN" # Failing fast HALF_OPEN = "HALF_OPEN" # Testing recovery
@dataclassclass CircuitBreakerConfig: failure_threshold: int = 5 recovery_timeout: float = 30.0 latency_threshold_ms: float = 2000.0 # Brownout detection latency_window_size: int = 20 latency_failure_pct: float = 0.5 # 50% of requests over threshold = open cloudwatch_namespace: str = "SRE/CircuitBreaker" service_name: str = "unknown"
class BrownoutAwareCircuitBreaker: """ Circuit breaker that opens on high latency, not just hard failures.
Standard circuit breakers require a dependency to return errors before opening. This one tracks p50 latency in a rolling window and opens the circuit when latency indicates brownout — before the cascade starts. """
def __init__(self, config: CircuitBreakerConfig): self.config = config self._state = CircuitState.CLOSED self._failure_count = 0 self._last_failure_time: Optional[float] = None self._latency_window: list[float] = [] self._lock = threading.Lock() self._cw = boto3.client("cloudwatch")
@property def state(self) -> CircuitState: if self._state == CircuitState.OPEN: if time.time() - (self._last_failure_time or 0) > self.config.recovery_timeout: logger.info( "Circuit transitioning to HALF_OPEN", extra={"service": self.config.service_name}, ) self._state = CircuitState.HALF_OPEN return self._state
def _record_latency(self, latency_ms: float): with self._lock: self._latency_window.append(latency_ms) if len(self._latency_window) > self.config.latency_window_size: self._latency_window.pop(0)
def _brownout_detected(self) -> bool: if len(self._latency_window) < self.config.latency_window_size: return False over_threshold = sum( 1 for l in self._latency_window if l > self.config.latency_threshold_ms ) pct_over = over_threshold / len(self._latency_window) return pct_over >= self.config.latency_failure_pct
def _trip(self, reason: str): with self._lock: self._state = CircuitState.OPEN self._last_failure_time = time.time() logger.error( "Circuit breaker OPEN", extra={"service": self.config.service_name, "reason": reason}, ) try: self._cw.put_metric_data( Namespace=self.config.cloudwatch_namespace, MetricData=[ { "MetricName": "CircuitBreakerOpen", "Dimensions": [ {"Name": "Service", "Value": self.config.service_name} ], "Value": 1, "Unit": "Count", } ], ) except Exception: pass # Never let metric emission block the circuit
def call( self, fn: Callable[[], T], fallback: Optional[Callable[[], T]] = None, ) -> T: """ Execute fn() through the circuit breaker. Falls back to fallback() if the circuit is open and fallback is provided. Raises RuntimeError if open and no fallback. """ current_state = self.state
if current_state == CircuitState.OPEN: if fallback: return fallback() raise RuntimeError( f"Circuit breaker OPEN for {self.config.service_name}. " "Dependency is in brownout — failing fast." )
start = time.time() try: result = fn() latency_ms = (time.time() - start) * 1000 self._record_latency(latency_ms)
if self._brownout_detected(): self._trip( f"Latency brownout: >{self.config.latency_threshold_ms}ms on " f"{self.config.latency_failure_pct * 100}% of last " f"{self.config.latency_window_size} requests" )
if current_state == CircuitState.HALF_OPEN: with self._lock: self._state = CircuitState.CLOSED self._failure_count = 0 self._latency_window.clear() logger.info( "Circuit breaker CLOSED after recovery", extra={"service": self.config.service_name}, )
return result
except Exception as e: latency_ms = (time.time() - start) * 1000 self._record_latency(latency_ms) with self._lock: self._failure_count += 1 self._last_failure_time = time.time() if self._failure_count >= self.config.failure_threshold: self._trip(f"Failure threshold reached: {str(e)}") raise
Putting It Together
These three patterns address the same root problem from different angles: production conditions are structurally different from testing conditions, and reliability engineering is the discipline of closing that gap before an incident does it for you.
The code above ships as part of the
agentsre library. The pre_action_gate.py and dependency_risk.py modules in v0.23.0 extend these patterns with SRE gate primitives that can be composed into pre-deployment validation pipelines.
What's the production failure that changed how you design for reliability? Drop it in the comments — the more specific, the more useful.
Tags:
reliability ** aws ** sre ** devops ** platform-engineering ** python ** production Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article