Skip to content

Observability and Tracing ​

LatticeDX exports runtime telemetry from the NocoBase core through plugin-lattice-foundation, scrapes quantitative metrics with Prometheus, and visualizes operational state in Grafana. The pipeline combines W3C traceparent distributed tracing, OpenTelemetry GenAI semantic conventions with pre-export PII redaction, and isolated internal health endpoints across Docker networks.

Telemetry Collection Architecture ​

Enabling --profile observability in infra/compose/prod.yml runs three observability services across the internal app and data networks:

  1. otel/opentelemetry-collector-contrib:0.123.0 ingests OTLP spans over gRPC (:4317) and HTTP (:4318), applies a 384 MiB memory limiter, batches payloads every 5s, and exposes OTLP-derived metrics on :8889.
  2. prom/prometheus:v3.3.0 scrapes 4 configured targets every 15s, evaluates 5 alert rules in alerts.yml, and retains TSDB blocks for 15 days.
  3. grafana/grafana-oss:11.5.8 auto-provisions the Prometheus datasource (uid: latticedx-prom) and mounts the latticedx-360.json dashboard.
bash
docker compose --env-file .env -f infra/compose/prod.yml --profile observability up -d

Health and Prometheus Endpoints ​

registerObservability in plugins/nocobase/plugin-lattice-foundation/src/server/observability.js installs the HTTP timing middleware and registers diagnostic actions on the dxos resource.

GET/api/dxos:health
Public
Reports PostgreSQL connectivity, platform version (0.4.2), process uptime, and OTel exporter queue statistics.
GET/api/dxos:metrics
Bearer DX_METRICS_TOKEN | Role root, ldx_admin
Exports Prometheus 0.0.4 text metrics covering HTTP latency histograms, outbox queues, active incidents, and OTel counters.
GET/api/dxos:openapi
Public
Generates OpenAPI 3.1.0 JSON including dynamically introspected latticeCustom* runtime collections.
GET/api/dxos:asyncapi
Public
Generates AsyncAPI 3.0.0 JSON covering MQTT, SSE surfaceEvents, Valkey PubSub, and context outbox channels.

Access to /api/dxos:metrics supports two authentication paths: constant-time SHA-256 comparison (timingSafeEqual) against DX_METRICS_TOKEN, or a verified session JWT holding the root or ldx_admin role. In production Compose, the prometheus container writes DX_METRICS_TOKEN to /tmp/dx_metrics_token under umask 077 at startup so credentials never reside inside prometheus.yml.

bash
curl -fsS http://127.0.0.1:13000/api/dxos:health | jq .

Observability Configuration Parameters ​

OpenTelemetry, Prometheus, and Grafana Environment Variables
ParameterTypeDefaultDescription
OTEL_EXPORTER_OTLP_ENDPOINT
stringhttp://otel-collector:4318Base OTLP HTTP endpoint where trace batches are posted to /v1/traces.
OTEL_SERVICE_NAME
stringlatticedx-nocobaseValue assigned to resource attribute service.name on exported OTLP spans.
DX_METRICS_TOKENrequired
string—Bearer token used by Prometheus to scrape /api/dxos:metrics.
DX_CORS_ALLOWED_ORIGINS
stringhttp://localhost:8080,http://127.0.0.1:8080Comma-separated allowlist of trusted browser origins enforced by CORS middleware.
DX_CORS_STRICT
booleantrueStrips Access-Control-Allow-* headers when requests arrive from untrusted origins.
GRAFANA_ADMIN_USER
stringadminInitial administrator username for the Grafana container.
GRAFANA_ADMIN_PASSWORDrequired
string—Administrator password for Grafana (public sign-up and telemetry reporting are disabled).

HTTP and OpenTelemetry GenAI Tracing ​

createOtelExporter in otel-exporter.js parses and propagates W3C traceparent headers (00-<traceId>-<spanId>-<flags>). Spans buffer in an in-memory queue capped at 256 entries, flushing batches of up to 64 spans every 5000ms with a 2000ms HTTP timeout. When the queue reaches capacity, new spans are dropped and counted via latticedx_otel_spans_dropped_total to bound Node.js memory usage.

For AI operations inside plugin-dxos-ai, recordGenAiSpan and startGenAiSpan emit spans following OpenTelemetry GenAI semantic conventions and optionally persist trace rows to latticeAiTraces inside the organization's FORCE ROW LEVEL SECURITY transaction context.

Span AttributeTypeTechnical Description
gen_ai.operation.namestringOperation stage (chat, invoke_agent, execute_tool).
gen_ai.systemstringAI runtime provider identifier (defaults to latticedx).
gen_ai.request.modelstringTarget model identifier serving the inference request.
gen_ai.usage.input_tokensintegerPrompt and context tokens consumed by the call.
gen_ai.usage.output_tokensintegerCompletion tokens returned by the model.
gen_ai.agent.namestringActive profile name across the 7 AI Agent Profiles.
gen_ai.tool.namestringUnified tool name executed during the ReAct loop.
dxos.run_uidstringCorrelation identifier linking multi-step agent runs.
dxos.orgstringOrganization identifier matching tenant RLS isolation.
dxos.pii.redacted_countintegerNumber of sensitive substrings scrubbed prior to persistence or OTLP export.

Pre-Export PII and Secret Redaction ​

redactPiiText and redactPiiDeep scrub span attributes, error messages, input/output previews, and metadata fields before spans enter the OTLP queue or write to latticeAiTraces:

Pattern CategoryReplacement TokenProtected Data
JWT (eyJ...)[REDACTED_JWT]User session tokens and OIDC bearer tokens.
API Keys (sk-..., ldx_pat_...)[REDACTED_KEY]Model provider keys and scoped Personal Access Tokens.
National ID (cccd, cmnd, 0\d{11})[REDACTED_CCCD]9-to-12-digit Vietnamese citizen identification numbers.
Vietnamese Phone (+84, 03/05/07/08/09)[REDACTED_PHONE]10-digit domestic mobile numbers.
Bank Accounts (stk, iban)[REDACTED_BANK]Account numbers and IBAN strings.
Tax ID (mst, 10 or 13 digits)[REDACTED_MST]Enterprise tax registration numbers.
Email Addresses[REDACTED_EMAIL]Any email address appearing in prompts, attributes, or errors.

Token accounting attributes (gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, total_tokens) are exempted via SAFE_TOKEN_COUNT_KEY_RE so key-based secret scrubbing never masks usage counters.

Prometheus Metric Families and Alert Rules ​

infra/config/prometheus/prometheus.yml defines 4 scrape jobs:

Job NameTargetPathAuthentication
nocobasenocobase:80/api/dxos:metricsBearer (/tmp/dx_metrics_token)
caddycaddy:2020/metricsInternal app network
keycloakkeycloak:9000/metricsInternal app network
otel-collectorotel-collector:8889/metricsInternal app network

Metric Families Exported by /api/dxos:metrics ​

  • latticedx_http_requests_total{method, status_class}: Counter partitioned by HTTP method and status class (2xx, 3xx, 4xx, 5xx).
  • latticedx_http_request_duration_seconds: Latency histogram with bucket bounds at 0.025, 0.1, 0.5, and 2.0 seconds.
  • latticedx_ai_audit_logs_total: Gauge of total rows stored in latticeAiAuditLogs.
  • latticedx_outbox_by_state{state}: Gauge of latticeContextOutbox rows across 5 states (pending, retry, processing, delivered, failed).
  • latticedx_active_alarms_total: Gauge of open or acknowledged incident records in latticeIncidentCases.
  • latticedx_unread_notifications_total: Gauge of active unread rows in latticeNotifications.
  • latticedx_sla_policies_active: Gauge of enabled SLA escalation policies.
  • latticedx_event_bus_by_status{status}: Gauge of CloudEvents bus rows (queued, dispatched, partial_failed).
  • latticedx_webhook_deliveries_by_status{status}: Gauge of outbound webhook deliveries (pending, processing, delivered, retry_wait, dlq).
  • latticedx_webhook_circuits_by_state{state}: Gauge of webhook subscription circuit breakers (closed, open, half_open).
  • latticedx_uptime_seconds: Gauge reporting Node.js process uptime in seconds.
  • latticedx_otel_spans_recorded_total, latticedx_otel_spans_exported_total, latticedx_otel_spans_dropped_total, latticedx_otel_export_failures_total, latticedx_otel_queue_size: OTLP export pipeline counters and queue depth.

Database gauge collection (collectDbGauges) executes read-only counts inside withSystemRlsBypass (transaction-local app.rls_bypass = 'on') so aggregate counts reflect platform-wide queue depths without exposing tenant row content.

Configured Alert Rules (alerts.yml) ​

Alert NamePromQL ConditionFor DurationSeverity
LatticeDxNocoBaseDownup{job="nocobase"} == 01mcritical
LatticeDxHigh5xxRate5xx request ratio > 0.05 (with RPS > 0.01)2mcritical
LatticeDxOutboxBacklogHighsum(latticedx_outbox_by_state{state=~"pending|retry|failed"}) > 505mwarning
LatticeDxCriticalColdAlarmsActivelatticedx_active_alarms_total > 03mcritical
LatticeDxQuotaSpikedelta(latticedx_ai_audit_logs_total[15m]) > 2005mwarning

Grafana Dashboard (latticedx-360) ​

Grafana mounts infra/config/grafana/provisioning and infra/config/grafana/dashboards/latticedx-360.json read-only (allowUiUpdates: false). The dashboard refreshes every 15s in the Asia/Ho_Chi_Minh timezone and includes 7 panels:

#Panel TitleMetrics & Visualization
1HTTP Request Rate & 5xx ErrorsTime series grouped by status_class alongside 5xx error rates.
2HTTP Latency p95 / p500.95 and 0.50 quantiles derived from latticedx_http_request_duration_seconds_bucket.
3Active Critical / Total AlarmsStat panel tracking latticedx_active_alarms_total and latticedx_sla_policies_active.
4Notification Inbox QueueStat panel for latticedx_unread_notifications_total with an orange threshold at 25.
5Database & Engine HealthScrape status (up{job="nocobase"}) paired with latticedx_uptime_seconds.
6Context Outbox Backlog (Pending / Retry / Failed)Time series tracking Orion-LD and webhook delivery queues.
7AI / MCP Audit Volume & Stack TargetsAudit volume alongside up status for caddy, keycloak, and otel-collector.

Apache-2.0 · LatticeDX v0.4.2 · Powered by NocoBase · v2.2.50 · Apache-2.0 (Clause 5.2)