Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 60

Scaling Workflows with Queue Mode and Workers

Recommended resources

Introduction

In our last lesson, we configured a robust, production-grade hosting environment for n8n using a VPS, PostgreSQL, and an Nginx reverse proxy. While this setup is secure and reliable, it has an architectural limitation: a single n8n process handles everything from the user interface and API calls to the actual execution of every workflow. As your automation load increases, this single process can become a bottleneck, leading to slowdowns and unresponsiveness.

This lesson addresses that limitation head-on. We will enable n8n's queue mode, a distributed architecture designed for scalability. You will learn how to reconfigure your Docker setup to offload workflow executions to dedicated worker processes using Redis as a high-speed message broker. This change is fundamental to building an n8n instance that can handle high-volume, mission-critical tasks, moving you another step closer to your goal of mastering n8n for production CI/CD automation.


Why Queue Mode? The Scalability Bottleneck

In the default configuration (called "main mode"), your n8n instance operates like a restaurant with a single employee who acts as the host, server, and chef. If a complex, time-consuming "dish" (a heavy workflow) is being prepared, no new "orders" (triggers or API calls) can be taken, and the entire "restaurant" (the UI) feels sluggish.

Queue mode solves this by separating responsibilities. To continue the analogy from the video "The Ultimate Guide to Scaling Your Self-Hosted n8n Instance":

  • The Main Process becomes the "host" who greets customers and takes orders. It manages the UI, API endpoints, and triggers, but it no longer "cooks the food."
  • A Message Queue (Redis) is introduced as the "order counter." The main process places an "order ticket" (a job) on this queue for every workflow that needs to run.
  • Workers are the "chefs" in the kitchen. They are dedicated processes that constantly check the queue, pick up the next available ticket, and execute the workflow.

This decoupling means that a surge in workflow executions won't impact the responsiveness of the UI or the ability to receive new webhook events. You can scale your "kitchen" by simply hiring more "chefs" (adding more worker containers) to handle increased demand.

The diagram below illustrates this distributed architecture. All incoming requests are handled by your reverse proxy (Nginx, in your case), which directs UI traffic to the n8n main process. When a workflow is triggered, the main process enqueues a job in Redis. A worker then picks up this job, executes it, and interacts with the PostgreSQL database to retrieve workflow data and store execution results.

A high-level view of the n8n queue mode architecture, where the main process offloads execution jobs to workers via a Redis queue.

The performance benefits are significant. Official n8n benchmarks show queue mode can handle up to 7 times more requests per second with a 0% failure rate compared to the default mode, which starts to fail under heavy load.


The Execution Flow in Detail

To fully appreciate the architecture, let's trace the lifecycle of a single workflow execution using the sequence diagram below.

A sequence diagram illustrating the interaction between components during a workflow execution in queue mode.
  1. Trigger: A user or an external service triggers a workflow (e.g., via a webhook call). The request hits the n8n Main Service.
  2. Enqueue: The main service creates a record for the execution in the PostgreSQL Database but does not run the workflow. Instead, it places a message containing the execution ID onto the Redis Queue.
  3. Poll & Retrieve: One of the Workers (Worker-1 in this diagram), which are constantly polling the Redis queue for new tasks, picks up the job.
  4. Process: The worker uses the execution ID to fetch the full workflow definition and credentials from the PostgreSQL database. It then executes the entire workflow.
  5. Persist & Acknowledge: Upon completion, the worker writes the results and logs back to the PostgreSQL database. It then acknowledges the job as complete, which removes it from the Redis queue.
  6. Status Update: The user can request the execution status from the main service, which now retrieves the final results directly from the PostgreSQL database.

The par block in the diagram signifies that multiple workers can perform these tasks in parallel, each pulling jobs from the queue independently. This is the key to horizontal scalability. For a clear walkthrough of this process, the following video provides an excellent conceptual overview.

Master n8n Queue Mode: Scale Your Workflows to Thousands of Users (Step-by-Step Advanced Tutorial)

The video "Master n8n Queue Mode" offers a detailed explanation of the logic and flow behind this architecture.

Watch the segment from the conceptual explanation to see a visual, step-by-step breakdown of how the main process, job system (Redis), workers, and database interact.


Hands-On: Reconfiguring for Queue Mode

Now, let's apply these concepts by reconfiguring your docker-compose.yml file. Since you are comfortable with Docker, we'll use a clean and efficient structure with YAML anchors to keep our configuration DRY (Don't Repeat Yourself).

This guide from idir.ai provides a robust template for this setup, which we will adapt.

Scale #n8n: The Ultimate Guide to Queue Mode & Docker | Blog

This guide provides an excellent, production-grade Docker Compose configuration for n8n in queue mode. It clearly defines the different services and the environment variables needed to connect them.

Focus on the following sections to understand the components and configuration: The problem statement and component breakdown, which reinforces the architecture we discussed. The .env file configuration, which lists all the necessary variables for queue mode. The docker-compose.yml structure, paying close attention to how the x-n8n-common anchor is used to share configuration between the n8n-main and n8n-worker services. The component descriptions, which clarify the role of each service in the Compose file.

Let's modify your existing setup. You should have a docker-compose.yml and likely an .env file from the previous lessons.

1. Update your .env file

First, ensure your .env file contains the variables needed for Redis and to activate queue mode. Add the following lines, creating a secure password for Redis. You can generate one with openssl rand -hex 16.




# .env




# ... (your existing variables like POSTGRES_PASSWORD, N8N_HOST, etc.)




# --- REDIS CONFIGURATION ---
REDIS_PASSWORD=your-secure-redis-password




# --- N8N QUEUE MODE ---
EXECUTIONS_MODE=queue
QUEUE_BULL_REDIS_HOST=redis
QUEUE_BULL_REDIS_PORT=6379
QUEUE_BULL_REDIS_PASSWORD=${REDIS_PASSWORD}
OFFLOAD_MANUAL_EXECUTIONS_TO_WORKERS=true
  • EXECUTIONS_MODE=queue: This is the master switch that enables queue mode.
  • QUEUE_BULL_...: These variables tell n8n how to connect to the Redis container.
  • OFFLOAD_MANUAL_EXECUTIONS_TO_WORKERS=true: This sends executions triggered manually from the editor to the workers, keeping the UI snappy during development and testing.

2. Overhaul your docker-compose.yml

Now, replace the content of your docker-compose.yml with the following structure. This version introduces the redis and n8n-worker services and uses anchors for efficiency.




# docker-compose.yml

volumes:
  postgres_data:
  redis_data:
  n8n_data:

x-n8n-common: &n8n-common
  image: docker.n8n.io/n8nio/n8n:${N8N_VERSION:-latest}
  restart: unless-stopped
  env_file:
    - .env
  volumes:
    - n8n_data:/home/node/.n8n
  depends_on:
    postgres:
      condition: service_healthy
    redis:
      condition: service_healthy
  networks:
    - n8n_network

services:
  postgres:
    image: postgres:16-alpine
    restart: unless-stopped
    env_file:
      - .env
    environment:
      - POSTGRES_USER=${POSTGRES_USER}
      - POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
      - POSTGRES_DB=${POSTGRES_DB}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
      interval: 10s
      timeout: 5s
      retries: 5
    networks:
      - n8n_network

  redis:
    image: redis:7-alpine
    restart: unless-stopped
    command: >
      redis-server --requirepass ${REDIS_PASSWORD}
    volumes:
      - redis_data:/data
    healthcheck:
      test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD}", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5
    networks:
      - n8n_network

  n8n-main:
    <<: *n8n-common
    hostname: n8n-main



    # This is the service your Nginx proxy should point to.
    # It handles the UI, API, and webhook triggers.
    ports:
      - "127.0.0.1:5678:5678"

  n8n-worker:
    <<: *n8n-common
    hostname: n8n-worker



    # This service executes the workflows.
    # It has no ports as it only communicates internally.
    command: worker
    environment:



      # This controls how many workflows a single worker can run in parallel.
      - QUEUE_WORKER_CONCURRENCY=5

networks:
  n8n_network:
    driver: bridge

Key Changes:

  • Redis Service: A new redis service is added, configured with the password from your .env file.
  • x-n8n-common Anchor: This defines a base configuration (image, environment file, volumes) shared by both the main and worker services.
  • n8n-main Service: This is your original n8n service. Note that the port 5678 is now bound only to 127.0.0.1 (localhost). Your external Nginx reverse proxy, running on the same VPS, will proxy requests to this local port.
  • n8n-worker Service: This new service inherits from the common anchor but adds command: worker. This tells the container to start in worker mode instead of main mode. It exposes no ports.

Launching and Scaling Your Workers

With the new configuration in place, you can bring up the distributed stack.

  1. Stop the old instance:
    docker compose down
    
  2. Start the new queue-mode stack:
    docker compose up -d
    
  3. Verify the services: Check that all four containers (postgres, redis, n8n-main, n8n-worker) are running and healthy.
    docker compose ps
    
    You should also check the logs of the worker to confirm it has started correctly.
    docker compose logs n8n-worker
    

Now, the most powerful feature: scaling your execution capacity is as simple as a single command. To scale from one to three workers, run:

docker compose up -d --scale n8n-worker=3

Docker Compose will automatically create and start two additional worker containers, which will immediately start pulling jobs from the Redis queue. You now have three "chefs" in your kitchen.


Tuning for Performance: Concurrency vs. Workers

Scaling isn't just about adding more workers; it's also about configuring them correctly. You have two primary levers for performance tuning:

  1. Number of Workers (Scaling Out): Controlled by the --scale flag in docker compose. This is best for handling more workflows in total.
  2. Worker Concurrency (Scaling Up): Controlled by the QUEUE_WORKER_CONCURRENCY environment variable. This determines how many workflows a single worker can execute simultaneously.

The optimal concurrency value depends on your typical workload.

  • I/O-Bound Workflows: If your workflows spend most of their time waiting (e.g., for API calls, database queries, file I/O), you can set a higher concurrency (e.g., 10-20). While one task is waiting, the worker's CPU is free to work on another.
  • CPU-Bound Workflows: If your workflows perform heavy computations (e.g., complex data transformations in a Python Code node), you should set a lower concurrency (e.g., 1-4, often matching the number of available vCPUs). Trying to run too many CPU-intensive tasks at once leads to context-switching overhead and slows everything down.

A good starting point is a concurrency of 5. You can then monitor your workers' CPU usage (docker stats) under a realistic load and adjust the value. If CPU usage is low, increase concurrency. If CPU is consistently maxed out, decrease concurrency and consider adding more worker containers instead.


Conclusion

In this lesson, you have fundamentally re-architected your n8n deployment for performance and scale. By enabling queue mode, you've decoupled the main application from the heavy lifting of workflow execution, ensuring your system remains responsive even under high load.

Key Takeaways:

  • Queue Mode Architecture: Separates responsibilities into a Main process (UI/API), Redis (message queue), and one or more Workers (execution).
  • Component Roles: The main process enqueues jobs, Redis holds them, and workers execute them, with PostgreSQL as the persistent data store for all services.
  • Configuration: The transition is managed through a modified docker-compose.yml and key environment variables, most importantly EXECUTIONS_MODE=queue.
  • Horizontal Scaling: You can easily increase execution capacity by adding more worker containers using the docker compose --scale command.
  • Performance Tuning: Balancing the number of workers with the QUEUE_WORKER_CONCURRENCY setting is key to optimizing throughput for your specific workloads.

This scalable foundation is crucial for any serious production environment. In our next lesson, we will continue hardening our self-hosted instance by exploring how to manage user authentication and permissions, giving you granular control over who can access and modify your workflows.