AlgoViz

gRPC

medium 27 min

gRPC 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

one streamYour codeclient sideStubgeneratedChannelHTTP/2gRPC serverdecodesYour methodserver sidePostgreSQL

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

Our systemClient1 callService A1 callService B1 callPostgreSQL

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

    critical

    The default is to wait forever. One stuck server ties up threads in every caller.

    Wrong
    stub.GetUser(request)
    Right
    stub.GetUser(request, timeout=0.3)
  • A channel for each call

    major

    Every call pays for DNS, TCP and TLS, and servers collect connections.

    Wrong
    def get(id):    with open_channel(addr) as ch:        return Stub(ch).GetUser(id)
    Right
    stub = Stub(open_channel(addr))   # oncedef get(id):    return stub.GetUser(id, timeout=0.3)
  • Reusing a field number

    critical

    Old clients read the new value as the old field, without an error.

    Wrong
    // was: string phone = 4;int64 points = 4;
    Right
    reserved 4;reserved "phone";int64 points = 5;
  • Alerting on HTTP status

    major

    Failed calls often travel with HTTP 200. The status is in the trailers.

    Wrong
    error = http_status >= 500
    Right
    error = 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.