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.
See it run
A call that looks local: pack it, send it, run it, return it, and survive the reply that is lost.
Operations
One unary call
Follow `client.GetUser(id="123")` through both stubs and back.
Step 1 of 9
Call the stub
The app writes client.GetUser(id="123"). It looks like a local call.
Step 1: Call the stub
def get_user(self, id, timeout): data = GetUserRequest(id=id).SerializeToString() reply = self.channel.send("/user.UserService/GetUser", data, timeout) return User.FromString(reply)def on_call(path, data): # server stub request = GetUserRequest.FromString(data) user = handler.GetUser(request) return user.SerializeToString()- Network trips
- One
- Safe to retry
- Yes, a read
- Local call
- no network
Name the parts in order: client, stub, network, server stub, server.
In the real world
The same remote procedure calls doing real jobs. Pick one and step through it.
A loop that is free locally becomes slow remotely. Assumed: 1 ms per call.
Step 1 of 2
One call per friend
100 ms
The page asks for 100 friends, one after another: 100 calls of 1 ms.
Step 1: One call per friend
Common mistakes
The bugs interviewers watch for, with the fix beside each.
No deadline
criticalgRPC sets none by default. One hanging server can hold every caller's resources.
Wrongstub.GetUser(request)Rightstub.GetUser(request, timeout=0.5)Blind retry of a write
criticalThe first attempt may have run. The retry creates a second order.
Wrongretry(lambda: stub.CreateOrder(order))Rightorder.request_id = new_id()retry(lambda: stub.CreateOrder(order)) # server ignores repeatsAny stream error means the end
majorTreating a broken connection as the end shows half a list as if it were complete.
Wrongtry: for user in stream: users.append(user)except grpc.RpcError: passRightfor user in stream: users.append(user) # an error is raised, not hiddenReusing a field number
criticalOld data and old programs read the bytes with the old meaning.
Wrongstring score = 3; // was emailRightreserved 3;string score = 6;
Interview tips
How to explain it
- A remote function with local syntax.
- Contract, stubs, serialise, send, run, return.
- gRPC: Protobuf over HTTP/2.
Memory trick: SCSR
- Serialise the data.
- Call over the wire.
- Server runs it, Return the result.
gRPC fits
- Internal microservices.
- Streaming and high performance.
- Several languages.
REST fits
- Public APIs and browsers.
- Simple CRUD.
- Requests people can read.