TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท web ยท protocols ยท rpc ยท serialization

gRPC and Protocol Buffers

A contract-first RPC framework. Services and messages are defined in .proto files, encoded as compact Protocol Buffers binary, and called through generated stubs over HTTP/2, with unary and streaming calls, deadlines and status codes.

14 min6 animations

๐Ÿ“š Builds on๐Ÿ“ฎ HTTP

๐Ÿ–จ๏ธ Cheat sheet

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";5 6service OrderService {7  rpc PlaceOrder (OrderRequest) returns (OrderReply);8  rpc WatchOrder (OrderId) returns (stream OrderEvent);9}10 11message OrderRequest {12  string item = 1;13  int32 quantity = 2;14}15 16message 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.

One contract, generated code on both sides4 steps
๐Ÿ“– Codebook๐Ÿ‘ฉMia๐Ÿง‘โ€๐Ÿ”งSam
Press play and watch it happen!

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 quantity was removed and price added as field 4:
1message OrderRequest {2  reserved 2;3  reserved "quantity";4  string item = 1;5  int32 price = 4;   // whole units; quantity was 26}

Compared with JSON, messages are smaller and faster to parse, but not human-readable without the schema.

Field numbers on the wire4 steps
First message0123๐Ÿ‘ฉMia (new codebook)๐Ÿ‘จLeo (old codebook)
Press play and watch it happen!

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 typeDeclarationExample
Unaryrpc Get (Req) returns (Res)look up one order
Server streamingrpc Watch (Req) returns (stream Res)push status updates
Client streamingrpc Upload (stream Req) returns (Res)send readings, get a summary
Bidirectional streamingrpc 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.

Four call types on one HTTP/2 connection4 steps
๐Ÿ‘ฉMia๐Ÿง‘โ€๐Ÿ”งSam
Press play and watch it happen!

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:

CodeMeaning
OKsuccess
INVALID_ARGUMENTthe request is wrong; don't retry
NOT_FOUNDthe thing asked for doesn't exist
DEADLINE_EXCEEDEDran out of time; the work may or may not have happened
UNAVAILABLEserver unreachable or overloaded; usually safe to retry with backoff
UNAUTHENTICATED / PERMISSION_DENIEDno valid credentials / not allowed
UNIMPLEMENTEDthe server doesn't have this method
INTERNALa 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.

Deadlines, cancellation and status codes4 steps
๐Ÿ‘ฉMia๐Ÿง‘โ€๐Ÿ”งSam๐Ÿ‘ทKim in the yard
Press play and watch it happen!

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 the round_robin policy. Many gRPC clients default to pick_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.

gRPCREST with JSON (see REST API design)
Contractrequired .proto, generated clientsoptional (OpenAPI)
Payloadcompact binaryreadable text
Streamingfour call types built inneeds SSE or WebSocket
Browsers and curlneeds gRPC-Web or tools such as grpcurlworks everywhere
HTTP cachingnoyes, 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.

Long-lived connections and load balancing4 steps
๐Ÿ‘ฉMia๐ŸŽ›๏ธChannel switch๐Ÿง‘โ€๐Ÿ”งSam
Press play and watch it happen!

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    @Override3    public void placeOrder(OrderRequest req, StreamObserver<OrderReply> responses) {4        if (!stock.has(req.getItem())) {5            responses.onError(Status.NOT_FOUND6                .withDescription("no " + req.getItem())7                .asRuntimeException());8            return;9        }10        responses.onNext(OrderReply.newBuilder().setOrderId(orders.place(req)).build());11        responses.onCompleted();12    }13}14 15Server 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();5 6var stub = OrderServiceGrpc.newBlockingStub(channel);7 8try {9    OrderReply reply = stub.withDeadlineAfter(2, TimeUnit.SECONDS)10        .placeOrder(OrderRequest.newBuilder().setItem("apples").setQuantity(12).build());11} catch (StatusRuntimeException e) {12    switch (e.getStatus().getCode()) {13        case NOT_FOUND -> showOutOfStock();14        case DEADLINE_EXCEEDED, UNAVAILABLE -> retryLater();15        default -> 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.

๐Ÿ”ง Going deeper

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.

grpc-java blocking stub and service3 steps
๐Ÿ‘ฉMia๐Ÿ“ปRadio channel๐Ÿง‘โ€๐Ÿ”งSam
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 4 questions about gRPC and Protocol Buffers, told the same way as the story.
  1. Mia and Sam stop using "two, how many". What should happen to the number two?
  2. Mia adds "three, gift wrap" to her codebook. What happens when Leo, with the old codebook, hears it?
  3. Mia gave Sam two minutes. Sam had to ask Kim, and the time ran out. What happens?
  4. The shop hires two more helpers, but every question still goes to Sam. Why?
Answer every question to check.Passing marks gRPC and Protocol Buffers as done.
Got the hang of gRPC and Protocol Buffers? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ”Œ Designing APIsStep 4 of 5

โ† Previous on the path๐Ÿฑ GraphQLNext on the path โ†’๐Ÿ”˜ Idempotency