Fix RequestTimeoutException: Request timeout: no response received within 30000ms in NestJS
This error occurs when a NestJS microservice client sends a message but does not receive a response within the configured timeout. Common causes include the target service being down, slow processing, or mismatched message patterns. Fix it by verifying service connectivity, increasing timeouts for slow operations, and adding proper error handling.
Reading the Stack Trace
Here's what each line means:
- at ClientProxy.dispatchEvent (node_modules/@nestjs/microservices/client/client-proxy.js:87:23): The microservice client proxy waited for a response but the timeout elapsed without receiving one.
- at ClientTCP.send (node_modules/@nestjs/microservices/client/client-tcp.js:42:18): The TCP transport sent the message but the target microservice did not respond in time.
- at OrderService.getUser (src/order/order.service.ts:24:30): Your order service at line 24 sends a request to the user microservice which timed out.
Common Causes
1. Target microservice is not running
The microservice that should handle the message is down or not started, so no response is ever sent.
// Order service sends to user service but user service is not running
this.userClient.send({ cmd: 'get_user' }, { userId: 1 }).toPromise();
2. Message pattern mismatch
The client sends a message with a pattern that does not match any handler in the target service.
// Client sends: { cmd: 'get_user' }
// Server handler: @MessagePattern({ cmd: 'getUser' }) -- different naming
3. Slow database query in handler
The microservice handler performs a long-running operation that exceeds the client's timeout.
@MessagePattern({ cmd: 'get_user' })
async getUser(data: { userId: number }) {
return await this.userRepo.findOneWithRelations(data.userId); // Takes 45s
}
The Fix
Use RxJS timeout() to set an explicit per-request timeout instead of relying on the global default. Catch TimeoutError specifically to return a descriptive error message. Use firstValueFrom instead of the deprecated toPromise().
import { Inject, Injectable } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
@Injectable()
export class OrderService {
constructor(@Inject('USER_SERVICE') private userClient: ClientProxy) {}
async getUser(userId: number) {
return this.userClient.send({ cmd: 'get_user' }, { userId }).toPromise();
}
}
import { Inject, Injectable, RequestTimeoutException } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { timeout, catchError, firstValueFrom } from 'rxjs';
import { throwError, TimeoutError } from 'rxjs';
@Injectable()
export class OrderService {
constructor(@Inject('USER_SERVICE') private userClient: ClientProxy) {}
async getUser(userId: number) {
return firstValueFrom(
this.userClient.send({ cmd: 'get_user' }, { userId }).pipe(
timeout(10000),
catchError((err) => {
if (err instanceof TimeoutError) {
return throwError(() => new RequestTimeoutException(
`User service did not respond within 10s for userId: ${userId}`
));
}
return throwError(() => err);
}),
),
);
}
}
Testing the Fix
import { Test, TestingModule } from '@nestjs/testing';
import { OrderService } from './order.service';
import { of, throwError, NEVER } from 'rxjs';
describe('OrderService', () => {
let service: OrderService;
const mockClient = { send: jest.fn() };
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
OrderService,
{ provide: 'USER_SERVICE', useValue: mockClient },
],
}).compile();
service = module.get<OrderService>(OrderService);
});
it('returns user data on success', async () => {
mockClient.send.mockReturnValue(of({ id: 1, name: 'Alice' }));
const user = await service.getUser(1);
expect(user.name).toBe('Alice');
});
it('throws RequestTimeoutException on timeout', async () => {
mockClient.send.mockReturnValue(NEVER);
await expect(service.getUser(1)).rejects.toThrow('did not respond within');
}, 15000);
it('re-throws non-timeout errors', async () => {
mockClient.send.mockReturnValue(throwError(() => new Error('Connection refused')));
await expect(service.getUser(1)).rejects.toThrow('Connection refused');
});
});
Run your tests:
npm test
Pushing Through CI/CD
git checkout -b fix/nestjs-microservice-timeout,git add src/order/order.service.ts src/order/__tests__/order.service.spec.ts,git commit -m "fix: add explicit timeout and error handling for microservice calls",git push origin fix/nestjs-microservice-timeout
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm test -- --coverage
- 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)
- Verify the target microservice is running and reachable.
- Ensure message patterns match between client and server.
- Add per-request timeouts with descriptive error messages.
- Run tests to verify timeout handling.
- Open a PR, merge after CI, and test inter-service communication 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.
Enable NestJS debug logging with logger: ['debug'] in the microservice options. It will log all registered message patterns and incoming messages.
TCP is simplest for direct communication. Redis or NATS add reliability with message queuing and are better for production. Choose based on your reliability and scalability needs.