pattern/observability/distributed-tracing
- @elysiajs/opentelemetry
- Bun
- Bun.spawn
- ElysiaJS
- Jaeger
- OpenTelemetry
- OpenTelemetry SDK
- TypeScript
- Docker
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.
pattern/observability/distributed-tracing
Cenário
PIX passa pelo gateway e pelo antifraude com modelo degradado: ~320 ms no total, gargalo em fraud.model.score.
Planta
Sequência6 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
O mesmo arquivo roda como dois processos, cada um com SDK e service.name
@elysiajs/opentelemetry abre o span SERVER; record abre spans de etapa
propagation.inject põe o traceparent no fetch (não instrumentado no Bun)
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
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./
src/
Executar com Docker
./docker.shuntil curl -sf http://localhost:16686/ >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f distributed-tracing-jaegerSaí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.
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
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
Jaegertracing
jaegertracing/all-in-one:1.60:16686:4317:4318
Variáveis de ambiente
Trilhapasso 3 de 4
Observabilidade
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 Distributed Tracing?
Mede contra a meta. Abrir Métricas, SLI, SLO e SLA
Seu progresso
0/157 estudados
Fica salvo só neste navegador.