n8n database connection timed out – PostgreSQL pool exhausted fix

Step by Step Guide to solve n8n queue mode database connection failure
Step by Step Guide to solve n8n queue mode database connection failure


Who this is for: SREs, DevOps engineers, and platform architects running n8n in production‑grade queue mode (Kubernetes, Docker‑Compose, or managed container services). We cover this in detail in the n8n Queue Mode Errors Guide.


Quick Diagnosis (Featured‑Snippet Ready)

Symptom: In queue mode n8n logs Error: Failed to connect to database and stops processing jobs.

Root cause: The workflow‑executor’s MySQL/PostgreSQL client cannot establish or maintain a DB connection (wrong credentials, TLS mismatch, connection‑pool exhaustion, or network/firewall block).

One‑line fix: Verify DB credentials & TLS settings, then raise N8N_QUEUE_MODE_DB_MAX_CONNECTIONS (default 5) to match your workload, and restart n8n.


1. How n8n Uses the Database in Queue Mode

If you encounter any n8n queue mode redis unavailable resolve them before continuing with the setup.

Component → Role

Component Role in Queue Mode
Workflow Executor Pulls pending jobs from execution_entity, updates status, writes results
Job Scheduler (BullMQ) Stores job metadata in the same DB (when queueMode=database)
Health‑Check Endpoint Periodically pings DB to report “queue‑mode‑healthy”

Component → Typical Failure Point

Component Typical Failure Point
Workflow Executor Connection timeout, authentication error
Job Scheduler (BullMQ) Pool exhaustion, dead‑lock
Health‑Check Endpoint Mis‑configured health‑check interval

EEFA note: In production, each executor pod or Docker container opens its own pool. Over‑provisioning without increasing N8N_QUEUE_MODE_DB_MAX_CONNECTIONS quickly saturates the DB, causing intermittent failures.


2. Step‑by‑Step Troubleshooting Checklist

Micro‑summary: Follow these actions in order to isolate network, credentials, TLS, and pool‑size problems.

Step Action Command / Config
1 Confirm DB is reachable from the n8n host nc -zvw3 <DB_HOST> <DB_PORT>
2 Validate credentials (user, password, database) mysql -u $USER -p$PASS -h $HOST $DB
or
psql "host=$HOST dbname=$DB user=$USER password=$PASS"
3 Check TLS/SSL settings – match N8N_QUEUE_MODE_DB_SSL flag openssl s_client -connect $HOST:$PORT -servername $HOST
4 Inspect connection‑pool size – default 5 may be too low echo $N8N_QUEUE_MODE_DB_MAX_CONNECTIONS
5 Review DB server logs for “too many connections” or auth failures tail -f /var/log/mysql/error.log
6 Increase pool size (recommended 20‑30 for medium load) export N8N_QUEUE_MODE_DB_MAX_CONNECTIONS=30
7 Restart n8n to apply env changes docker restart n8n
or
kubectl rollout restart deployment/n8n
8 Validate queue health via API curl http://localhost:5678/healthz → look for "queueMode":"healthy"
9 Monitor for 15 min (Prometheus/Grafana or docker logs -f n8n)
10 Persist env changes in your orchestration (docker‑compose, k8s ConfigMap)

EEFA warning: Setting the pool too high can overwhelm the DB, especially on managed services with connection caps (e.g., AWS RDS default 150). Stay within 70 % of the DB’s max_connections. If you encounter any n8n queue mode sqlite locking issue resolve them before continuing with the setup.


3. Configuring Database Connection for Queue Mode

3.1 Environment Variables Overview

Variable Example Description
N8N_QUEUE_MODE database Enables DB‑backed queue mode
DB_TYPE postgresdb postgresdb or mysqldb
DB_POSTGRESDB_HOST db.mycompany.internal Hostname / IP
DB_POSTGRESDB_PORT 5432 Port
DB_POSTGRESDB_DATABASE n8n Database name
DB_POSTGRESDB_USER n8n_user DB user
DB_POSTGRESDB_PASSWORD •••••• Secret (Docker secret / k8s Secret)
DB_POSTGRESDB_SSL true Force TLS (recommended)
N8N_QUEUE_MODE_DB_MAX_CONNECTIONS 30 Max connections per n8n instance
N8N_QUEUE_MODE_DB_CONNECTION_TIMEOUT 5000 ms before aborting connection attempt

3.2 Docker‑Compose – Service Definition

services:
  n8n:
    image: n8nio/n8n:latest
    ports:
      - "5678:5678"
    depends_on:
      - postgres

Docker‑Compose – Environment Block

environment:
  - N8N_QUEUE_MODE=database
  - DB_TYPE=postgresdb
  - DB_POSTGRESDB_HOST=postgres.internal
  - DB_POSTGRESDB_PORT=5432
  - DB_POSTGRESDB_DATABASE=n8n
  - DB_POSTGRESDB_USER=n8n_user
  - DB_POSTGRESDB_PASSWORD=${POSTGRES_PASSWORD}
  - DB_POSTGRESDB_SSL=true
  - N8N_QUEUE_MODE_DB_MAX_CONNECTIONS=30
  - N8N_QUEUE_MODE_DB_CONNECTION_TIMEOUT=8000

EEFA tip: Store POSTGRES_PASSWORD in a Docker secret or Kubernetes Secret; never hard‑code it.

3.3 Kubernetes – Deployment Metadata

apiVersion: apps/v1
kind: Deployment
metadata:
  name: n8n
spec:
  replicas: 3
  selector:
    matchLabels:
      app: n8n

Kubernetes – Container Spec

template:
  metadata:
    labels:
      app: n8n
  spec:
    containers:
      - name: n8n
        image: n8nio/n8n:latest
        envFrom:
          - secretRef:
              name: n8n-db-creds
        env:
          - name: N8N_QUEUE_MODE
            value: "database"
          - name: DB_TYPE
            value: "postgresdb"
          - name: N8N_QUEUE_MODE_DB_MAX_CONNECTIONS
            value: "25"
          - name: N8N_QUEUE_MODE_DB_CONNECTION_TIMEOUT
            value: "7000"
        ports:
          - containerPort: 5678

EEFA note: With three replicas, each pod requests 25 connections → 75 total. Ensure PostgreSQL max_connections is > 90 to leave headroom for admin tools.


4. Deep‑Dive into Common Failure Scenarios

4.1 Invalid TLS Certificate

Symptom: error: self signed certificate in logs.

Root cause: DB server presents a cert not trusted by the n8n container.

Fix:

  1. Temporary test – set DB_POSTGRESDB_SSL_REJECT_UNAUTHORIZED=false.
  2. Production – import the CA cert into the container:
    COPY ca.crt /usr/local/share/ca-certificates/
    RUN update-ca-certificates
  3. Or switch to SSL_MODE=verify-full with proper hostname verification.

4.2 “Too many connections” Error

Log excerpt: Error: connect ECONNREFUSED - connection pool exhausted.

Why it happens: Each workflow execution opens a new DB client; the pool limit is hit before the DB can recycle idle connections.

Resolution:

  • Increase N8N_QUEUE_MODE_DB_MAX_CONNECTIONS.
  • Reduce concurrent executions via EXECUTIONS_PROCESS=1 if you cannot raise DB limits.
  • Enable an idle timeout (default 30 s) by setting N8N_QUEUE_MODE_DB_IDLE_TIMEOUT=20000.

4.3 Network Policy Blocking Port

Symptom: connect ECONNREFUSED <IP>:5432 after initial successful connections.

Cause: Kubernetes NetworkPolicy or cloud security group restricts concurrent connections per pod.

Action:

  1. Verify NetworkPolicy ingress rules allow traffic from the n8n namespace to the DB service.
  2. In AWS, adjust the **Security Group** outbound rule to allow tcp:5432 for the pod’s ENI.

5. Monitoring & Alerting for Queue‑Mode DB Health

5.1 Prometheus – Scrape Config (n8n v0.215+)

scrape_configs:
  - job_name: 'n8n'
    static_configs:
      - targets: ['n8n:5678']
    metrics_path: '/metrics'

5.2 Prometheus – Relevant Metrics

Metric Meaning Alert Threshold
n8n_queue_db_connections Current active DB connections > 0.8 × max_connections
n8n_queue_db_errors_total Cumulative connection errors > 5 per minute

EEFA recommendation: Pair alerts with an automatic pod restart (kubectl rollout restart) to recover from transient blips, but always investigate the root cause first.

5.3 Grafana Loki – Log‑Based Alert

{app="n8n"} |~ "Failed to connect to database|ECONNREFUSED|TLS handshake"
|= "queue mode"
| count_over_time(5m) > 3

TL;DR (Featured Snippet)

Problem: n8n in queue mode stops processing with “Failed to connect to database”.
Fix: Verify DB host/port, user, password, and TLS; then raise N8N_QUEUE_MODE_DB_MAX_CONNECTIONS (e.g., to 30) and restart n8n. Ensure the DB’s max_connections exceeds the total needed by all n8n instances.


All commands assume a Unix‑like shell. Adjust paths and secret handling for Windows containers as needed.

Leave a Comment

Your email address will not be published. Required fields are marked *