pattern/deployment/feature-flags
- Bun
- Bun RedisClient
- PostgreSQL
- Redis
- TypeScript
- node-postgres
- node:crypto
- Docker
Separa deploy de release: o código vai desligado e liga para uma fração das contas sem deploy; kill switch desliga em milissegundos.
pattern/deployment/feature-flags
Cenário
pix-engine-v2 liberado para 25% das contas; no incidente, o kill switch volta todas as instâncias ao motor antigo.
Planta
Sequência9 passos — reproduza para seguir o fluxo
Como funciona
4passos
Separa deploy de release: o código vai desligado e liga para uma fração das contas, com kill switch
Esconde cada passo: lembre antes de tocar para revelar.
Snapshot das flags do PostgreSQL em memória; avaliação sem banco
Bucket sha256(flagKey:conta) mod 100 estável por conta
Mudança gravada no PostgreSQL e publicada no Redis após o commit
Instâncias recarregam o snapshot; enabled = false desliga para todos
Trade-offs
O que se ganha, o que se paga
Vantagens
Release sem deploy, kill switch instantâneo
Avaliação em memória
Custos
Cada flag = um if e dois caminhos a testar
Flag esquecida vira dívida
Código
pattern/deployment/feature-flags
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec feature-flags-db sh -c 'pg_isready -h 127.0.0.1 -U postgres' >/dev/null 2>&1; do sleep 1; doneuntil docker exec feature-flags-cache redis-cli ping >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f feature-flags-db feature-flags-cacheSaída: com 25%, pix-engine-v2 ligada para 2 de 20 contas (CC-0015, CC-0020); após o kill switch, 0 de 20.
Código
src/demo.ts// Demo: the new PIX engine is on for 25% of accounts by a stable bucket; the kill switch reaches the running process through Redis.
import { createHash } from "node:crypto";
import { RedisClient } from "bun";
import pg from "pg";
const FLAG_CHANNEL = "feature_flag:prod:changed";
const FLAG_ROLLOUT_PERCENT = 25;
const ACCOUNTS_COUNT = 20;
const pool = new pg.Pool({ connectionString: Bun.env.FEATURE_FLAGS_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/feature_flags_db" });
const redis = new RedisClient(Bun.env.FEATURE_FLAGS_REDIS_URL ?? "redis://localhost:6379");
type FlagRecord = { enabled: boolean; rolloutPercentage: number };
// In-memory snapshot: evaluation never queries the database; a reload replaces it whole.
const snapshot = new Map<string, FlagRecord>();
async function snapshotReload(): Promise<void> {
const { rows } = await pool.query<{ key: string; enabled: boolean; rollout_percentage: number }>("SELECT key, enabled, rollout_percentage FROM feature_flags WHERE environment = 'prod'");
for (const row of rows) snapshot.set(row.key, { enabled: row.enabled, rolloutPercentage: row.rollout_percentage });
}
// flagKey in the hash: the same account always lands in the same bucket of this flag, and raising 25% → 50% only adds accounts.
const flagBucket = (flagKey: string, accountId: string) => createHash("sha256").update(`${flagKey}:${accountId}`).digest().readUInt32BE(0) % 100;
// Unknown flag or kill switch → the old path; otherwise the stable bucket decides.
function flagEvaluate(flagKey: string, accountId: string): boolean {
const record = snapshot.get(flagKey);
return Boolean(record?.enabled) && flagBucket(flagKey, accountId) < record!.rolloutPercentage;
}
await pool.query("UPDATE feature_flags SET enabled = true, rollout_percentage = $1 WHERE key = 'pix-engine-v2'", [FLAG_ROLLOUT_PERCENT]);
await snapshotReload();
// A subscribed connection cannot run other commands: the watch gets its own.
const subscriber = await redis.duplicate();
const reloaded = Promise.withResolvers<void>();
await subscriber.subscribe(FLAG_CHANNEL, () => void snapshotReload().then(reloaded.resolve));
const accounts = Array.from({ length: ACCOUNTS_COUNT }, (_, index) => `CC-${String(index + 1).padStart(4, "0")}`);
const accountsOn = () => accounts.filter((accountId) => flagEvaluate("pix-engine-v2", accountId));
console.log(` [ROLLOUT ${FLAG_ROLLOUT_PERCENT}%] pix-engine-v2 on for ${accountsOn().length}/${ACCOUNTS_COUNT} accounts: ${accountsOn().join(", ")}`);
// Kill switch: commit in PostgreSQL first, then publish — an instance that reloads on the message already sees the new row.
await pool.query("UPDATE feature_flags SET enabled = false, updated_by = 'ops-maria', updated_at = now() WHERE key = 'pix-engine-v2' AND environment = 'prod'");
await redis.publish(FLAG_CHANNEL, "pix-engine-v2");
await reloaded.promise;
console.log(` [KILL SWITCH] pushed by Redis and reloaded: pix-engine-v2 on for ${accountsOn().length}/${ACCOUNTS_COUNT} accounts`);
await subscriber.unsubscribe();
subscriber.close();
redis.close();
await pool.end();
Nível
intermediário
6/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine:5432
Rediscache / estrutura de dados
redis:7-alpine:6379
Banco
sql/01_schema.sql
Variáveis de ambiente
Relações
Onde ele se encaixa
Por que se relacionam
Próximo passo
Teste rápido
Qual é o próximo passo depois de Feature Flags?
Troca de versão sem parada. Abrir Blue-Green Deployment
Seu progresso
0/157 estudados
Fica salvo só neste navegador.