Bookmarks
ReferenceBackendVerified

gRPC

gRPC — a remote procedure call (RPC) framework on top of HTTP/2. In this reference: Protocol Buffers, services and streaming, code generation, deadlines, status codes and TLS.

checked 1 Nov · next check 8 Nov · 49 min read

Sections
12
Reading
49 min
Current version
1.85.1; protoc 36.2
Written from
grpc.io/docs

Check status of the reference

Verified 1 Nov · next check 8 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What gRPC is and how it works

gRPC is a remote procedure call (RPC) framework: the client calls a method of a service on another machine as if it were a method of a local object. Methods and messages are described in a .proto file in the Protocol Buffers language, the protoc compiler generates the client and server code, and the calls travel over HTTP/2.

gRPC suits communication between microservices, between mobile clients and the server, and everywhere that needs a strict contract for several languages and streams of messages: a Java server is called from Go, Python or Ruby through the same .proto. For calls from the browser there is a separate project, gRPC-Web. A public API that people read with their own eyes and call through curl is easier to build with REST and JSON.

The contract is a .proto file: it contains the service, its methods and messages. protoc with a language plugin generates from it a stub for the client and a service interface for the server. The client code calls a method of the stub; the stub packs the arguments into a protobuf message and sends it through a channel — an HTTP/2 connection to the server. The gRPC server parses the request, calls your implementation of the method and returns the response together with a status.

The client and the server can be written in different languages: the only thing they share is the .proto file.

Every call is a separate HTTP/2 stream. The method is passed in the request path, for example /orders.v1.OrderService/GetOrder, the messages in DATA frames, and the status code in trailers at the end of the response. This is why one connection carries many calls at once, and the server can answer with a stream of messages.

How it differs from REST and JSON

AspectgRPCREST and JSON
ContractThe .proto file is required; the client and the server are generated from itAn API description (for example, OpenAPI) is optional
Message formatBinary Protocol Buffers; JSON can be plugged inText, usually JSON
AddressingA method of a service: POST /orders.v1.OrderService/GetOrderA resource in the URL and an HTTP method
StreamsFour kinds of call, including the bidirectional streamA request and a response
Errors17 gRPC status codesHTTP response codes
DebuggingNeeds .proto or reflection on the server and a tool like grpcurlcurl and a browser

Choose gRPC for internal APIs between services, for streams of data and for clients in different languages; choose REST for public APIs that are called from the browser and read by people.

What to know in advance

  • HTTP/2 streams and frames — the HTTP and REST reference, section “HTTP/1.1, HTTP/2 and HTTP/3”.
  • The language the service is written in — the Go, Python or Java and Spring references.
  • Certificates and TLS for secure channels — the TLS and PKI reference.

Section sources

the section is written from these pages

Cheat sheet

.proto syntax, code generation commands, status codes and calls with grpcurl. Every line is explained in detail in its own section of the reference; replace the names (orders.v1, OrderService, port 50051) with your own.

Messages in .proto

SyntaxWhat it means
syntax = "proto3";A proto3 file; the first meaningful line of the file
package orders.v1;A namespace; it forms part of the service’s full name
import "google/protobuf/timestamp.proto";Import definitions from another file
message Order { … }A message type
string id = 1;A field: type, name and number; the number never changes
optional string comment = 5;A field with presence: “not set” is not the same as an empty string
repeated Item items = 3;A list of values
map<string, string> labels = 4;A map; the key is an integer or a string
oneof delivery { … }At most one field of the group can be set
enum OrderStatus { ORDER_STATUS_UNSPECIFIED = 0; … }An enum; the first value is 0
reserved 9, 12 to 15;Numbers of removed fields that must not be reused

Services

SyntaxWhat it means
service OrderService { … }A service is a set of methods
rpc GetOrder(GetOrderRequest) returns (Order);Unary RPC: one message in each direction
returns (stream OrderEvent)Server streaming: the server replies with a stream of messages
rpc ImportItems(stream Item) returns (…)Client streaming: the client sends a stream, the server replies once
rpc Chat(stream …) returns (stream …)Bidirectional streaming

Code generation

TaskCommand
Messages plugin for Gogo install google.golang.org/protobuf/cmd/protoc-gen-go@latest
gRPC plugin for Gogo install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
Tools for Pythonpython -m pip install grpcio grpcio-tools
Compiler versionprotoc --version
bashfrom the project root
# Go: messages and gRPC code into the gen directoryprotoc -I proto \  --go_out=gen --go_opt=paths=source_relative \  --go-grpc_out=gen --go-grpc_opt=paths=source_relative \  orders/v1/orders.proto# Python: protoc is included in grpcio-toolspython -m grpc_tools.protoc -I proto \  --python_out=. --pyi_out=. --grpc_python_out=. \  orders/v1/orders.proto

Status codes

CodeWhen
OK (0)Success
CANCELLED (1)The call was cancelled, usually by the client
INVALID_ARGUMENT (3)An invalid argument, whatever the state of the system
DEADLINE_EXCEEDED (4)The deadline expired before a response arrived
NOT_FOUND (5)The object was not found
PERMISSION_DENIED (7)The caller is authenticated but has no permission
RESOURCE_EXHAUSTED (8)A quota or another resource has run out
UNIMPLEMENTED (12)The method is not implemented or is not supported by the server
INTERNAL (13)Internal invariants are broken — a serious bug
UNAVAILABLE (14)The service is temporarily unavailable; retry with a pause
UNAUTHENTICATED (16)No valid credentials

Calls with grpcurl

TaskCommand
List services (requires reflection)grpcurl -plaintext localhost:50051 list
Methods of a servicegrpcurl -plaintext localhost:50051 list orders.v1.OrderService
Describe a methodgrpcurl -plaintext localhost:50051 describe orders.v1.OrderService.GetOrder
Call a method with a JSON bodygrpcurl -plaintext -d '{"id": "42"}' localhost:50051 orders.v1.OrderService/GetOrder
Add metadata-H x-request-id:req-7
Without reflection: schema from a file-import-path proto -proto orders/v1/orders.proto
A server with TLSgrpcurl orders.example.com:443 list

Section sources

the section is written from these pages

Protocol Buffers

Protocol Buffers (protobuf) is a language for describing messages and the binary format in which gRPC carries them. Every field in .proto gets a type, a name and a number. Only numbers and values travel in binary form, so a field number, once it has gone into use, must never change.

protobuforders/v1/orders.proto
syntax = "proto3"; package orders.v1; import "google/protobuf/timestamp.proto"; option go_package = "example.com/shop/gen/orders/v1;ordersv1"; enum OrderStatus {  ORDER_STATUS_UNSPECIFIED = 0;  ORDER_STATUS_NEW = 1;  ORDER_STATUS_PAID = 2;  ORDER_STATUS_SHIPPED = 3;} message Item {  string sku = 1;  int32 quantity = 2;  // price in tiyin: an integer, no rounding errors  int64 price_tiyin = 3;} message Order {  string id = 1;  OrderStatus status = 2;  repeated Item items = 3;  map<string, string> labels = 4;  // optional: “not set” is distinct from an empty string  optional string comment = 5;  google.protobuf.Timestamp created_at = 6;  oneof delivery {    string pickup_point_id = 7;    string address = 8;  }}

The first meaningful line of the file is syntax or edition. Without it protoc treats the file as proto2. Messages can be nested inside one another, and types from other files can be brought in with import. A map field cannot be made repeated, and a oneof cannot contain a map or a repeated field.

Scalar types

TypeWhen to use it
int32, int64Integers that are mostly non‑negative: encoded as varints, while a negative value takes 10 bytes
sint32, sint64Integers that are often negative (ZigZag encoding)
uint32, uint64Strictly non‑negative integers
fixed32, fixed64Always 4 or 8 bytes; cheaper than varints when values are often larger than 2²⁸ and 2⁵⁶
double, floatIEEE 754 floating‑point numbers
boolTwo states, for good; if there may ever be more, use an enum
stringText in UTF‑8 or 7‑bit ASCII
bytesArbitrary bytes

Field numbers and the binary format

A field number runs from 1 to 536 870 911 and is unique within a message; numbers 19 000–19 999 are reserved by protobuf itself. Numbers 1–15 encode into one byte, 16–2047 into two, so give the small numbers to frequently used fields.

In a binary message every field is a tag and a value. The tag is a varint made up of the field number and the encoding type (wire type). Strings, bytes and nested messages (the LEN type) also carry a length, while integers travel as varints: 7 bits per byte, with the topmost bit marking continuation. Field names are not part of the message; only the .proto knows them.

The tag 0A is field 1 with type 2 (LEN), the tag 10 is field 2 with type 0 (VARINT).
protobuforders/v1/orders.proto
message Order {  // fields 9–11 removed: do not reuse the numbers or names  reserved 9 to 11;  reserved "discount", "coupon";  string id = 1;}

Default values and optional

If a field is absent from the message, reading yields the default value: an empty string, empty bytes, false, 0, an empty list or dictionary; for an enum — the first value, which must be 0. A proto3 scalar field without the optional label cannot tell “set to 0” apart from “not set”: the default value is not even transmitted over the network.

The optional label adds a presence flag: in the code that protoc generates a check appears for whether the field is set. The proto3 guide advises making optional the default — for compatibility with editions and proto2. Message fields carry a presence flag anyway.

How to change the schema without breaking clients

ChangePossible?
Add a fieldYes: old code will skip the new field, and new code will read old messages with the default
Delete a fieldYes, if the number and the name are recorded in reserved
Add a value to an enumYes for the format; code with an exhaustive switch may stop compiling
Rename a fieldYes for the binary format; JSON and the text format will break
Change a field numberNo: that deletes the field and creates a new one
Change int32 to int64With caveats: old code will truncate a large value to 32 bits
Move a field into an existing oneofNo
Make a repeated field out of a singular oneWith caveats: yes for string, bytes and messages (they take the last value or merge the elements), no for numbers — the packed encoding will not make sense of it

Roll out conditionally compatible changes only if you control every client and server: first everyone who reads receives the new schema, and only then does anyone start writing the new values. proto3 preserves unknown fields when parsing and writes them back when serialising, but they are lost on conversion to JSON.

Well‑known and common types

For time and durations use the ready‑made types google.protobuf.Timestamp and google.protobuf.Duration: they ship with protoc. Do not store time as an int64 with seconds or milliseconds — protobuf also has common types for dates, money and coordinates, which are imported from the googleapis repository. For a method with no payload there is the ready‑made google.protobuf.Empty. protobuf messages also have a canonical JSON mapping: in it Timestamp is an RFC 3339 string, and Empty is an empty object.

protobuforders/v1/delivery.proto
import "google/protobuf/duration.proto";import "google/protobuf/timestamp.proto"; message Delivery {  google.protobuf.Timestamp promised_at = 1;  google.protobuf.Duration window = 2;}

Editions instead of syntax

Editions replace proto2 and proto3: instead of syntax, the file declares, for example, edition = "2024";, and behaviour is governed by features. Every edition changes the feature defaults, and each one can be overridden for a file, a message or a field. In editions 2023 and later, fields have explicit presence by default, as with optional in proto3.

EditionWhat it changes by default
2023The first edition: explicit presence for all singular fields
2024Nested types are invisible from other files (local), strict naming style
2026All symbols local unless marked export; collision checks for field names; limits: 1,500 fields in a message, 1,700 values in an enum

The examples in this reference and in the gRPC documentation are written in proto3. Which protoc each edition needs is covered in the section “Versions and what’s new”.

Style and file layout

  • Files use lower_snake_case.proto, an indent of 2 spaces, and lines of up to 80 characters.
  • Packages are lowercase words separated by dots: orders.v1. Not the Java style (com.example.orders) — Java has option java_package for that.
  • Messages, enums, services and methods use TitleCase: OrderService, GetOrder.
  • Fields and oneof use lower_snake_case; repeated fields take a plural name: items.
  • enum values use UPPER_SNAKE_CASE prefixed with the enum’s name; the zero value is ORDER_STATUS_UNSPECIFIED, meaning nothing, so that unfamiliar values read as “not set”.
  • One file holds one main entity (a message, an enum or a service) and its supporting types.
  • Keep .proto files in a directory of their own, not next to the code of a single language; -I (--proto_path) points at its root, and the paths in import are written relative to it.

Section sources

the section is written from these pages

Services and kinds of RPC

A service is a named set of methods in a .proto file: each rpc has one request type and one response type. The word stream before a type turns that side into a stream of messages, so there are four kinds of call — depending on how many messages go in each direction.

protobuforders/v1/orders.proto
service OrderService {  // one message each way  rpc GetOrder(GetOrderRequest) returns (Order);  // the server sends events until the order is closed  rpc WatchOrder(WatchOrderRequest) returns (stream OrderEvent);  // the client uploads items, the server replies with a summary  rpc ImportItems(stream Item) returns (ImportSummary);  // both sides write independently of each other  rpc Chat(stream ChatMessage) returns (stream ChatMessage);}
KindMessagesWhen to use
Unary1 → 1A plain request and response: get, create, update
Server streaming1 → NA large result in parts, subscribing to events
Client streamingN → 1Uploading a batch of data with a single summary at the end
Bidirectional streamingN ↔ MExchange in both directions: chat, collaboration

A call of any kind follows the same sequence: metadata, messages, status. Within a single call gRPC preserves the order of messages. In a bidirectional call the two streams are independent: the server can wait for all of the client’s messages or reply to each one in turn.

The server sends the status and trailers at the end of any call, even a successful one.

Lifecycle of a call

  1. The client invokes the stub method. The server receives the client’s metadata, the method name and the deadline, if one is set.
  2. The server may send its initial metadata right away, or wait for the request first.
  3. The two sides exchange messages.
  4. The server completes the call with a status — a code and an optional message — and with trailers (trailing metadata).
  5. Client and server judge success independently. The server may believe it has sent everything while the client gets DEADLINE_EXCEEDED, because the response arrived after the deadline.

Server streaming in Go

A streaming handler receives a stream object instead of a response: Send emits the next message, and returning from the function completes the call. The client reads the stream through Recv until it gets io.EOF.

goserver/main.go
func (s *server) WatchOrder(	req *pb.WatchOrderRequest,	stream grpc.ServerStreamingServer[pb.OrderEvent],) error {	for _, st := range []pb.OrderStatus{		pb.OrderStatus_ORDER_STATUS_PAID,		pb.OrderStatus_ORDER_STATUS_SHIPPED,	} {		ev := &pb.OrderEvent{OrderId: req.GetId(), Status: st}		if err := stream.Send(ev); err != nil {			return err		}	}	// returning nil completes the call with status OK	return nil}
goclient/main.go
stream, err := client.WatchOrder(ctx, &pb.WatchOrderRequest{Id: "42"})if err != nil {	log.Fatalf("WatchOrder: %v", err)}for {	ev, err := stream.Recv()	if err == io.EOF {		// the server closed the stream with status OK		break	}	if err != nil {		log.Fatalf("WatchOrder: %v", err)	}	log.Println(ev.GetStatus())}

Streaming in Python

In Python the server’s streaming handler is a generator (yield), and the incoming stream is an iterator. The client passes an iterator of requests and loops over the responses with a for loop.

pythonserver.py
class OrderService(orders_pb2_grpc.OrderServiceServicer):    def ImportItems(self, request_iterator, context):        count, total = 0, 0        for item in request_iterator:            count += 1            total += item.quantity * item.price_tiyin        return orders_pb2.ImportSummary(item_count=count, total_tiyin=total)     def Chat(self, request_iterator, context):        for message in request_iterator:            yield orders_pb2.ChatMessage(text="echo: " + message.text)
pythonclient.py
items = [orders_pb2.Item(sku="A1", quantity=2, price_tiyin=150000)]summary = stub.ImportItems(iter(items), timeout=5)messages = iter([orders_pb2.ChatMessage(text="hi")])for reply in stub.Chat(messages, timeout=5):    print(reply.text)

In most languages gRPC offers both a synchronous and an asynchronous API. In Go a call blocks the current goroutine, so concurrent calls are started in separate goroutines; in Python the synchronous call stub.GetOrder(request) can be replaced with stub.GetOrder.future(request), and the result is picked up later through result().

Health checking

gRPC defines a standard health checking service, grpc.health.v1.Health: the Check method answers once and suits monitoring systems and load balancers, while the Watch method streams changes. Libraries ship a ready-made implementation, but the SERVING or NOT_SERVING status is set by your code; an empty service name stands for the whole server.

goserver/main.go
import (	"google.golang.org/grpc/health"	healthpb "google.golang.org/grpc/health/grpc_health_v1") hs := health.NewServer()healthpb.RegisterHealthServer(s, hs)// "" is the state of the whole serverhs.SetServingStatus("", healthpb.HealthCheckResponse_SERVING)hs.SetServingStatus("orders.v1.OrderService",	healthpb.HealthCheckResponse_SERVING)

The client can check servers on its own: specify the service name in the channel’s service config. The client then calls Watch after connecting and sends no calls to the server until it answers SERVING. If the server answers UNIMPLEMENTED, the check is disabled. The pick_first policy does not perform this check, which is why it is enabled together with round_robin.

jsonservice config
{"healthCheckConfig": {"serviceName": "orders.v1.OrderService"}}

Reflection

Reflection is a utility service through which the server reports its methods and message types. grpcurl and Postman rely on it: without it, making a call requires a .proto file. A server does not enable reflection on its own: in Go it is reflection.Register(s) from the google.golang.org/grpc/reflection package, in Python reflection.enable_server_reflection(...) from the grpcio-reflection package. Enable it for development and internal services; whether to expose it to public clients is a security decision.

Section sources

the section is written from these pages

Code generation

The protoc compiler with a language plugin generates the gRPC code: message types, a client stub and a service interface all come out of the .proto file. The generated code is never edited by hand — after every change to .proto, generation is run again.

Installing protoc

protoc is installed from a prebuilt release on GitHub or with a package manager. The package from a distribution can be much older than the current release, so check protoc --version against the table of supported versions. On macOS — brew install protobuf, on Windows — winget install protobuf.

bashUbuntu and Debian
sudo apt install -y protobuf-compilerprotoc --version
bashbuild from GitHub
# latest release for Linux x86-64 from GitHubAPI=https://api.github.com/repos/protocolbuffers/protobufURL=$(curl -s "$API/releases/latest" | jq -r '.assets[]  | select(.name | endswith("linux-x86_64.zip"))  | .browser_download_url')curl -LO "$URL"unzip "$(basename "$URL")" -d "$HOME/.local"export PATH="$PATH:$HOME/.local/bin"

Go

Go needs two plugins: protoc-gen-go generates the messages (.pb.go), and protoc-gen-go-grpc the client and the server (_grpc.pb.go). protoc looks up the plugins in PATH. The go_package option in .proto sets the import path of the package with the generated code; public projects cannot do without it. The part after the semicolon sets the package name; otherwise Go derives it from the last element of the path (ordersv1 in the example below).

bashon the developer’s machine
go install google.golang.org/protobuf/cmd/protoc-gen-go@latestgo install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latestexport PATH="$PATH:$(go env GOPATH)/bin"
textproject tree
shop/├── go.mod├── proto/│   └── orders/v1/orders.proto├── gen/│   └── orders/v1/│       ├── orders.pb.go│       └── orders_grpc.pb.go├── server/main.go└── client/main.go
bashin the shop directory
go mod init example.com/shopmkdir -p genprotoc -I proto \  --go_out=gen --go_opt=paths=source_relative \  --go-grpc_out=gen --go-grpc_opt=paths=source_relative \  orders/v1/orders.protogo mod tidy
  • orders.pb.go — the message types: construction, reading fields, serialisation.
  • orders_grpc.pb.go — the client interface OrderServiceClient with the NewOrderServiceClient constructor and the server interface OrderServiceServer with the RegisterOrderServiceServer function.

The minimal server embeds UnimplementedOrderServiceServer: methods you have not implemented reply with UNIMPLEMENTED, and adding a method to .proto does not break the build.

goserver/main.go
package main import (	"context"	"log"	"net" 	"google.golang.org/grpc"	"google.golang.org/grpc/codes"	"google.golang.org/grpc/status" 	pb "example.com/shop/gen/orders/v1") type server struct {	pb.UnimplementedOrderServiceServer} func (s *server) GetOrder(	ctx context.Context, req *pb.GetOrderRequest,) (*pb.Order, error) {	if req.GetId() != "42" {		return nil, status.Errorf(codes.NotFound,			"order %s not found", req.GetId())	}	return &pb.Order{Id: "42", Status: pb.OrderStatus_ORDER_STATUS_PAID}, nil} func main() {	lis, err := net.Listen("tcp", ":50051")	if err != nil {		log.Fatalf("listen: %v", err)	}	s := grpc.NewServer()	pb.RegisterOrderServiceServer(s, &server{})	log.Fatal(s.Serve(lis))}
goclient/main.go
package main import (	"context"	"log"	"time" 	"google.golang.org/grpc"	"google.golang.org/grpc/credentials/insecure" 	pb "example.com/shop/gen/orders/v1") func main() {	// no TLS: local development only	conn, err := grpc.NewClient("localhost:50051",		grpc.WithTransportCredentials(insecure.NewCredentials()))	if err != nil {		log.Fatalf("new client: %v", err)	}	defer conn.Close()	client := pb.NewOrderServiceClient(conn) 	ctx, cancel := context.WithTimeout(context.Background(), time.Second)	defer cancel()	order, err := client.GetOrder(ctx, &pb.GetOrderRequest{Id: "42"})	if err != nil {		log.Fatalf("GetOrder: %v", err)	}	log.Printf("order %s: %s", order.GetId(), order.GetStatus())}
bashin the shop directory
go run ./server# in a second terminalgo run ./client

Python

The grpcio-tools package already includes protoc and the gRPC plugin for Python; there is no need to install them separately.

bashin the project root
python -m pip install grpcio grpcio-toolspython -m grpc_tools.protoc -I proto \  --python_out=. --pyi_out=. --grpc_python_out=. \  orders/v1/orders.proto
  • orders/v1/orders_pb2.py — the message classes; orders_pb2.pyi — type hints for the editor.
  • orders/v1/orders_pb2_grpc.py — OrderServiceStub for the client, OrderServiceServicer and add_OrderServiceServicer_to_server for the server.
  • The 2 in _pb2 is the version of the Python API, not proto2: files written in proto3 are named the same way.
pythonserver.py
from concurrent import futures import grpc from orders.v1 import orders_pb2, orders_pb2_grpc  class OrderService(orders_pb2_grpc.OrderServiceServicer):    def GetOrder(self, request, context):        if request.id != "42":            context.abort(                grpc.StatusCode.NOT_FOUND, f"order {request.id} not found"            )        return orders_pb2.Order(id="42", status=orders_pb2.ORDER_STATUS_PAID)  server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))orders_pb2_grpc.add_OrderServiceServicer_to_server(OrderService(), server)server.add_insecure_port("[::]:50051")server.start()server.wait_for_termination()
pythonclient.py
import grpc from orders.v1 import orders_pb2, orders_pb2_grpc with grpc.insecure_channel("localhost:50051") as channel:    stub = orders_pb2_grpc.OrderServiceStub(channel)    order = stub.GetOrder(orders_pb2.GetOrderRequest(id="42"), timeout=1)    print(order.id, orders_pb2.OrderStatus.Name(order.status))

Java

In Java, .proto files go into src/main/proto, and the build generates the code: every build (./gradlew installDist) recreates the message classes and OrderServiceGrpc.java.

Where to keep .proto and when to generate

  • .proto files live in a separate directory (proto/) shared by all languages; -I points at its root.
  • After changing .proto, regenerate the code for all languages; otherwise the client and the server will diverge in their schemas.
  • Do not edit the files produced by the generator: their header says DO NOT EDIT, and the next generation will overwrite your edits.

Section sources

the section is written from these pages

Metadata and interceptors

Metadata is key–value pairs that travel with a call: a token, a request ID, tracing data. The client and the server send them in HTTP/2 headers before the messages, and the server also sends them in trailers afterwards. Common metadata handling is moved into interceptors.

Keys are ASCII strings: letters, digits, -, _ and .. Case does not matter; libraries convert keys to lower case. The grpc- prefix is reserved for gRPC itself. Values are ASCII strings or binary data: the key of a binary value ends with -bin, and the library itself encodes it in base64. A server may limit the size of the request headers; the recommended limit — 8 KiB.

This is how a call lands on HTTP/2. The first HEADERS frame carries the call definition — POST, the path /package.Service/Method, content-type: application/grpc, the deadline grpc-timeout — followed by your metadata. Each message in DATA frames comes with a 5-byte prefix: a compression flag and the length. The response ends with a second HEADERS frame — trailers with grpc-status and the server’s metadata; the status arrives in the trailers even when the call succeeds.

How the HTTP/2 frames themselves are built — see the “HTTP and REST” reference, the section “HTTP/1.1, HTTP/2 and HTTP/3”.

Metadata in Go

The client attaches pairs to the call context with metadata.AppendToOutgoingContext and picks up the response headers and trailer with the grpc.Header and grpc.Trailer options. The server reads the metadata with metadata.FromIncomingContext and replies with its own through grpc.SetHeader and grpc.SetTrailer.

goclient/main.go
ctx = metadata.AppendToOutgoingContext(ctx, "x-request-id", "req-7")var header, trailer metadata.MDorder, err := client.GetOrder(ctx, &pb.GetOrderRequest{Id: "42"},	grpc.Header(&header), grpc.Trailer(&trailer))
goserver/main.go
func (s *server) GetOrder(	ctx context.Context, req *pb.GetOrderRequest,) (*pb.Order, error) {	md, _ := metadata.FromIncomingContext(ctx)	// keys are already lower case	log.Printf("request ID: %v", md.Get("x-request-id"))	grpc.SetTrailer(ctx, metadata.Pairs("x-cost", "3"))	return &pb.Order{Id: req.GetId()}, nil}

Metadata in Python

pythonclient.py
order, call = stub.GetOrder.with_call(    orders_pb2.GetOrderRequest(id="42"),    metadata=(("x-request-id", "req-7"),),    timeout=1,)print(call.trailing_metadata())
pythonserver.py
def GetOrder(self, request, context):    metadata = dict(context.invocation_metadata())    print("request ID:", metadata.get("x-request-id"))    context.set_trailing_metadata((("x-cost", "3"),))    return orders_pb2.Order(id=request.id)

Interceptors

An interceptor is a function the library calls for every call on a channel or a server: logging, metrics, caching, token checks, metadata handling. It works at the call level, so it is not the tool for tuning TCP or TLS. The client and the server have different interceptor APIs. For sending credentials from the client there is a separate mechanism — call credentials.

The order in the chain matters. An interceptor closer to the network sees what actually goes on the wire; one closer to the application sees what the code does. For example, logging before the cache records every call, while logging after the cache records only the calls that reached the server.

goserver/main.go
func logCalls(	ctx context.Context, req any,	info *grpc.UnaryServerInfo, handler grpc.UnaryHandler,) (any, error) {	start := time.Now()	resp, err := handler(ctx, req)	log.Printf("%s %s %v",		info.FullMethod, status.Code(err), time.Since(start))	return resp, err} s := grpc.NewServer(grpc.ChainUnaryInterceptor(logCalls))

This interceptor fires for unary methods only; streaming calls need a stream interceptor (grpc.ChainStreamInterceptor). In Python a server interceptor is a class with an intercept_service method:

pythonserver.py
class RequestIdInterceptor(grpc.ServerInterceptor):    def intercept_service(self, continuation, handler_call_details):        metadata = dict(handler_call_details.invocation_metadata)        print(handler_call_details.method, metadata.get("x-request-id"))        return continuation(handler_call_details)  server = grpc.server(    futures.ThreadPoolExecutor(max_workers=10),    interceptors=[RequestIdInterceptor()],)

What you must not set yourself

  • HTTP/2 pseudo-headers with a colon (:path, :authority, :method) — the library sets them.
  • content-type, te, user-agent, grpc-timeout, grpc-encoding — part of the call definition.
  • grpc-status, grpc-message and any other keys with the grpc- prefix: they are reserved, including for the future.

Section sources

the section is written from these pages

Deadlines, cancellation and retries

A deadline is the moment after which the client stops waiting for a response and finishes the call with the code DEADLINE_EXCEEDED. By default there is no deadline, and a call to a hung server can wait forever, so set a realistic deadline on every call.

Some APIs take a deadline — a point in time; others take a timeout — a duration. A timeout becomes a deadline at the moment of the call. Start with an estimate based on network latency and processing time, and check it with a load test. When the deadline expires, the server cancels the call itself: the handler sees the status CANCELLED, and the client receives DEADLINE_EXCEEDED.

If the server calls other services itself, it passes them what is left of the deadline. In Go and Java this happens automatically when you pass the incoming call’s context along; in C++ you enable it explicitly. Over the wire the deadline travels as the time remaining, not as a point on the clock, so clock skew between servers does not affect it.

This is how deadline propagation works in Go and Java: service A passes the incoming call’s context to the call to B.

Deadline in Go

goclient/main.go
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)defer cancel()_, err := client.GetOrder(ctx, &pb.GetOrderRequest{Id: "42"})if status.Code(err) == codes.DeadlineExceeded {	log.Print("GetOrder: deadline exceeded")}
goserver/main.go
for _, item := range items {	// call cancelled or deadline expired: stop working	if err := ctx.Err(); err != nil {		return nil, status.FromContextError(err).Err()	}	// calls to other services use the same ctx	if err := s.reserve(ctx, item); err != nil {		return nil, err	}}

Deadline in Python

The client passes the timeout in seconds as the timeout argument. The handler finds out the remaining time through context.time_remaining(), and context.is_active() returns False when the call is cancelled or the deadline has expired.

pythonclient.py
try:    order = stub.GetOrder(orders_pb2.GetOrderRequest(id="42"), timeout=0.3)except grpc.RpcError as err:    if err.code() == grpc.StatusCode.DEADLINE_EXCEEDED:        print("GetOrder: deadline exceeded")

Cancellation

The client cancels a call when the result is no longer needed: in Go with the context’s cancel() function, in Python with the cancel() method of the call object. The deadline and a dropped connection also cancel the call. The library cannot interrupt a handler that is already running, so a long-running handler checks from time to time whether the call has been cancelled and stops working. Go, Java and C++ automatically cancel outgoing calls started from a cancelled one; in Python this is the handler author’s job.

Retries

Retries in gRPC are enabled by default, but there is no policy. Without one, the library retries only calls that definitely never reached the server code (a transparent retry). The policy is set in the service config for a service or a method: the number of attempts, exponential backoff and the status codes to retry on. Retry only methods that are safe to run twice.

jsonservice config fragment
"retryPolicy": {  "maxAttempts": 4,  "initialBackoff": "0.1s",  "maxBackoff": "1s",  "backoffMultiplier": 2,  "retryableStatusCodes": ["UNAVAILABLE"]}

A random deviation of ±20% is added to the pause: after the first attempt the client waits 80–120 ms. As soon as the client has received the response headers, the call is committed and is not retried again. To keep retries from piling onto an overloaded server, set retryThrottling — a token counter for each server. Hedging complements retries and is configured in a similar way. The service config in full is covered in the section “Load balancing and name resolution”.

Keepalive

Keepalive is HTTP/2 pings (PING frames) that check the connection while no data is flowing over it. They are needed for long-lived streams, unreliable mobile networks and proxies that close idle connections. This is not a health check of the service: keepalive knows only about the connection.

OptionWhat it setsClientServer
KEEPALIVE_TIMEInterval between pingsdisabled2 hours
KEEPALIVE_TIMEOUTHow long to wait for a ping response before closing the connection20 seconds20 seconds
KEEPALIVE_WITHOUT_CALLSSend pings when there are no callsno—
PERMIT_KEEPALIVE_WITHOUT_CALLSAccept client pings without calls—no
PERMIT_KEEPALIVE_TIMEMinimum interval for client pings—5 minutes
MAX_CONNECTION_IDLEClose a connection with no calls after this time—infinite
MAX_CONNECTION_AGEMaximum age of a connection—infinite
MAX_CONNECTION_AGE_GRACEHow long to wait for calls to finish after MAX_CONNECTION_AGE—infinite

Section sources

the section is written from these pages

Status codes and errors

Every gRPC call ends with a status: a code — one of 17 values — and an optional message. The handler on the server chooses the code; on network, deadline or protocol failures the gRPC library itself does, on the client or server. Return only codes from this list.

CodeNumberWhen to return
OK0Success
CANCELLED1The operation was cancelled, usually by the caller
UNKNOWN2Unknown error, including an error with no details
INVALID_ARGUMENT3The argument is invalid regardless of the system state: for example, a name in the wrong format
DEADLINE_EXCEEDED4The deadline expired before the operation completed; a mutating operation may nevertheless have gone through
NOT_FOUND5The entity was not found
ALREADY_EXISTS6The entity that was being created already exists
PERMISSION_DENIED7The caller is authenticated but has no permission for the operation
RESOURCE_EXHAUSTED8A user quota has run out, or some other resource
FAILED_PRECONDITION9The system is not in the required state: for example, the directory to delete is not empty
ABORTED10The operation was aborted due to concurrency: a version conflict, a transaction rollback
OUT_OF_RANGE11Beyond the valid range, for example reading past the end of a file
UNIMPLEMENTED12The operation is not implemented or not supported
INTERNAL13Internal invariants are broken; reserve for serious errors
UNAVAILABLE14The service is temporarily unavailable; retrying after a pause usually helps
DATA_LOSS15Unrecoverable loss or corruption of data
UNAUTHENTICATED16No valid credentials

The library never produces seven codes: INVALID_ARGUMENT, NOT_FOUND, ALREADY_EXISTS, FAILED_PRECONDITION, ABORTED, OUT_OF_RANGE, DATA_LOSS. If a client receives one of them, it was the service code that returned it. On failures the library itself may produce the remaining codes: most often DEADLINE_EXCEEDED (the deadline expired), UNAVAILABLE (a dropped connection or a server shutting down), UNIMPLEMENTED (the method was not found) and RESOURCE_EXHAUSTED (stream limits have been hit).

How to choose a code

  • INVALID_ARGUMENT — the argument is bad regardless of the system state; FAILED_PRECONDITION — the system is not in the right state; OUT_OF_RANGE — the boundary depends on the state, and a client iterating over the range will know from this code that it has reached the end.
  • On retries: UNAVAILABLE — the client may retry the same call; ABORTED — retry at a higher level, the whole “read — modify — write” chain; FAILED_PRECONDITION — do not retry until the state is fixed.
  • UNAUTHENTICATED — the caller is not identified; PERMISSION_DENIED — identified but without permission. A rejection because of a quota is RESOURCE_EXHAUSTED, not PERMISSION_DENIED.
  • NOT_FOUND can be returned when access is closed to an entire class of users, for example when a feature is not yet open; denying individual users is PERMISSION_DENIED.
  • A handler that throws an exception or returns an error not in the form of a gRPC status leaves the client with UNKNOWN. Return codes explicitly.

Error in Go

goGo
// serverreturn nil, status.Errorf(codes.NotFound, "order %s not found", id) // client_, err := client.GetOrder(ctx, &pb.GetOrderRequest{Id: id})if err != nil {	st := status.Convert(err)	log.Printf("code=%s message=%q", st.Code(), st.Message())}

Error in Python

pythonPython
# servercontext.abort(grpc.StatusCode.NOT_FOUND, f"order {request.id} not found") # clienttry:    stub.GetOrder(orders_pb2.GetOrderRequest(id="7"), timeout=1)except grpc.RpcError as err:    print(err.code(), err.details())
textexample output
StatusCode.NOT_FOUND order 7 not found

Error details

The code and the message do not say which exact field is wrong. For that there is the richer error model: the server attaches a google.rpc.Status message to the status with a list of details of standard types — invalid parameters, exceeded quotas, stack traces. The details travel in the response trailers. The model is supported by the C++, Go, Java, Python and Ruby libraries.

goserver/main.go
st := status.New(codes.InvalidArgument, "invalid order id")ds, err := st.WithDetails(&errdetails.BadRequest{	FieldViolations: []*errdetails.BadRequest_FieldViolation{{		Field:       "id",		Description: "id must not be empty",	}},})if err != nil {	return nil, st.Err()}return nil, ds.Err()
pythonclient.py, the grpcio-status package
from google.rpc import error_details_pb2from grpc_status import rpc_status try:    stub.GetOrder(orders_pb2.GetOrderRequest(), timeout=1)except grpc.RpcError as err:    status = rpc_status.from_call(err)    for detail in status.details:        if detail.Is(error_details_pb2.BadRequest.DESCRIPTOR):            info = error_details_pb2.BadRequest()            detail.Unpack(info)            print(info.field_violations)

A response without a gRPC status

If a proxy sits between the client and the server, the response may arrive without grpc-status — for example, a 502 error page. The client then derives the gRPC code from the HTTP code using the table. The table only works in this direction: a server must not pick an HTTP code by it.

HTTP codegRPC code
400 Bad RequestINTERNAL
401 UnauthorizedUNAUTHENTICATED
403 ForbiddenPERMISSION_DENIED
404 Not FoundUNIMPLEMENTED
429, 502, 503, 504UNAVAILABLE
All others, including 200 without grpc-statusUNKNOWN

Section sources

the section is written from these pages

Load balancing and name resolution

gRPC spreads the load across calls, not connections. The client keeps a single long-lived HTTP/2 connection to the server and sends every call over it, so a balancer that picks a server once per TCP connection will send the whole client’s load to one server.

There are two options. Client-side balancing: the channel connects to all of the service’s addresses itself and alternates calls between them — the round_robin policy. Or an application-layer (L7) proxy that understands HTTP/2 and picks a server for each call. Either way a stream that has already started stays on its server: once started, a stream is never rebalanced.

The right-hand scheme needs name resolution to return the addresses of all servers to the client.

How the client picks a server

  1. The channel resolves the name in the target address: it gets a list of addresses and a service config.
  2. The channel creates the load-balancing policy named in the service config and hands the addresses to it.
  3. The policy opens subchannels — connections to the servers — and watches their state.
  4. For each call, the policy picks a subchannel, which means a server.
PolicyHow it works
pick_first (the default)Connects to the addresses in turn and sends all calls to the first one that is available; there is no balancing
round_robinKeeps connections to all addresses and sends each next call to the next ready server
grpclbDeprecated: use the xDS policies instead
xDS policiesWork together with xDS; they are not set directly in the service config

The target address

A channel’s address is a URI: the scheme chooses the name-resolution mechanism. With no scheme, DNS is used. If the port is omitted, the DNS resolver fills in 443, and some implementations use 80 for insecure channels.

EntryWhat it means
orders.example.com:443No scheme — resolution goes through DNS
dns:///orders.example.com:443DNS explicitly; between // and the third / you can name a DNS server, but not in every implementation
unix:///run/orders.sockA Unix socket at an absolute path (Unix only)
ipv4:192.0.2.10:50051,192.0.2.11:50051A list of addresses without DNS; available in gRPC core (C++, Python), not in every language

Service config

A service config is JSON with client-side settings for a specific address: the load-balancing policy, deadlines, retries or hedging, and health checking — for the whole service or individual methods. The service owner distributes it through name resolution: for example, the DNS resolver in Go reads it from a TXT record. The client can also set a default configuration in code — it applies when the resolver does not return one of its own.

jsonservice_config.json
{  "loadBalancingConfig": [{"round_robin": {}}],  "methodConfig": [    {      "name": [{"service": "orders.v1.OrderService"}],      "timeout": "1s",      "retryPolicy": {        "maxAttempts": 3,        "initialBackoff": "0.1s",        "maxBackoff": "1s",        "backoffMultiplier": 2,        "retryableStatusCodes": ["UNAVAILABLE"]      }    },    {      "name": [        {"service": "orders.v1.OrderService", "method": "ImportItems"}      ],      "timeout": "30s"    }  ]}

Here all methods of OrderService get a deadline of 1 s and up to three attempts on UNAVAILABLE, while ImportItems gets a deadline of 30 s and no retries: a method’s settings override the service’s.

goclient/main.go
conn, err := grpc.NewClient("dns:///orders.example.com:443",	grpc.WithTransportCredentials(creds),	grpc.WithDefaultServiceConfig(serviceConfig))

Balancing in Kubernetes

An ordinary Service in Kubernetes hands out a single virtual IP, and a client with round_robin will see one address. For DNS to return the addresses of all pods, make the Service headless (clusterIP: None): then the A and AAAA records point straight at the pods. Service is covered in detail in the Kubernetes reference, the section “Service, Ingress and Gateway API”.

Server health is checked with health checking: set healthCheckConfig in the channel’s service config, and a client with round_robin polls each server’s health service itself and does not send calls to a server that does not report SERVING. How to run such a service — see the section “Services and RPC types”.

Section sources

the section is written from these pages

Security

The main threats to a gRPC service are traffic interception and calls from unauthorised clients. Protection is built in two layers: channel credentials (TLS or mTLS) encrypt the connection and verify the identity of both parties, and call credentials — a token in the metadata — tell the server who is calling.

TLS on the server and the client

Enable TLS on every channel that leaves the machine: it verifies the server and encrypts all data. The client needs the root certificate that signed the server’s certificate. For a publicly signed certificate the default roots are enough: in Go they are the system roots, in Python the roots.pem set bundled with grpcio.

goGo
// servercreds, err := credentials.NewServerTLSFromFile("server.crt", "server.key")if err != nil {	log.Fatalf("load TLS: %v", err)}s := grpc.NewServer(grpc.Creds(creds)) // client: the system root certificatesconn, err := grpc.NewClient("orders.example.com:443",	grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")))
pythonPython
def read(path):    with open(path, "rb") as f:        return f.read()  # serverserver_creds = grpc.ssl_server_credentials(    [(read("server.key"), read("server.crt"))])server.add_secure_port("[::]:50051", server_creds) # client: your own CA instead of the bundled rootschannel = grpc.secure_channel(    "orders.example.com:50051",    grpc.ssl_channel_credentials(root_certificates=read("ca.crt")),)

An insecure channel — only on your own machine

A channel without TLS sends data and tokens in plaintext: any node along the way can read and replay them. Use it only for localhost during development.

gowrong: the server is on the network
conn, err := grpc.NewClient("orders.example.com:443",	grpc.WithTransportCredentials(insecure.NewCredentials()))
gothe right way
conn, err := grpc.NewClient("orders.example.com:443",	grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")))

Mutual authentication (mTLS)

For calls between your own services the server may also require a certificate from the client: TLS then verifies both sides. How mTLS and certificate chains work — the TLS and PKI reference, section “Mutual authentication (mTLS)”.

pythonPython
# the server accepts only clients with a certificate issued by ca.crtserver_creds = grpc.ssl_server_credentials(    [(read("server.key"), read("server.crt"))],    root_certificates=read("ca.crt"),    require_client_auth=True,)# the client presents its own certificatechannel_creds = grpc.ssl_channel_credentials(    root_certificates=read("ca.crt"),    private_key=read("client.key"),    certificate_chain=read("client.crt"),)

ALTS is Google’s mechanism for transport protection instead of TLS; it works only on Compute Engine and in Google Kubernetes Engine.

Tokens in metadata

Call credentials attach a token to every call, usually to the authorization header. Combine them with the channel’s TLS: most implementations will not send a token over an insecure channel, and the oauth.TokenSource credentials in Go refuse to work without TLS (RequireTransportSecurity).

goclient/main.go
perRPC := oauth.TokenSource{TokenSource: oauth2.StaticTokenSource(	&oauth2.Token{AccessToken: os.Getenv("ORDERS_TOKEN")},)}conn, err := grpc.NewClient("orders.example.com:443",	grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),	grpc.WithPerRPCCredentials(perRPC))
pythonclient.py
call_creds = grpc.access_token_call_credentials(os.environ["ORDERS_TOKEN"])creds = grpc.composite_channel_credentials(    grpc.ssl_channel_credentials(), call_creds)channel = grpc.secure_channel("orders.example.com:443", creds)

Token verification in an interceptor

Verify the token in a server interceptor rather than in each method: that way a new method is never left unprotected. Reject with UNAUTHENTICATED when the token is missing or invalid, and with PERMISSION_DENIED when there are not enough permissions. Streaming methods need the same kind of stream interceptor. How to verify the signature of JWT tokens — the OAuth and OIDC reference, section “JWT, JWS and JWKS”.

goserver/main.go
func checkToken(	ctx context.Context, req any,	info *grpc.UnaryServerInfo, handler grpc.UnaryHandler,) (any, error) {	md, _ := metadata.FromIncomingContext(ctx)	auth := md.Get("authorization")	// valid checks the token’s signature and expiry	if len(auth) == 0 || !valid(strings.TrimPrefix(auth[0], "Bearer ")) {		return nil, status.Error(codes.Unauthenticated, "invalid token")	}	return handler(ctx, req)} s := grpc.NewServer(grpc.Creds(creds), grpc.UnaryInterceptor(checkToken))

Bundled services and message size

  • Reflection exposes every method and every message type. A public API usually leaves it off, and an internal one lets it through only to debugging tools inside the network.
  • The Check method of the health service is needed by monitoring systems and load balancers; direct it to them only.
  • Cap the sizes of requests and responses: a protobuf message is under 2 GiB in any case, and parsing nested messages beyond the depth limit (100 levels in Java and C++) ends in an error.

Section sources

the section is written from these pages

Common errors and diagnostics

Start diagnosing from the status code and message: the code shows whether the call reached the handler or was cut short by the network, a deadline or the library itself. Next, turn on gRPC logs on the client and the server and repeat the call with grpcurl to rule out your own client code.

Diagnostic sequence

  1. The status code and message on the client, the handler’s log on the server.
  2. Library logs: in Go — GRPC_GO_LOG_VERBOSITY_LEVEL and GRPC_GO_LOG_SEVERITY_LEVEL, in the core (C++, Python, Ruby, PHP) — GRPC_TRACE and GRPC_VERBOSITY.
  3. The same call with grpcurl: if it gets through, the fault is in your client.
bashon the client and the server
# Go: all gRPC logsexport GRPC_GO_LOG_VERBOSITY_LEVEL=99export GRPC_GO_LOG_SEVERITY_LEVEL=info# gRPC core: tracing of the API and the HTTP/2 transportGRPC_TRACE=api,http GRPC_VERBOSITY=DEBUG python client.py

GRPC_TRACE takes tracer names and prefix globs, separated by commas. GRPC_VERBOSITY is deprecated: it changes the log level for the whole application, so switch it on only for the duration of debugging.

bashon the developer’s machine
grpcurl -plaintext localhost:50051 listgrpcurl -plaintext -d '{"id": "42"}' \  localhost:50051 orders.v1.OrderService/GetOrder# without reflection: the schema from a .proto filegrpcurl -plaintext \  -import-path proto \  -proto orders/v1/orders.proto \  -d '{"id": "42"}' \  localhost:50051 orders.v1.OrderService/GetOrder

grpcurl sends the request body as JSON and prints the response as JSON; without the -plaintext flag it connects over TLS, and metadata is added with the -H flag.

code = Unavailable desc = transport is closing

Cause: the connection the call was going over has closed. The TLS handshake did not complete, a proxy mangled the traffic, the server stopped or closed the connection itself according to its keepalive settings. The client sees the error; the cause is usually on the server.

bashon the client and the server
export GRPC_GO_LOG_VERBOSITY_LEVEL=99export GRPC_GO_LOG_SEVERITY_LEVEL=info
  • Look for a transport error in the logs on both sides: the handshake, GOAWAY, the connection being closed.
  • Compare the credentials: a client with TLS will not connect to a server without TLS, and vice versa.
  • If the server closes connections because of MaxConnectionAge, raise MaxConnectionAgeGrace so that long calls have time to finish.

UNAVAILABLE on the first call

Cause: the client failed to establish a connection — the server is not running or is listening on another address, the name did not resolve, or the two sides did not agree on TLS. The same code arrives when the server is shutting down, when the connection drops after part of the data has been sent and when the keepalive ping goes unanswered.

basha check
# server without TLSgrpcurl -plaintext localhost:50051 list# server with TLSgrpcurl orders.example.com:443 list
  • Check the address and port in the client’s target and the address the server is listening on.
  • Turn TLS on on both sides or on neither.
  • For transient failures configure retries on UNAVAILABLE in the service config.

DEADLINE_EXCEEDED

Cause: the deadline expired before the status arrived. The server responds slowly, the request never reached the server, or the deadline is too tight — including the remaining deadline propagated along the chain of calls. The mutating operation may nevertheless have gone through.

bashhow long the call takes
time grpcurl -plaintext -d '{"id": "42"}' \  localhost:50051 orders.v1.OrderService/GetOrder
  • Compare the client’s deadline with the processing time in the server’s log.
  • If the server never saw the call, look for the problem in the network and in load balancing, not in the handler.
  • Raise the deadline to a realistic value or make the handler faster; make mutating methods idempotent so that they can be retried safely.

UNIMPLEMENTED

Cause: the server has no such method — the client was built against a different package or service name in .proto, the service is not registered on the server, or the client and the server were built from different versions of .proto. The server returns the same code if it does not support client compression or if a unary method received more than one message.

basha check
grpcurl -plaintext localhost:50051 list orders.v1.OrderService
  • Verify the full method name: package, service and method (orders.v1.OrderService/GetOrder).
  • Regenerate the client and the server from one and the same .proto.
  • Check that the service is registered on the server (RegisterOrderServiceServer in Go).

RESOURCE_EXHAUSTED

Cause: the message sent or received exceeds the configured limit, the server has run out of flow-control resources, or the application itself has exhausted a quota. In grpc-go the default receive limit is 4 MB.

goGo
// 16 MB instead of the 4 MB defaultconst maxMsg = 16 << 20 s := grpc.NewServer(grpc.MaxRecvMsgSize(maxMsg))conn, err := grpc.NewClient(target,	grpc.WithTransportCredentials(creds),	grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxMsg)))

Raise the limit deliberately, and on the side that receives. Large volumes are better shipped in parts, with a server or client stream.

UNAUTHENTICATED

Cause: the credential metadata could not be obtained, incompatible credentials are set on the channel and the call, the wrong host is given in :authority, or the server rejected the token.

basha check
grpcurl -H "authorization:Bearer $ORDERS_TOKEN" \  -d '{"id": "42"}' \  orders.example.com:443 orders.v1.OrderService/GetOrder
  • Check the token’s expiry and signature on the server.
  • Make sure the token is sent over a channel with TLS: otherwise the library may not send it.

UNKNOWN

Cause: the handler on the server threw an exception or returned an error not as a gRPC status, or the client failed to parse the status it received.

bashthe server’s log in Python
grep -n Traceback server.log
  • Find the exception in the server’s log.
  • Return codes explicitly: status.Error in Go, context.abort in Python.

Section sources

the section is written from these pages

Versions and what’s new

This reference describes gRPC 1.85 and Protocol Buffers 36.x. The latest release of the gRPC core is 1.85.1, dated 30 October 2026 (grpc-go 1.85.0, grpc-java 1.85.1); the latest protoc compiler release is 36.2, dated 17 September 2026. gRPC ships roughly every 6 weeks, has no LTS and supports the current and the previous release; protobuf ships once a quarter.

BranchStatusLatest releaseSupported until
gRPC 1.85current, described in this reference1.85.1, 30 October 2026until 1.87 is released
gRPC 1.84supported1.84.2, 30 October 2026until 1.86 is released
gRPC 1.83out of support1.83.2, 2 November 2026until 1.85 is released
protoc 36.xcurrent, described in this reference36.2, 17 September 2026until 37.0 is released
protoc 33.xcritical and security fixes only33.6, 18 March 202631 March 2027 (C++ and Python 6.x)
protoc 37.0pre-release37.0-rc1, 15 October 2026—

The gRPC branch number is shared between the core (C++, Python, Ruby, PHP, C#, Objective-C), grpc-go and grpc-java, but patch releases are made separately for each. The protobuf number is shared between all languages in the minor.patch part: release 36.2 corresponds, for example, to Java 4.36.2 and Python 7.36.2. A new protobuf minor version immediately ends support for the previous one.

Protocol Buffers editions

Editionprotoc requiredReleased
202636.020 August 2026
202432.023 May 2025
202327.013 August 2024
proto33.02016

The edition number is not related to the protobuf release number. What each edition changes is covered in the “Protocol Buffers” section.

What is new in 1.84 and 1.85

  • Security: core 1.85 added MLKEM1024 key exchange in TLS and support for OpenSSL 4.
  • Security: 1.84.1 and 1.85.0 refreshed the bundled root certificate set roots.pem; the vulnerability this closes is described in the “Security” section.
  • Services and RPC types: Python 1.85.1 and 1.84.2 fixed a denial of service in the Watch method of the health checking service and a memory leak in asyncio client threads with interceptors.
  • Code generation: since 1.84, grpcio wheels for Python 3.15 are published.
  • Metadata and interceptors: since 1.82.2, the grpc-go server rejects requests that carry neither :authority nor Host.
  • Status codes and errors: since 1.79.3, the grpc-go server rejects requests whose :path does not start with / with the UNIMPLEMENTED status code.
  • Deadlines, cancellation and retries: grpc-java 1.85.0 closes the connection properly on receiving a GOAWAY frame with an unknown error code; previously such calls hung until the deadline expired.
  • Protocol Buffers: protoc 36.0 added the 2026 edition.

Deprecated and removed

  • The gRPC core 1.85 no longer supports OpenSSL 1.0.2.
  • Protocol Buffers: support for releases 26.x–29.x (C++ and Python 5.x) ended on 31 March 2026; 30.x–33.x (C++ and Python 6.x) receive critical fixes only until 31 March 2027.

Security releases

IdentifierWhat is affectedFixed in
CVE-2026-84445grpc-go, xDS servers: process crash on a request without :authority and Host1.82.2, 1.83.2, 1.84.0
CVE-2026-84304grpc-go: memory exhaustion when data is chopped into 1-byte DATA frames1.83.1
CVE-2026-84303grpc-go, xDS RBAC: DENY rules bypassed via upper-case headers1.83.1
GHSA-hrxh-6v49-42gfgrpc-go: xDS RBAC bypass, HTTP/2 Rapid Reset protection bypass, crash on NOT rules1.82.1
CVE-2026-33186grpc-go: authorisation bypass through :path without the leading /1.79.3

How to upgrade

  1. Read the release notes of every release between your current one and the target: behaviour changes are listed there.
  2. Update the gRPC library to the latest patch of the branch, for example go get google.golang.org/grpc@latest or python -m pip install -U grpcio grpcio-tools.
  3. Update protoc and the plugins and regenerate the code: the protobuf documentation advises doing this on every upgrade, and code from an old protoc is supported only for compatibility.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 3 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

9 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “gRPC” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61