n8n Automation

n8n Monitoring: Building Self-Healing Workflows

Petru Constantin
••10 min read
#n8n#monitoring#observability#automation#alerting

Petru Constantin is the founder of DeviDevs and designed the multi-agent platform the company runs on, with guardrails enforced in code. Code examples are written against the n8n 2.47 (stable 2.47.7) documentation.

n8n Monitoring and Observability: Building Self-Healing Workflows

Monitoring n8n in production starts with what n8n already exposes: the /healthz and /healthz/readiness endpoints, the Prometheus /metrics endpoint and error workflows built on the Error Trigger. This guide covers those first, then alert routing to PagerDuty and Slack and a few self-healing patterns built from node settings and Code nodes.

Workflow Health Monitoring

Execution Health Tracker

// Code node (Run Once for All Items), first node after an Error Trigger.
// Set this workflow as "Error workflow" in the settings of every workflow you monitor.
// Turns the Error Trigger payload into a normalized alert for the routing step.
return $input.all().map(item => {
  const { execution = {}, workflow = {} } = item.json;
 
  return {
    json: {
      alertId: `n8n-${workflow.id}-${execution.id ?? 'unknown'}`,
      // Failures in manual runs are rarely worth paging someone
      severity: execution.mode === 'manual' ? 'low' : 'high',
      title: `Workflow failed: ${workflow.name}`,
      workflow: workflow.name,
      workflowId: workflow.id,
      executionId: execution.id ?? null,
      executionUrl: execution.url ?? null,
      lastNode: execution.lastNodeExecuted ?? null,
      error: execution.error?.message ?? 'Unknown error',
      retryOf: execution.retryOf ?? null,
      status: 'failed',
      source: 'n8n-error-workflow',
      createdAt: $now.toISO()
    }
  };
});

Health Check Endpoint Workflow

#!/usr/bin/env bash
# External health check for n8n (cron, uptime monitor or Kubernetes probe script)
# /healthz: the instance is reachable. /healthz/readiness: the database is connected and migrated.
# Workers in queue mode expose /healthz only with QUEUE_HEALTH_CHECK_ACTIVE=true.
set -euo pipefail
 
N8N_BASE_URL="${N8N_BASE_URL:?Set N8N_BASE_URL, for example https://n8n.yourdomain.com}"
 
curl --fail --silent --show-error --max-time 5 "${N8N_BASE_URL}/healthz" > /dev/null
curl --fail --silent --show-error --max-time 5 "${N8N_BASE_URL}/healthz/readiness" > /dev/null
 
echo "n8n is reachable and ready"

Metrics Collection

Prometheus Metrics Export

# docker-compose.yml excerpt: n8n's built-in Prometheus endpoint (self-hosted only)
services:
  n8n:
    environment:
      - N8N_METRICS=true                          # enables /metrics (default: false)
      - N8N_METRICS_INCLUDE_WORKFLOW_ID_LABEL=true
      - N8N_METRICS_INCLUDE_QUEUE_METRICS=true    # queue mode only
      # N8N_METRICS_PREFIX defaults to n8n_
 
# prometheus.yml excerpt
scrape_configs:
  - job_name: n8n
    metrics_path: /metrics
    static_configs:
      - targets: ['n8n:5678']

Custom Metrics Collection

// Code node (Run Once for All Items): execution counts from the n8n node
// Upstream: two n8n nodes, Resource "Execution", Operation "Get Many",
// named "Failed executions" (Status: Error) and "Successful executions" (Status: Success).
// The counts cover the executions those nodes returned, not a fixed time window;
// for rates over time, use the Prometheus metrics from N8N_METRICS.
const failed = $('Failed executions').all().length;
const succeeded = $('Successful executions').all().length;
const total = failed + succeeded;
 
return [{
  json: {
    collectedAt: $now.toISO(),
    failed,
    succeeded,
    total,
    failureRate: total > 0 ? Number((failed / total).toFixed(4)) : 0
  }
}];

Alerting Integration

Multi-Channel Alert System

// Code node (Run Once for All Items): alert routing
// Outputs one item per channel; a Switch node on $json.channel sends each to its node.
const routingConfig = {
  critical: {
    channels: ['pagerduty', 'slack', 'email'],
    slackChannel: '#incidents',
    escalateAfter: 300  // 5 minutes
  },
  high: {
    channels: ['slack', 'email'],
    slackChannel: '#alerts',
    escalateAfter: 1800  // 30 minutes
  },
  medium: {
    channels: ['slack'],
    slackChannel: '#alerts-low',
    escalateAfter: null
  },
  low: {
    channels: ['slack'],
    slackChannel: '#alerts-info',
    escalateAfter: null
  }
};
 
const output = [];
 
for (const item of $input.all()) {
  const alert = item.json;
  const severity = routingConfig[alert.severity] ? alert.severity : 'medium';
  const config = routingConfig[severity];
 
  for (const channel of config.channels) {
    output.push({
      json: {
        channel,
        alert: {
          ...alert,
          severity,
          routedAt: new Date().toISOString(),
          config: {
            slackChannel: config.slackChannel,
            escalateAfter: config.escalateAfter
          }
        }
      }
    });
  }
}
 
return output;

PagerDuty Integration

// Code node (Run Once for Each Item): PagerDuty Events API v2 payload
// Next node: HTTP Request, POST https://events.pagerduty.com/v2/enqueue, JSON body {{ $json }}.
// PAGERDUTY_ROUTING_KEY is read with $env, which needs N8N_BLOCK_ENV_ACCESS_IN_NODE=false.
// Set that variable explicitly: the n8n 2.0 breaking changes guide lists true as the new default.
const alert = $input.item.json.alert;
 
function mapSeverity(severity) {
  // PagerDuty accepts critical, error, warning, info
  const mapping = { critical: 'critical', high: 'error', medium: 'warning', low: 'info' };
  return mapping[severity] || 'warning';
}
 
const payload = {
  routing_key: $env.PAGERDUTY_ROUTING_KEY,
  event_action: alert.resolved ? 'resolve' : 'trigger',
  dedup_key: String(alert.alertId).slice(0, 255),
  payload: {
    summary: alert.title,
    severity: mapSeverity(alert.severity),
    source: alert.source || 'n8n-workflow',
    timestamp: new Date().toISOString(),
    custom_details: {
      workflow: alert.workflow,
      error: alert.error,
      executionId: alert.executionId,
      lastNode: alert.lastNode
    }
  }
};
 
if (alert.executionUrl) {
  payload.links = [{ href: alert.executionUrl, text: 'View Execution' }];
}
 
return { json: payload };

Slack Alert Formatting

// Code node (Run Once for Each Item): Slack Block Kit message for chat.postMessage
// Uses top-level blocks; Slack documents message attachments as legacy.
const alert = $input.item.json.alert;
 
// Slack treats &, < and > as control characters in text
const escapeSlack = (value) => String(value ?? '')
  .replace(/&/g, '&amp;')
  .replace(/</g, '&lt;')
  .replace(/>/g, '&gt;');
 
const severityEmoji = {
  critical: ':red_circle:',
  high: ':large_orange_circle:',
  medium: ':large_yellow_circle:',
  low: ':large_green_circle:'
};
 
const severity = severityEmoji[alert.severity] ? alert.severity : 'medium';
const timestamp = Math.floor(Date.now() / 1000);
 
const blocks = [
  {
    type: 'header',
    text: {
      type: 'plain_text',
      text: `${severityEmoji[severity]} ${severity.toUpperCase()}: ${String(alert.title).slice(0, 120)}`,
      emoji: true
    }
  },
  {
    type: 'section',
    fields: [
      { type: 'mrkdwn', text: `*Workflow:*\n${escapeSlack(alert.workflow)}` },
      { type: 'mrkdwn', text: `*Time:*\n<!date^${timestamp}^{date_short_pretty} {time}|${new Date().toISOString()}>` },
      { type: 'mrkdwn', text: `*Execution ID:*\n${escapeSlack(alert.executionId)}` },
      { type: 'mrkdwn', text: `*Status:*\n${escapeSlack(alert.status)}` }
    ]
  }
];
 
if (alert.error) {
  blocks.push({
    type: 'section',
    text: { type: 'mrkdwn', text: `*Error:*\n\`\`\`${escapeSlack(String(alert.error).substring(0, 500))}\`\`\`` }
  });
}
 
if (alert.executionUrl) {
  blocks.push({
    type: 'actions',
    elements: [
      {
        type: 'button',
        text: { type: 'plain_text', text: 'View Execution' },
        url: alert.executionUrl
      }
    ]
  });
}
 
return {
  json: {
    channel: alert.config?.slackChannel || '#alerts',
    text: `${severity.toUpperCase()}: ${alert.title}`, // notification fallback
    blocks
  }
};

Self-Healing Patterns

Automatic Retry with Backoff

// Code node (Run Once for Each Item): decide retry, fail or escalate
// For transient errors on a single node, the node setting "Retry On Fail" is enough.
// Use this when you retry through a Wait node or need a different path per error type.
const MAX_RETRIES = 5;
const BASE_DELAY_MS = 1000;
const MAX_DELAY_MS = 60000;
const RETRYABLE = ['ECONNRESET', 'ETIMEDOUT', 'ECONNREFUSED', 'rate_limit', '429', '503', '504'];
 
const data = $input.item.json;
const currentRetry = data.retryCount ?? 0;
const originalData = data.originalData ?? data;
 
// lastError can be a string or an error object from an error output
const errorText = typeof data.lastError === 'string'
  ? data.lastError
  : JSON.stringify(data.lastError ?? '');
 
if (currentRetry >= MAX_RETRIES) {
  return {
    json: { action: 'escalate', reason: 'Max retries exceeded', totalRetries: currentRetry, lastError: errorText, originalData }
  };
}
 
if (!RETRYABLE.some(code => errorText.includes(code))) {
  return {
    json: { action: 'fail', reason: 'Non-retryable error', lastError: errorText, originalData }
  };
}
 
// Exponential backoff with jitter, capped
const delayMs = Math.min(BASE_DELAY_MS * 2 ** currentRetry + Math.random() * 1000, MAX_DELAY_MS);
 
// Feed delaySeconds to a Wait node, then loop back to the failing step
return {
  json: {
    action: 'retry',
    retryCount: currentRetry + 1,
    delaySeconds: Math.ceil(delayMs / 1000),
    scheduledFor: $now.plus({ milliseconds: delayMs }).toISO(),
    originalData
  }
};

Circuit Breaker Implementation

// Circuit breaker built from two Code nodes that share workflow static data.
// n8n saves static data only after a successful production execution, so set the
// HTTP Request node's On Error to "Continue (using error output)" instead of letting the run fail.
 
// ---- Node "Circuit check" (Run Once for Each Item), before the HTTP Request node ----
const OPEN_TIMEOUT_MS = 60000; // 1 minute
const serviceName = $input.item.json.serviceName || 'default';
const staticData = $getWorkflowStaticData('global');
 
staticData.circuitBreakers ??= {};
staticData.circuitBreakers[serviceName] ??= { state: 'closed', failures: 0, successes: 0, openedAt: null };
const breaker = staticData.circuitBreakers[serviceName];
 
if (breaker.state === 'open') {
  if (Date.now() - breaker.openedAt > OPEN_TIMEOUT_MS) {
    breaker.state = 'half-open';
    breaker.successes = 0;
  } else {
    // Fail fast; an If node on $json.proceed skips the HTTP call
    return {
      json: {
        proceed: false,
        reason: 'Circuit breaker open',
        service: serviceName,
        retryAfter: new Date(breaker.openedAt + OPEN_TIMEOUT_MS).toISOString()
      }
    };
  }
}
 
return { json: { ...$input.item.json, proceed: true, service: serviceName, circuitState: breaker.state } };
 
// ---- Node "Circuit record" (Run Once for Each Item) ----
// One copy on the HTTP Request success output with SUCCESS = true,
// one copy on its error output with SUCCESS = false.
const SUCCESS = true;
const FAILURE_THRESHOLD = 5;
const SUCCESS_THRESHOLD = 3;
 
const service = $('Circuit check').item.json.service;
const state = $getWorkflowStaticData('global').circuitBreakers[service];
 
if (SUCCESS) {
  state.failures = 0;
  if (state.state === 'half-open' && ++state.successes >= SUCCESS_THRESHOLD) {
    state.state = 'closed';
  }
} else {
  state.failures += 1;
  if (state.state === 'half-open' || state.failures >= FAILURE_THRESHOLD) {
    state.state = 'open';
    state.openedAt = Date.now();
  }
}
 
return { json: { ...$input.item.json, service, circuitState: state.state } };

Automatic Failover

Failover doesn't need a Code node. Set the primary HTTP Request node's On Error to Continue (using error output) and connect the error output to a second HTTP Request node that calls the failover URL. Turn on Retry On Fail on the primary first, so short glitches don't switch traffic, and put the circuit breaker above in front of the primary when an outage lasts longer.

Dashboard and Reporting

Workflow Status Dashboard Data

// Code node (Run Once for All Items): dashboard status from the metrics item (see above)
// Thresholds on the failure rate: above 5% degraded, above 20% unhealthy
const THRESHOLDS = { degraded: 0.05, unhealthy: 0.20 };
const m = $input.first().json;
 
let systemHealth = 'healthy';
if (m.failureRate > THRESHOLDS.unhealthy) systemHealth = 'unhealthy';
else if (m.failureRate > THRESHOLDS.degraded) systemHealth = 'degraded';
 
return [{
  json: {
    timestamp: $now.toISO(),
    systemHealth,
    summary: {
      executionsSampled: m.total,
      failed: m.failed,
      succeeded: m.succeeded,
      successRate: m.total > 0 ? Number(((1 - m.failureRate) * 100).toFixed(1)) : null
    }
  }
}];

Common mistakes

  • Testing static data in the editor. n8n doesn't save workflow static data during test runs; publish the workflow and start it from its trigger before you judge the circuit breaker.
  • Looking for /metrics on n8n Cloud. The endpoint exists on self-hosted instances only, and only after N8N_METRICS=true.
  • Probing queue-mode workers without enabling the endpoint. Workers expose /healthz only with QUEUE_HEALTH_CHECK_ACTIVE=true.
  • Treating /healthz as a database check. It only says the instance is reachable; /healthz/readiness returns 200 only when the database is connected and migrated.

Best Practices Summary

  1. Comprehensive Health Checks - Monitor workflow execution, duration, and error rates
  2. Metrics Collection - Export metrics to Prometheus or similar for visualization
  3. Multi-Channel Alerting - Route alerts based on severity to appropriate channels
  4. Self-Healing Patterns - Implement retries, circuit breakers, and failover
  5. Dashboard Visibility - Provide real-time visibility into workflow health

By implementing these monitoring patterns, you can build reliable, observable n8n workflows that automatically recover from failures.


Official references

Related on this site: AI-Powered n8n Workflows: Integration Patterns, Data Synchronization Workflows with n8n, n8n Email Automation: Complete Workflow Implementation Guide. More articles in the n8n Automation category.

Want AI agents and automations your business can actually run on?

We ship production AI in fixed two-week sprints, then secure them. Book a 30-minute call to scope yours.

Book a Call

Before you book, you can see what we build, how a sprint works, how our pricing works, what we have already built, or write to us directly.

Weekly AI Agents, Automation & Security Digest

How we build AI agents and automations with Claude Code, plus practical AI security, integrations, and platform notes, delivered weekly.

No spam. Unsubscribe anytime.