RPC and gRPC
While REST (HTTP-based) is common for public APIs, internal communication between microservices often uses RPC (Remote Procedure Call) for better performance and type safety.
1. What is RPC?
RPC is a protocol that allows a program to execute a procedure (function) in another address space (commonly on another machine) as if it were a local function call.
- Abstraction: The developer doesn't need to worry about the details of network communication.
- Efficiency: Often uses binary serialization instead of text (JSON/XML), making it faster and smaller.
2. gRPC (Google RPC)
gRPC is a modern high-performance RPC framework developed by Google. It is the de-facto standard for microservices communication.
- Protocol Buffers (Protobuf): Uses Protobuf as the Interface Definition Language (IDL) and message serialization format.
- HTTP/2: Built on top of HTTP/2, allowing features like bidirectional streaming and multiplexing.
- Language Agnostic: You can have a server in Go and a client in Python, and they can communicate seamlessly using generated code.
3. Protobuf Example
Protobuf is a binary format, so it's much smaller than JSON. You define your data structure in a .proto file:
1syntax = "proto3"; 2 3message UserRequest { 4 string user_id = 1; 5 uint32 version = 2; 6} 7 8message UserResponse { 9 string name = 1; 10 string email = 2; 11} 12 13service UserService { 14 rpc GetUser (UserRequest) returns (UserResponse); 15}
RPC vs REST
| Feature | REST | gRPC |
|---|---|---|
| Protocol | HTTP/1.1 or HTTP/2 | HTTP/2 Only |
| Payload | JSON (Text) | Protobuf (Binary) |
| Contract | Optional (OpenAPI) | Strict (.proto file) |
| Streaming | Request-Response | Client/Server/Bidirectional |
Knowledge Check
Question 1 of 3
Q1Single choice
What is the primary benefit of using gRPC for internal service communication?