pattern/resilience/throttling
- Bun
- Bun RedisClient
- ElysiaJS
- Redis
- TypeScript
- Docker
Limita as chamadas que o sistema faz a um terceiro para nunca passar da cota: o excedente espera um token de um bucket no Redis compartilhado. Inverso do rate limiting.
pattern/resilience/throttling
Cenário
BACEN aceita 10 consultas/s; 20 consultas de PIX de uma vez passam pelo bucket (8 de rajada, 9/s) sem nenhum 429.
Planta
Sequência9 passos — reproduza para seguir o fluxo
Como funciona
4passos
Limita as chamadas que o sistema faz a um terceiro para nunca passar da cota
Esconde cada passo: lembre antes de tocar para revelar.
Lua repõe tokens pelo tempo, limita à capacidade e consome atomicamente
Sem token, devolve a espera; a chamada aguarda e tenta de novo
Bucket no RedisUma cota para todas as réplicas
Capacidade e taxa abaixo da cota, margem para relógio e rede
Trade-offs
O que se ganha, o que se paga
Vantagens
Fornecedor nunca recebe acima da cota
Cota única, nada descartado
Custos
Excedente fica mais lento
Demanda acima da cota acumula espera
Código
pattern/resilience/throttling
6 arquivos./
src/
Executar com Docker
./docker.shuntil docker exec throttling-cache redis-cli ping >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f throttling-cacheSaída: 20 consultas em cerca de 1,3 s → BACEN served 20, refused 0.
Código
src/demo.ts// Demo: 20 PIX status queries to BACEN (quota 10/s) through a token bucket in Redis — delayed, never refused.
import { RedisClient } from "bun";
import { Elysia } from "elysia";
const redis = new RedisClient(Bun.env.THROTTLING_REDIS_URL ?? "redis://localhost:6379");
const BACEN_URL = Bun.env.THROTTLING_BACEN_URL ?? "http://localhost:4302";
// Slightly below the quota BACEN announces: clock skew between replicas never pushes the fleet over it.
const BUCKET = { key: "throttle:bacen:pix-status", capacity: 8, tokensPerSecond: 9 };
// BACEN as a third party: its own quota per second, 429 above it.
const BACEN_QUOTA_PER_SECOND = 10;
let bacenTokens = BACEN_QUOTA_PER_SECOND;
let bacenUpdatedAt = performance.now();
const stats = { served: 0, refused: 0 };
const bacen = new Elysia().get("/pix/:endToEndId/status", ({ params, status }) => {
bacenTokens = Math.min(BACEN_QUOTA_PER_SECOND, bacenTokens + ((performance.now() - bacenUpdatedAt) * BACEN_QUOTA_PER_SECOND) / 1_000);
bacenUpdatedAt = performance.now();
if (bacenTokens < 1) return (stats.refused++, status(429, { error: "quota exceeded" }));
bacenTokens--;
return (stats.served++, { endToEndId: params.endToEndId, status: "SETTLED" });
}).listen(new URL(BACEN_URL).port);
// Refill by elapsed time and take a token in one atomic step; with no token, answer how long until the next one.
const BUCKET_SCRIPT = `
local capacity, rate, now = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3])
local tokens = tonumber(redis.call('HGET', KEYS[1], 'tokens')) or capacity
local updated = tonumber(redis.call('HGET', KEYS[1], 'updatedAt')) or now
tokens = math.min(capacity, tokens + math.max(0, now - updated) * rate / 1000)
local granted = 0
if tokens >= 1 then tokens = tokens - 1; granted = 1 end
redis.call('HSET', KEYS[1], 'tokens', tostring(tokens), 'updatedAt', tostring(math.max(now, updated)))
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / rate * 1000) + 1000)
return {granted, math.ceil((1 - math.min(1, tokens)) * 1000 / rate)}`;
// The call waits for a token, however long it takes: delayed, never discarded, and BACEN is never called before.
async function throttleAcquire(): Promise<void> {
for (;;) {
const [granted, waitMs] = (await redis.send("EVAL", [BUCKET_SCRIPT, "1", BUCKET.key, String(BUCKET.capacity), String(BUCKET.tokensPerSecond), String(Date.now())])) as [number, number];
if (granted === 1) return;
await Bun.sleep(waitMs);
}
}
await redis.del(BUCKET.key);
const started = performance.now();
await Promise.all(Array.from({ length: 20 }, async (_, index) => {
await throttleAcquire();
await fetch(`${BACEN_URL}/pix/E${String(index).padStart(4, "0")}/status`);
}));
console.log(` [THROTTLE] 20 queries in ${Math.round(performance.now() - started)} ms → BACEN served ${stats.served}, refused ${stats.refused}`);
await bacen.stop(true);
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
Relações
Onde ele se encaixa
Por que se relacionam
Próximo passo
Combina com
Teste rápido
Qual é o próximo passo depois de Throttling?
Isola pools por dependência. Abrir Bulkhead
Seu progresso
0/157 estudados
Fica salvo só neste navegador.