Backend Core SDK Instrumentation Guide

Backend SDK, Frameworks & Telemetry

Instrument Node.js server applications in one line. Expose Prometheus metrics, track distributed OpenTelemetry traces, capture unhandled exceptions, and monitor queue performance.

Express Middleware Instrumentation

Call setupObservability(app) after initializing your Express application instance:

Express Server (src/server.ts)
import express from "express";
import { setupObservability } from "@stacklenzz/server";

const app = express();
app.use(express.json());

// Enable Stacklenzz Telemetry Pipeline & /metrics endpoint
setupObservability(app, {
  serviceName: "payment-service",
  metricsPath: "/metrics",
  statsPath: "/api/observability/stats",
  enableTracing: true,
});

app.get("/api/checkout", (req, res) => {
  res.json({ status: "success", orderId: "ord_99482" });
});

app.listen(5000, () => {
  console.log("Server listening on port 5000");
});

Express Setup Options

Configure custom Prometheus metrics endpoints, trace sampling rates, and error breadcrumb limits.

NestJS Module & Interceptor Setup

Import ObservabilityModule into your root AppModule:

NestJS App Module (src/app.module.ts)
import { Module } from "@nestjs/common";
import { ObservabilityModule } from "@stacklenzz/server";

@Module({
  imports: [
    ObservabilityModule.forRoot({
      serviceName: "billing-microservice",
      enableInterceptors: true,
      captureErrors: true,
    }),
  ],
})
export class AppModule {}

NestJS Interceptor Features

Automatically injects request execution duration, controller method metadata, and unhandled Nest HTTP exception breadcrumbs.

Fastify & Koa Framework Instrumentation

Dedicated 1-line subpath adapters for Fastify (@stacklenzz/server/fastify) and Koa (@stacklenzz/server/koa):

Fastify Setup (src/server.ts)
import Fastify from "fastify";
import { fastifyObservability } from "@stacklenzz/server/fastify";

const app = Fastify();

await app.register(fastifyObservability, {
  serviceName: "payment-fastify-api",
});

await app.listen({ port: 5000 });
Koa Setup (src/server.ts)
import Koa from "koa";
import { koaObservability } from "@stacklenzz/server/koa";

const app = new Koa();

app.use(koaObservability({
  serviceName: "billing-koa-api",
}));

app.listen(5000);

📦 Node.js Framework Compatibility Matrix

Stacklenzz is compatible across popular Node.js frameworks:

FrameworkSupport LevelAdapter / Setup
Express.jsNative First-ClasssetupObservability(app)
NestJSNative First-ClassObservabilityModule.forRoot()
FastifyNative Plugin Adapterapp.register(fastifyObservability)
Koa / ConnectNative Middleware Adapterapp.use(koaObservability())

⚡️ Advanced Telemetry APIs & Custom Spans

Instrument custom code execution blocks, measure DB queries, and emit custom counter metrics:

Custom Metrics & Prom-Client Exports (src/services/payment.service.ts)
import { Counter, register, logger, addBreadcrumb } from "@stacklenzz/server/core";

// Register custom Prometheus counter metric
const ordersCounter = new Counter({
  name: "orders_processed_total",
  help: "Total processed checkout orders",
  labelNames: ["currency"],
  registers: [register],
});

export async function processPayment(amount: number) {
  addBreadcrumb({ category: "payment", message: `Processing ${amount} USD` });
  ordersCounter.inc({ currency: "USD" });
  
  const result = await stripe.charges.create({ amount });
  return result;
}

Custom OpenTelemetry Spans & Database Tracing (trackDatabaseQuery)

Wrap PostgreSQL, MongoDB, or Prisma calls with trackDatabaseQuery to generate child spans in your trace waterfall:

Tracing Database Queries (src/db/users.ts)
import { trackDatabaseQuery } from "@stacklenzz/server";

export async function findUser(id: string) {
  return await trackDatabaseQuery("pg.users.findById", async () => {
    return await db.query("SELECT * FROM users WHERE id = $1", [id]);
  });
}

Pluggable Database Crash Adaptors (PostgreSQL, MongoDB, Prisma)

Persist 5xx server crash logs and breadcrumbs directly into your primary database for historical analysis:

PostgreSQL / MongoDB Adaptor Configuration
setupObservability(app, {
  serviceName: "my-api",
  crashLogAdaptor: {
    async save(errorLog) {
      await db.query("INSERT INTO crash_logs (id, timestamp, message) VALUES ($1, $2, $3)", 
        [errorLog.id, errorLog.timestamp, errorLog.message]);
    },
    async list() {
      return await db.query("SELECT * FROM crash_logs ORDER BY timestamp DESC LIMIT 50");
    },
  },
});

🤖 Agentic AI & Model Context Protocol (@stacklenzz/mcp)

Allow AI coding assistants (Claude Desktop, Cursor, Antigravity) to query server telemetry, active error logs, and metrics directly via MCP:

MCP Configuration (.cursor/mcp.json or Claude Desktop)
{
  "mcpServers": {
    "stacklenzz": {
      "command": "npx",
      "args": ["-y", "@stacklenzz/mcp"],
      "env": {
        "STACKLENZZ_URL": "http://localhost:5000/api/observability/stats"
      }
    }
  }
}

🔄 Distributed Trace Explorer & W3C Propagation

Stacklenzz automatically injects and extracts W3C traceparent headers across HTTP requests for microservice trace continuity.

W3C Traceparent Header Format

traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
W3C TRACEPARENT SUPPORT
Compatible with Jaeger, Zipkin, OpenTelemetry Collectors, and Datadog trace formats.

⚙️ Background Jobs & Queue Monitoring (trackJob)

Track job throughput, queue lag, failed job retry attempts, and worker execution durations:

Wrapping Worker Tasks with trackJob
import { trackJob } from "@stacklenzz/server";

// Wrap any async job or queue worker function
await trackJob("send-welcome-email", "email-queue", async () => {
  await mailer.send({ to: user.email, subject: "Welcome to Stacklenzz!" });
});