Unary, Server, Client, and Bidirectional Streaming RPCs
Implement the four gRPC call types and choose the right pattern for each interaction.
Four Ways to Call an RPC
gRPC defines four kinds of method in your .proto file, and each one maps to a different streaming shape:
- Unary — one request, one response (like a normal function call).
- Server streaming — one request, a stream of responses.
- Client streaming — a stream of requests, one response.
- Bidirectional streaming — both sides stream independently.
The stream keyword in the service definition is what decides the shape. In this lesson you'll implement all four in Node.js with @grpc/grpc-js and learn when to reach for each.
syntax = "proto3";
package chat;
service ChatService {
// unary
rpc GetUser (UserRequest) returns (User);
// server streaming
rpc ListMessages (RoomRequest) returns (stream Message);
// client streaming
rpc UploadLogs (stream LogLine) returns (UploadSummary);
// bidirectional streaming
rpc Chat (stream Message) returns (stream Message);
}Loading the Proto in Node.js
Before you implement any handler, you load the .proto definition at runtime with @grpc/proto-loader and turn it into a gRPC service object with @grpc/grpc-js.
The loaded packageDefinition mirrors your proto packages and services. You attach handlers to the service with server.addService() — the names you provide must match the rpc names exactly.
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');
const pkgDef = protoLoader.loadSync('chat.proto', {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true,
});
const proto = grpc.loadPackageDefinition(pkgDef).chat;
const server = new grpc.Server();
// handlers get attached here
server.addService(proto.ChatService.service, { /* ... */ });All lessons in this course
- Defining Services and Messages with Protobuf IDL
- Unary, Server, Client, and Bidirectional Streaming RPCs
- Interceptors, Deadlines, and Metadata
- Proto Evolution and Backward Compatibility