What are gRPC and Protocol Buffers, and when would you use them over REST?
Topic: microservices, Communication. Level: Intermediate.
Answer
**gRPC** is a high-performance RPC framework using HTTP/2 (multiplexing, streaming) and **Protocol Buffers** (Protobuf) — a compact binary, schema-first serialization format. You define services and messages in a `.proto` file; codegen produces strongly-typed client/server stubs in many languages. Benefits: smaller payloads, faster (de)serialization, bidirectional streaming, and an enforced contract. Use gRPC for internal, high-throughput, low-latency service-to-service calls. Keep REST/JSON at the public edge (browser support for gRPC is limited without gRPC-Web).
```protobuf
// payment.proto — the contract, shared by both services
syntax = "proto3";
service PaymentService {
rpc Charge (ChargeRequest) returns (ChargeReply);
}
message ChargeRequest { string order_id = 1; int64 amount_cents = 2; }
message ChargeReply { bool success = 1; string txn_id = 2; }
```
```java
// Generated stub — strongly typed, no manual JSON parsing
ChargeReply reply = paymentStub.charge(
ChargeRequest.newBuilder().setOrderId("A1").setAmountCents(4200).build());
```