Streaming RPCs in Protobuf (Server, Client, Bidirectional)
Define streaming RPC methods in protobuf: server streaming, client streaming, and bidirectional streaming. Learn when to use each pattern and their performance characteristics.
Detailed Explanation
Streaming RPC Patterns
gRPC supports four communication patterns: unary (one request, one response), server streaming, client streaming, and bidirectional streaming. The stream keyword enables the streaming variants.
syntax = "proto3";
package chat.v1;
service ChatService {
// Unary: single request, single response
rpc SendMessage(SendMessageRequest) returns (SendMessageResponse);
// Server streaming: client sends one request, server sends many responses
rpc GetMessageHistory(GetHistoryRequest) returns (stream ChatMessage);
// Client streaming: client sends many requests, server sends one response
rpc UploadAttachments(stream UploadChunk) returns (UploadResponse);
// Bidirectional streaming: both sides send streams
rpc LiveChat(stream ChatMessage) returns (stream ChatMessage);
}
message SendMessageRequest {
string channel_id = 1;
string content = 2;
string sender_id = 3;
}
message SendMessageResponse {
string message_id = 1;
}
message GetHistoryRequest {
string channel_id = 1;
int32 limit = 2;
string before_message_id = 3;
}
message ChatMessage {
string message_id = 1;
string channel_id = 2;
string sender_id = 3;
string content = 4;
int64 timestamp = 5;
}
message UploadChunk {
string filename = 1;
bytes data = 2;
int32 chunk_index = 3;
int32 total_chunks = 4;
}
message UploadResponse {
string file_id = 1;
int64 total_size = 2;
string url = 3;
}
When to Use Each Pattern
| Pattern | Use Case |
|---|---|
| Unary | Simple CRUD operations, queries with bounded results |
| Server streaming | Large result sets, real-time feeds, log tailing, event subscriptions |
| Client streaming | File uploads in chunks, bulk data ingestion, telemetry reporting |
| Bidirectional | Chat applications, collaborative editing, multiplayer games, interactive sessions |
Server Streaming Details
The server sends multiple response messages before closing the stream. The client reads messages until it receives an end-of-stream signal. This is ideal for paginated data where you want to start processing before the full result is available.
Client Streaming Details
The client sends multiple messages and then signals completion. The server processes all messages and sends a single response. Useful for aggregating client data before producing a result.
Bidirectional Streaming
Both sides can send messages independently at any time. The two streams operate independently — the server does not have to wait for all client messages before responding. This enables real-time interactive communication patterns.
Use Case
Building real-time chat systems, live dashboards with streaming data, file upload services with progress tracking, or any application requiring persistent bidirectional communication channels.