How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
NestJS · TypeScript/React

Fix Error: connect ECONNREFUSED 127.0.0.1:6379 - Redis connection to localhost:6379 failed in NestJS

This error occurs when the NestJS Bull/BullMQ queue module cannot connect to Redis because the Redis server is not running or is unreachable at the configured host and port. Fix it by starting Redis, verifying the connection config, and adding connection retry logic in the queue module registration.

Reading the Stack Trace

Error: connect ECONNREFUSED 127.0.0.1:6379 - Redis connection to localhost:6379 failed at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) at RedisClient.connect (node_modules/ioredis/built/Redis.js:253:17) at BullModule.registerQueue (node_modules/@nestjs/bull/dist/bull.module.js:48:22) at InstanceLoader.createInstancesOfProviders (node_modules/@nestjs/core/injector/instance-loader.js:44:9) at InstanceLoader.createInstances (node_modules/@nestjs/core/injector/instance-loader.js:29:9) at InstanceLoader.createInstancesOfDependencies (node_modules/@nestjs/core/injector/instance-loader.js:16:9) at /node_modules/@nestjs/core/nest-factory.js:96:9 at NestApplication.init (node_modules/@nestjs/core/nest-application.js:68:36) at NestApplication.listen (node_modules/@nestjs/core/nest-application.js:106:33) at bootstrap (src/main.ts:12:3)

Here's what each line means:

Common Causes

1. Redis server not running

The Redis server is not installed or not started on the host machine or container.

// app.module.ts
BullModule.forRoot({
  redis: {
    host: 'localhost',
    port: 6379,
  },
})
// Redis is not running

2. Wrong Redis host in production

The app is configured for localhost but the Redis instance runs on a different host in production.

BullModule.forRoot({
  redis: {
    host: 'localhost', // Should be redis.internal.svc
    port: 6379,
  },
})

3. No retry configuration

The connection fails immediately without retrying, even though Redis might become available shortly.

BullModule.forRoot({
  redis: { host: 'localhost', port: 6379 },
  // No retry strategy configured
})

The Fix

Use environment variables for Redis connection details so each environment can configure its own Redis instance. Add a retryStrategy with exponential backoff so the app retries transient connection failures instead of crashing immediately.

Before (broken)
import { BullModule } from '@nestjs/bull';
import { Module } from '@nestjs/common';

@Module({
  imports: [
    BullModule.forRoot({
      redis: {
        host: 'localhost',
        port: 6379,
      },
    }),
    BullModule.registerQueue({ name: 'email' }),
  ],
})
export class AppModule {}
After (fixed)
import { BullModule } from '@nestjs/bull';
import { Module } from '@nestjs/common';

@Module({
  imports: [
    BullModule.forRoot({
      redis: {
        host: process.env.REDIS_HOST || 'localhost',
        port: parseInt(process.env.REDIS_PORT, 10) || 6379,
        password: process.env.REDIS_PASSWORD || undefined,
        maxRetriesPerRequest: 3,
        retryStrategy: (times: number) => {
          if (times > 10) return null; // Stop retrying after 10 attempts
          return Math.min(times * 200, 5000);
        },
      },
    }),
    BullModule.registerQueue({ name: 'email' }),
  ],
})
export class AppModule {}

Testing the Fix

import { Test, TestingModule } from '@nestjs/testing';
import { getQueueToken } from '@nestjs/bull';
import { EmailProcessor } from './email.processor';

describe('EmailProcessor', () => {
  let processor: EmailProcessor;

  const mockQueue = {
    add: jest.fn().mockResolvedValue({ id: '1' }),
    process: jest.fn(),
  };

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        EmailProcessor,
        { provide: getQueueToken('email'), useValue: mockQueue },
      ],
    }).compile();

    processor = module.get<EmailProcessor>(EmailProcessor);
  });

  it('should be defined', () => {
    expect(processor).toBeDefined();
  });

  it('adds a job to the queue', async () => {
    await mockQueue.add('sendWelcome', { to: 'user@example.com' });
    expect(mockQueue.add).toHaveBeenCalledWith('sendWelcome', { to: 'user@example.com' });
  });
});

Run your tests:

npm test

Pushing Through CI/CD

git checkout -b fix/nestjs-queue-redis-connection,git add src/app.module.ts src/processors/__tests__/email.processor.spec.ts,git commit -m "fix: add Redis retry strategy and env-based config for Bull queues",git push origin fix/nestjs-queue-redis-connection

Your CI config should look something like this:

name: CI
on:
  pull_request:
    branches: [main]
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      redis:
        image: redis:7
        ports:
          - 6379:6379
        options: >-
          --health-cmd "redis-cli ping"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      - run: npm ci
      - run: npm test -- --coverage
        env:
          REDIS_HOST: localhost
          REDIS_PORT: 6379
      - run: npm run build

The Full Manual Process: 18 Steps

Here's every step you just went through to fix this one bug:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. Monitor production to confirm the error is resolved

Total time: 30-60 minutes. For one bug.

Or Let bugstack Fix It in Under 2 minutes

Every step above? bugstack does it automatically.

Step 1: Install the SDK

npm install bugstack-sdk

Step 2: Initialize

import { initBugStack } from 'bugstack-sdk'

initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })

Step 3: There is no step 3.

bugstack handles everything from here:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. Deploys to production (or opens a PR for review)

Time from error to fix deployed: Under 2 minutes.

Human involvement: zero.

Try bugstack Free →

No credit card. 5-minute setup. Cancel anytime.

Deploying the Fix (Manual Path)

  1. Ensure Redis is running and accessible from the application environment.
  2. Configure REDIS_HOST and REDIS_PORT environment variables.
  3. Add retry strategy to handle transient connection failures.
  4. Run tests with a Redis service to verify queue operations.
  5. Open a PR, merge after CI, and verify queue processing in staging.

Frequently Asked Questions

BugStack runs the fix through your existing test suite, generates additional edge-case tests, and validates that no other modules are affected before marking it safe to deploy.

BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.

Yes, Bull and BullMQ require Redis as their backend. Redis stores job data, handles scheduling, and manages concurrency across workers.

Jobs persisted in Redis survive restarts. If Redis is unavailable, new jobs cannot be added or processed. Once Redis returns, processing resumes from where it left off.