gRPC
medium 27 mingRPC lets one program call a method in another program as if it were local.
See it run
One call from method to method, the bytes it sends, the time it may take and the server it reaches.
Operations
One unary call
From a method call in one program to a method in another, and back.
Step 1 of 5
Call the stub
stub.GetUser
Your code calls GetUser like a local method. The channel was opened when the program started.
Step 1: Call the stub
channel = open_channel("dns:///users") # once per servicestub = UserServiceStub(channel)try: user = stub.GetUser(Request(user_id="u-42"), timeout=1.0, metadata=auth)except RpcError as e: handle(e.code())- Costs
- 1 round trip
- Gives
- Typed answer
- Connection
- shared by many calls
Keep the channel. Opening one for each call pays for a new connection and handshake every time.
In the real world
The same grpc doing real jobs. Pick one and step through it.
The database is slow, and every layer retries four times.
Step 1 of 4
One click
1 query
The client calls A, A calls B, B reads the database.
Step 1: One click
Common mistakes
The bugs interviewers watch for, with the fix beside each.
No deadline
criticalThe default is to wait forever. One stuck server ties up threads in every caller.
Wrongstub.GetUser(request)Rightstub.GetUser(request, timeout=0.3)A channel for each call
majorEvery call pays for DNS, TCP and TLS, and servers collect connections.
Wrongdef get(id): with open_channel(addr) as ch: return Stub(ch).GetUser(id)Rightstub = Stub(open_channel(addr)) # oncedef get(id): return stub.GetUser(id, timeout=0.3)Reusing a field number
criticalOld clients read the new value as the old field, without an error.
Wrong// was: string phone = 4;int64 points = 4;Rightreserved 4;reserved "phone";int64 points = 5;Alerting on HTTP status
majorFailed calls often travel with HTTP 200. The status is in the trailers.
Wrongerror = http_status >= 500Righterror = grpc_status in ("UNAVAILABLE", "INTERNAL", "UNKNOWN", "DEADLINE_EXCEEDED", "DATA_LOSS")
Interview tips
How to explain it
- One .proto, code for both sides.
- Numbers on the wire, HTTP/2 underneath.
- Four call shapes and a deadline.
Say in an interview
- Deadline on every call, passed on.
- Retries by method, in one layer.
- Balance calls, not connections.
Reach for it when
- Both sides are yours.
- Several languages share a contract.
- Programs stream to each other.
Look elsewhere when
- Browsers call it directly.
- A CDN should keep the answers.
- Partners want plain HTTP and JSON.