Walkie-talkies and a codebook
Mia works at the front desk of a big shop. Sam works in the stockroom. They talk all day by walkie-talkie, and they don't waste words.
Before the first shift, they sat down and wrote a codebook together. It lists every question Mia may ask ("how many of this item?", "put an order aside") and what each answer looks like. Each one has a short number.
From the codebook, a printer makes a card for each of them. Mia's pocket card turns what she wants into codes and sends them. Sam's answer sheet turns the codes he hears back into a question he can answer. Neither of them has to think about the codes at all: Mia just asks, and Sam just answers.
Contract first: .proto files and generated code
gRPC is a remote procedure call framework: a client calls a method on a server as if it were a local method. The contract lives in a .proto file, written in the Protocol Buffers (protobuf) language. It declares services (the methods you can call) and messages (their request and response types):
1syntax = "proto3";2package shop;3option java_multiple_files = true;4option java_package = "com.example.shop";56service OrderService {7rpc PlaceOrder (OrderRequest) returns (OrderReply);8rpc WatchOrder (OrderId) returns (stream OrderEvent);9}1011message OrderRequest {12string item = 1;13int32 quantity = 2;14}1516message OrderReply { string order_id = 1; }17message OrderId { string id = 1; }18message OrderEvent { string status = 1; }
The protoc compiler, with the gRPC plugin for each language, generates code from this file: message
classes with builders and serializers, a client stub whose methods look like local calls, and a server
base class you extend to implement the methods. Client and server can be in different languages; the .proto
file is the single source of truth, and both sides are type-checked against it.
Short numbered codes
When Mia asks for apples, she doesn't say "item name: apples, how many: twelve". She says "one, apples; two, twelve". The numbers stand for the parts of the message, and both of them know what each number means. That's why messages are so short: the names never go over the radio, only the numbers.
The numbers matter more than the names. If they later add a new part, say "three, gift wrap", they give it a new number. Leo, who still has an old codebook, hears "three" and simply ignores it, and everything else still works.
But a number must never be given a new meaning. If they cross out "two, how many" and reuse "two" for the price, Leo's old codebook hears "two, nine" and thinks someone wants nine apples. So crossed-out numbers stay crossed out, for good.
Binary encoding and field numbers
Protobuf's wire format is binary. Each field is written as a tag (the field number plus a wire type) and
its value; field names never appear on the wire. Integers are varints, so small non-negative numbers take one byte (use sint32 for negatives). Field
numbers 1 to 15 fit the tag in one byte and 16 to 2047 in two, so give the low numbers to frequent fields.
Valid numbers run up to 536,870,911, except 19000 to 19999, which are reserved by protobuf itself.
This is what makes schemas evolve safely:
- Adding a field with a new number is backward and forward compatible. Old readers skip fields they don't know; new readers see the field's default value (0, empty string, false) when an old writer left it out.
- Renaming a field is harmless on the wire, because only the number travels (JSON mapping uses names, so it isn't harmless there).
- Never reuse a field number or change a field's type. Data written with the old meaning will be decoded
with the new one, silently. When you delete a field, mark its number (and name) as reserved, and give any new
field a fresh number. Here
quantitywas removed andpriceadded as field 4:
1message OrderRequest {2reserved 2;3reserved "quantity";4string item = 1;5int32 price = 4; // whole units; quantity was 26}
Compared with JSON, messages are smaller and faster to parse, but not human-readable without the schema.
One channel, four ways to talk
Mia and Sam share one radio channel, but many conversations can run on it at the same time. Each little burst of talk is tagged with which conversation it belongs to, so nothing gets mixed up and nobody waits for a free channel.
There are four ways to talk:
- Ask and answer: "how many apples?", "twelve".
- Ask once, hear a list: "read me today's orders", and Sam reads them out one by one.
- Read a list, get one answer: Mia reads out every item she scanned, then Sam says "got all three".
- Both talk at once: Mia and Sam chat back and forth freely, each speaking whenever they like.
HTTP/2 underneath and the four call types
gRPC runs over HTTP/2 (see HTTP). Every call is an HTTP/2 POST to /package.Service/Method
with content-type: application/grpc, on its own stream. Streams are multiplexed as interleaved frames on one
long-lived TCP connection, so many calls run concurrently without opening new connections or blocking each
other at the HTTP level. Each message in a stream is length-prefixed, which is what makes streaming possible.
The .proto file chooses one of four call types with the stream keyword:
| Call type | Declaration | Example |
|---|---|---|
| Unary | rpc Get (Req) returns (Res) | look up one order |
| Server streaming | rpc Watch (Req) returns (stream Res) | push status updates |
| Client streaming | rpc Upload (stream Req) returns (Res) | send readings, get a summary |
| Bidirectional streaming | rpc Chat (stream Req) returns (stream Res) | chat, live sync |
In a bidirectional call the two directions are independent: either side can send whenever it likes, and messages within each direction stay in order. A call ends when the server sends its status.
Time limits, "never mind" and sign-off codes
When Mia asks Sam something, she adds a time limit: "answer within two minutes, or don't bother". If Sam needs to ask Kim in the back yard, he passes on the time that's left, not a fresh two minutes.
If the time runs out, Mia stops waiting, and her "never mind" travels down the line, so Sam and Kim stop working on something nobody needs any more. Anything they already did stays done, though, so Mia should only ask again for things that are safe to repeat.
Every conversation ends with a short sign-off code: "done", "too late", "nobody's there", "we don't have that". Before the question, Mia can also say a few extra words that aren't part of it, such as who she is. These are called metadata.
Deadlines, cancellation, status codes and metadata
A deadline is the point in time by which the client needs an answer. It travels to the server as the
grpc-timeout header, so the server knows the time budget too. gRPC sets no deadline by default, which means a
call can wait forever: always set one. When it passes, the call fails with DEADLINE_EXCEEDED on the client and
is cancelled on the server. Servers that call other services should pass the remaining deadline on; grpc-java
and grpc-go propagate it automatically through the call context. Cancellation does not roll anything back: a
DEADLINE_EXCEEDED change may still have happened, so make such calls idempotent.
Every call ends with a status: a code plus an optional message, sent in HTTP/2 trailers (grpc-status,
grpc-message), not as an HTTP status code. There are 17 codes, among them:
| Code | Meaning |
|---|---|
OK | success |
INVALID_ARGUMENT | the request is wrong; don't retry |
NOT_FOUND | the thing asked for doesn't exist |
DEADLINE_EXCEEDED | ran out of time; the work may or may not have happened |
UNAVAILABLE | server unreachable or overloaded; usually safe to retry with backoff |
UNAUTHENTICATED / PERMISSION_DENIED | no valid credentials / not allowed |
UNIMPLEMENTED | the server doesn't have this method |
INTERNAL | a bug or broken invariant on the server |
Metadata is key-value pairs sent as HTTP/2 headers (at the start) and trailers (at the end), alongside the
messages: auth tokens, request ids, tracing context. Keys are lowercase; keys ending in -bin carry binary values.
Interceptors on either side read and add metadata.
Sharing the work, and when to use it
The shop gets busy and hires two more stockroom helpers, Kim and Lee. A channel switch by the stockroom door connects Mia's radio to one helper when she tunes in, and it stays tuned there all day. Every question still goes to Sam, while the new helpers stand around.
The fix is a dispatcher, called a load balancer, who listens to each question and hands it to whichever helper is free, or a walkie-talkie that takes turns between all the helpers on its own.
Codes and walkie-talkies are best between people who work together every day. For customers walking in off the street, plain words are easier: anyone can understand them without a codebook. The cheap radios customers carry can't use the full channel either. They need a helper at the door who passes their messages on, and they can ask and hear a list read out, but not read out lists or chat both ways at once.
Load balancing, browsers and gRPC versus REST
Because one HTTP/2 connection carries every call, a connection-level (L4) load balancer picks a backend
once, when the connection opens, and every later call follows it. Scale from one server to three and the new
ones may sit idle; in Kubernetes, a plain ClusterIP Service behaves this way. Balance per call instead (see
load balancing):
- an L7 proxy that understands HTTP/2 and gRPC (Envoy, NGINX, a service mesh) spreads streams across backends;
- or client-side balancing: resolve every backend address (for example a headless Service with
dns:///) and use theround_robinpolicy. Many gRPC clients default topick_first, which uses one address only.
Long-lived connections also mean servers should set a maximum connection age, so clients reconnect and rebalance after scaling.
Browsers can't use gRPC directly: their APIs don't expose HTTP/2 frames and trailers. gRPC-Web is a variant that a proxy such as Envoy (or built-in server support in some frameworks) translates to gRPC. It supports unary and server-streaming calls; client and bidirectional streaming are not supported.
| gRPC | REST with JSON (see REST API design) | |
|---|---|---|
| Contract | required .proto, generated clients | optional (OpenAPI) |
| Payload | compact binary | readable text |
| Streaming | four call types built in | needs SSE or WebSocket |
| Browsers and curl | needs gRPC-Web or tools such as grpcurl | works everywhere |
| HTTP caching | no | yes, with GET |
Pick gRPC for internal service-to-service calls, polyglot teams sharing contracts, high call volume and streaming. Pick REST for public APIs, browsers and anything that benefits from HTTP caching.
Sam's answer sheet and Mia's pocket card
In practice, Sam fills in his answer sheet: for each question in the codebook, he writes what to do and what to say back. Mia picks up her walkie-talkie, sets her time limit, and asks.
If Sam can't help, he signs off with a code like "we don't have that", and Mia's card tells her exactly which code it was, so she knows whether to try again.
grpc-java: a service and a blocking stub
With the grpc-java Maven or Gradle plugin, the .proto above generates OrderServiceGrpc. The server extends
the generated base class and answers through a StreamObserver:
1public class OrderServiceImpl extends OrderServiceGrpc.OrderServiceImplBase {2@Override3public void placeOrder(OrderRequest req, StreamObserver<OrderReply> responses) {4if (!stock.has(req.getItem())) {5responses.onError(Status.NOT_FOUND6.withDescription("no " + req.getItem())7.asRuntimeException());8return;9}10responses.onNext(OrderReply.newBuilder().setOrderId(orders.place(req)).build());11responses.onCompleted();12}13}1415Server server = ServerBuilder.forPort(9090)16.addService(new OrderServiceImpl())17.build()18.start();
The client opens one ManagedChannel and reuses it for every call; it's thread-safe and expensive to create.
A blocking stub makes unary calls look like plain method calls. withDeadlineAfter returns a copy of the stub
with a deadline counted from now, so call it per request, not once at startup:
1ManagedChannel channel = ManagedChannelBuilder.forTarget("dns:///orders:9090")2.defaultLoadBalancingPolicy("round_robin")3.usePlaintext() // use TLS outside local development4.build();56var stub = OrderServiceGrpc.newBlockingStub(channel);78try {9OrderReply reply = stub.withDeadlineAfter(2, TimeUnit.SECONDS)10.placeOrder(OrderRequest.newBuilder().setItem("apples").setQuantity(12).build());11} catch (StatusRuntimeException e) {12switch (e.getStatus().getCode()) {13case NOT_FOUND -> showOutOfStock();14case DEADLINE_EXCEEDED, UNAVAILABLE -> retryLater();15default -> throw e;16}17}
newStub gives an async stub with StreamObserver callbacks, needed for client and bidirectional streaming;
newFutureStub returns a ListenableFuture for unary calls.
Don't throw from a handler: an uncaught exception reaches the client as UNKNOWN with no useful message.
Report failures with onError(Status.X.withDescription(...).asRuntimeException()), and call exactly one of onCompleted or
onError.
Retries: gRPC can retry calls on chosen status codes through the service config, but only retry what is safe
to repeat. UNAVAILABLE usually is; DEADLINE_EXCEEDED on a write may not be.
Message size: grpc-java rejects incoming messages over 4 MiB by default (maxInboundMessageSize). For large
payloads, stream chunks instead of raising the limit.