AlgoViz

Remote procedure calls (RPC)

medium 26 min

A 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

0:00 / 4:03

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

  1. January 1976

    RFC 707 by James White proposes a procedure call model for using programs on other computers of the ARPA network.

  2. 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.

  3. April 1988

    RFC 1050 specifies Sun's RPC protocol.

  4. April 2007

    Thrift, developed at Facebook, is released as open source. It later becomes an Apache project.

  5. July 2008

    Google releases Protocol Buffers as open source.

  6. 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.

Step 1 of 3

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.

Take a photo, from another planet
SENDINGEarthMars

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 writeWhat 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

App code on the order machine calls the client stub. The stub sends request bytes over HTTP/2 to the server stub on the user machine, which calls GetUser. GetUser queries the database. The reply goes back through the server stub as bytes, then the client stub hands a User to the app code.
Blue is the request, brown is the answer. Client, stub, network, server stub (skeleton), server.

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

FrameworkOriginNotes
gRPCGoogleProtocol Buffers over HTTP/2
Apache ThriftFacebookOwn IDL, several formats and transports
tRPCTypeScript communityTypes shared between a TypeScript server and client, no IDL file
JSON-RPCOpen specificationA small JSON message format for calls
XML-RPCOlder web servicesCalls as XML over HTTP, mostly legacy

Process

How RPC is built

  1. 1

    Define the service

    Write a .proto file with methods and messages.

  2. 2

    Generate code

    The protoc compiler produces client and server stubs.

  3. 3

    Implement the server

    Fill in the generated interface with business logic.

  4. 4

    Call from the client

    Create a channel and a stub, then call methods with a deadline.

Text
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 {}
The contract. request_id lets the server recognise a repeated create. optional lets it tell "not sent" from "set to empty".
Python
# 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:            raise
Create the channel once and reuse it. The example closes it only because the program ends.

On 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

BytesMeaning
0aTag: field 1, length-delimited: (1 << 3) | 2 = 10
03Length: 3 bytes follow
31 32 33The text "123"
5 bytes. gRPC puts a 5 byte prefix in front: 1 for a compression flag and 4 for the length. The JSON {"id":"123"} is 12 bytes.

Message bytes on a gRPC stream

5⏟prefix+1+1+3⏟tag, length, text=10 bytes\underbrace{5}_{\text{prefix}} + \underbrace{1 + 1 + 3}_{\text{tag, length, text}} = 10 \text{ bytes}
HTTP/2 frame headers and request headers come on top, so for tiny messages the saving is smaller than it looks.

Changing a message safely

ChangeSafe?Why
Add a field with a new numberYesOld readers skip it
Rename a field, same numberOn the wire, yesNames are not sent, but generated code and JSON change
Remove a fieldYes, if you reserve its numberNobody may reuse it later
Reuse a number for something elseNoOld bytes would be read as the wrong thing
Change a typeUsually noOnly a few type pairs are compatible

Transport

gRPC and HTTP/2

What HTTP/2 brings

FeatureWhat it does
MultiplexingMany calls share one connection at the same time
Header compressionRepeated headers cost few bytes
Bidirectional streamingBoth sides can send during one call
Binary framingMessages travel as small binary frames
A call to GetUser is a POST to the path /user.UserService/GetUser: package, service, method.

A unary call

The status comes at the end, in trailers, so a stream can fail after it has already sent messages.

Shapes

Four kinds of call

KindPatternExample
UnaryOne request, one responseGetUser
Server streamingOne request, many responsesDownload a long list of users
Client streamingMany requests, one responseUpload readings, get one summary
BidirectionalBoth sides send independentlyLive chat or collaboration

Server streaming

For reaching browsers and phones, see real-time APIs.

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

GetUser is safe to repeat. CreateUser is not, unless the server recognises the request_id. See idempotency.

How often does the function run?

PromiseHowRisk
At most onceNever retryIt may not have run
At least onceRetry until a replyIt may run several times
Effectively onceRetry, and the server ignores repeatsThe server must remember request ids

Why chatty calls hurt

100×1 ms=100 msone batch call≈1 ms+work100 \times 1\text{ ms} = 100\text{ ms} \qquad \text{one batch call} \approx 1\text{ ms} + \text{work}
Assumed 1 ms per sequential call inside one data centre. A loop that is free locally is slow remotely, so offer a batch method.

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

The client stub on the order machine has one connection with many calls to a proxy that understands HTTP/2. The proxy spreads the calls over user machines 1, 2 and 3.
How the client finds the servers is service discovery. How traffic is spread is load balancing.

Choose

gRPC or REST?

AspectgRPCREST
ProtocolHTTP/2Any HTTP version
FormatBinary (Protobuf) by defaultUsually text (JSON, sometimes XML)
ContractRequired (.proto)Optional (OpenAPI)
StreamingBuilt in, both directionsNot part of the style; possible with chunked responses or server-sent events
BrowserNeeds gRPC-Web and usually a proxyNative
CachingCalls are POST, so HTTP caches do not helpGET responses can be cached
Best forInternal microservices, polyglot systems, streaming, high performancePublic APIs, browser clients, simple CRUD, easy to read by people
The full comparison, with GraphQL, is in REST, GraphQL and gRPC.

A quick choice

Rules

Best practices

  1. 1

    Use deadlines

    Always. A call without one can hold resources for as long as the other side hangs.

  2. 2

    Handle errors

    Use the right status code, such as NOT_FOUND or UNAVAILABLE, and add details callers can act on.

  3. 3

    Version your APIs

    Put a version in the package, for example user.v1, and keep changes compatible. See API versioning.

  4. 4

    Retry with care

    Exponential backoff with jitter, a limit, and only for calls that are safe to repeat. See retries.

  5. 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.

Sources