Skip to content

RPC and gRPC: calls with a contract and a deadline

A remote procedure call, RPC, makes a call to another machine look like a call to a function. The caller writes stock.Reserve(item, 2) and gets a result back. A generated piece of code, the stub, turns the arguments into bytes, sends them, waits, and turns the answer back into a value.

The convenience is real, and so is the danger. A function call in the same process takes nanoseconds and cannot half-succeed. A remote call crosses a network: it takes a round trip, it can be lost, the server can crash after doing the work, and the answer can be late. Microsoft’s microservices guidance warns about the result of ignoring this: a direct conversion of in-process method calls into RPC calls gives communication that is chatty and does not perform well in distributed systems.

Mental model. An RPC is a phone call that has been dressed as a function call. The dress is good for the code that you write. It does not change that the line can drop, and that you can hang up without knowing whether the other person acted.

gRPC is a widely used RPC system. Its documentation says that it uses protocol buffers as the interface definition language for describing both the service interface and the structure of the payload messages. You write the contract once, and the gRPC tools generate the client and server code from it, so that both sides are written against the same description.

A gRPC service can offer four kinds of call:

Kind What is sent
Unary One request, one response, like a normal function call
Server streaming One request, and a stream of messages back
Client streaming A stream of messages sent to the server, then one response
Bidirectional streaming Both sides send a sequence of messages, and the two streams work independently

With a streaming call, a server can send many messages on one call, and the client does not need to ask for each one.

The gRPC specification maps a call onto HTTP/2, the version that carries many streams on one connection, which the HTTP versions lesson described. A call is an HTTP/2 request with the method POST and a path made of the service and the method, /Service/Method, with the content type application/grpc. Each message is sent with a one-byte flag for compression and a four-byte length in front of it. The specification uses the HTTP/2 stream id as the identifier of the call.

The status of the call is not in the first line of the response. A gRPC response uses HTTP status 200, and the outcome is sent in the trailers, the header fields that come after the messages, as grpc-status and grpc-message. The specification says that the status must be sent in trailers even if the status code is OK. A trace that shows a 200 on a failed call is not wrong; the status is further on.

Two ideas of REST do not carry over. The path names an action, not a resource, and the method is always POST, so a gateway or a cache cannot tell from the method whether a call is safe to repeat. Whether a gRPC call can be repeated is a fact about the operation that the contract has to state, as the duplicate requests lesson argued for POST.

A call that can wait for ever is a call that holds a thread, a connection and a user for ever. gRPC’s guide says plainly that you should always explicitly set a realistic deadline in your clients. A deadline is a point in time after which the client is unwilling to wait for a response. A timeout is a length of time, and a timeout becomes a deadline when it is added to the current time.

When the deadline passes, the client gives up and fails the call with DEADLINE_EXCEEDED, and the server’s side of the call is cancelled. Either side can also cancel a call at any time, and a cancelled call stops, so that no more work is done for it.

The important case is a chain. A client calls a gateway, which calls the orders service, which calls the stock service. If each service started its own fresh timeout, the stock service could work for 500 ms to answer a call that the client abandoned after 300 ms. gRPC’s guide says that some implementations pass the deadline from an incoming call to the outgoing one, and that they send it as a time left, not as a clock time, so that machines do not need synchronised clocks. The code below does the same arithmetic with a fake clock.

C# exampleA 500 ms deadline passed down a chain of services
deadline-propagation.cs
// A deadline is a point in time. Each service passes on what is left of it, so a call down the chain
// gives up when the caller has already given up, instead of working for an answer nobody waits for.
using ShardCraft.Playground;
var clock = new FakeClock();
var deadline = clock.UtcNow + TimeSpan.FromMilliseconds(500); // the client waits at most 500 ms
Console.WriteLine($"client: deadline in {Left()} ms");
Work("gateway", 80);
Console.WriteLine($"gateway calls orders, deadline in {Left()} ms");
Work("orders", 120);
Console.WriteLine($"orders calls stock with {Left()} ms left");
Call("stock", needs: 250);
Console.WriteLine($"orders calls prices with {Left()} ms left");
Call("prices", needs: 300);
double Left() => (deadline - clock.UtcNow).TotalMilliseconds;
void Work(string name, int ms)
{
clock.Advance(TimeSpan.FromMilliseconds(ms));
Console.WriteLine($" {name} worked {ms} ms");
}
void Call(string name, int needs)
{
// A service that cannot finish inside what is left stops at the deadline: DEADLINE_EXCEEDED.
var spend = Math.Min(needs, (int)Left());
clock.Advance(TimeSpan.FromMilliseconds(spend));
Console.WriteLine(spend < needs
? $" {name} needed {needs} ms, stopped after {spend} ms: DEADLINE_EXCEEDED"
: $" {name} answered after {needs} ms");
}
Output
client: deadline in 500 ms
gateway worked 80 ms
gateway calls orders, deadline in 420 ms
orders worked 120 ms
orders calls stock with 300 ms left
stock answered after 250 ms
orders calls prices with 50 ms left
prices needed 300 ms, stopped after 50 ms: DEADLINE_EXCEEDED

This is the exact code that produced this output, run with the .NET SDK when the site was built. Nothing runs in your browser.

The client allows 500 ms. The gateway works for 80 ms and passes on 420 ms. Orders works for 120 ms, so stock gets 300 ms and answers after 250 ms. Then orders calls prices with 50 ms left, prices needs 300 ms, and the call stops after 50 ms with DEADLINE_EXCEEDED. The code in the page is never run in the browser: the output was produced by a CI run of the same file.

Check the arithmetic, and what an expired deadline tells the client.

Check your understanding: deadlines

This quiz needs JavaScript to check your answers.

Question 1 of 3

A client calls a gateway with a deadline of 500 ms. The gateway works for 80 ms and calls the orders service. Orders works for 120 ms and calls the stock service.

How much time does the stock service have to answer?

Enter a number and choose its unit.

Question 2 of 3

A gRPC client sets a deadline of 200 ms. At 200 ms the call fails with DEADLINE_EXCEEDED.

What does the client know?

Choose one answer.

Question 3 of 3

A client calls a service with a timeout of 250 ms. The service spends 40 ms on its own work, and then calls a second service.

What timeout does the second call carry if the time left is passed on?

Enter a number and choose its unit.

ms

What happens if the deadline is never set?

Section titled “What happens if the deadline is never set?”

Say orders calls prices without a deadline and prices becomes slow. Each call waits for as long as prices takes. Calls pile up in orders, holding their threads and connections, and the slowness spreads upstream: the reliability module is about this kind of failure, where one slow dependency drags down its callers. A deadline turns the wait into a bounded cost: the call fails at a known time, and the caller can fall back, retry within the time left, or tell its own caller.

A deadline is not a promise that the work stopped or never started. Cancelling takes time to reach the server, and a server that finished just after the deadline did the work. So a call that is retried after DEADLINE_EXCEEDED needs the same protection as any retried request.

  • An RPC makes a remote call look local. The network does not go away: calls cost round trips, can be lost and can half-succeed.
  • gRPC describes services with protocol buffers and offers four kinds of call: unary, server streaming, client streaming and bidirectional streaming.
  • A gRPC call is an HTTP/2 POST to /Service/Method, with length-prefixed messages, and its status arrives in the trailers.
  • A deadline is a point in time. Pass what is left to each call down the chain: 500 ms at the client, then 420 ms, then 300 ms, then 50 ms in the example.
  • DEADLINE_EXCEEDED means the client gave up. It does not say whether the work was done.

Next: polling and long polling, when the server has news but the client has to ask.

Your progress

Built by GhaziAlibi.

© ShardCraft. All rights reserved.