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

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

RequestTimeoutException: Request timeout: no response received within 30000ms at ClientProxy.dispatchEvent (node_modules/@nestjs/microservices/client/client-proxy.js:87:23) at ClientTCP.send (node_modules/@nestjs/microservices/client/client-tcp.js:42:18) at OrderService.getUser (src/order/order.service.ts:24:30) at OrderController.create (src/order/order.controller.ts:18:28) at /node_modules/@nestjs/core/router/router-execution-context.js:46:28 at /node_modules/@nestjs/core/router/router-proxy.js:9:23 at Layer.handle [as handle_request] (node_modules/express/lib/router/layer.js:95:5) at next (node_modules/express/lib/router/route.js:144:13) at Route.dispatch (node_modules/express/lib/router/route.js:114:3) at Layer.handle [as handle_request] (node_modules/express/lib/router/layer.js:95:5)

Here's what each line means:

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().

Before (broken)
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();
  }
}
After (fixed)
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:

  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. Verify the target microservice is running and reachable.
  2. Ensure message patterns match between client and server.
  3. Add per-request timeouts with descriptive error messages.
  4. Run tests to verify timeout handling.
  5. 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.