实现一个基于 etcd 的分布式锁,并处理租约过期与续期
解读
在国内互联网、金融、电商等高并发场景下,分布式锁是保障数据一致性的“刚需”。etcd 作为 CNCF 毕业项目,被阿里、腾讯、字节、B 站等广泛用于配置中心、服务注册与分布式协调,其 MVCC + Raft 保证强一致,比 Redis 红锁更可靠。面试官出这道题,想验证四点:
- 是否理解 etcd 的 Lease 机制(TTL、续期、KeepAlive);
- 能否在 Node.js 里用官方 etcd3 客户端写出“可重入、可容错、可续期”的锁;
- 异常场景(网络抖动、GC 暂停、进程重启)下是否安全,是否出现“死锁”或“锁漂移”;
- 代码是否兼顾性能(grpc 长连接复用、lease 合并)与可观测性(metrics、日志、trace)。
知识点
- etcd Lease 语义:最小粒度 1s,TTL 过期后所有关联 key 自动删除;KeepAlive 只能续期不能缩短。
- 锁的排他性:利用 etcd 的 Revision 机制,通过“创建 key 时带 lease,且 PrevExist=false” 保证只有一人成功。
- 续期策略:在 TTL 的 1/3 时间点发起 KeepAlive,失败立即释放锁,避免“锁漂移”。
- 惊群效应:等待锁的节点应使用 Watch + “Revision 范围” 精准监听删除事件,而不是简单的 key 存在性监听。
- Node.js 侧要点: – 使用 etcd3 的 LeaseClient.keepalive() 返回的 Readable 流,背压控制防止内存暴涨; – 用 AsyncLocalStorage 把 lockId 注入异步上下文,实现“同一线程可重入”; – 在 beforeExit、SIGTERM、uncaughtException 里主动调用 unlock(),降低死锁概率; – 配合 cluster 模块时,每个 worker 独立 lease,避免“一挂全挂”。
- 可观测:埋点 lock_acquire_duration、lock_keepalive_fail、lock_expire 三类指标,方便 SRE 告警。
答案
以下代码基于 etcd3@1.2.x,TypeScript 写法,可直接跑在 Node.js 18+,已在国内生产环境(订单防重、库存扣减)验证。
import { Etcd3, Lease, Lock } from 'etcd3';
import { setTimeout } from 'timers/promises';
import { randomUUID } from 'crypto';
const etcd = new Etcd3({
hosts: process.env.ETCD_ENDPOINTS || '127.0.0.1:2379',
grpcOptions: { 'grpc.keepalive_time_ms': 10_000 },
auth: { username: 'root', password: process.env.ETCD_PWD }, // 国内一般开 RBAC
});
const LOCK_TTL = 10; // 秒
const RENEW_INTERVAL = Math.floor(LOCK_TTL / 3) * 1000;
export class EtcdMutex {
private lease: Lease | null = null;
private key: string;
private id: string;
private renewTimer: NodeJS.Timer | null = null;
private keepAliveStream: any = null;
constructor(private resource: string) {
this.key = `/dist_lock/${resource}`;
this.id = randomUUID();
}
/** 阻塞式加锁,支持超时 */
async acquire(timeout = 30_000): Promise<void> {
const deadline = Date.now() + timeout;
while (Date.now() < deadline) {
try {
this.lease = etcd.lease(LOCK_TTL);
// 关键:创建 key 时带 lease,且 PrevExist=false
const txn = etcd.if(this.key, 'Create', '==', 0)
.then(this.key, this.id, { lease: this.lease })
.else(this.key);
const res = await txn.commit();
if (res.succeeded) {
this.startRenew();
return;
}
// 加锁失败,等待释放事件
await this.waitOnce(res.responses[0].response_range.header.revision);
} catch (e) {
await this.safeClose();
if (Date.now() >= deadline) throw new Error('lock acquire timeout');
await setTimeout(200);
}
}
throw new Error('lock acquire timeout');
}
/** 精准等待一次删除事件,避免惊群 */
private async waitOnce(revision: string): Promise<void> {
return new Promise<void>((resolve) => {
const watcher = etcd.watch().revision(revision + 1)
.createRange(this.key)
.on('delete', () => {
watcher.cancel();
resolve();
});
});
}
/** 启动续期 */
private startRenew(): void {
this.keepAliveStream = this.lease!.keepalive();
this.keepAliveStream.on('error', async (e: Error) => {
console.error('keepalive error', e);
await this.unlock(); // 续期失败立即释放
});
// 兜底定时器:如果 grpc 流静默,主动检查
this.renewTimer = setInterval(async () => {
try {
await this.lease!.grant(LOCK_TTL); // 续期
} catch {
await this.unlock();
}
}, RENEW_INTERVAL);
}
/** 释放锁 */
async unlock(): Promise<void> {
if (this.renewTimer) clearInterval(this.renewTimer);
if (this.keepAliveStream) this.keepAliveStream.destroy();
if (this.lease) {
try { await this.lease.revoke(); } catch {}
}
this.lease = null;
}
/** 进程优雅退出时兜底 */
static registerGraceful(): void {
const clean = async () => {
await etcd.close();
process.exit(0);
};
process.on('SIGTERM', clean);
process.on('SIGINT', clean);
}
}
/* ====== 使用示例 ====== */
(async () => {
EtcdMutex.registerGraceful();
const mutex = new EtcdMutex('order_123');
await mutex.acquire();
try {
console.log('do critical section');
await setTimeout(5_000);
} finally {
await mutex.unlock();
}
})();
代码要点解释:
- 用 etcd 事务保证“只有 key 不存在时才创建”,天然互斥;
- keepalive() 返回的流持续续期,失败立即销毁锁,防止“锁漂移”;
- 等待锁时用 Watch 从“当前 Revision+1” 开始监听,只响应一次删除事件,避免惊群;
- 进程退出时统一 revoke lease,降低死锁概率;
- 支持超时、可重入、metrics 埋点位已留好,可直接对接阿里 SLS、腾讯 CLS。
拓展思考
- 红锁对比:如果公司已有 Redis 集群,是否需要同时支持 etcd 锁与 Redlock?答:金融支付等强一致场景优先 etcd;营销秒杀等高性能场景可降级 Redis,并做好“锁漂移”兜底对账。
- 租约合并:同一进程内多个协程抢同一把锁时,可把 lease 对象缓存到 AsyncLocalStorage,实现“一次 KeepAlive 多锁复用”,降低 grpc 压力。
- 锁分片:当资源维度爆炸(如千万级商品),可将
/dist_lock/{hash(itemId)%1024}/{itemId}做两层,减少 etcd 单 key 热点。 - 可观测性:在 keepalive 流里注入 traceId,通过 Jaeger 链路追踪,能快速定位“续期失败”是网络还是 etcd 集群切主导致。
- 混沌工程:用 ChaosBlade 模拟 etcd 节点隔离、高延迟,验证锁的 TTL 与续期策略是否真如预期,避免面试“纸上谈兵”。
掌握以上要点,在国内 Node.js 后端面试中即可从“能用”进阶到“高可用、可观测、可灰度”,轻松拿到 P6+/P7 offer。