Request Observability & W3C Distributed Tracing

Modern microservice architectures require distributed tracing and correlation IDs across service boundaries. Katal v3 provides built-in observability middleware complying with the W3C Trace Context specification and RFC correlation headers.


1. Quick Start

Enable global request observability with a single method call:

import { Application, LoggingIntegration } from "katal";

const app = new Application({ port: 3000 });
const logger = new LoggingIntegration().toConsole();

// Register global request observability
app.useRequestObservability({
    logger,
    setResponseHeaders: true,    // Injects X-Request-ID and X-Response-Time
    includeQueryInPath: false,   // Masks query string params from logs for privacy
});

await app.listen();

2. Standard Telemetry Headers

When setResponseHeaders: true (default), Katal attaches standardized telemetry headers to all outgoing responses:

Header Example Specification / Purpose
X-Request-ID 550e8400-e29b-41d4-a716-446655440000 Universal correlation ID. Reuses client-sent X-Request-ID or generates a cryptographically random UUIDv4.
traceparent 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01 W3C Distributed Trace Context. Propagates upstream trace and span IDs across downstream microservices.
X-Response-Time 2.45ms Total elapsed execution duration measured from request arrival to response transmission.

3. Structured Per-Request JSON Log Shape

Katal emits one structured JSON telemetry log at the conclusion of every HTTP transaction:

{
  "requestId": "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d",
  "traceparent": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
  "method": "POST",
  "path": "/api/v1/orders",
  "status": 201,
  "durationMs": 4.12
}

This structured output is immediately parseable by Datadog, Grafana Loki, AWS CloudWatch, and Elasticsearch (ELK) without custom log parsing regexes.


4. W3C Distributed Trace Propagation

When receiving an incoming request from an API Gateway or microservice, Katal parses and preserves the incoming traceparent header:

Upstream Service (e.g. Next.js Frontend)
  │
  ├─ Headers:
  │    traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
  │    x-request-id: req-abc-123
  ▼
Katal v3 API Service
  │
  ├─ Ingests traceparent & x-request-id into ctx.id and ctx.state
  ├─ Executes controller & middleware
  ▼
Downstream Service (e.g. Payment Gateway / Database)
  │
  └─ Katal forwards traceparent to preserve distributed trace waterfall in APM

Accessing Trace Context in Controllers

import { Controller } from "katal";
import type { RequestContext } from "katal";

export class OrderController extends Controller {
    async handle(ctx: RequestContext) {
        // Access correlation ID
        const correlationId = ctx.id;

        // Forward to external microservice
        const res = await fetch("https://inventory.service/reserve", {
            headers: {
                "X-Request-ID": correlationId,
                "traceparent": ctx.request.headers.get("traceparent") ?? "",
            },
        });

        return this.success({ orderId: "123" });
    }
}

5. Configuration Options

export interface RequestObservabilityOptions {
    /**
     * Custom logger instance with an info(message, context) method.
     * Defaults to JSON console.log output.
     */
    logger?: { info(message: string, context?: Record<string, unknown>): void };

    /**
     * Whether to mutate response headers with X-Request-ID, traceparent, and X-Response-Time.
     * Default: true
     */
    setResponseHeaders?: boolean;

    /**
     * Whether to append ?query=params to the path field in logs.
     * Disable to prevent logging sensitive tokens or passwords in URLs.
     * Default: false
     */
    includeQueryInPath?: boolean;
}

See Also