运行状况检查、断路器与重试逻辑
使用 ELB 运行状况检查、Route 53 终端节点检查和应用级断路器检测故障,并自动重新路由流量
运行状况检查、断路器与重试逻辑 是 CoddyKit 上的免费 AWS Solutions Architect 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AWS Solutions Architect 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AWS Solutions Architect 课程共包含 4 节课。
为什么自动故障检测很重要
在分布式系统中,组件会持续发生故障——实例崩溃、网络分区出现、下游服务过载。如果没有自动故障检测,流量仍会继续发送到已故障的组件,从而导致级联故障。AWS 提供多层运行状况检查:ELB 运行状况检查检测不健康实例,Route 53 运行状况检查检测不健康 Endpoint,Auto Scaling替换已故障实例。断路器和重试等应用层模式则进一步完善了整体韧性。
ELB Health 检查
Elastic Load Balancer Health 检查会定期向已注册的目标发送请求,以确定目标是否健康。您可以配置Health 检查路径(例如 /health)、协议、Port、间隔(Default 为 30 Seconds)以及健康/不健康阈值(连续 Success 或 Failure 的次数)。当某个目标未通过 Health 检查时,ELB 会停止向其路由流量。系统会持续重新评估该目标,目标通过健康阈值后会重新加入。
# 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 检查
Route 53 Health 检查会从全球多个位置监控端点,并与 DNS failover 路由协同工作。共有三种类型:端点检查会直接轮询您的应用 URL;计算检查使用 AND/OR 逻辑组合多个子 Health 检查(适用于复杂的监控场景);CloudWatch 告警检查将健康状态的判定交给 CloudWatch——当您无法公开健康端点,或需要基于指标做出健康判断时,这种方式非常有用。
# 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 检查
Auto Scaling Groups可以使用两种 Health 检查:EC2 Health 检查在 hypervisor 层检测实例 Failure(实例状态检查 Failure);ELB Health 检查对应用的感知能力更强——实例可能仍在运行,但提供的服务返回 errors,而 ELB Health 检查可以捕获这种情况。您可以将 ASG 配置为使用 ELB Health 检查,使应用层 Failure 也能触发实例替换,而不仅仅是底层 EC2 Failure。
# 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 startupCircuit Breaker 模式
Circuit breaker是一种应用层模式,它通过监控对下游服务的调用,并在 Failure 超过阈值时暂时停止调用,从而防止 Failure 级联。Circuit 有三种状态:Closed(正常运行)、OPEN(Failure 超过阈值,立即阻止调用)和HALF(timeout 后允许少量 test 调用,以检查服务是否已恢复)。AWS App Mesh 和 Resilience4j 等应用 SDK 都实现了这种模式。
# 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 -> OPEN用于 Circuit Breaking 的 AWS App Mesh
AWS App Mesh是一种 service mesh,可在基础设施层实现 Circuit breaking、重试和 timeout 策略,而无需修改代码。您可以在 virtual node 或 virtual router 配置中定义Circuit breaker 策略。当上游服务变得不健康时,App Mesh 的 Envoy proxy 会自动打开 Circuit,立即返回 errors,而不是等待 timeout。在运行于 ECS 或 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
}
}]
}
}重试逻辑与指数退避
重试逻辑会自动重新尝试失败的操作,但简单的重试逻辑(在紧密循环中立即重试)可能会使过载情况恶化。指数退避会按指数增加重试之间的等待时间:1s、2s、4s、8s……这可以降低对负载过高服务的压力,并给它恢复的时间。抖动(随机化重试间隔)可以防止出现惊群问题:短暂中断后,所有 client 同时重试。AWS SDK 会自动使用带抖动的指数退避。
# 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)通过幂等性实现安全重试
只有当操作是幂等的时,重试才是安全的——多次执行同一操作会产生相同结果。例如,使用相同 Key 创建 S3 对象具有幂等性(结果相同);但两次下单会创建两个订单,因此不具备幂等性。请使用由 client 提供的幂等 Key来设计幂等 API:服务器保存第一个请求的结果,并对后续使用相同 Key 的请求返回相同结果。DynamoDB、SQS 和 API Gateway 都支持幂等 Key 模式。
# 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 配置
如果没有明确设置timeout,缓慢的下游服务会导致线程无限期阻塞,耗尽连接池并引发级联 Failure。请在每一层设置 timeout:连接 timeout(建立 TCP 连接所需的时间)、读取 timeout(接收响应所需的时间)以及整体请求 timeout。在 AWS 中,请配置 ELB idle timeout(Default 为 60s)、Lambda 执行 timeout(最长 15 分钟)和 API Gateway 集成 timeout(最长 29s)。Timeout 会触发您的重试或 Circuit-breaker 逻辑。
# 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 29000ms用于失败处理的 Dead Letter 队列
当消息处理反复 Failure 时,Dead Letter Queue(DLQ)会捕获在达到最大接收尝试次数后仍无法处理的消息。请在 SQS 队列和 Lambda 事件源映射上配置 DLQ,防止错误消息无限期阻塞队列。您可以检查 DLQ 中的消息,在修复错误后重新处理,或将其归档。DLQ 是具备弹性的事件驱动架构中的关键组件。
# 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 DLQ使用 CloudWatch 观察 Failure
有效的 Health 检查和 Circuit breaker 需要监控来了解 Failure 模式。CloudWatch是可观测性层:针对ELB UnHealthyHostCount(未通过 Health 检查的实例)、Lambda Errors速率、SQS NumberOfMessagesSentToDLQ(进入 DLQ 的消息)以及目标组 RequestCountPerTarget创建告警。请设置 SNS 通知,以便自动 Health 检查检测到服务降级时,值班团队立即收到提醒。
# 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-team快速检查
请测试您对本课 AWS Solutions Architect(SAA-C03)概念的理解。
课程回顾
本课您学习了:ELB 和 Route 53 Health 检查可在基础设施层自动检测 Failure,Circuit breaker 通过停止对不健康服务的调用来防止级联 Failure,以及带抖动的指数退避可让重试在负载下保持安全。Dead Letter 队列会捕获失败消息,供您检查。接下来,我们将学习 RTO、RPO 和灾难恢复层级。
常见问题解答
「运行状况检查、断路器与重试逻辑」课时是免费的吗?
是的 — 「运行状况检查、断路器与重试逻辑」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AWS Solutions Architect 课程的其余内容,请升级到 CoddyKit PRO。 AWS Solutions Architect 课程共包含 4 节课。
「运行状况检查、断路器与重试逻辑」这节课中我会学到什么?
使用 ELB 运行状况检查、Route 53 终端节点检查和应用级断路器检测故障,并自动重新路由流量 你通过在浏览器中直接运行的动手代码来练习 AWS Solutions Architect,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AWS Solutions Architect 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AWS Solutions Architect 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「运行状况检查、断路器与重试逻辑」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AWS Solutions Architect 课中编写并运行代码吗?
能。每节 AWS Solutions Architect 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- HA 与容错:定义与权衡
- 有状态服务的多 AZ 模式
- 多 Region 主动-主动与主动-被动
- 运行状况检查、断路器与重试逻辑