Bird
Raised Fist0
NestJSframework~20 mins

TCP transport in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
TCP Transport Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
Understanding TCP Transport Client Behavior in NestJS
Consider a NestJS microservice client configured with TCP transport connecting to a server. What will happen if the server is not running when the client tries to send a message?
NestJS
const client = ClientProxyFactory.create({ transport: Transport.TCP, options: { host: '127.0.0.1', port: 3001 } });

async function sendMessage() {
  return client.send('test_pattern', { data: 'hello' }).toPromise();
}

sendMessage().catch(err => console.error(err));
AThe client will throw an error immediately because the server is unreachable.
BThe client will connect to a default fallback server automatically.
CThe client will silently drop the message without any error or retry.
DThe client will queue the message and retry sending until the server becomes available.
Attempts:
2 left
💡 Hint
Think about how NestJS TCP clients handle connection retries by default.
📝 Syntax
intermediate
2:00remaining
Correct TCP Transport Server Setup in NestJS
Which of the following code snippets correctly creates a TCP microservice server in NestJS listening on port 4000?
A
const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.TCP, options: { port: 4000 } });
await app.listen();
B
const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.TCP, port: 4000 });
await app.listen();
C
const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.TCP, options: { host: 'localhost' } });
await app.listen();
D
const app = await NestFactory.createMicroservice(AppModule, { transport: 'tcp', options: { port: 4000 } });
await app.listen();
Attempts:
2 left
💡 Hint
Check how the port is specified inside the options object.
🔧 Debug
advanced
2:00remaining
Diagnosing TCP Transport Connection Refused Error
A NestJS TCP client throws a "connect ECONNREFUSED" error when trying to send a message. Which of the following is the most likely cause?
AThe client and server have mismatched message payload formats.
BThe client is using the wrong message pattern name.
CThe server is not running or not listening on the specified port.
DThe client forgot to import the Transport module.
Attempts:
2 left
💡 Hint
ECONNREFUSED means the connection was actively refused by the target machine.
❓ state_output
advanced
2:00remaining
Output of TCP Client Send with Timeout
Given a NestJS TCP client configured with a 2-second timeout, what will be the output if the server takes 5 seconds to respond?
NestJS
const client = ClientProxyFactory.create({
  transport: Transport.TCP,
  options: { host: '127.0.0.1', port: 3001, timeout: 2000 }
});

async function send() {
  try {
    const response = await client.send('delayed_response', {}).toPromise();
    console.log('Response:', response);
  } catch (err) {
    console.log('Error:', err.message);
  }
}
send();
ALogs: 'Error: Timeout has occurred' after 2 seconds.
BLogs: 'Error: Connection refused' immediately.
CLogs: 'Response: <server response>' after 5 seconds.
DNo output; the client waits indefinitely.
Attempts:
2 left
💡 Hint
Consider the effect of the timeout option on client requests.
🧠 Conceptual
expert
3:00remaining
TCP Transport Message Pattern Matching in NestJS
In a NestJS TCP microservice, how does the server determine which handler to invoke for an incoming message?
AIt uses the message payload type to select the handler automatically.
BIt matches the message's pattern property to the @MessagePattern decorator's pattern on handlers.
CIt invokes all handlers and returns the first non-null response.
DIt relies on the client to specify the handler function name explicitly.
Attempts:
2 left
💡 Hint
Think about how NestJS uses decorators to route messages.

Practice

(1/5)
1. What is the main purpose of using Transport.TCP in a NestJS microservice?
easy
A. To connect to a database using TCP.
B. To serve static files over HTTP.
C. To enable communication between microservices using TCP sockets.
D. To handle WebSocket connections.

Solution

  1. Step 1: Understand the role of Transport.TCP

    Transport.TCP is used in NestJS to set up microservices communication over TCP sockets.
  2. Step 2: Compare with other options

    Serving static files, database connections, and WebSocket handling are different concerns not related to Transport.TCP.
  3. Final Answer:

    To enable communication between microservices using TCP sockets. -> Option C
  4. Quick Check:

    Transport.TCP = Microservice TCP communication [OK]
Hint: Remember TCP transport is for microservice socket communication [OK]
Common Mistakes:
  • Confusing TCP transport with HTTP or WebSocket protocols
  • Thinking it handles database connections
  • Assuming it serves static files
2. Which of the following is the correct way to create a TCP microservice in NestJS?
easy
A. const app = await NestFactory.createMicroservice(AppModule, { protocol: Transport.TCP, port: 3000 });
B. const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.TCP, options: { port: 3000 } });
C. const app = await NestFactory.createMicroservice(AppModule, { transport: 'tcp', port: 3000 });
D. const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.HTTP, options: { port: 3000 } });

Solution

  1. Step 1: Check NestJS microservice creation syntax

    The correct syntax uses transport: Transport.TCP and an options object with port.
  2. Step 2: Identify incorrect options

    The other options use wrong properties like protocol instead of transport, pass port directly without an options object, use string 'tcp' instead of the Transport.TCP enum, or use the wrong transport type like Transport.HTTP.
  3. Final Answer:

    const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.TCP, options: { port: 3000 } }); -> Option B
  4. Quick Check:

    Use transport: Transport.TCP with options object [OK]
Hint: Use Transport.TCP enum and options object for port [OK]
Common Mistakes:
  • Using 'protocol' instead of 'transport'
  • Passing port directly without options object
  • Using string 'tcp' instead of Transport.TCP enum
  • Confusing TCP with HTTP transport
3. Given this NestJS TCP microservice setup:
const app = await NestFactory.createMicroservice(AppModule, {
  transport: Transport.TCP,
  options: { host: '127.0.0.1', port: 4000 }
});
await app.listen();
console.log('Microservice is listening');

What will be the output when the microservice starts successfully?
medium
A. Microservice failed to start
B. Error: Port 4000 is already in use
C. Listening on HTTP port 4000
D. Microservice is listening

Solution

  1. Step 1: Understand the code flow

    The microservice is created with TCP transport on host 127.0.0.1 and port 4000, then listens successfully.
  2. Step 2: Identify the console output

    After await app.listen(), the console logs 'Microservice is listening'. No errors are shown.
  3. Final Answer:

    Microservice is listening -> Option D
  4. Quick Check:

    Successful listen logs message [OK]
Hint: Successful listen logs 'Microservice is listening' [OK]
Common Mistakes:
  • Assuming automatic HTTP server start
  • Expecting error without port conflict
  • Confusing TCP with HTTP output
4. Identify the error in this NestJS TCP microservice code:
const app = await NestFactory.createMicroservice(AppModule, {
  transport: Transport.TCP,
  options: { port: '3000' }
});
await app.listen();
medium
A. Port should be a number, not a string.
B. Missing host option causes failure.
C. Transport.TCP is invalid here.
D. app.listen() must be called with a callback.

Solution

  1. Step 1: Check the options object

    The port value is given as a string '3000', but it must be a number.
  2. Step 2: Validate other parts

    Host is optional, Transport.TCP is valid, and app.listen() can be awaited without callback.
  3. Final Answer:

    Port should be a number, not a string. -> Option A
  4. Quick Check:

    Port must be numeric type [OK]
Hint: Port option must be a number, not quoted string [OK]
Common Mistakes:
  • Passing port as string instead of number
  • Thinking host is mandatory
  • Expecting app.listen to require callback
5. You want to create a NestJS TCP microservice that listens on all network interfaces on port 5000 and logs a message when a client connects. Which code snippet correctly implements this?
hard
A. const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.TCP, options: { host: '0.0.0.0', port: 5000 } }); await app.listen(); app.on('connection', () => console.log('Client connected'));
B. const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.TCP, options: { host: '0.0.0.0', port: 5000 } }); app.listen(() => console.log('Client connected'));
C. const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.TCP, options: { host: 'localhost', port: 5000 } }); app.listen(() => console.log('Client connected'));
D. const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.TCP, options: { port: 5000 } }); app.listen(() => console.log('Client connected'));

Solution

  1. Step 1: Set host and port correctly

    To listen on all interfaces, host must be '0.0.0.0' and port 5000 is correct.
  2. Step 2: Attach client connection event properly

    TCP microservice emits 'connection' event; attaching listener after await app.listen() is correct.
  3. Step 3: Evaluate distractors

    Distractors either use the wrong host like 'localhost', omit the host, fail to await app.listen(), or attach the logger to the listen() callback instead of the 'connection' event.
  4. Final Answer:

    const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.TCP, options: { host: '0.0.0.0', port: 5000 } }); await app.listen(); app.on('connection', () => console.log('Client connected')); -> Option A
  5. Quick Check:

    Host 0.0.0.0 + event listener after listen [OK]
Hint: Use host '0.0.0.0' and listen before event binding [OK]
Common Mistakes:
  • Using 'localhost' instead of '0.0.0.0' to listen on all interfaces
  • Logging inside listen callback instead of connection event
  • Not awaiting app.listen() before event binding
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard