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
Here's what each line means:
- at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16): The TCP connection to Redis was refused because nothing is listening on port 6379.
- at BullModule.registerQueue (node_modules/@nestjs/bull/dist/bull.module.js:48:22): The NestJS Bull module tried to establish a Redis connection during queue registration at startup.
- at bootstrap (src/main.ts:12:3): The application fails to bootstrap because the queue module cannot initialize without Redis.
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.
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 {}
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:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- 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:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- 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)
- Ensure Redis is running and accessible from the application environment.
- Configure REDIS_HOST and REDIS_PORT environment variables.
- Add retry strategy to handle transient connection failures.
- Run tests with a Redis service to verify queue operations.
- 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.