I'm building a microservices architecture using NestJS, and I have an API Gateway that proxies requests to different services (Order, Email, User).
Everything works fine for GET requests, but POST requests to the Email service hang indefinitely and eventually fail with socket hang up.
Setup I have a simple routing setup in my API Gateway:
export const routes = {
Order: 'http://localhost:3001/api/Order',
Email: 'http://localhost:3002/api/Email',
User: 'http://localhost:3003/api/User',
};
Here's my API Gateway controller that proxies requests:
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@All('api/:service/*')
async proxy(
@Param('service') service: string,
@Req() req: Request,
@Res() res: Response,
@Body() body: any,
) {
console.log('Service:', service);
const path = req.url.replace(`/api/${service}`, '');
try {
const response = await this.appService.forwardRequest(req, res, body, path, service);
res.status(response.status).json(response.data);
} catch (error) {
console.error('Proxy request failed:', error);
return res.status(500).json({ message: 'Error forwarding request' });
}
}
}
My API Gateway service forwards requests using axios (@nestjs/axios):
async forwardRequest(
req: Request,
res: Response,
body: any,
path: string,
service: string,
): Promise<AxiosResponse> {
const baseURL = routes[service];
const url = baseURL + path;
const configuredHeaders = this.httpHelper.configureHeaders(req.headers);
console.log('Forwarding request:', {
method: req.method,
url,
headers: configuredHeaders,
body: JSON.stringify(body),
});
return lastValueFrom(
this.http.request({
method: req.method,
url: url,
data: body,
headers: configuredHeaders,
timeout: 10000, // 10 seconds
}),
);
}
The Issue
- GET requests work perfectly!
- POST requests to http://localhost:3000/api/Email/SendEmail hang indefinitely (or any other POST requests).
- But if I call http://localhost:3002/api/Email/SendEmail directly, it works fine.
When I created a test GET endpoint in my Email service:
@Get('SendEmail')
sendEmailTest() {
console.log('Test log!');
return { message: 'Email sent!' };
}
It worked fine through the API Gateway, meaning the issue is only for POST requests.
What I've Tried So Far
- Checked if the Email service receives the request → It doesn't (so the problem is likely in the API Gateway).
- Enabled express.json() and express.urlencoded in main.ts → Still hangs.
- Logged request body in forwardRequest() → body seems present.
- Added a timeout to Axios (10s) → Just fails after 10s instead of hanging forever.
Why would POST requests hang, but GET requests work fine through the API Gateway? What could be causing NestJS to hang indefinitely on a proxied POST request?