实现一个 /health 端点,聚合数据库、Redis、下游服务状态并返回 503 当依赖异常
解读
国内生产环境普遍要求“可读、可报警、可灰度”。/health 是 K8s 存活与就绪探针的唯一依据,直接影响 Pod 重启与流量切换。面试官想确认三件事:
- 能否把“业务可用”与“进程可用”区分——进程活着但 DB 连不上必须报 503,否则流量仍会被转发到故障实例;
- 能否在 3~5 s 内完成多依赖并行探测,不阻塞事件循环;
- 是否具备可观测性意识:耗时、错误分类、降级策略、日志格式要符合阿里/腾讯/字节等内部规范(JSON 统一日志、带 traceId)。
因此,答题必须给出“并行检测 + 超时熔断 + 详细日志 + 可插拔”的完整代码,并解释为何不用同步 try/catch、为何不用 Promise.allSettled 之外的写法。
知识点
- 非阻塞健康检查:使用 Promise.race 实现超时,避免单个依赖 Hang 住整个探针;
- 资源池探针:mysql2/pool、ioredis 自带 ping,不额外建连接;
- 下游 HTTP 探针:用 http/http2 模块原生请求,设置 agent.keepAlive=false、timeout=2 s,防止健康检查流量污染连接池;
- 状态聚合算法:任一关键依赖异常即整体 503,但返回体里需明细到“db:down/redis:up”方便排障;
- 错误分类:对 DNS 解析、TCP 超时、证书失效、读写超时给出不同 errno,方便告警平台做收敛;
- 性能指标:记录每个依赖耗时,通过 histogram 暴露给 Prometheus(面试时口头说明即可);
- 安全合规:/health 不暴露在内网之外,若必须公网则加固定源 IP 鉴权;
- K8s 就绪与存活区别:就绪探针失败仅摘流,存活探针失败会重启容器,代码里可用 ?type=liveness 参数区分检查深度。
答案
以下示例基于 NestJS(国内大厂 Node 主流选型),但刻意使用原生 promise 与 DI,方便迁移到 Express/Egg。
// health.controller.ts
import { Controller, Get, Query, Res, HttpStatus, Logger } from '@nestjs/common';
import { Response } from 'express';
import * as mysql from 'mysql2/promise';
import * as Redis from 'ioredis';
import * as http from 'http';
const DB_CONFIG = { host: 'rds-internal.mysql.rds.aliyuncs.com', user: 'health', password: process.env.DB_PWD, database: 'demo', connectTimeout: 2000 };
const REDIS_CONFIG = { host: 'redis-cache.redis.rds.aliyuncs.com', port: 6379, password: process.env.REDIS_PWD, connectTimeout: 2000, maxRetriesPerRequest: 0 };
const DOWNSTREAM = { hostname: 'user-service', port: 80, path: '/health', timeout: 2000 };
@Controller()
export class HealthController {
private logger = new Logger('Health');
private dbPool = mysql.createPool(DB_CONFIG);
private redis = new Redis(REDIS_CONFIG);
@Get('/health')
async health(@Query('type') type: string, @Res() res: Response) {
const start = Date.now();
const results = await Promise.allSettled([
this.checkDb(),
this.checkRedis(),
this.checkDownstream()
]);
const [db, redis, downstream] = results.map(r => r.status === 'fulfilled' ? r.value : r.reason);
const allUp = db.status === 'up' && redis.status === 'up' && downstream.status === 'up';
const cost = Date.now() - start;
this.logger.log(`health=${allUp ? 'UP' : 'DOWN'} db=${db.status} redis=${redis.status} downstream=${downstream.status} cost=${cost}ms`);
res.status(allUp ? HttpStatus.OK : HttpStatus.SERVICE_UNAVAILABLE).json({
status: allUp ? 'UP' : 'DOWN',
cost,
details: { db, redis, downstream }
});
}
private async checkDb() {
try {
const conn = await this.dbPool.getConnection();
await conn.ping();
conn.release();
return { status: 'up', latency: 0 };
} catch (e) {
this.logger.warn(`db down: ${e.message}`);
return { status: 'down', error: e.code || 'UNKNOWN' };
}
}
private async checkRedis() {
try {
const latency = await this.redis.ping();
return { status: 'up', latency };
} catch (e) {
this.logger.warn(`redis down: ${e.message}`);
return { status: 'down', error: e.code || 'UNKNOWN' };
}
}
private async checkDownstream(): Promise<any> {
return new Promise((resolve) => {
const timer = setTimeout(() => resolve({ status: 'down', error: 'TIMEOUT' }), DOWNSTREAM.timeout);
const req = http.request(DOWNSTREAM, (res) => {
clearTimeout(timer);
if (res.statusCode === 200) resolve({ status: 'up', latency: 0 });
else resolve({ status: 'down', error: `HTTP_${res.statusCode}` });
});
req.on('error', e => {
clearTimeout(timer);
resolve({ status: 'down', error: e.code || 'UNKNOWN' });
});
req.end();
});
}
}
关键点解释
- 使用 Promise.allSettled 保证三个探针并行,任一失败仍继续;
- 每个探针内部自带超时(DB connectTimeout、Redis connectTimeout、HTTP 外部 setTimeout),防止事件循环被占满;
- 返回体中 details 字段给到具体组件状态,方便运维一眼定位;
- 日志统一打印 cost 与组件状态,接入阿里 SLS 或腾讯 CLS 后可配置告警;
- 整体状态码与 K8s 就绪探针约定一致:非 200 即摘流。
拓展思考
- 缓存健康结果:高并发场景下每秒数千次探针会打爆 DB/Redis,可在内存缓存 3 s 结果,通过 Date 时间戳判断过期;
- 深度检查与浅检查分离:浅检查只 ping,深度检查可执行 select 1+1、Redis get 一个真实 key、下游查询一个用户白名单接口;通过 ?depth=deep 参数切换,存活探针用浅检查,就绪探针可选深度;
- 熔断与降级:若下游频繁超时,可在内存维护失败计数器,连续失败 3 次后标记为“熔断”,探针直接返回 503,避免雪崩;
- 多区域探测:国内主流云厂商支持多可用区,若应用跨区部署,可在 /health 里带上 region 字段,方便 CDN 与灰度平台做流量调度;
- 安全加固:/health 默认绑定在 0.0.0.0:3000,需通过 ingress 注解 nginx.ingress.kubernetes.io/whitelist-source-range 限制只允许 100.64.0.0/10(K8s 内网段)访问,防止外网扫描泄露内部拓扑。