Pular para o conteúdo

Correlation ID

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.

passos
4
arquivos
5
testes
0
tecnologias
4

Cenário

Dois PIX simultâneos (um liquidado, um recusado); o filtro pelo id do recusado traz só as linhas dele.

Planta

Sequência
4/4
POST /pix1sem x-correlation-id: gera umPOST /settlements (x-correlation-id)24223422 + x-correlation-id4App do clienteGateway (borda)Pagamentos
4

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

  1. 1

    middlewareCorrelation aceita o id válido ou gera na borda

  2. 2

    O id vai ao header antes do handler: volta mesmo em erro

  3. 3

    Id, requestId por salto e serviço no AsyncLocalStorage

  4. 4

    correlationLog grava o contexto; correlationFetch repassa o header

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

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

src/

  • demo.tsdemo

Executar só Bun

  1. bun install# dependências
  2. bun run demo# roda o cenário

Saí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.

Requisitos
Bun

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)]);

Por que se relacionam

Teste rápido

Qual é o próximo passo depois de Correlation ID?

Próximo projeto, ObservabilidadeDistributed Tracing
Esc

↑ ↓ navegarEnter abrir239 resultados