pattern/observability/correlation-id
- AsyncLocalStorage
- Bun
- ElysiaJS
- TypeScript
Id único por operação, gerado na borda, levado em x-correlation-id, em todo log e de volta ao cliente. Filtrar por ele conta a história de um PIX.
pattern/observability/correlation-id
Cenário
Dois PIX simultâneos (um liquidado, um recusado); o filtro pelo id do recusado traz só as linhas dele.
Planta
Sequência4 passos — reproduza para seguir o fluxo
Como funciona
4passos
Id único por operação, gerado na borda, levado em x-correlation-id, em todo log e de volta ao cliente
Esconde cada passo: lembre antes de tocar para revelar.
middlewareCorrelation aceita o id válido ou gera na borda
O id vai ao header antes do handler: volta mesmo em erro
Id, requestId por salto e serviço no AsyncLocalStorage
correlationLog grava o contexto; correlationFetch repassa o header
Trade-offs
O que se ganha, o que se paga
Vantagens
Um UUID e um header; filtrável em qualquer agregador
Cliente usa o id no chamado
Custos
Sem latência por salto
Toda saída precisa propagar
Código
pattern/observability/correlation-id
5 arquivos./
src/
Executar só Bun
bun install# dependênciasbun run demo# roda o cenárioSaída: o cliente recebe 201 e 422, cada um com seu x-correlation-id; das 6 linhas intercaladas, o filtro pelo id do recusado traz 3: pix received e pix answered do gateway e pix refused de pagamentos.
Código
src/demo.ts// Demo: two concurrent PIX cross gateway → payments over HTTP; the interleaved logs, filtered by one x-correlation-id, tell that PIX's whole story.
import { AsyncLocalStorage } from "node:async_hooks";
import { Elysia, t } from "elysia";
type CorrelationContext = { correlationId: string; requestId: string; service: string };
const storeCorrelation = new AsyncLocalStorage<CorrelationContext>();
// A header value ends up on every log line: anything but a short token is replaced, never trusted.
const CORRELATION_PATTERN = /^[A-Za-z0-9-]{8,64}$/;
const GATEWAY_URL = Bun.env.CORRELATION_ID_GATEWAY_URL ?? "http://localhost:4601";
const PAYMENTS_URL = Bun.env.CORRELATION_ID_PAYMENTS_URL ?? "http://localhost:4602";
const PIX_NIGHT_LIMIT_CENTS = 500_000;
// The edge generates the id; every other service takes the one it received. Each hop gets its own requestId.
const middlewareCorrelation = (service: string) =>
new Elysia({ name: `correlation:${service}` }).derive({ as: "global" }, ({ headers, set }) => {
const received = headers["x-correlation-id"];
const correlationId = received && CORRELATION_PATTERN.test(received) ? received : crypto.randomUUID();
// Set before the handler runs, so the client gets it back even when the handler fails.
set.headers["x-correlation-id"] = correlationId;
storeCorrelation.enterWith({ correlationId, requestId: crypto.randomUUID(), service });
return {};
});
// The log aggregator: every JSON line of both services lands here.
const lines: Record<string, unknown>[] = [];
const correlationLog = (message: string, extra: Record<string, unknown> = {}) => lines.push({ ...storeCorrelation.getStore(), message, ...extra });
const correlationFetch = (url: string, body: unknown) =>
fetch(url, { method: "POST", headers: { "content-type": "application/json", "x-correlation-id": storeCorrelation.getStore()?.correlationId ?? "" }, body: JSON.stringify(body) });
const schemaPix = t.Object({ pixKey: t.String(), amountCents: t.Integer({ minimum: 1 }) });
const payments = new Elysia().use(middlewareCorrelation("payments")).post("/settlements", ({ body, status }) => {
if (body.amountCents > PIX_NIGHT_LIMIT_CENTS) return (correlationLog("pix refused", { reason: "above the night limit" }), status(422, "above the night limit"));
correlationLog("pix settled", { amountCents: body.amountCents });
return status(201, "settled");
}, { body: schemaPix }).listen(new URL(PAYMENTS_URL).port);
const gateway = new Elysia().use(middlewareCorrelation("gateway")).post("/pix", async ({ body, status }) => {
correlationLog("pix received", { amountCents: body.amountCents });
const response = await correlationFetch(`${PAYMENTS_URL}/settlements`, body);
correlationLog("pix answered", { status: response.status });
return status(response.status as 201, await response.text());
}, { body: schemaPix }).listen(new URL(GATEWAY_URL).port);
const pixSend = (amountCents: number) => fetch(`${GATEWAY_URL}/pix`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ pixKey: "maria@banco.com", amountCents }) });
const responses = await Promise.all([pixSend(15_000), pixSend(900_000)]);
const refused = responses[1]?.headers.get("x-correlation-id");
console.log(` [CLIENT] ${responses.map((response) => `${response.status} x-correlation-id=${response.headers.get("x-correlation-id")}`).join(" | ")}`);
console.log(` [AGGREGATOR] ${lines.length} interleaved lines; filtered by ${refused}:`);
for (const line of lines.filter((entry) => entry.correlationId === refused)) console.log(` ${JSON.stringify(line)}`);
await Promise.all([gateway.stop(true), payments.stop(true)]);
Nível
introdutório
1/13
Domínio financeiro
Padrões do catálogo que implementa
Variáveis de ambiente
Trilhapasso 1 de 4
Observabilidade
Parecidos
Relações
Onde ele se encaixa
Por que se relacionam
Próximo passo
Teste rápido
Qual é o próximo passo depois de Correlation ID?
Centraliza os logs. Abrir Log Aggregation
Seu progresso
0/157 estudados
Fica salvo só neste navegador.