Enable TCP Keep-Alive in your NestJS microservice by creating a custom socket class that configures the connection to stay active. This prevents AWS NLB timeouts caused by inactivity ( I have this problem with docker swarm ideal network connection ).
import { JsonSocket } from '@nestjs/microservices/helpers';
import { Socket } from 'net';
class CustomTcpSocket extends JsonSocket {
constructor(socket: Socket) {
socket.setKeepAlive(true, 10000); // Enable Keep-Alive with a 10s
super(socket);
}
}
app.connectMicroservice<MicroserviceOptions>({
transport: Transport.TCP,
options: {
host: '0.0.0.0',
port: tcpPort, // Replace with your port
socketClass: CustomTcpSocket,
},
});