gRPC
medium 27 mingRPC 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
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
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.
March 2015
gRPC is announced, together with Square, as an open source successor to the ideas in Stubby.
August 2016
Version 1.0 is released and called ready for production.
February 2017
The Cloud Native Computing Foundation accepts gRPC, at its incubating level.
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.
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
- 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
Call the stub
It encodes the request, adds metadata such as a token or trace id, and starts the deadline.
- 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
Balance
In the client (pick first, round robin, or a control plane) or in a proxy that understands HTTP/2.
- 5
Handle it
Interceptors run first, then your method, with a context that holds the deadline, the metadata and the cancel signal.
- 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
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;}Field types you use most
| Type | Holds | Example |
|---|---|---|
| string | UTF-8 text | string name = 1; |
| int32, int64 | Integers, short when small | int64 created_at = 2; |
| bool | True or false | bool active = 3; |
| bytes | Any bytes | bytes avatar = 4; |
| repeated | A list | repeated string tags = 5; |
| map | Keys and values | map<string, int32> scores = 6; |
| enum, oneof, optional | One of a set; one of several fields; set or not set | optional 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
| Field | Bytes (hex) | Meaning |
|---|---|---|
| 1, id | 08 ac 02 | Field 1, varint 300 |
| 2, name | 12 04 41 73 68 61 | Field 2, 4 bytes, Asha |
| 3, email | 1a 10, then 16 bytes | Field 3, 16 bytes of text |
| 4, created_at | 20 80 f0 9d c7 06 | Field 4, varint 1760000000 |
How long is a varint?
: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)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
| Kind | Signature | Use for | Watch |
|---|---|---|---|
| Unary | GetUser(Req) returns (User) | Almost everything | Message size |
| Server streaming | ListUsers(Req) returns (stream User) | Feeds, notifications, large results | Slow readers |
| Client streaming | Upload(stream Log) returns (Ack) | Uploads, telemetry | Nothing is confirmed until the end |
| Both ways | Chat(stream M) returns (stream M) | Chat, games, sync | Reconnect and resume are yours |
A server stream, then cancel
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
The time left shrinks
How to choose the number: timeouts.
Errors
Status codes
All seventeen
| Code | Number | Meaning | Retry? |
|---|---|---|---|
| OK | 0 | Success | - |
| CANCELLED | 1 | The caller gave up | No |
| UNKNOWN | 2 | Error without a known code | No |
| INVALID_ARGUMENT | 3 | Wrong in any state | No |
| DEADLINE_EXCEEDED | 4 | Time ran out | Only if idempotent |
| NOT_FOUND | 5 | No such thing | No |
| ALREADY_EXISTS | 6 | It is there already | No |
| PERMISSION_DENIED | 7 | Known caller, not allowed | No |
| RESOURCE_EXHAUSTED | 8 | Quota, or message too large | Only as the server says |
| FAILED_PRECONDITION | 9 | State must be fixed first | No |
| ABORTED | 10 | Lost a race | Restart the whole operation |
| OUT_OF_RANGE | 11 | Past the valid end | No |
| UNIMPLEMENTED | 12 | No such method here | No |
| INTERNAL | 13 | A broken invariant | No |
| UNAVAILABLE | 14 | Try again later | Yes, with backoff, if safe |
| DATA_LOSS | 15 | Data is lost or damaged | No |
| UNAUTHENTICATED | 16 | No valid credentials | After signing in |
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%.
{ "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" }}Why only one layer should retry
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
| Way | How | Good for | Cost |
|---|---|---|---|
| Client side | DNS gives all addresses, round_robin spreads calls | Own services, a headless Kubernetes service | Clients must learn about new addresses |
| Layer 7 proxy | Envoy, NGINX or an AWS ALB balances each call | Many languages, the edge | One more hop |
| xDS control plane | Clients get endpoints and rules from a service such as a mesh | Large fleets | A control plane to run |
Background: layer 4 and layer 7 balancers, Kubernetes load balancing and service discovery.
Build it
A server in 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()# 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/GetUserOperate
Limits, health and shutdown
Defaults to know
| Setting | Default | Think about |
|---|---|---|
| Deadline | None | Always set one |
| Largest message received | 4 MB (documented for Go) | Stream or use object storage for more |
| Balancing policy | pick_first | round_robin for several servers |
| Client keepalive pings | Off | Turn on for mobile or idle paths |
| Server accepts pings every | 5 minutes | Faster clients are cut off |
| Server's own ping after | 2 hours, waits 20 seconds | Lower behind proxies that drop idle links |
| Connection age | Infinite | Some minutes, to rebalance |
| Message size in Protocol Buffers | Under 2 GiB | Far 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
| Watch | Because |
|---|---|
| Calls by method and status code | HTTP status is 200 even for failures |
| Time per attempt and per call | Retries hide inside the call |
| Calls per server | Uneven means balancing by connection |
| Deadline left at entry | Near zero means work for nobody |
| Open streams | They pin memory and servers |
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
| gRPC | REST | GraphQL | WebSockets | |
|---|---|---|---|---|
| Contract | .proto, required | OpenAPI, optional | Schema, required | Yours |
| Message | Binary by default | Often JSON | Usually JSON | Text or bytes |
| Address | Methods | Resources | One endpoint | One connection |
| Who shapes the answer | The contract | The server | The client | Both |
| Streaming | Four shapes | Not part of it | Subscriptions | Both ways |
| Code generation | Built in | Optional | Common | None |
| Browser | Through a bridge | Yes | Yes | Yes |
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.