Protobuf & gRPC
Protobuf
Protobuf (Protocol Buffers) is a language-neutral, platform-neutral data serialization format developed by Google. It’s designed for efficient communication and storage, especially in distributed systems.
Compact and Efficient: Protobuf uses binary serialization, which is smaller and faster than formats like JSON or XML.
Schema-based: Data is defined in .proto files using a schema, which ensures strict typing and compatibility. Less ambiguous and easier to use programmatically.
Cross-language: Supported in many languages like Go, Python, Java, etc.
gRPC
(Google Remote Procedure Calls) is a high-performance RPC framework that uses Protobuf for data serialization. It enables seamless communication between services, regardless of the programming language.
Supports Multiple Communication Types:
Unary (one request, one response)
Server-streaming (one request, multiple responses)
Client-streaming (multiple requests, one response)
Bi-directional streaming (multiple requests, multiple responses)
Built-in Code Generation: gRPC generates client and server stubs automatically from the
.proto
file.HTTP/2 Support: Enables multiplexing, compression, and improved performance over HTTP/1.1.
Example
Define the Protobuf File
user.proto
Generate Code
Run the following command to generate the code (example for Go):
This generates:
user.pb.go
: Contains Protobuf message definitions.user_grpc.pb.go
: Contains gRPC service definitions (interfaces for server and client).
Step 3: Implement the Server
server.go
Implement the Client
client.go
Run the System
Start the gRPC server:
Run the client:
Output
On the server:
On the client:
Last updated