0
0
NestJSframework~8 mins

TCP transport in NestJS - Performance & Optimization

Choose your learning style9 modes available
Performance: TCP transport
MEDIUM IMPACT
This affects the speed and responsiveness of backend communication between microservices or clients and servers using TCP protocol.
Sending messages between microservices using NestJS TCP transport
NestJS
const client = new ClientTCP({ host: 'localhost', port: 3000 });
await client.connect();
const response1 = await client.send('event1', { data1 }).toPromise();
const response2 = await client.send('event2', { data2 }).toPromise();
// reuse client without reconnecting
await client.close();
Reusing a single TCP client connection avoids repeated handshakes and reduces latency.
📈 Performance Gainreduces latency by 100-200ms per message, improves throughput
Sending messages between microservices using NestJS TCP transport
NestJS
const client = new ClientTCP({ host: 'localhost', port: 3000 });
await client.connect();
const response = await client.send('event', { data }).toPromise();
await client.close();
Creating and closing the TCP client for every message causes repeated connection overhead and delays.
📉 Performance Costadds 100-200ms latency per message due to TCP handshake and teardown
Performance Comparison
PatternConnection OverheadLatency per MessageResource UsageVerdict
Create and close client per messageHigh (new TCP handshake each time)High (100-200ms extra)High CPU and network usage[X] Bad
Reuse persistent client connectionLow (single handshake)Low (minimal extra latency)Lower CPU and network usage[OK] Good
Rendering Pipeline
TCP transport in NestJS involves establishing a socket connection, sending data packets, and receiving responses asynchronously. The main bottleneck is the network handshake and socket management.
Connection Establishment
Data Transmission
Response Handling
⚠️ BottleneckConnection Establishment due to TCP handshake overhead
Optimization Tips
1Reuse TCP client connections to avoid repeated handshakes.
2Avoid creating and closing TCP clients for every message.
3Monitor TCP connections to detect unnecessary reconnections.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance cost of creating a new TCP client for every message in NestJS?
ARepeated TCP handshakes causing latency
BIncreased memory usage on the client
CSlower JavaScript execution
DMore database queries
DevTools: Network panel in backend monitoring tools or tcpdump
How to check: Capture TCP packets during message sending; check for repeated connection setups and teardowns.
What to look for: Multiple TCP handshakes indicate inefficient connection reuse; persistent connections show fewer handshakes and lower latency.