Performance Middleware
Monitoring & Metrics
Built-in observability: OpenTelemetry traces and metrics for any OTLP backend, dependency-free Prometheus and CloudWatch EMF metrics, request logging, and live framework statistics.
Overview
MoroJS ships monitoring middleware for every style of stack. Pick what matches your infrastructure: OpenTelemetry traces and metrics for OTLP collectors and the platforms behind them (Grafana, Datadog, Honeycomb, Jaeger), pull-based Prometheus scraping for servers, push-via-logs CloudWatch EMF for AWS Lambda, or plain request logging anywhere. Prometheus and CloudWatch need no dependencies; OpenTelemetry needs only the @opentelemetry/api package your SDK already brings.
1import { createApp, middleware } from '@morojs/moro';
2
3const app = await createApp();
4
5// Prometheus: records request metrics and serves GET /metrics
6app.use(middleware.prometheus({ endpoint: '/metrics' }));
7
8app.get('/api/hello', () => ({ ok: true }));
9
10app.listen(3000);
11// curl http://localhost:3000/metricsOpenTelemetry Traces & Metrics
The OpenTelemetry middleware opens one server span per request and records the standard HTTP server metrics, through the OpenTelemetry SDK your application registers. MoroJS instruments its own request lifecycle because the native engine never touches Node's http module, so the generic HTTP instrumentation sees nothing there. Only @opentelemetry/api is a (optional) peer dependency: the SDK, exporters, sampling and resource attributes stay yours, as the OpenTelemetry project recommends for libraries.
1npm install @opentelemetry/api @opentelemetry/sdk-node @opentelemetry/exporter-trace-otlp-http @opentelemetry/exporter-metrics-otlp-http1// otel.ts - start the SDK before the app is created
2import { NodeSDK } from '@opentelemetry/sdk-node';
3import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
4import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';
5import { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';
6
7const sdk = new NodeSDK({
8 serviceName: 'orders-api',
9 traceExporter: new OTLPTraceExporter(), // honours OTEL_EXPORTER_OTLP_ENDPOINT
10 metricReader: new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter() }),
11});
12sdk.start();
13
14// app.ts
15import './otel.js';
16import { createApp, middleware } from '@morojs/moro';
17
18const app = await createApp();
19
20// First in the chain, so every other middleware and the handler run inside the span
21app.use(middleware.openTelemetry({ ignorePaths: ['/health'] }));
22
23app.get('/orders/:id', (req) => getOrder(req.params.id));
24
25app.listen(3000);Prefer zero code? The OpenTelemetry Node auto-instrumentation bundle configures the same SDK from environment variables, and its instrumented clients (fetch, pg, ioredis, ...) nest under the Moro server span automatically.
1npm install @opentelemetry/api @opentelemetry/auto-instrumentations-node
2
3OTEL_SERVICE_NAME=orders-api OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 node --require @opentelemetry/auto-instrumentations-node/register app.js1// One span per request, named by method and matched route template
2GET /orders/:id kind: SERVER (INTERNAL when nested under an outer HTTP span)
3 http.request.method GET
4 http.route /orders/:id // the template, never the raw path
5 url.path /orders/42
6 url.query expand=items // when present
7 url.scheme http // transport scheme (https when TLS terminates here)
8 server.address api.example.com // from Host
9 server.port 8080
10 client.address 10.0.0.7 // req.ip
11 user_agent.original curl/8.6.0
12 network.protocol.version 1.1 // Node transport
13 http.response.status_code 200
14 error.type 500 | aborted // 5xx, or the client disconnected; span status ERROR
15
16// Metrics (OpenTelemetry HTTP semantic conventions)
17http.server.request.duration histogram, seconds
18 {http.request.method, http.response.status_code, http.route, url.scheme, error.type}
19http.server.active_requests up/down counter, opt-in (activeRequests: true)
20 {http.request.method, url.scheme}
21
22// Attributes that need a header or address lookup (Host, User-Agent, client
23// address, url.query, captured headers) are collected only for spans that
24// record, so sampled-out requests pay for the route lookup and the metric point.
25
26// Unmatched paths (404) get the bare method as span name and no http.route,
27// so metric cardinality stays bounded by your route table.1app.use(middleware.openTelemetry({
2 traces: true, // server span per request (default true)
3 metrics: true, // duration histogram (default true)
4 activeRequests: false, // + http.server.active_requests counter (default false)
5 propagation: true, // continue traces from traceparent/baggage (default true)
6 ignorePaths: ['/health', /^/metrics/], // exact strings or RegExps
7 captureRequestHeaders: ['x-tenant-id'], // -> http.request.header.x-tenant-id
8 captureResponseHeaders: ['content-type'], // -> http.response.header.content-type
9 attributes: { 'deployment.environment.name': 'production' },
10 spanName: (req, route) => (route ? `${req.method} ${route}` : `${req.method} unmatched`),
11 // tracer / meter: bring your own instead of the global providers' '@morojs/moro' scope
12}));1import { trace } from '@opentelemetry/api';
2
3app.get('/orders/:id', async (req) => {
4 // The request span is the active context for middleware, handlers and
5 // everything they await - add your own attributes, events or child spans
6 trace.getActiveSpan()?.setAttribute('order.id', req.params.id);
7
8 const order = await db.orders.find(req.params.id); // instrumented clients nest here
9 return order;
10});Prometheus Metrics
The Prometheus middleware records request counters and duration histograms — labeled by method and status only, so label cardinality stays bounded — and serves the standard text exposition format at the configured endpoint. No client library required.
1app.use(middleware.prometheus({
2 endpoint: '/metrics', // scrape path (default '/metrics')
3 includeProcessMetrics: true, // memory / heap / uptime gauges (default true)
4 includePoolMetrics: true, // object pool + route cache metrics (default true)
5 buckets: [0.005, 0.01, 0.05, 0.1, 0.5, 1, 5] // histogram bounds in seconds
6}));1# Request metrics
2http_requests_total{method="GET",status="200"} 1027
3http_request_duration_seconds_bucket{method="GET",status="200",le="0.01"} 998
4http_request_duration_seconds_sum{method="GET",status="200"} 3.2
5http_request_duration_seconds_count{method="GET",status="200"} 1027
6
7# Process metrics
8process_resident_memory_bytes 104857600
9nodejs_heap_size_used_bytes 52428800
10process_uptime_seconds 86400
11
12# Framework internals: object pools and route cache
13moro_pool_size{pool="params"} 42
14moro_pool_max_size{pool="params"} 180
15moro_route_cache_hits_total 98452
16moro_route_cache_misses_total 15481# prometheus.yml
2scrape_configs:
3 - job_name: 'moro-api'
4 scrape_interval: 15s
5 static_configs:
6 - targets: ['localhost:3000']CloudWatch (Embedded Metric Format)
The CloudWatch middleware emits one Embedded Metric Format JSON line per request to stdout. On AWS Lambda (and any environment shipping stdout to CloudWatch Logs), CloudWatch extracts these as real metrics automatically — no AWS SDK, credentials, or network calls.
1import { createAppLambda, middleware } from '@morojs/moro';
2
3const app = await createAppLambda();
4
5app.use(middleware.cloudWatch({
6 namespace: 'MoroAPI', // CloudWatch namespace (default 'MoroJS')
7 dimensions: { Service: 'orders' } // extra static dimensions
8}));
9
10app.get('/api/orders/:id', (req) => getOrder(req.params.id));
11
12export const handler = app.getHandler();1// One EMF record per completed request (stdout):
2{
3 "_aws": {
4 "Timestamp": 1753747200000,
5 "CloudWatchMetrics": [{
6 "Namespace": "MoroAPI",
7 "Dimensions": [["Method", "Status", "Service"]],
8 "Metrics": [
9 { "Name": "RequestCount", "Unit": "Count" },
10 { "Name": "RequestDuration", "Unit": "Milliseconds" }
11 ]
12 }]
13 },
14 "Method": "GET",
15 "Status": "200",
16 "Service": "orders",
17 "RequestCount": 1,
18 "RequestDuration": 12,
19 "Path": "/api/orders/42"
20}1// Redirect EMF lines anywhere (useful outside Lambda or in tests)
2app.use(middleware.cloudWatch({
3 namespace: 'MoroAPI',
4 emit: line => myLogPipeline.write(line)
5}));Request Logging
For plain request logging and slow-request warnings, use the built-in observability middleware — zero-config factories like every other entry in the middleware namespace.
1// Log each request and its completion time
2app.use(middleware.requestLogger());
3
4// Warn on requests slower than 1s
5app.use(middleware.performanceMonitor());Framework Statistics
Beyond middleware, the framework exposes live internal statistics you can surface on your own health or metrics endpoints.
1import { ObjectPoolManager } from '@morojs/moro';
2
3app.get('/api/stats', async () => {
4 const pools = ObjectPoolManager.getInstance().getPerformanceSummary();
5 const workers = await app.getWorkerStats(); // null if workers unused
6
7 return {
8 pools, // { routeCacheHitRate, responseCacheHitRate, paramPoolUtilization, totalMemoryKB }
9 workers, // { workerCount, activeTasks, queuedTasks, isShuttingDown }
10 uptime: process.uptime()
11 };
12});