Observability Security

Comprehensive guide to observability security for production observability and monitoring systems.

Observability security is the practice of using observability data—logs, metrics, traces, and events—to detect, analyze, and respond to security threats across distributed systems. It matters when a security incident is not just a log entry or a firewall alert, but a cascade of correlated signals across services, infrastructure, and user behavior. This is where traditional SIEMs fall short: observability security uses the full context of system behavior to answer "What happened?" and "Why now?" in real time.

Detecting Anomalies in System Behavior

Anomalies in observability data are the first line of defense in observability security. A service’s latency spikes, a database query count drops, a new error rate appears—these signals are not just performance issues; they are security indicators. To detect these, define thresholds and patterns using time-series data.

Use Prometheus to monitor key security-relevant metrics. Define a recording rule in prometheus.yml to compute the ratio of failed login attempts to total attempts:

rule_files:
  - "security-rules.yml"

scrape_configs:
  - job_name: 'auth-service'
    static_configs:
      - targets: ['auth-service:8080']
    metrics_path: '/metrics'
    scheme: 'http'

In security-rules.yml:

groups:
  - name: auth-security
    rules:
      - record: 'login_failure_rate'
        expr: |
          sum(rate(auth_login_failed_total[5m])) / sum(rate(auth_login_total[5m]))
        labels:
          severity: 'warning'

When login_failure_rate > 0.15, create an alert in Alertmanager using the route and match directives:

route:
  group_by: ['alertname', 'service']
  group_wait: 30s
  group_interval: 5m
  repeat_interval: 1h
  receiver: 'security-team'
  routes:
    - match:
        severity: 'warning'
      receiver: 'security-team'
    - match:
        alertname: 'LoginFailureRateHigh'
      receiver: 'incident-response'

receivers:
  - name: 'security-team'
    email_configs:
      - to: '[email protected]'
        send_resolved: true

An alert fires when login failure rate exceeds 15% over 5 minutes. The alert includes the auth_login_failed_total time series, the auth_login_total series, and a list of top 10 failing users from a backend SQL query.

Correlating Events Across Services and Logs

Security incidents often span multiple services. A login failure in auth-service may originate from a database connection issue in user-service, triggered by a network delay in gateway. To correlate, embed a shared trace ID in all logs and metrics.

In every service, propagate a trace_id header through HTTP requests using OpenTelemetry. In a Go service, use the opentelemetry-go SDK:

import (
    "context"
    "net/http"
    "go.opentelemetry.io/otel"
    "go.opentelemetry.io/otel/propagation"
    "go.opentelemetry.io/otel/trace"
)

func handler(w http.ResponseWriter, r *http.Request) {
    ctx, span := otel.Tracer("auth-service").Start(r.Context(), "Login")
    defer span.End()

    traceID := span.SpanContext().TraceID().String()
    log.Printf("trace_id=%s user_id=%s", traceID, r.Header.Get("X-User-ID"))

    // Process login
    if err := authenticateUser(r); err != nil {
        span.RecordError(err)
        span.SetStatus(codes.Error, err.Error())
    }
}

On the backend, the database query logs include the same trace_id via structured JSON:

{
  "timestamp": "2023-09-15T10:30:00Z",
  "level": "error",
  "service": "user-service",
  "trace_id": "a3b9f1c8e2d4a5b6c7d8e9f0a1b2c3d4",
  "message": "Failed to fetch user profile",
  "error": "context deadline exceeded",
  "user_id": "u742839"
}

In a centralized logging system like Fluentd, use a filter block to enrich logs with metadata:

<filter **>
  @type record_transformer
  enable_ruby true
  <record>
    trace_id ${record["trace_id"] || "" }
    service_name ${record["service"] || "unknown" }
    severity ${record["level"] == "error" ? "critical" : "info" }
  </record>
</filter>

<match **>
  @type elasticsearch
  host localhost
  port 9200
  logstash_format true
  logstash_prefix "logs"
  index_name "logs-%Y-%m-%d"
  type_name "log"
</match>

With this, a security engineer can query the Elasticsearch index with trace_id: a3b9f1c8e2d4a5b6c7d8e9f0a1b2c3d4 and see all related logs, metrics, and traces in one place.

Enriching Observability with Security Context

To detect advanced threats, enrich observability data with security-specific context. This includes user behavior, IP geolocation, device fingerprints, and threat intelligence.

Add a user_context field to every log entry and metric. In a Node.js service, use express middleware:

const { tracer } = require('@opentelemetry/api');

function enrichUserContext(req, res, next) {
  const ctx = tracer.currentSpanContext();
  const traceId = ctx ? ctx.traceId : 'unknown';

  const userContext = {
    userId: req.headers['x-user-id'],
    userAgent: req.headers['user-agent'],
    ipAddress: req.headers['x-forwarded-for'] || req.socket.remoteAddress,
    sessionId: req.cookies.sessionId,
    traceId: traceId,
    loginTime: Date.now(),
  };

  req.userContext = userContext;

  // Add to OpenTelemetry span
  const span = tracer.startSpan('UserContextEnrichment');
  span.setAttribute('user.id', userContext.userId);
  span.setAttribute('user.ip', userContext.ipAddress);
  span.end();

  next();
}

app.use(enrichUserContext);

This context is available in logs, metrics, and traces. Use it to define security-specific metrics:

A dashboard in Grafana can display the user_login_frequency metric with a threshold: users logging in more than once per hour are likely bots. A sudden spike in user_session_count with low user_login_frequency suggests credential stuffing.

Detecting and Responding to Threat Patterns

With enriched data, build detection rules for common attack patterns. Use a simple event-driven pipeline with curl, jq, and psql to detect credential stuffing.

A service logs login attempts with userId, ipAddress, timestamp, and success:

{
  "userId": "u742839",
  "ipAddress": "192.168.1.10",
  "timestamp": "2023-09-15T10:30:00Z",
  "success": false
}

Use psql to query a login_attempts table and detect credential stuffing:

psql -c "
SELECT 
  user_id,
  COUNT(*) AS attempt_count,
  ARRAY_AGG(ip_address) AS ip_list
FROM login_attempts
WHERE timestamp >= NOW() - INTERVAL '1 hour'
  AND success = false
GROUP BY user_id
HAVING COUNT(*) > 5
ORDER BY attempt_count DESC
LIMIT 10;
"

When more than 5 failed attempts for a user in one hour, trigger an alert via curl to a monitoring API:

curl -X POST https://alerting-api.example.com/v1/alert \
  -H 'Content-Type: application/json' \
  -d '{
    "alertname": "CredentialStuffingDetected",
    "description": "User u742839 attempted login 6 times in 1 hour with different IPs",
    "details": {
      "user_id": "u742839",
      "attempt_count": 6,
      "ip_addresses": ["192.168.1.10", "10.0.1.5", "203.0.113.22"],
      "first_attempt": "2023-09-15T10:25:00Z",
      "last_attempt": "2023-09-15T11:15:00Z"
    },
    "severity": "critical",
    "labels": {
      "source": "observability-security",
      "attack_type": "credential-stuffing"
    }
  }'

This alert appears in the central dashboard and triggers an incident in the response workflow.

Building a Security-First Observability Pipeline

Observability security is not a one-off setup. It requires a consistent pipeline from data generation to detection and response.

Define a standard event schema across all services using a JSON format with a fixed set of keys:

{
  "timestamp": "2023-09-15T10:30:00Z",
  "event_type": "user.login.failed",
  "source": "auth-service",
  "trace_id": "a3b9f1c8e2d4a5b6c7d8e9f0a1b2c3d4",
  "user_id": "u742839",
  "ip_address": "192.168.1.10",
  "session_id": "sess_abc123",
  "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",
  "data": {
    "error_code": "invalid_credentials",
    "login_attempt": 3,
    "retry_count": 2
  }
}

Use systemctl to manage a fluentd daemon that ingests these events from Kafka, processes them, and forwards to Elasticsearch:


[Unit]
Description=Fluentd for Observability Security
After=network.target

[Service]
Type=simple
User=fluent
ExecStart=/usr/bin/fluentd -c /etc/fluent/fluentd-security.conf
Restart=on-failure
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target

The configuration file fluentd-security.conf includes filters for enriching and routing:

<match observability.security.**>
  @type elasticsearch
  host es-cluster.example.com
  port 9200
  logstash_format true
  logstash_prefix "security"
  index_name "security-%Y-%m-%d"
  type_name "event"
  <buffer>
    @type file
    path /var/lib/fluentd/buffer/security
    flush_interval 30s
    chunk_limit_size 2M
    queue_limit_length 1000
  </buffer>
</match>

Common Failures and Sharp Edges

Several issues silently degrade observability security:

  promtool check rules security-rules.yml
  cat logs/*.json | jq 'map(select(.user_role == null)) | length'

Summary

Observability security is not just monitoring for failures—it is using the full spectrum of system behavior to detect and respond to security threats. It begins with detecting anomalies in metrics and logs, correlates events across services using distributed tracing, enriches data with security context, and builds detection rules for attack patterns. The pipeline is grounded in standard tools: curl, psql, systemctl, jq, and promtool. The key is consistency: a shared event schema, a common trace ID, and a unified alerting flow. When the system breaks, the answer is not just “the service is down,” but “the attacker has been inside for 12 hours.”

This page was rewritten on 18 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.