API Design
gRPC & Protobuf
High-performance RPC, Binary payloads, and Contract-First design.
gRPC
REST and GraphQL are text-based (JSON). They are human-readable but inefficient (parsing JSON takes CPU). gRPC is Binary. It uses Protocol Buffers (Protobuf) to serialize data.
Why gRPC?
- Performance: Smaller payload (binary), faster serialization, uses HTTP/2 (multiplexing) by default.
- Code Generation: You write a
.protofile, and gRPC generates the Client SDK and Server stubs for you in Go, Java, Python, etc. - Streaming: Built-in support for Server Streaming, Client Streaming, and Bidirectional Streaming.
Protocol Buffers (Protobuf)
The Interface Definition Language (IDL).
syntax = "proto3";
service OrderService {
rpc CreateOrder (OrderRequest) returns (OrderResponse);
}
message OrderRequest {
int32 user_id = 1;
repeated string items = 2;
}Field Numbers (= 1): Crucial. Protobuf doesn't send field names ("user_id"), it sends the field number ("1"). This saves space. Never change the field number of an existing field.
gRPC vs. REST
| Feature | REST | gRPC |
|---|---|---|
| Payload | JSON (Text) | Protobuf (Binary) |
| Transport | HTTP/1.1 (usually) | HTTP/2 (required) |
| Browser Support | Native | Poor (Requires gRPC-Web proxy) |
| Use Case | Public APIs, Web Apps | Internal Microservices |
The Microservice Standard
In a microservice architecture, use REST/GraphQL at the edge (for the browser/mobile app), but use gRPC for internal communication between services. It's faster, type-safe, and handles the "Chatty" nature of microservices better.