pattern/concurrency/leader-election
- Bun
- Bun RedisClient
- Redis
- TypeScript
- Docker
Entre réplicas, só quem detém o lease no Redis executa o trabalho único e o renova por heartbeat; se some, o lease expira e outro assume. Use em jobs únicos de cluster.
pattern/concurrency/leader-election
Cenário
Três réplicas de conciliação; o líder cai sem liberar o lease e, após o TTL, outra assume com mandato maior.
Planta
Estados5 passos — reproduza para seguir o fluxo
Como funciona
4passos
Entre réplicas, só quem detém o lease no Redis executa o trabalho único e o renova por heartbeat
Esconde cada passo: lembre antes de tocar para revelar.
SET leader:reconciliation <dono> NX PX <ttl>; quem vence faz INCR do mandato
Renovação por LuaPEXPIRE só se o valor ainda for o dono
Renovação falhouVira FOLLOWER
Heartbeat × 3 abaixo do TTL
Trade-offs
O que se ganha, o que se paga
Vantagens
Execução única sem coordenador próprio
Failover em até um TTL
Custos
Redis é ponto único de coordenação
Lacuna até a expiração; líder pausado exige fencing token
Código
pattern/concurrency/leader-election
6 arquivos./
src/
Executar com Docker
./docker.shuntil docker exec leader-election-cache redis-cli ping >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f leader-election-cacheSaída: reconciler-1 eleito no mandato 1; após a queda, reconciler-2 assume em menos de 2300 ms no mandato 2.
Código
src/demo.ts// Demo: three reconciliation nodes elect one leader through a Redis lease; the leader crashes and another takes over after the TTL.
import { RedisClient } from "bun";
const redis = new RedisClient(Bun.env.LEADER_ELECTION_REDIS_URL ?? "redis://localhost:6379");
const LEASE_KEY = "leader:reconciliation";
const FENCING_KEY = "leader:reconciliation:fencing";
// Three missed heartbeats must fit inside the lease, or a slow tick costs the leadership for nothing.
const LEASE_TTL_MS = 1_500;
const HEARTBEAT_MS = 400;
// Renewal checks the owner and extends in one Lua call: a node never extends a lease that is not its own.
const RENEW_LUA = `if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('PEXPIRE', KEYS[1], ARGV[2]) end return 0`;
type Node = { nodeId: string; state: "FOLLOWER" | "LEADER"; owner: string; term: number; timer?: ReturnType<typeof setInterval> };
async function tick(node: Node): Promise<void> {
if (node.state === "LEADER") {
if ((await redis.send("EVAL", [RENEW_LUA, "1", LEASE_KEY, node.owner, String(LEASE_TTL_MS)])) !== 1) node.state = "FOLLOWER";
return;
}
// SET NX PX elects; a fresh owner per candidacy, and INCR hands the winner a term number that only grows.
const owner = `${node.nodeId}:${crypto.randomUUID()}`;
if ((await redis.send("SET", [LEASE_KEY, owner, "NX", "PX", String(LEASE_TTL_MS)])) !== "OK") return;
Object.assign(node, { state: "LEADER", owner, term: Number(await redis.send("INCR", [FENCING_KEY])) });
}
const nodes: Node[] = ["reconciler-1", "reconciler-2", "reconciler-3"].map((nodeId) => ({ nodeId, state: "FOLLOWER", owner: "", term: 0 }));
const leader = () => nodes.find((node) => node.state === "LEADER");
const until = async (condition: () => boolean) => {
while (!condition()) await Bun.sleep(20);
};
// Clears lease and term, so every run starts from term 1.
await redis.del(LEASE_KEY, FENCING_KEY);
for (const node of nodes) node.timer = setInterval(() => void tick(node), HEARTBEAT_MS);
await until(() => leader() !== undefined);
const first = leader() as Node;
console.log(` [ELECTION] leader ${first.nodeId}, term ${first.term}`);
// Crash: the leader stops renewing and keeps the lease until its TTL runs out.
clearInterval(first.timer);
const crashedAt = performance.now();
await until(() => nodes.some((node) => node !== first && node.state === "LEADER"));
const second = nodes.find((node) => node !== first && node.state === "LEADER") as Node;
// Worst case: the lease was renewed right before the crash, then a follower waits up to one heartbeat to try; one more heartbeat of margin.
const FAILOVER_MAX_MS = LEASE_TTL_MS + 2 * HEARTBEAT_MS;
const takeoverMs = performance.now() - crashedAt;
console.log(` [FAILOVER] ${first.nodeId} crashed; ${second.nodeId} took over in under ${FAILOVER_MAX_MS} ms: ${takeoverMs < FAILOVER_MAX_MS}, term ${second.term}`);
for (const node of nodes) clearInterval(node.timer);
redis.close();
Nível
introdutório
3/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
Rediscache / estrutura de dados
redis:7-alpine:6379
Variáveis de ambiente
Parecidos
Por que se relacionam
Teste rápido
Qual destes combina com Leader Election?
Instância única, agora no cluster. Abrir Singleton
Seu progresso
0/157 estudados
Fica salvo só neste navegador.