Bird
Raised Fist0
NestJSframework~10 mins

gRPC transport in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - gRPC transport
Define Proto File
↓
Generate gRPC Service Interfaces
↓
Create NestJS gRPC Microservice
↓
Implement Service Handlers
↓
Start Microservice
↓
Client Sends gRPC Request
↓
Server Processes Request
↓
Server Sends Response
↓
Client Receives Response
This flow shows how NestJS uses gRPC transport: define proto, generate interfaces, create microservice, implement handlers, start service, then client-server communication.
Execution Sample
NestJS
import { Controller } from '@nestjs/common';
import { GrpcMethod } from '@nestjs/microservices';

@Controller()
export class HeroService {
  @GrpcMethod('HeroService', 'FindOne')
  findOne(data: { id: number }) {
    return { id: data.id, name: 'Hero' + data.id };
  }
}
This NestJS service listens for gRPC calls to 'FindOne' method and returns a hero object with id and name.
Execution Table
StepActionInputInternal StateOutput
1Receive gRPC request{ id: 1 }Waiting for requestNone
2Invoke findOne handler{ id: 1 }Processing request with id=1None
3Create response object{ id: 1 }Response = { id: 1, name: 'Hero1' }None
4Send response backResponse objectResponse sent{ id: 1, name: 'Hero1' }
5Client receives responseResponse objectClient processes response{ id: 1, name: 'Hero1' }
6EndNo inputIdleNo further output
💡 No more requests; microservice continues listening for new calls.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
dataundefined{ id: 1 }{ id: 1 }{ id: 1 }undefined
responseundefinedundefined{ id: 1, name: 'Hero1' }{ id: 1, name: 'Hero1' }undefined
Key Moments - 2 Insights
Why does the findOne method receive an object with id instead of separate parameters?
Because gRPC methods receive a single object representing the request message, matching the proto definition. See execution_table step 2 where data is { id: 1 }.
How does NestJS know which method to call for a gRPC request?
The @GrpcMethod decorator links the proto service and method name to the handler. In the code, @GrpcMethod('HeroService', 'FindOne') tells NestJS to call findOne for that gRPC method.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'response' after Step 3?
A{ id: 1, name: 'Hero1' }
Bundefined
C{ id: 1 }
Dnull
💡 Hint
Check the 'Internal State' column at Step 3 in execution_table.
At which step does the server send the response back to the client?
AStep 2
BStep 4
CStep 5
DStep 3
💡 Hint
Look for 'Send response back' action in execution_table.
If the client sends { id: 5 } instead, what will be the 'name' in the response?
A'Hero1'
B'Hero'
C'Hero5'
Dundefined
💡 Hint
See the code in execution_sample where name is 'Hero' + data.id.
Concept Snapshot
NestJS gRPC transport uses proto files to define services.
Use @GrpcMethod to link proto methods to handlers.
Handlers receive request objects and return response objects.
Microservice listens and processes gRPC calls asynchronously.
Client-server communicate via defined proto messages.
Full Transcript
This visual execution shows how NestJS handles gRPC transport. First, a proto file defines the service and messages. NestJS generates interfaces and creates a microservice. The service class uses @GrpcMethod to handle specific gRPC calls. When a client sends a request like { id: 1 }, the findOne method receives it as an object. It processes and returns a response object with id and name. The microservice sends this back to the client. Variables like 'data' and 'response' change during execution steps. Key points include how NestJS maps proto methods to handlers and how request data is structured. The quiz tests understanding of response values and flow steps.

Practice

(1/5)
1. What is the main purpose of using gRPC transport in a NestJS application?
easy
A. To enable fast and clear communication between microservices using Protocol Buffers
B. To create RESTful APIs with JSON responses
C. To manage database connections efficiently
D. To handle user authentication and authorization

Solution

  1. Step 1: Understand gRPC transport role

    gRPC transport in NestJS is designed to enable fast communication between services using Protocol Buffers.
  2. Step 2: Compare with other options

    Options B, C, and D describe other unrelated features like REST APIs, database, or auth, which are not the main purpose of gRPC transport.
  3. Final Answer:

    To enable fast and clear communication between microservices using Protocol Buffers -> Option A
  4. Quick Check:

    gRPC transport = fast microservice communication [OK]
Hint: gRPC = fast microservice communication with Protocol Buffers [OK]
Common Mistakes:
  • Confusing gRPC with REST APIs
  • Thinking gRPC manages databases
  • Assuming gRPC handles authentication
2. Which decorator is used in NestJS to link a method to a gRPC service method?
easy
A. @GrpcMethod
B. @GrpcClient
C. @GrpcHandler
D. @GrpcService

Solution

  1. Step 1: Recall NestJS gRPC decorators

    The correct decorator to connect a method to a gRPC service method is @GrpcMethod.
  2. Step 2: Eliminate incorrect options

    @GrpcService, @GrpcHandler, and @GrpcClient are not valid decorators for this purpose in NestJS.
  3. Final Answer:

    @GrpcMethod -> Option A
  4. Quick Check:

    Method to gRPC service = @GrpcMethod [OK]
Hint: Method to gRPC service uses @GrpcMethod decorator [OK]
Common Mistakes:
  • Using @GrpcService instead of @GrpcMethod
  • Confusing client decorators with method decorators
  • Misspelling the decorator name
3. Given this NestJS gRPC service method, what will be the output when called with { id: 5 }?
  @GrpcMethod('HeroService', 'FindOne')
  findOne(data: { id: number }): { name: string } {
    const heroes = [{ id: 1, name: 'Superman' }, { id: 5, name: 'Batman' }];
    return { name: heroes.find(hero => hero.id === data.id)?.name || 'Unknown' };
  }
medium
A. { name: 'Unknown' }
B. { name: 'Superman' }
C. undefined
D. { name: 'Batman' }

Solution

  1. Step 1: Analyze the input and method logic

    The method receives { id: 5 } and searches the heroes array for a hero with id 5.
  2. Step 2: Find matching hero

    Hero with id 5 is { id: 5, name: 'Batman' }, so it returns { name: 'Batman' }.
  3. Final Answer:

    { name: 'Batman' } -> Option D
  4. Quick Check:

    Input id 5 returns Batman [OK]
Hint: Find hero by id in array returns matching name [OK]
Common Mistakes:
  • Returning Superman instead of Batman
  • Returning Unknown when hero exists
  • Returning undefined instead of fallback
4. Identify the error in this NestJS gRPC service method:
  @GrpcMethod('HeroService', 'FindOne')
  findOne(data: { id: number }): { name: string } {
    const heroes = [{ id: 1, name: 'Superman' }];
    return heroes.find(hero => hero.id === data.id).name;
  }
medium
A. Incorrect decorator name
B. Missing return type annotation
C. Possible runtime error if hero not found
D. heroes array should be empty

Solution

  1. Step 1: Understand the find method behavior

    If no hero matches data.id, find returns undefined.
  2. Step 2: Identify the error

    Accessing .name on undefined causes a runtime error.
  3. Final Answer:

    Possible runtime error if hero not found -> Option C
  4. Quick Check:

    Accessing property on undefined causes error [OK]
Hint: Check if find() result can be undefined before accessing properties [OK]
Common Mistakes:
  • Ignoring undefined result from find()
  • Assuming decorator name is wrong
  • Thinking return type annotation is missing
5. You want to implement a streaming gRPC method in NestJS that sends multiple messages back to the client. Which approach correctly sets up the method signature and decorator?
hard
A. @GrpcMethod('ChatService', 'StreamMessages') streamMessages(data: { userId: number }): Promise<{ message: string }> { // implementation }
B. @GrpcMethod('ChatService', 'StreamMessages') streamMessages(data: { userId: number }): Observable<{ message: string }> { // implementation }
C. @GrpcMethod('ChatService', 'StreamMessages') streamMessages(data: { userId: number }): { message: string } { // implementation }
D. @GrpcMethod('ChatService', 'StreamMessages') streamMessages(data: { userId: number }): void { // implementation }

Solution

  1. Step 1: Understand streaming method return types

    Streaming gRPC methods in NestJS return an Observable to send multiple messages over time.
  2. Step 2: Evaluate options

    @GrpcMethod('ChatService', 'StreamMessages') streamMessages(data: { userId: number }): Observable<{ message: string }> { // implementation } returns Observable, suitable for streaming. Options A and C return single responses (Promise or object). @GrpcMethod('ChatService', 'StreamMessages') streamMessages(data: { userId: number }): void { // implementation } returns void, which is invalid.
  3. Final Answer:

    Method returning Observable for streaming -> Option B
  4. Quick Check:

    Streaming gRPC method returns Observable [OK]
Hint: Streaming methods return Observable, not Promise or plain object [OK]
Common Mistakes:
  • Using Promise instead of Observable for streaming
  • Returning plain object for streaming method
  • Using void return type for gRPC method
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