雪崩不是冰山崩塌,而是服务之间层层依赖引发的连锁灾难。 本文将从真实项目出发,深度拆解一次“服务雪崩”的排障全过程,并分享实战经验与代码示例。
在微服务架构中,A调用B,B又调用C,一旦C出现性能问题或不可用,会导致B响应变慢甚至阻塞,最终A大量请求堆积,触发线程耗尽、连接满载、系统雪崩。
典型特征:
我们遇到过一个典型问题:
服务 A(订单服务)依赖服务 B(用户服务),服务 B 在高峰期因为某个慢查询挂死,引发服务 A 大量超时,最终整个订单模块全部挂掉。
当时的表现是:
借助 Prometheus + Grafana + Alertmanager 报警:
java.util.concurrent.TimeoutException。# FastAPI 集成 Jaeger 示例
from fastapi import FastAPI
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.exporter.jaeger.thrift import JaegerExporter
from opentelemetry.sdk.trace.export import BatchSpanProcessor
app = FastAPI()
jaeger_exporter = JaegerExporter(
agent_host_name='localhost',
agent_port=6831,
)
trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(jaeger_exporter))
FastAPIInstrumentor.instrument_app(app)Trace 图展示了服务 A 卡在调用服务 B 的某个 /user/profile 接口。
查看用户服务日志:
SELECT * FROM user_table WHERE last_login_time < '2020-01-01';该 SQL 未命中索引,在并发高时数据库锁表,引发线程池阻塞。
# 加入FastAPI超时机制 & 熔断保护(示例)
import httpx
from tenacity import retry, stop_after_attempt, wait_fixed
@retry(stop=stop_after_attempt(3), wait=wait_fixed(1))
def call_user_service(user_id):
try:
with httpx.Client(timeout=2.0) as client:
return client.get(f"http://user-service/user/{user_id}").json()
except httpx.RequestError:
return {"error": "fallback user"}
# FastAPI 路由中调用
@app.get("/order/{id}")
def get_order(id: int):
user_info = call_user_service(get_user_id_by_order(id))
return {"order_id": id, "user": user_info}关键做法:
CREATE INDEX idx_user_login ON user_table(last_login_time);排障环节 | 工具/策略 | 建议 |
|---|---|---|
快速判断 | Prometheus + Grafana | 指标告警要及时 |
精准定位 | Trace(Jaeger/Zipkin) | 要开启链路追踪 |
应急处理 | 熔断 + 超时 + fallback | 最小侵入止血 |
根因修复 | SQL优化 + 线程隔离 + 缓存 | 病灶清除 |
防御改进 | 熔断/限流/缓存/降级 | 体系化设计 |
服务雪崩并不可怕,可怕的是没有预案、没有防线、没有监控。只有建立起主动监测、快速定位、自动熔断的能力体系,才能真正做到:
“崩溃不可避免,但你可以不跟着崩。”
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。