Remote procedure calls (RPC)
medium 26 minA remote procedure call lets a program call a function that runs on another machine, using code that looks like a local call.
Video lesson · Chapter 1 of 6
Make one unary call
Remote procedure call
1:17Reel
Theory
Read or listen first. About 2 min.
What it is
In a normal program, one function calls another in the same memory. A remote procedure call, or RPC, keeps that style when the second function lives on another machine. You write user = client.GetUser(id="123"), and the answer comes back as an ordinary value.
Between the two sit stubs: pieces of code, usually generated from a contract. The client stub turns the call into bytes and sends them. The server stub turns bytes back into arguments and calls the real function. The reply makes the same trip in reverse.
Why it exists
Without RPC, every team would write its own code to open connections, pack data, match replies to requests and report errors. RPC does that once, and the contract lets two programs in different languages agree on types before they run.
The danger is in the comfort. A local call is fast and either runs or does not. A remote call takes far longer, can fail halfway, and sometimes leaves you not knowing whether it ran. Good RPC use keeps the convenient syntax and still treats the call as remote.
A short history
January 1976
RFC 707 by James White proposes a procedure call model for using programs on other computers of the ARPA network.
1981
Bruce Jay Nelson is generally credited with coining the term remote procedure call. With Andrew Birrell at Xerox PARC came Lupine, which generated stubs automatically.
April 1988
RFC 1050 specifies Sun's RPC protocol.
April 2007
Thrift, developed at Facebook, is released as open source. It later becomes an Apache project.
July 2008
Google releases Protocol Buffers as open source.
February 2015
Google open-sources gRPC, an RPC framework over HTTP/2, after using an internal system called Stubby for over a decade.
Words to know
- Stub
- Client-side code with the same methods as the remote service. It packs and sends calls.
- Skeleton
- The older name for the server-side stub that unpacks calls.
- Marshalling
- Turning values into bytes for the wire. Also called serialisation.
- IDL
- Interface definition language: the contract, such as a .proto file.
- Deadline
- The moment after which the caller no longer wants the answer.
- Idempotent
- Safe to repeat: doing it twice has the same effect as once.
- Unary call
- One request and one response.
How it works
Step through the idea, or press Play.
Agree on a contract. Methods and messages in one file, code generated for both sides
Understand it
Start here
The Mars rover story
Imagine one button in a control room on Earth and one rover on Mars. Pressing the button feels like using a camera on the desk. The camera is very far away.
A button that looks local, work that is remote, and a trip that can fail in either direction.
The idea
What you write and what happens
| What you write | What actually happens |
|---|---|
user = client.GetUser(id="123") | 1. Serialise the request to binary |
| 2. Use an open HTTP/2 connection, or open one | |
| 3. Send the request | |
| 4. Wait for the response, up to a deadline | |
| 5. Deserialise the response, or raise an error | |
| 6. Return an object |
One call, there and back
Why teams like it
Familiar
It looks like a local function call.
Typed
Code generation catches wrong names and types early.
Compact
Binary serialisation is usually smaller than JSON.
Streaming
gRPC supports streams in both directions.
Any language
A Go server can serve a Java client.
Popular frameworks
| Framework | Origin | Notes |
|---|---|---|
| gRPC | Protocol Buffers over HTTP/2 | |
| Apache Thrift | Own IDL, several formats and transports | |
| tRPC | TypeScript community | Types shared between a TypeScript server and client, no IDL file |
| JSON-RPC | Open specification | A small JSON message format for calls |
| XML-RPC | Older web services | Calls as XML over HTTP, mostly legacy |
Process
How RPC is built
- 1
Define the service
Write a .proto file with methods and messages.
- 2
Generate code
The protoc compiler produces client and server stubs.
- 3
Implement the server
Fill in the generated interface with business logic.
- 4
Call from the client
Create a channel and a stub, then call methods with a deadline.
syntax = "proto3";package user;service UserService { rpc GetUser (GetUserRequest) returns (User); rpc CreateUser (CreateUserRequest) returns (User); rpc ListUsers (ListUsersRequest) returns (ListUsersResponse); // one page per call rpc StreamUsers (ListUsersRequest) returns (stream User); // server streaming rpc UpdateUser (UpdateUserRequest) returns (User); rpc DeleteUser (DeleteUserRequest) returns (Empty);}message User { string id = 1; string name = 2; string email = 3; int64 created_at = 4;}message GetUserRequest { string id = 1; }message CreateUserRequest { string name = 1; string email = 2; string request_id = 3; }message ListUsersRequest { int32 page_size = 1; string page_token = 2; }message ListUsersResponse { repeated User users = 1; string next_page_token = 2; }message UpdateUserRequest { string id = 1; optional string name = 2; optional string email = 3; }message DeleteUserRequest { string id = 1; }message Empty {}request_id lets the server recognise a repeated create. optional lets it tell "not sent" from "set to empty".# Server: needs grpcio and the generated user_pb2 modulesclass UserServicer(user_pb2_grpc.UserServiceServicer): def __init__(self): self.users = {} def GetUser(self, request, context): if request.id not in self.users: context.abort(grpc.StatusCode.NOT_FOUND, f"User {request.id} not found") return self.users[request.id] def UpdateUser(self, request, context): if request.id not in self.users: context.abort(grpc.StatusCode.NOT_FOUND, f"User {request.id} not found") user = self.users[request.id] if request.HasField("name"): user.name = request.name if request.HasField("email"): user.email = request.email return user# Clientwith grpc.insecure_channel("localhost:50051") as channel: # local demo only, use TLS elsewhere stub = user_pb2_grpc.UserServiceStub(channel) try: user = stub.GetUser(user_pb2.GetUserRequest(id="123"), timeout=0.5) except grpc.RpcError as err: if err.code() == grpc.StatusCode.NOT_FOUND: user = None else: raiseOn the wire
Protocol Buffers
Binary
Usually smaller than JSON, because field names are not sent.
Schema first
The .proto file is the source of the types.
Strongly typed
Generated classes in many languages.
Compatible
Old and new programs can talk, if you follow the field rules.
GetUserRequest with id 123, byte by byte
| Bytes | Meaning |
|---|---|
0a | Tag: field 1, length-delimited: (1 << 3) | 2 = 10 |
03 | Length: 3 bytes follow |
31 32 33 | The text "123" |
{"id":"123"} is 12 bytes.Message bytes on a gRPC stream
Changing a message safely
| Change | Safe? | Why |
|---|---|---|
| Add a field with a new number | Yes | Old readers skip it |
| Rename a field, same number | On the wire, yes | Names are not sent, but generated code and JSON change |
| Remove a field | Yes, if you reserve its number | Nobody may reuse it later |
| Reuse a number for something else | No | Old bytes would be read as the wrong thing |
| Change a type | Usually no | Only a few type pairs are compatible |
Transport
gRPC and HTTP/2
What HTTP/2 brings
| Feature | What it does |
|---|---|
| Multiplexing | Many calls share one connection at the same time |
| Header compression | Repeated headers cost few bytes |
| Bidirectional streaming | Both sides can send during one call |
| Binary framing | Messages travel as small binary frames |
/user.UserService/GetUser: package, service, method.A unary call
Shapes
Four kinds of call
| Kind | Pattern | Example |
|---|---|---|
| Unary | One request, one response | GetUser |
| Server streaming | One request, many responses | Download a long list of users |
| Client streaming | Many requests, one response | Upload readings, get one summary |
| Bidirectional | Both sides send independently | Live chat or collaboration |
Server streaming
The hard part
When no reply comes
The caller waits and nothing arrives. Three different things may have happened, and they look the same from the caller's side.
Three failures, one symptom
request_id. See idempotency.How often does the function run?
| Promise | How | Risk |
|---|---|---|
| At most once | Never retry | It may not have run |
| At least once | Retry until a reply | It may run several times |
| Effectively once | Retry, and the server ignores repeats | The server must remember request ids |
Why chatty calls hurt
Scale
Balance calls, not connections
gRPC keeps a connection open and sends many calls through it. A balancer that only picks a server when a connection opens may leave one server with all the work. Use a proxy that understands HTTP/2, or balance in the client.
One connection, three servers
Choose
gRPC or REST?
| Aspect | gRPC | REST |
|---|---|---|
| Protocol | HTTP/2 | Any HTTP version |
| Format | Binary (Protobuf) by default | Usually text (JSON, sometimes XML) |
| Contract | Required (.proto) | Optional (OpenAPI) |
| Streaming | Built in, both directions | Not part of the style; possible with chunked responses or server-sent events |
| Browser | Needs gRPC-Web and usually a proxy | Native |
| Caching | Calls are POST, so HTTP caches do not help | GET responses can be cached |
| Best for | Internal microservices, polyglot systems, streaming, high performance | Public APIs, browser clients, simple CRUD, easy to read by people |
A quick choice
Rules
Best practices
- 1
Use deadlines
Always. A call without one can hold resources for as long as the other side hangs.
- 2
Handle errors
Use the right status code, such as NOT_FOUND or UNAVAILABLE, and add details callers can act on.
- 3
Version your APIs
Put a version in the package, for example
user.v1, and keep changes compatible. See API versioning. - 4
Retry with care
Exponential backoff with jitter, a limit, and only for calls that are safe to repeat. See retries.
- 5
Use load balancing
Spread calls, not only connections, over the instances.
Summary
The whole topic in one minute.
RPC makes a remote function look local. Stubs generated from a contract serialise the call, send it, run it on the server and return the result. gRPC does this with Protocol Buffers over HTTP/2 and adds streaming.
The syntax is local and the physics is not. Set a deadline on every call, handle status codes, retry only what is safe to repeat, keep messages compatible, and balance calls rather than connections.
- RPC: a remote function with the syntax of a local call.
- Contract, generated stubs, serialise, send, run, return.
- gRPC is Protocol Buffers over HTTP/2, with four kinds of call.
- No reply does not mean it did not run.
- Deadline on every call, retries only when safe, never reuse field numbers.