gRPC uses HTTP/2 and Protocol Buffers for fast, typed APIs. See when it beats REST, how contracts work, and what breaks in browsers and ops.
Most tutorials still start with JSON over HTTP. That is fine for public CRUD APIs, but backend teams moving thousands of small messages between services often hit REST limits: verbose payloads, weak typing, and awkward streaming. gRPC is Google's RPC framework built on HTTP/2 and Protocol Buffers (protobuf). It gives you strongly typed contracts, binary serialization, and first-class streaming in one toolchain.
If you have only used Postman on REST, gRPC feels different—not harder, but more explicit about schemas and code generation.
How gRPC differs from REST mentally
REST maps resources to URLs and verbs. gRPC maps service methods to remote procedure calls defined in .proto files. A tiny example:
syntax = "proto3";
service InventoryService {
rpc GetStock (GetStockRequest) returns (GetStockResponse);
rpc WatchStock (WatchStockRequest) returns (stream StockUpdate);
}
message GetStockRequest {
string sku = 1;
}
message GetStockResponse {
string sku = 1;
int32 quantity = 2;
}
Codegen produces client and server stubs in Go, Java, Python, Node, and more. Your team shares one contract; breaking changes show up at compile time instead of as silent JSON field drift in production.
| Concern | Typical REST | gRPC |
|---|---|---|
| Payload | JSON text | Protobuf binary |
| Schema | OpenAPI optional | .proto required |
| Streaming | Chunky workarounds | Unary, server, client, bidi |
| Browser | Native fetch | Needs grpc-web proxy |
When gRPC is worth the switch
Good fits:
- Microservice chatter with lots of small requests between trusted services.
- Low-latency internal APIs where JSON parsing cost matters at high QPS.
- Streaming telemetry (logs, metrics, live updates) over a single connection.
- Polyglot shops that want one IDL instead of hand-maintained client SDKs.
Stick with REST (or GraphQL) when:
- You expose a public API to unknown third-party developers who expect HTTP verbs and curl examples.
- Clients are primarily browsers without a gateway layer.
- You need aggressive HTTP caching on CDN edge nodes for anonymous GET traffic.
Many architectures use REST at the edge and gRPC mesh-internal behind an API gateway.
Request lifecycle under the hood
- Client stub serializes the request message with protobuf.
- HTTP/2 frames carry the data on a single connection (header compression via HPACK).
- Server stub deserializes, invokes your handler, serializes the response.
- Deadline metadata (
grpc-timeout) propagates so slow callees cancel work.
Status codes become grpc-status trailers with rich error details via google.rpc.Status if you adopt the common error model.
Deadlines and cancellation
Always set deadlines from the caller:
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
defer cancel()
resp, err := client.GetStock(ctx, &pb.GetStockRequest{Sku: "abc"})
Without deadlines, hung downstream services pile up goroutines and thread pools. Propagate context through your call graph.
Versioning and compatibility
Protobuf field numbers are sacred. You evolve APIs by:
- Adding new fields with new numbers (old code ignores unknown fields).
- Never renumbering or changing wire types.
- Using
reservedwhen removing fields to prevent reuse mistakes.
Breaking renames at the JSON gateway layer do not break binary protobuf as long as field numbers stay stable. Document deprecation in comments and use feature flags for behavioral changes.
Security and operations
gRPC runs over TLS in production (credentials.NewClientTLSFromCert). Mutual TLS (mTLS) is common inside service meshes like Istio or Linkerd.
Load balancers must speak HTTP/2 end-to-end. Classic L4 TCP pass-through works; some older L7 appliances mishandle gRPC streams.
Observability hooks:
- OpenTelemetry/grpc middleware for traces and metrics.
- grpc-health-probe for Kubernetes liveness instead of naive TCP checks.
- Structured logging of
:authority, method, status, and latency histograms.
grpc-web and gateways
Browsers cannot speak native gRPC directly. Patterns:
- Envoy or grpc-web proxy translating grpc-web ↔ gRPC.
- API gateway exposing REST while backends stay gRPC (gRPC-Gateway generates reverse HTTP handlers from annotations).
Plan this boundary early; retrofitting grpc-web after mobile web clients ship is painful.
Local development tips
- grpcurl explores services without codegen:
grpcurl -plaintext localhost:50051 list. - Buf lints
.protofiles and enforces style in CI. - Docker Compose with shared volume for
.protokeeps languages in sync.
Write contract tests that fail CI when server implementations drift from protobuf definitions.
Interceptors: cross-cutting logic without copy-paste
gRPC interceptors (middleware) wrap calls for logging, auth metadata, retries, and tracing. Unary server interceptors can validate JWTs in metadata headers before your handler runs:
func authInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, status.Error(codes.Unauthenticated, "missing metadata")
}
// validate token from md["authorization"]
return handler(ctx, req)
}
Keep interceptors fast; heavy work belongs in handlers or queues.
Failure modes to rehearse
- MESSAGE_TOO_LARGE – Default limits are ~4 MB; tune
MaxRecvMsgSizethoughtfully. - UNAVAILABLE storms – Clients retry idempotent RPCs with jittered backoff; protect servers with rate limits.
- Schema skew – One service deploys new protos before peers; use versioned packages (
inventory.v1,inventory.v2). - L7 proxies closing streams – Idle timeouts must exceed long-lived streaming RPCs.
Mini case study: inventory microservice
Imagine an e-commerce platform where the cart service asks inventory for stock levels on every cart refresh. REST returned 2 KB JSON per SKU; at 3k RPS the CPU spent noticeable time marshaling strings.
Moving internal checks to gRPC dropped payloads to a few hundred bytes and allowed server-streaming updates when warehouse counts changed, so the cart service subscribed instead of polling. Public checkout still used REST for partner plugins; only east-west traffic switched.
FAQ
Is gRPC faster than REST always?
Often faster for small, frequent RPCs due to binary encoding and HTTP/2 multiplexing, but measure your paths. Large messages dominated by payload size see smaller gaps.
Can I use JSON with gRPC?
/grpc-json transcoding exists via gateways, but you lose much of the typing benefit. Pick one model per boundary.
How does gRPC compare to GraphQL?
GraphQL optimizes flexible reads for product UIs. gRPC optimizes deterministic service contracts. They solve different problems; some BFFs speak GraphQL outward and gRPC inward.
Do I need a service mesh?
No, but meshes add mTLS, retries, and traffic shaping with less application code. Plain gRPC plus good client libraries is enough for many small teams.
Where should I put authentication metadata?
Use per-RPC metadata headers (authorization tokens, trace IDs). Avoid baking secrets into protobuf message bodies where logs might capture them.
gRPC is not a REST killer. It is a precision tool for teams that want strict contracts and efficient machine-to-machine conversation. Learn the .proto workflow, respect HTTP/2 operations requirements, and keep REST where humans and caches need it.
Comments
Loading comments…