3: Resilient Cloud Solutions

    Implement highly available solutions to meet resilience and business requirements

    High availability begins with a numeric target, not a service catalogue. Translate the business expectation into an availability budget: 99.9% allows roughly 8 hours 45 minutes of unavailability per year, 99.99% allows 52 minutes, and 99.999% allows 5 minutes. Every architectural decision then trades cost against the remaining error budget. Treat HA as the answer to "what categories of failure must my workload survive without a human in the loop," and pick the smallest blast radius that satisfies the answer. The most common categories are instance failure, Availability Zone (AZ) impairment, control-plane throttling, and Regional service event. Workloads with sub-second customer impact typically need Multi-AZ at minimum; workloads with regulatory or geographic continuity requirements escalate to multi-Region.

    The four engineering rules that produce high availability on AWS at professional depth are: isolate failure domains, design every dependency as either retried or replaceable, drive recovery from data-plane signals rather than control-plane assumptions, and prove the recovery path with fault injection before the workload is in production. Failure-domain isolation maps to AZs, Regions, accounts, and service quotas. Retry vs. replace is the difference between a transient timeout that backoff resolves and a poisoned dependency that requires routing away. Data-plane signals (an actual TCP failure observed by Network Load Balancer or a target health-check failure) drive faster reactions than control-plane signals (such as a missing alarm transition). Fault injection, covered later in this chapter, is the only way to verify that the assumed recovery actually fires.

    Scaling automation is the workhorse that converts these rules into running infrastructure. Three AWS automation surfaces matter: AWS Auto Scaling (the orchestration layer that creates scaling plans across multiple resource types), Amazon EC2 Auto Scaling groups (the per-fleet primitive that adds and removes EC2 instances), and Application Auto Scaling (the per-resource API for ECS services, DynamoDB tables, Aurora read replicas, Lambda provisioned concurrency, and a long list of other resource types). Lambda contributes a fourth automation surface in the form of self-driven recovery functions invoked by Amazon EventBridge rules, Amazon CloudWatch alarm state changes, AWS Health events, or Route 53 Application Recovery Controller routing decisions.

    Scaling automation across AWS Auto Scaling, Application Auto Scaling, and AWS Lambda

    AWS Auto Scaling creates a scaling plan that targets several resources at once: an EC2 Auto Scaling group, an ECS service, a DynamoDB table, and Aurora replicas can share a single plan with a unified policy and predictive scaling enabled. Application Auto Scaling is the underlying API that the plan calls for non-EC2 resources. Target tracking is the recommended policy type for almost every workload because it computes the scaling action directly from a representative metric (CPU utilization, request count per target, custom metric) without requiring step thresholds.

    # Register a DynamoDB table's write capacity as a scalable target
    aws application-autoscaling register-scalable-target \
     --service-namespace dynamodb \
     --resource-id "table/orders" \
     --scalable-dimension dynamodb:table:WriteCapacityUnits \
     --min-capacity 100 \
     --max-capacity 4000
    
    # Attach a target-tracking policy that holds DynamoDB writes at 70% utilization
    aws application-autoscaling put-scaling-policy \
     --service-namespace dynamodb \
     --resource-id "table/orders" \
     --scalable-dimension dynamodb:table:WriteCapacityUnits \
     --policy-name orders-write-target-tracking \
     --policy-type TargetTrackingScaling \
     --target-tracking-scaling-policy-configuration '{
     "TargetValue": 70.0,
     "PredefinedMetricSpecification": {
     "PredefinedMetricType": "DynamoDBWriteCapacityUtilization"
     },
     "ScaleOutCooldown": 60,
     "ScaleInCooldown": 60
     }'
    

    Lambda participates in two scaling roles. As a target, Lambda concurrency is governed by Application Auto Scaling against provisioned-concurrency utilization, which holds a warm pool that absorbs cold-start latency for synchronous APIs. As an actor, a Lambda function attached to an EventBridge rule, a CloudWatch alarm state-change event, or an SNS topic executes recovery logic such as draining a node, flipping a Route 53 record set, or rotating an Aurora reader. The pattern below subscribes a Lambda to an EC2 Auto Scaling lifecycle hook so it can copy diagnostic data off a terminating instance before the hook releases it.

    # CloudFormation snippet: lifecycle hook plus Lambda for graceful termination
    Resources:
     GracefulHook:
     Type: AWS::AutoScaling::LifecycleHook
     Properties:
     AutoScalingGroupName: !Ref WebFleet
     LifecycleTransition: autoscaling:EC2_INSTANCE_TERMINATING
     DefaultResult: CONTINUE
     HeartbeatTimeout: 300
     NotificationTargetARN: !GetAtt LifecycleTopic.Arn
     RoleARN: !GetAtt LifecycleRole.Arn
    
     DrainFunction:
     Type: AWS::Lambda::Function
     Properties:
     Handler: index.handler
     Runtime: python3.12
     Role: !GetAtt DrainRole.Arn
     Timeout: 240
     Code:
     ZipFile: |
     import boto3, json, os
     asg = boto3.client("autoscaling")
     ssm = boto3.client("ssm")
     def handler(event, context):
     msg = json.loads(event["Records"][0]["Sns"]["Message"])
     instance = msg["EC2InstanceId"]
     ssm.send_command(
     InstanceIds=[instance],
     DocumentName="AWS-RunShellScript",
     Parameters={"commands": ["systemctl stop app && aws s3 cp /var/log s3://logs/$(hostname)/ --recursive"]}
     )
     asg.complete_lifecycle_action(
     LifecycleHookName=msg["LifecycleHookName"],
     AutoScalingGroupName=msg["AutoScalingGroupName"],
     LifecycleActionToken=msg["LifecycleActionToken"],
     LifecycleActionResult="CONTINUE"
     )
    

    Picking the right policy type for the workload

    Target-tracking policies are the default for predictable, smooth metrics. Step scaling is required when the metric is bursty and the action needs to be proportional to the breach magnitude (for example, double the fleet on a sustained 5x queue depth). Scheduled scaling pre-positions capacity for known traffic windows such as weekday market opens or the start of a marketing campaign. Predictive scaling, the machine-learning policy in AWS Auto Scaling and EC2 Auto Scaling, observes 24 hours to 14 days of metric history and pre-warms the fleet up to 48 hours ahead of forecast peaks; it pairs with a dynamic policy (target tracking) to handle the residual variation. Predictive scaling is read-only for the first 24 hours after enablement to validate forecast quality before issuing scaling actions.

    💡 Exam Trap: Target-tracking does not preserve a fixed instance count, it preserves a fixed metric value. When the metric is artificially low (the application is broken and CPU drops to 5%), target tracking will scale the fleet down toward the minimum, which can amplify an outage. Pair target tracking with health checks and a non-zero MinSize derived from a steady-state quorum.

    💡 Exam Trap: AWS Auto Scaling scaling plans and direct EC2 Auto Scaling group policies can collide. If you attach a policy to a group that is already governed by a plan, both engines try to write a desired-capacity value, and the most recent write wins. Use one orchestration layer per resource.

    ⚠️ Anti-Pattern: Wiring a Lambda function as the only path that decrements a fleet (for example, in response to a custom CloudWatch metric) and giving it AutoScalingFullAccess. A throttled or failing function silently halts scale-in, the fleet grows without a ceiling, and you discover the failure on the bill. Use the native scaling policies and reserve Lambda for recovery actions that have no built-in equivalent.

    📊 Limit: EC2 Auto Scaling supports up to 50 launch configurations per Region by default and up to 200 Auto Scaling groups per Region; lifecycle hooks support a HeartbeatTimeout of 30 seconds to 7,200 seconds (2 hours) with a default of 3,600 seconds (1 hour).

    Decision Anchor: Choose target tracking when the metric tracks load proportionally and you want one knob. Choose step scaling when the magnitude of the breach must translate into the size of the action. Choose scheduled scaling when the load curve is calendar-driven and known. Choose predictive scaling when the load curve is calendar-driven but irregular enough that scheduled actions over-provision or under-provision; layer a target-tracking policy on top for the residual.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the AWS - DevOps Engineer Professional learning hub.