Pular para o conteúdo

Distributed Tracing

Mede cada etapa entre serviços: spans filhos do traceparent recebido, exportados por OTLP ao Jaeger. Aponta o gargalo, o que o correlation ID não faz.

passos
4
arquivos
6
testes
0
tecnologias
9

Cenário

PIX passa pelo gateway e pelo antifraude com modelo degradado: ~320 ms no total, gargalo em fraud.model.score.

Planta

Sequência
6/6
POST /pix (traceparent 00-trace-span-01)1POST /score (traceparent do span fraud.check)2span fraud.model.score, 300 msapprove32004spans do gateway5spans do fraud6Clientepix-gatewaypix-fraudJaeger (OTLP)
6

6 passos — reproduza para seguir o fluxo

Como funciona

4passos

Spans filhos do traceparent recebido, exportados por OTLP ao Jaeger para apontar o gargalo entre serviços

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

  1. 1

    O mesmo arquivo roda como dois processos, cada um com SDK e service.name

  2. 2

    @elysiajs/opentelemetry abre o span SERVER; record abre spans de etapa

  3. 3

    propagation.inject põe o traceparent no fetch (não instrumentado no Bun)

  4. 4

    A demo lê o trace no Jaeger e calcula o tempo próprio de cada span

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Gargalo apontado entre serviços

  • Parent-based evita trace pela metade

Custos

  • SDK, exportador e backend para operar

  • Todo serviço propaga o traceparent

Código

pattern/observability/distributed-tracing

6 arquivos

./

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

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until curl -sf http://localhost:16686/ >/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 distributed-tracing-jaeger

Saída: PIX 200 approve com o trace id; o Jaeger devolve 6 spans dos dois serviços (cerca de 330 ms no total) e [BOTTLENECK] pix-fraud fraud.model.score, com cerca de 300 ms de tempo próprio.

Jaeger UI: http://localhost:16686.

Requisitos
BunDocker
Sobe junto
Jaeger

Código

src/demo.ts

// Demo: a PIX crosses two processes, pix-gateway → pix-fraud; each exports its spans to Jaeger over OTLP, and the trace read back names the bottleneck.
import { opentelemetry, record } from "@elysiajs/opentelemetry";
import { SpanKind, context, propagation } from "@opentelemetry/api";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
import { resourceFromAttributes } from "@opentelemetry/resources";
import { NodeSDK } from "@opentelemetry/sdk-node";
import { BatchSpanProcessor, ParentBasedSampler, TraceIdRatioBasedSampler } from "@opentelemetry/sdk-trace-node";
import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
import { Elysia, t } from "elysia";

// The same file runs as both services: with argument "fraud" it is the fraud process, otherwise the gateway.
const hex = (bytes: number) => Buffer.from(crypto.getRandomValues(new Uint8Array(bytes))).toString("hex");
const role = Bun.argv[2] === "fraud" ? "fraud" : "gateway";
const JAEGER_URL = Bun.env.DISTRIBUTED_TRACING_JAEGER_URL ?? "http://localhost:16686";
const GATEWAY_URL = Bun.env.DISTRIBUTED_TRACING_GATEWAY_URL ?? "http://localhost:4701";
const FRAUD_URL = Bun.env.DISTRIBUTED_TRACING_FRAUD_URL ?? "http://localhost:4702";
const FRAUD_MODEL_LATENCY_MS = 300;
const sdk = new NodeSDK({
  resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: `pix-${role}` }),
  spanProcessors: [new BatchSpanProcessor(new OTLPTraceExporter())], // endpoint: OTEL_EXPORTER_OTLP_ENDPOINT, default localhost:4318
  // ParentBased keeps the caller's decision, so a trace is never cut between services.
  sampler: new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(1) }),
});
sdk.start();

if (role === "fraud") {
  new Elysia()
    .use(opentelemetry())
    .post("/score", ({ body }) =>
      record("fraud.model.score", async (span) => {
        span.setAttributes({ "fraud.model.name": "pix-risk", "pix.amount_cents": body.amountCents });
        await Bun.sleep(FRAUD_MODEL_LATENCY_MS); // the degraded risk model the trace has to reveal
        return { decision: "approve" };
      }), { body: t.Object({ amountCents: t.Integer({ minimum: 1 }) }) })
    .listen(new URL(FRAUD_URL).port);
  // The exporter works in batches: without shutdown the last spans are lost.
  process.on("SIGTERM", () => void sdk.shutdown().finally(() => process.exit(0)));
} else {
  const fraud = Bun.spawn(["bun", import.meta.path, "fraud"], { stdout: "inherit", stderr: "inherit" });
  while (!(await fetch(`${FRAUD_URL}/`).then(() => true, () => false))) await Bun.sleep(25);

  const gateway = new Elysia()
    .use(opentelemetry())
    .post("/pix", ({ body }) =>
      record("fraud.check", { kind: SpanKind.CLIENT }, async () => {
        // Bun's fetch is not auto-instrumented: without the injected traceparent, fraud would start a new trace.
        const headers: Record<string, string> = { "content-type": "application/json" };
        propagation.inject(context.active(), headers);
        return (await fetch(`${FRAUD_URL}/score`, { method: "POST", headers, body: JSON.stringify(body) })).json();
      }), { body: t.Object({ amountCents: t.Integer({ minimum: 1 }) }) })
    .listen(new URL(GATEWAY_URL).port);

  // The client opens the trace with a W3C traceparent, so it knows the trace id.
  const traceId = hex(16);
  const response = await fetch(`${GATEWAY_URL}/pix`, { method: "POST", headers: { "content-type": "application/json", traceparent: `00-${traceId}-${hex(8)}-01` }, body: JSON.stringify({ amountCents: 15_000 }) });
  console.log(`  [CLIENT] PIX → ${response.status} ${await response.text()}, trace ${traceId}`);
  await gateway.stop(true);
  fraud.kill("SIGTERM");
  await Promise.all([fraud.exited, sdk.shutdown()]);
  await traceShow(traceId);
}

type JaegerTrace = { spans: { spanID: string; operationName: string; duration: number; processID: string; references: { spanID: string }[] }[]; processes: Record<string, { serviceName: string }> };

// Jaeger indexes asynchronously: wait until the trace holds spans from both services. Self time = duration minus children.
async function traceShow(traceId: string) {
  let found: JaegerTrace | undefined;
  while (new Set(Object.values(found?.processes ?? {}).map((process) => process.serviceName)).size < 2) {
    await Bun.sleep(100);
    found = ((await (await fetch(`${JAEGER_URL}/api/traces/${traceId}`)).json()) as { data?: JaegerTrace[] }).data?.[0];
  }
  const { spans: raw, processes } = found as JaegerTrace;
  const spans = raw.map((span) => ({ spanID: span.spanID, operationName: span.operationName, service: processes[span.processID]?.serviceName, ms: span.duration / 1_000, parent: span.references[0]?.spanID }));
  const selfMs = (span: (typeof spans)[number]) => span.ms - spans.filter((child) => child.parent === span.spanID).reduce((sum, child) => sum + child.ms, 0);
  for (const span of spans.toSorted((left, right) => right.ms - left.ms)) console.log(`  [JAEGER] ${span.service?.padEnd(12)} ${span.operationName.padEnd(18)} ${span.ms.toFixed(0).padStart(4)} ms  self ${selfMs(span).toFixed(0).padStart(4)} ms`);
  const slowest = spans.toSorted((left, right) => selfMs(right) - selfMs(left))[0];
  console.log(`  [BOTTLENECK] ${slowest?.service} ${slowest?.operationName}`);
}

Nível

introdutório

3/13

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

Domínio financeiro

  • PIX
  • Antifraude

Padrões do catálogo que implementa

  • Distributed Tracing

Infraestrutura

  • Jaegertracing

    jaegertracing/all-in-one:1.60:16686:4317:4318

Variáveis de ambiente

OTEL_EXPORTER_OTLP_ENDPOINT
http://localhost:4318
OTLP/HTTP base endpoint; the SDK appends /v1/traces. Jaeger all-in-one accepts OTLP natively.
DISTRIBUTED_TRACING_JAEGER_URL
http://localhost:16686
Jaeger query API, read by the demo to rebuild the trace.
DISTRIBUTED_TRACING_GATEWAY_URL
http://localhost:4701
The two services, both started by the demo.
DISTRIBUTED_TRACING_FRAUD_URL
http://localhost:4702

Trilhapasso 3 de 4

Observabilidade

  1. 1Correlation ID
  2. 2Log Aggregation
  3. 3Distributed Tracing
  4. 4Métricas, SLI, SLO e SLA

Parecidos

Por que se relacionam

Teste rápido

Qual é o próximo passo depois de Distributed Tracing?

Próximo projeto, ObservabilidadeHealth Check
Esc

↑ ↓ navegarEnter abrir239 resultados