Health Checks, Circuit Breakers, and Retry Logic
Use ELB health checks, Route 53 endpoint checks, and application-level circuit breakers to detect failures and reroute traffic automatically.
Health Checks, Circuit Breakers, and Retry Logic is a free AWS Solutions Architect lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AWS Solutions Architect learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Automated Failure Detection Matters
In distributed systems, components fail continuously — instances crash, network partitions occur, downstream services become overloaded. Without automated failure detection, traffic continues flowing to failed components, causing cascading failures. AWS provides multiple layers of health checking: ELB health checks detect unhealthy instances, Route 53 health checks detect unhealthy endpoints, and Auto Scaling replaces failed instances. Application-level patterns like circuit breakers and retries complete the resilience picture.
ELB Health Checks
Elastic Load Balancer health checks periodically send requests to registered targets to determine if they are healthy. You configure the health check path (e.g., /health), protocol, port, interval (default 30 seconds), and healthy/unhealthy threshold (number of consecutive successes/failures). When a target fails health checks, the ELB stops routing traffic to it. The target is re-evaluated continuously and added back once it passes the healthy threshold.
# Configure ALB target group health check
aws elbv2 modify-target-group \
--target-group-arn arn:aws:elasticloadbalancing::123:targetgroup/my-tg/abc \
--health-check-protocol HTTPS \
--health-check-port 443 \
--health-check-path /health \
--health-check-interval-seconds 15 \
--healthy-threshold-count 2 \
--unhealthy-threshold-count 3 \
--matcher HttpCode=200Route 53 Health Checks
Route 53 health checks monitor endpoints from multiple locations globally and work in tandem with DNS failover routing. Three types exist: Endpoint checks directly poll your application URL. Calculated checks combine multiple child health checks with AND/OR logic (useful for complex monitoring). CloudWatch alarm checks delegate health determination to CloudWatch — useful when you cannot expose a public health endpoint or need metric-based health decisions.
# Create endpoint health check
aws route53 create-health-check \
--caller-reference ref-$(date +%s) \
--health-check-config '{
"Type": "HTTPS",
"FullyQualifiedDomainName": "api.example.com",
"Port": 443,
"ResourcePath": "/health",
"RequestInterval": 10,
"FailureThreshold": 2,
"EnableSNI": true
}'Auto Scaling Health Checks
Auto Scaling Groups can use two types of health checks: EC2 health checks detect instance failures at the hypervisor level (instance status check failure). ELB health checks are more application-aware — an instance might be running but serving errors, and ELB health checks catch this. You can configure ASG to use ELB health checks so that application-level failures also trigger instance replacement, not just underlying EC2 failures.
# Configure ASG to use ELB health checks
aws autoscaling update-auto-scaling-group \
--auto-scaling-group-name my-asg \
--health-check-type ELB \
--health-check-grace-period 300
# Grace period: time after launch before health checks start
# Prevents premature termination during startupThe Circuit Breaker Pattern
A circuit breaker is an application-level pattern that prevents cascading failures by monitoring calls to a downstream service and temporarily stopping calls when failures exceed a threshold. The circuit has three states: Closed (normal operation), Open (failures exceeded threshold, calls are blocked immediately), and Half-Open (after a timeout, a small number of test calls are allowed to check if the service has recovered). AWS App Mesh and application SDKs like Resilience4j implement this pattern.
# Circuit breaker states
# CLOSED: All calls pass through
# failureCount < threshold -> stay CLOSED
# failureCount >= threshold -> open circuit
# OPEN: All calls fail immediately
# After timeout -> enter HALF-OPEN
# HALF-OPEN: Allow limited test calls
# Success -> return to CLOSED
# Failure -> return to OPEN
# Example threshold: 5 failures in 10 seconds -> OPENAWS App Mesh for Circuit Breaking
AWS App Mesh is a service mesh that implements circuit breaking, retries, and timeout policies at the infrastructure level without code changes. You define circuit breaker policies in the virtual node or virtual router configuration. When an upstream service becomes unhealthy, App Mesh's Envoy proxy automatically opens the circuit, returning errors immediately rather than waiting for timeouts. This is particularly valuable in microservices architectures running on ECS or EKS.
# App Mesh virtual node with circuit breaker
# (JSON configuration)
{
'spec': {
'listeners': [{
'outlierDetection': {
'consecutiveErrors': 5,
'interval': {'unit': 'ms', 'value': 10000},
'baseEjectionDuration': {'unit': 's', 'value': 30},
'maxEjectionPercent': 50
}
}]
}
}Retry Logic and Exponential Backoff
Retry logic automatically reattempts failed operations, but naive retry logic (immediate retry in a tight loop) can worsen overload situations. Exponential backoff increases the wait time between retries exponentially: 1s, 2s, 4s, 8s... This reduces load on a struggling service and gives it time to recover. Jitter (randomising retry intervals) prevents the thundering herd problem where all clients retry simultaneously after a brief outage. The AWS SDK implements exponential backoff with jitter automatically.
# AWS SDK retries with exponential backoff automatically
# Default retry config for most AWS services:
# Max retries: 3-5 (varies by service)
# Base delay: 100ms
# Max delay: ~20 seconds
# Python boto3 custom retry configuration
import boto3
from botocore.config import Config
config = Config(
retries={'max_attempts': 5, 'mode': 'adaptive'}
)
client = boto3.client('s3', config=config)Idempotency for Safe Retries
Retries are only safe if operations are idempotent — performing the same operation multiple times produces the same result. For example, creating an S3 object with the same key is idempotent (same result). But placing an order twice creates two orders — not idempotent. Design APIs to be idempotent using client-supplied idempotency keys: the server stores the result of the first request and returns the same result for subsequent requests with the same key. DynamoDB, SQS, and API Gateway support idempotency key patterns.
# SQS message deduplication ID for FIFO queues
aws sqs send-message \
--queue-url https://sqs.us-east-1.amazonaws.com/123/orders.fifo \
--message-body '{"orderId":"ord-123","items":[...]}' \
--message-group-id 'customer-456' \
--message-deduplication-id 'ord-123-attempt-1'
# SQS deduplicates messages with same ID for 5 minutesTimeout Configuration
Without explicit timeouts, a slow downstream service causes threads to block indefinitely, exhausting the connection pool and causing cascading failures. Set timeouts at every layer: connection timeout (time to establish TCP connection), read timeout (time to receive a response), and overall request timeout. In AWS, configure ELB idle timeout (default 60s), Lambda execution timeout (max 15 min), and API Gateway integration timeout (max 29s). Timeouts trigger your retry or circuit-breaker logic.
# Lambda: set execution timeout
aws lambda update-function-configuration \
--function-name my-function \
--timeout 30
# ALB: configure idle timeout
aws elbv2 modify-load-balancer-attributes \
--load-balancer-arn <ALB-ARN> \
--attributes Key=idle_timeout.timeout_seconds,Value=60
# API Gateway: integration timeout max 29000msDead Letter Queues for Failed Processing
When message processing fails repeatedly, a Dead Letter Queue (DLQ) captures messages that could not be processed after the maximum number of receive attempts. Configure DLQs on SQS queues and Lambda event source mappings to prevent bad messages from blocking your queue indefinitely. Messages in the DLQ can be inspected, replayed after fixing the bug, or archived. DLQs are a critical component of resilient event-driven architectures.
# Configure DLQ on SQS queue
aws sqs set-queue-attributes \
--queue-url https://sqs.us-east-1.amazonaws.com/123/main-queue \
--attributes '{
"RedrivePolicy": "{\"deadLetterTargetArn\":\"arn:aws:sqs:us-east-1:123:dlq\",\"maxReceiveCount\":3}"
}'
# After 3 failed processing attempts, message goes to DLQObserving Failures with CloudWatch
Effective health checks and circuit breakers require monitoring to understand failure patterns. CloudWatch is the observability layer: create alarms on ELB UnHealthyHostCount (instances failing health checks), Lambda Errors rate, SQS NumberOfMessagesSentToDLQ (messages hitting DLQ), and Target group RequestCountPerTarget. Set up SNS notifications so your on-call team is alerted immediately when automated health checks detect degradation.
# CloudWatch alarm for unhealthy hosts
aws cloudwatch put-metric-alarm \
--alarm-name 'ALB-UnhealthyHosts' \
--alarm-description 'Alert when targets fail health checks' \
--metric-name UnHealthyHostCount \
--namespace AWS/ApplicationELB \
--period 60 \
--evaluation-periods 2 \
--threshold 1 \
--comparison-operator GreaterThanOrEqualToThreshold \
--alarm-actions arn:aws:sns:us-east-1:123:ops-teamQuick Check
Test your understanding of AWS Solutions Architect (SAA-C03) concepts from this lesson.
Lesson Recap
In this lesson you learned: ELB and Route 53 health checks automate failure detection at the infrastructure level, circuit breakers prevent cascading failures by stopping calls to unhealthy services, and exponential backoff with jitter makes retries safe under load. Dead Letter Queues capture failed messages for inspection. Next up we explore RTO, RPO, and disaster recovery tiers.
Frequently asked questions
Is the “Health Checks, Circuit Breakers, and Retry Logic” lesson free?
Yes — the full text of “Health Checks, Circuit Breakers, and Retry Logic” is free to read here on the web, and the AWS Solutions Architect course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AWS Solutions Architect course, upgrade to CoddyKit PRO.
What will I learn in “Health Checks, Circuit Breakers, and Retry Logic”?
Use ELB health checks, Route 53 endpoint checks, and application-level circuit breakers to detect failures and reroute traffic automatically. You practise AWS Solutions Architect with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AWS Solutions Architect?
No prior experience is required. AWS Solutions Architect on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Health Checks, Circuit Breakers, and Retry Logic” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AWS Solutions Architect lesson?
Yes. Every AWS Solutions Architect lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- HA vs Fault Tolerance: Definitions and Trade-offs
- Multi-AZ Patterns for Stateful Services
- Multi-Region Active-Active and Active-Passive
- Health Checks, Circuit Breakers, and Retry Logic