Pular para o conteúdo

Leader Election

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.

passos
4
arquivos
6
testes
0
tecnologias
5

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

Estados
5/5
heartbeat renova(Lua confere o dono)FOLLOWERLEADERSET NX PX ok,INCR do mandatorenovação falhoulease do líder expirou
5

5 passos — reproduza para seguir o fluxo

  • chamada
  • resposta ou assíncrono
  • falha
  • passo
  • toque num nó para focar
  • repouso ou sucesso
  • transição
  • falha ou recusa
  • Outras plantas de estados

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.

  1. 1

    SET leader:reconciliation <dono> NX PX <ttl>; quem vence faz INCR do mandato

  2. 2

    Renovação por LuaPEXPIRE só se o valor ainda for o dono

  3. 3

    Renovação falhouVira FOLLOWER

  4. 4

    Heartbeat × 3 abaixo do TTL

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .env.exampleinfra
  • docker.shinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec leader-election-cache redis-cli ping >/dev/null 2>&1; do sleep 1; done
  3. bun install# dependências
  4. bun run demo# roda o cenário
  5. docker rm -f leader-election-cache

Saída: reconciler-1 eleito no mandato 1; após a queda, reconciler-2 assume em menos de 2300 ms no mandato 2.

Requisitos
BunDocker
Sobe junto
Redis

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

Linhas de TypeScript
43
Tipo
B — um serviço (docker.sh)

Domínio financeiro

  • Conciliação

Padrões do catálogo que implementa

Infraestrutura

  • Rediscache / estrutura de dados

    redis:7-alpine:6379

Variáveis de ambiente

LEADER_ELECTION_REDIS_URL
redis://localhost:6379

Parecidos

Por que se relacionam

Teste rápido

Qual destes combina com Leader Election?

Próximo projeto, EscalabilidadeAuto-Scaling
Esc

↑ ↓ navegarEnter abrir239 resultados