Pular para o conteúdo

Throttling

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.

passos
4
arquivos
6
testes
0
tecnologias
6

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ência
9/9
EVAL pega token1concedido2GET /pix/E1/status32004EVAL pega token5negado, próximo em 111 ms6espera, não chama o BACENEVAL pega token7concedido8GET /pix/E2/status9Serviço do bancoRedis (bucket)API BACEN (10/s)
9

9 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.

  1. 1

    Lua repõe tokens pelo tempo, limita à capacidade e consome atomicamente

  2. 2

    Sem token, devolve a espera; a chamada aguarda e tenta de novo

  3. 3

    Bucket no RedisUma cota para todas as réplicas

  4. 4

    Capacidade e taxa abaixo da cota, margem para relógio e rede

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

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

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec throttling-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 throttling-cache

Saída: 20 consultas em cerca de 1,3 s → BACEN served 20, refused 0.

Requisitos
BunDocker
Sobe junto
Redis

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

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

Domínio financeiro

  • PIX
  • BACEN/SPI

Padrões do catálogo que implementa

  • Throttling

Infraestrutura

  • Rediscache / estrutura de dados

    redis:7-alpine:6379

Variáveis de ambiente

THROTTLING_REDIS_URL
redis://localhost:6379
THROTTLING_BACEN_URL
http://localhost:4302

Parecidos

Por que se relacionam

Teste rápido

Qual é o próximo passo depois de Throttling?

Próximo projeto, ResiliênciaTimeout
Esc

↑ ↓ navegarEnter abrir239 resultados