AlgoViz

gRPC

medium 27 min

gRPC lets one program call a method in another program as if it were local.

Video lesson · Chapter 1 of 5

A local-looking call crosses a network

0:00 / 4:08

Theory

Read or listen first. About 2 min.

What it is

gRPC is an open source framework for remote procedure calls. You describe a service and its messages in a .proto file. A compiler makes a stub for the caller and a base class for the server, in the language of each. The caller calls a method; the framework turns it into bytes, sends it and brings the answer back.

By default the messages are Protocol Buffers, a compact binary format in which each field is known by its number. The transport is HTTP/2, so many calls share one connection and a call can carry a stream of messages in either direction.

Why it exists

Inside a company, services written in different languages call each other all day. Handwritten clients drift away from the server, text messages cost processor time, and every team builds its own timeouts. gRPC gives all of them one contract, one wire format and one set of rules for deadlines, errors and cancelling.

The cost is distance from the web's everyday tools. You cannot read the messages by eye, a browser cannot speak gRPC directly, HTTP caches do not help, and a connection that lives for days upsets simple load balancers.

A short history

  1. Before 2015

    Google runs its internal services on an RPC system called Stubby for more than a decade. It is tied to internal infrastructure and based on no open standard.

  2. March 2015

    gRPC is announced, together with Square, as an open source successor to the ideas in Stubby.

  3. August 2016

    Version 1.0 is released and called ready for production.

  4. February 2017

    The Cloud Native Computing Foundation accepts gRPC, at its incubating level.

  5. 2021

    A specification for gRPC over HTTP/3 is written and implemented in the .NET version. HTTP/2 remains the usual transport.

Words to know

Stub
The generated client object. Calling a method on it makes the remote call.
Channel
A client's virtual connection to a named service. It holds zero or more real connections.
Unary
One request and one response.
Deadline
The moment after which the caller no longer wants the answer.
Metadata
Key and value pairs beside the message, sent as HTTP/2 headers and trailers.
Trailers
Headers that come after the body. gRPC puts the final status there.
Interceptor
Code that wraps every call, for logging, sign-in or metrics.
Service config
JSON that tells clients how to balance, time out and retry calls to one service.

Understand it

Start here

Two kitchens and one printing plate

Two kitchens work together. They agreed on one order form, and both print their pads from the same plate. The cook writes only a number and a value, because both sides know what each number means.

The numbered order form
KITCHEN AKITCHEN B1 dish2 count3 note1 dish2 count3 note1 dish2 count3 noteOne plate, two pads

Agree once on the numbers, then never use a number for anything else.

Parts

What is inside the product

The idea of a remote call, the lost reply and the four call shapes are taught in RPC. This page is about the product: how gRPC does it, and how to run it.

One call through client and server

Inside our system are two machines. The client machine holds application code, then a generated stub with interceptors, then a channel. One HTTP/2 connection crosses to the server machine, which holds the gRPC server with interceptors, then the service code. The service queries PostgreSQL in its own box.
You write the two ends. The stub, the channel, the server and the bytes between them come from gRPC.
  1. 1

    Create a channel

    One per service, kept for the life of the program. It resolves the name, opens connections when needed and reconnects. Creating one per call is a common and costly mistake.

  2. 2

    Call the stub

    It encodes the request, adds metadata such as a token or trace id, and starts the deadline.

  3. 3

    Open a stream

    The channel picks a connection and opens an HTTP/2 stream. Headers are compressed, and several calls share the connection.

  4. 4

    Balance

    In the client (pick first, round robin, or a control plane) or in a proxy that understands HTTP/2.

  5. 5

    Handle it

    Interceptors run first, then your method, with a context that holds the deadline, the metadata and the cancel signal.

  6. 6

    Answer

    One message or many, then trailers with the status.

Why teams choose it

  • Compact and quick to parse

    Binary fields by number. Measure with your own messages: the gain depends on their shape.

  • Typed contract

    A wrong field or type fails when you build, not at night.

  • Streams

    Server, client, or both ways, with flow control.

  • Many languages

    Code generation for C++, C#, Go, Java, Kotlin, Node.js, Python, Ruby, PHP, Dart and Objective-C.

  • Less data

    Small messages and compressed headers help on mobile and small devices.

  • Tools

    grpcurl for calls by hand, grpc-gateway for a JSON front, plugins for validation and documentation.

Contract

The .proto file

proto
syntax = "proto3";package user.v1;option go_package = "example.com/app/gen/user/v1;userv1";service UserService {  rpc GetUser(GetUserRequest) returns (User);              // unary  rpc ListUsers(ListUsersRequest) returns (stream User);   // server streaming  rpc UploadUsers(stream User) returns (UploadResponse);   // client streaming  rpc Chat(stream ChatMessage) returns (stream ChatMessage); // both ways}message GetUserRequest {  string user_id = 1;  bool include_profile = 2;}message User {  string id = 1;  string name = 2;  string email = 3;  int64 created_at = 4;  Profile profile = 5;}message Profile {  string avatar_url = 1;  string bio = 2;  repeated string interests = 3;}message ListUsersRequest {  int32 page_size = 1;  string page_token = 2;  string filter = 3;}message UploadResponse {  int32 users_created = 1;  int32 users_updated = 2;}message ChatMessage {  string sender_id = 1;  string content = 2;  int64 timestamp = 3;}
proto3 is still valid. Newer files may say edition = "2024", the latest released edition, in place of syntax.

Field types you use most

TypeHoldsExample
stringUTF-8 textstring name = 1;
int32, int64Integers, short when smallint64 created_at = 2;
boolTrue or falsebool active = 3;
bytesAny bytesbytes avatar = 4;
repeatedA listrepeated string tags = 5;
mapKeys and valuesmap<string, int32> scores = 6;
enum, oneof, optionalOne of a set; one of several fields; set or not setoptional int32 age = 7;

Safe changes

  • Add a field with a new number
  • Add a method
  • Reserve a removed number and name
  • Add an enum value, if readers accept unknown ones

Breaking changes

  • Reuse a number for another meaning
  • Change a number
  • Change a type to one that is not wire compatible
  • Rename a package, service or method: the path changes

Numbers 1 to 15 take one byte for number and type together, so give them to the fields you always send. Numbers 19,000 to 19,999 are reserved for Protocol Buffers itself. In proto3 a plain number field that is 0 is not sent, so use optional when zero and not set must differ. Run a breaking change check in CI.

On the wire

The bytes

Each field is a tag (number and wire type) and a value. Integers are varints: seven bits per byte, and the top bit says that more follows. There are no names, quotes or commas.

User with id 300 (int32), name Asha, an email and a time

FieldBytes (hex)Meaning
1, id08 ac 02Field 1, varint 300
2, name12 04 41 73 68 61Field 2, 4 bytes, Asha
3, email1a 10, then 16 bytesField 3, 16 bytes of text
4, created_at20 80 f0 9d c7 06Field 4, varint 1760000000
33 bytes. The same object as compact JSON is 75 bytes. This is one small example, not a rule.

How long is a varint?

bytes(n)=max⁡(1,⌈bits(n)7⌉)300:9 bits→2−1 as int32:10\text{bytes}(n) = \max\left(1, \left\lceil \frac{\text{bits}(n)}{7} \right\rceil\right) \qquad 300: 9 \text{ bits} \to 2 \qquad -1 \text{ as int32}: 10
Negative int32 and int64 values always take ten bytes. Use sint32 or sint64 when negatives are common.
Text
:method = POST:path   = /user.v1.UserService/GetUserte = trailersgrpc-timeout = 5Scontent-type = application/grpc+protoauthorization = Bearer ...00 00 00 00 21   <- not compressed, 33 bytes follow08 ac 02 12 ...  <- the message:status = 200            (response headers)00 00 00 00 ..           (response message)grpc-status = 0          (trailers)
Every message has a 5 byte prefix: one flag for compression and four for the length. HTTP status 200 only means that gRPC answered; read grpc-status. With an error the response may be trailers only.

HTTP/2 removes waiting in line between requests. A lost packet still holds up every stream on that TCP connection: see HTTP/2 and HTTP/3. A connection also has a limit on concurrent streams. Calls above it wait in the client.

Shapes

Four kinds of call

KindSignatureUse forWatch
UnaryGetUser(Req) returns (User)Almost everythingMessage size
Server streamingListUsers(Req) returns (stream User)Feeds, notifications, large resultsSlow readers
Client streamingUpload(stream Log) returns (Ack)Uploads, telemetryNothing is confirmed until the end
Both waysChat(stream M) returns (stream M)Chat, games, syncReconnect and resume are yours
The word stream before a type means that this side sends many messages. Order is kept inside one call.

A server stream, then cancel

The server code must look at the context. gRPC cannot stop your database query for you.

Time

Deadlines and cancelling

gRPC sets no deadline by default: a call may wait forever. Set one on every call. Pass it on when your server calls another server. Java and Go propagate it through the context; in C++ you must enable it. On the wire it travels as the time that is left, not as a clock time, so that two clocks need not agree.

What the next service gets

left=1000−350=650 ms\text{left} = 1000 - 350 = 650\ \text{ms}
The client allowed 1,000 ms. Service A used 350 ms before calling B, so B hears grpc-timeout of 650 ms.

The time left shrinks

DEADLINE_EXCEEDED does not tell you whether the work was done. A write may have succeeded.

How to choose the number: timeouts.

Errors

Status codes

All seventeen

CodeNumberMeaningRetry?
OK0Success-
CANCELLED1The caller gave upNo
UNKNOWN2Error without a known codeNo
INVALID_ARGUMENT3Wrong in any stateNo
DEADLINE_EXCEEDED4Time ran outOnly if idempotent
NOT_FOUND5No such thingNo
ALREADY_EXISTS6It is there alreadyNo
PERMISSION_DENIED7Known caller, not allowedNo
RESOURCE_EXHAUSTED8Quota, or message too largeOnly as the server says
FAILED_PRECONDITION9State must be fixed firstNo
ABORTED10Lost a raceRestart the whole operation
OUT_OF_RANGE11Past the valid endNo
UNIMPLEMENTED12No such method hereNo
INTERNAL13A broken invariantNo
UNAVAILABLE14Try again laterYes, with backoff, if safe
DATA_LOSS15Data is lost or damagedNo
UNAUTHENTICATED16No valid credentialsAfter signing in
Do not send database messages to callers: log them and answer INTERNAL with a general text.

Which of three?

Retry

Retries, hedging and service config

Retries are switched on, but there is no default retry policy, so beyond a few safe transparent cases nothing is repeated. You add a policy for each method in the service config. Values above 5 for maxAttempts are treated as 5. Backoff has a jitter of plus or minus 20%.

JSON
{  "loadBalancingConfig": [{ "round_robin": {} }],  "methodConfig": [{    "name": [{ "service": "user.v1.UserService", "method": "GetUser" }],    "timeout": "1s",    "retryPolicy": {      "maxAttempts": 4,      "initialBackoff": "0.1s",      "maxBackoff": "1s",      "backoffMultiplier": 2,      "retryableStatusCodes": ["UNAVAILABLE"]    }  }],  "retryThrottling": { "maxTokens": 10, "tokenRatio": 0.1 },  "healthCheckConfig": { "serviceName": "user.v1.UserService" }}
Only GetUser is retried, because reading twice is harmless. Throttling: each failure costs one token, each success gives back 0.1, and retries pause when fewer than half are left.

Why only one layer should retry

4×4×4=644 \times 4 \times 4 = 64
Three layers with four attempts each can turn one click into 64 calls at the bottom, just when it is ill.

Hedging sends a second copy before the first has failed, and takes the first answer. Use it for idempotent reads with a long tail. A method can have a retry policy or a hedging policy, not both. See retries and circuit breaker.

Balance

Balance calls, not connections

The default policy is pick_first: one address gets everything. And a layer 4 balancer chooses a server once per connection, while a gRPC connection can live for days. New servers stay idle.

One connection stuck, against one call at a time

Top: a client's calls pass an L4 balancer over one connection, and all go to server 1; server 2 is idle. Bottom: a client whose channel uses round robin has a connection to each of two servers and spreads its calls over both.
Thick boxes are machines. In the lower picture the client itself chooses a server for each call.
WayHowGood forCost
Client sideDNS gives all addresses, round_robin spreads callsOwn services, a headless Kubernetes serviceClients must learn about new addresses
Layer 7 proxyEnvoy, NGINX or an AWS ALB balances each callMany languages, the edgeOne more hop
xDS control planeClients get endpoints and rules from a service such as a meshLarge fleetsA control plane to run
Set MAX_CONNECTION_AGE on servers, for example to some minutes, so that clients reconnect and look the name up again. The default is infinite.

Build it

A server in Python

Python
import timefrom concurrent import futuresimport grpcfrom grpc_health.v1 import health, health_pb2, health_pb2_grpcfrom grpc_reflection.v1alpha import reflectionfrom user.v1 import user_pb2, user_pb2_grpc     # generatedclass UserService(user_pb2_grpc.UserServiceServicer):    def GetUser(self, request, context):        if not request.user_id:            context.abort(grpc.StatusCode.INVALID_ARGUMENT, "user_id is required")        context.set_trailing_metadata((("request-id", "req-1"),))        return user_pb2.User(id=request.user_id, name="Asha", created_at=int(time.time()))    def ListUsers(self, request, context):        for user in rows(request.filter, request.page_size):   # your query            if not context.is_active():          # cancelled or too late                return            yield user    def UploadUsers(self, request_iterator, context):        created = updated = 0        for user in request_iterator:            if save(user):                       # your write: True when new                created += 1            else:                updated += 1        return user_pb2.UploadResponse(users_created=created, users_updated=updated)    def Chat(self, request_iterator, context):        for m in request_iterator:            yield user_pb2.ChatMessage(sender_id="server", content="Got: " + m.content,                                       timestamp=int(time.time()))def serve():    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10),                         options=[("grpc.max_connection_age_ms", 300_000)])    user_pb2_grpc.add_UserServiceServicer_to_server(UserService(), server)    checks = health.HealthServicer()    health_pb2_grpc.add_HealthServicer_to_server(checks, server)    checks.set("", health_pb2.HealthCheckResponse.SERVING)    names = (user_pb2.DESCRIPTOR.services_by_name["UserService"].full_name,             reflection.SERVICE_NAME)    reflection.enable_server_reflection(names, server)   # lets grpcurl list methods    server.add_insecure_port("127.0.0.1:50051")          # TLS outside your own machine    server.start()    server.wait_for_termination()
In the synchronous Python server each running stream holds a worker thread: ten workers, at most ten open streams. Use the asyncio server for many long streams.
Shell
# generate the Python codepython -m grpc_tools.protoc -I proto --python_out=. --grpc_python_out=. proto/user/v1/user.proto# call it by hand (needs reflection, or pass -proto)grpcurl -plaintext localhost:50051 listgrpcurl -plaintext -max-time 5 -d '{"user_id": "u-42"}' localhost:50051 user.v1.UserService/GetUser

Operate

Limits, health and shutdown

Defaults to know

SettingDefaultThink about
DeadlineNoneAlways set one
Largest message received4 MB (documented for Go)Stream or use object storage for more
Balancing policypick_firstround_robin for several servers
Client keepalive pingsOffTurn on for mobile or idle paths
Server accepts pings every5 minutesFaster clients are cut off
Server's own ping after2 hours, waits 20 secondsLower behind proxies that drop idle links
Connection ageInfiniteSome minutes, to rebalance
Message size in Protocol BuffersUnder 2 GiBFar above what you should send

Health. The standard health service has Check for probes and Watch for clients. A client with a health check config stops sending calls to a server that says NOT_SERVING. Kubernetes has a built-in gRPC probe that uses the same service.

Stop without losing calls

Kubernetes sends SIGTERM and removes the pod from its endpoints at about the same time, so new calls may still arrive for a moment. The grace period is 30 seconds by default: finish before that.
WatchBecause
Calls by method and status codeHTTP status is 200 even for failures
Time per attempt and per callRetries hide inside the call
Calls per serverUneven means balancing by connection
Deadline left at entryNear zero means work for nobody
Open streamsThey pin memory and servers
gRPC can export OpenTelemetry metrics such as grpc.client.call.duration and grpc.client.attempt.duration.

Interceptors are the place for logging, sign-in, metrics and tracing. Unary and stream calls have separate kinds, and the order of a chain matters. Security: TLS on every connection that leaves a machine, mutual TLS between services where you can, tokens in metadata, and reflection off on public servers.

The edge

Browsers and partners

A browser page cannot control HTTP/2 frames or read gRPC's trailers, so it cannot speak gRPC. There are two usual bridges.

gRPC-Web

  • Generated browser client
  • A proxy such as Envoy, or a server with support, translates
  • Unary, and server streaming in its text mode
  • No client streaming or both ways yet

JSON transcoding

  • grpc-gateway or Envoy maps HTTP and JSON to your methods
  • Mapping is in google.api.http options in the .proto
  • Partners use plain REST and OpenAPI
  • One more mapping to keep true

Decide

When to use it

Use gRPC for

  • Calls between your own services
  • Streams of updates and telemetry
  • Teams in several languages with one contract
  • Mobile clients where bytes matter and you own the app
  • Very high call rates
  • Both sides talking at once

Choose another for

  • Public APIs called from browsers
  • Simple CRUD where REST is enough
  • Answers that a CDN should keep
  • Teams with no time to learn the tools
  • Systems where people must read the wire
  • An established REST estate that works

Beside its neighbours

gRPCRESTGraphQLWebSockets
Contract.proto, requiredOpenAPI, optionalSchema, requiredYours
MessageBinary by defaultOften JSONUsually JSONText or bytes
AddressMethodsResourcesOne endpointOne connection
Who shapes the answerThe contractThe serverThe clientBoth
StreamingFour shapesNot part of itSubscriptionsBoth ways
Code generationBuilt inOptionalCommonNone
BrowserThrough a bridgeYesYesYes

Good

  • Performance: small messages, shared connections.
  • Type safety: errors at build time.
  • Streaming: part of the contract.
  • Code generation: clients in many languages.

Costs

  • Browsers: need a bridge.
  • Debugging: bytes need tools such as grpcurl.
  • Learning: .proto rules and HTTP/2.
  • Tooling: curl and simple proxies do not fit.

The three styles in depth: REST, GraphQL and gRPC.

Summary

The whole topic in one minute.

gRPC makes one .proto file the contract for callers and servers in many languages. Messages are small because fields travel as numbers, and HTTP/2 lets many calls and streams share one connection. The four shapes are unary, server streaming, client streaming and both ways.

Production work is in the details: set a deadline on every call, retry only what is safe, balance calls and not connections, keep messages under the 4 MB default, report health, and drain before stopping. Use it between your own services, and put REST or gRPC-Web at the edge for browsers and partners.

  • One .proto file is the contract; the code is generated.
  • Fields travel as numbers, so never reuse a number.
  • There is no deadline unless you set one.
  • Retry only safe methods, in one layer, with a budget.
  • Balance calls, not connections.
  • Report health and drain before you stop.

Sources