What Is gRPC? Understanding Four RPC Patterns and Service Contracts
gRPC is a remote procedure call (RPC) framework that lets one program call functionality implemented by another program across a network. Teams define a service and its messages as a contract, then generate client and server code from it, making communication between services written in different languages more consistent. It is especially useful for service-to-service calls and continuous data flows, but browser access and public APIs centered on readable JSON can require extra components and operational work.
gRPC is a remote procedure call (RPC) framework that lets one program call functionality implemented by another program across a network. Teams define a service and its messages as a contract, then generate client and server code from it, making communication between services written in different languages more consistent. It is especially useful for service-to-service calls and continuous data flows, but browser access and public APIs centered on readable JSON can require extra components and operational work.
What problem does gRPC solve?
Separate services run in different processes or computers, so they cannot share memory as if they were calling an ordinary local function. A caller must encode a request for the network; the receiving service must interpret it, perform work, and return a response. gRPC connects the interface, message serialization, transport, and calling API into one framework.
RPC means remote procedure call. A developer calls a client method that looks like a local function, but the call actually creates a network request and runs server-side code. Network delay, connection failures, and server errors still exist, so an RPC must not be treated as an ordinary local function. Calls need time limits and error handling.
By default, gRPC uses Protocol Buffers (Protobuf) as both its interface definition language (IDL) and message format. gRPC is not inherently restricted to Protobuf; other data formats can be supported. A common starting point is a human-readable .proto file. Compiler plugins generate language-specific message types and code such as a client stub. A stub is a client-side object that exposes methods for calling the remote service. (Introduction, core concepts)
From service contract to an actual call
Suppose a catalog service looks up an item and continuously reports stock changes. The following compact .proto example is illustrative. A production service also needs policies for errors, field selection, pagination, authentication, and compatibility.
syntax = "proto3";
package catalog;
service Catalog {
rpc GetItem (GetItemRequest) returns (Item);
rpc WatchStock (WatchStockRequest) returns (stream StockUpdate);
}
message GetItemRequest {
string item_id = 1;
}
message Item {
string item_id = 1;
string name = 2;
}
message WatchStockRequest {
string item_id = 1;
}
message StockUpdate {
int32 available = 1;
}service groups callable operations; each rpc line names a method and its request and response types. A message describes data sent over the wire. The number after each field is its Protobuf field number, used to identify it in serialized data. Once a field number is in use, changing or reusing it can break compatibility. Reserve numbers for fields you delete so they cannot be accidentally assigned again. (Protobuf field numbers, deleting fields)
A typical flow is:
The team defines and versions service methods and messages in `.proto` files.
The Protobuf compiler and gRPC plugins generate language-specific message classes and client/server interfaces.
The server developer implements the generated service interface and runs a gRPC server.
The client calls `GetItem` on its generated stub. The library serializes and sends the request; the server deserializes it and invokes the implementation.
The server returns an `Item` response and call status. The client library exposes them as language-specific objects.
The standard gRPC transport uses HTTP/2 framing. A request contains headers such as the method path and content type, followed by length-prefixed message data. A response can finish with trailers that carry the final status. Therefore, an HTTP status code alone does not tell you whether the RPC succeeded; inspect the gRPC status. Libraries handle most wire details, but verify in your deployment that proxies and load balancers pass HTTP/2 and trailers correctly. (HTTP/2 protocol, error handling)
How do the four RPC patterns differ?
The position of stream in a method declaration determines the direction of the message flow. A stream is a sequence of messages exchanged during one call. Message order is preserved within each direction of a call, but bidirectional streams do not have to alternate one message at a time.
| Pattern | Requests and responses | Suitable example | Considerations |
|---|---|---|---|
| Unary | One request → one response | Look up an item or create an order | Simplest shape, but still needs network failure handling and a deadline |
| Server streaming | One request → many responses | Subscribe to logs, search results, or stock updates | Define completion, slow-consumer behavior, and cleanup after cancellation |
| Client streaming | Many requests → one response | Send measurements and receive one summary | Define when input is complete and how partial-input failures work |
| Bidirectional streaming | Many requests ↔ many responses | Interactive session or real-time control | Both directions progress independently; flow control, termination, reconnect, and state recovery are more complex |
For a stock screen, an easy-to-follow design is to fetch the initial item state with a unary GetItem call, then subscribe to changes with server-streaming WatchStock. Since updates flow only from the server, bidirectional streaming is unnecessary. If a client sends sensor readings continuously and needs intermediate results back, bidirectional streaming may fit. A stream alone does not recover changes missed during a disconnect; the application may need a resume token or last-seen position.
A long-lived stream can avoid repeatedly starting calls, but it is difficult to load-balance after it starts and may complicate debugging and recovery. Do not choose streaming merely to reduce call count; first check whether the application naturally has a long-lived flow. (core concepts, performance guidance)
Why do deadlines, cancellation, and errors matter?
If a distributed call never returns, it can tie up client and server resources. A gRPC deadline is the point after which the client stops waiting for a call. Many language APIs do not set a deadline by default, so clients should provide a realistic limit based on expected service latency and the caller’s wait tolerance. The exact API and propagation behavior depend on the language implementation. (deadlines)
After the deadline, a call can finish with DEADLINE_EXCEEDED. A client can also cancel when it no longer needs the result. Do not assume this automatically interrupts application-handler code. For long-running work, the server should check cancellation and stop database or downstream calls that it started when possible. Deadline and cancellation propagation to downstream RPCs may be automatic or may require explicit wiring, depending on the language. (cancellation)
Errors use gRPC status codes. Invalid arguments, permission denial, unimplemented methods, temporary unavailability, and deadline expiry can be distinguished. A client should not retry every error in the same way; consider both the status and the operation’s meaning. For example, if an order was processed but its response was lost, blindly retrying could create a duplicate. If retries are needed, design idempotency keys or deduplication, along with attempt limits and backoff. (error handling, retry guide)
Criteria for choosing gRPC
gRPC generates code from service contracts, supports shared types across languages, and explicitly models streaming calls. These features can help when many internal services call one another or a data flow persists over a connection. The team must also manage .proto changes, code-generation tools, runtime libraries, and proxies and observability tools that support HTTP/2. Binary messages are less readable in logs than plain-text JSON, so teams need suitable diagnostic tools and safe logging rules. (core concepts, HTTP/2 protocol)
Per-call information such as authentication and tracing data can travel as gRPC metadata. Metadata uses HTTP/2 headers and trailers, so account for size limits and avoid exposing tokens or personal data in logs. Configure transport protection and caller authentication separately; adding metadata by itself does not secure a connection. (metadata, authentication)
| Situation | Option to consider first | Why and conditions |
|---|---|---|
| Internal service calls, multiple languages, strict type contracts | gRPC | Generated clients and service interfaces help; the team must operate schema changes and build tooling |
| Browser-facing public API where manual inspection and general HTTP tooling matter | REST/JSON or gRPC-Web / HTTP JSON transcoding | Do not assume browsers can call standard HTTP/2 gRPC directly. gRPC-Web needs compatible client and server/proxy configuration; check the exact features supported by your stack |
| Clients need to request flexible combinations of fields or data relationships | GraphQL or another query API | gRPC methods model operations defined in the contract; per-query field selection needs a separate design |
| Simple CRUD exposed to many external consumers | REST/JSON | Familiar HTTP representations and tooling may help; compare against authentication, versioning, and caching requirements |
The table is not a universal ranking. A browser client may use gRPC-Web or gRPC JSON transcoding, but verify server configuration, CORS, proxies, and support for the required streaming modes. gRPC-Web uses a browser-oriented protocol that differs from standard HTTP/2 gRPC. (gRPC-Web basics, protocol differences)
Before adopting gRPC
Have you selected runtimes and code-generation plugins for the client and server languages?
Are `.proto` changes reviewed and field numbers/types managed compatibly?
Have you set suitable deadlines, cancellation handling, and error-status mapping?
Have you defined stream completion, reconnection, duplication, and slow-consumer behavior?
Are TLS and authentication configured safely, with sensitive metadata excluded from logs?
Do proxies and load balancers pass HTTP/2, gRPC status trailers, and the needed streaming modes?
If there is a browser client, have you verified the gRPC-Web or JSON-transcoding path against actual needs?
gRPC is not a choice to make based on the slogan “faster API.” Weigh the value of contract-based, multilingual service communication and streaming against the work of code generation, protocol support, and diagnostics. Even for a small internal RPC, making deadlines, error behavior, and compatibility rules explicit helps teams manage failures and changes predictably.
References
[gRPC introduction](https://grpc.io/docs/what-is-grpc/introduction/)
[Core concepts, architecture, and lifecycle](https://grpc.io/docs/what-is-grpc/core-concepts/)
[Deadlines](https://grpc.io/docs/guides/deadlines/)
[Cancellation](https://grpc.io/docs/guides/cancellation/)
[Error handling](https://grpc.io/docs/guides/error/)
[Metadata](https://grpc.io/docs/guides/metadata/)
[Authentication](https://grpc.io/docs/guides/auth/)
[Performance best practices](https://grpc.io/docs/guides/performance/)
[Protobuf proto3 language guide](https://protobuf.dev/programming-guides/proto3/)
[gRPC retry guide](https://grpc.io/docs/guides/retry/)
[gRPC HTTP/2 protocol](https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md)
[gRPC-Web basics](https://grpc.io/docs/platforms/web/basics/)
[gRPC-Web protocol differences](https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-WEB.md)