An introduction to gRPC

A Practical Introduction to gRPC (Part 1)

TL;DR: gRPC simplifies communication between desktop applications and embedded devices by generating client and server code from a single shared contract, eliminating hand-written serialization and parsing.

Nearly every medical device and industrial instrument we build has the same seam in it: a desktop application on one side, a piece of hardware on the other, and a steady flow of commands and data that must cross between them. The desktop is often C# on Windows; the device might be C++ or Python on embedded Linux. Someone must define what the bytes look like, and then two teams must implement that definition, separately, in two languages.

The Problem: Two Implementations of One Format

The hand-rolled approach looks like this. The desktop application has a hand-written serializer. The device firmware has a hand-written parser. The "contract" between them is a byte layout on a wiki page. That is two implementations of one format, and over time they drift. Usually, you find out during integration testing, and occasionally you find out in the field.

gRPC inverts this. You write the contract once, in a .proto file, and generate both sides from it. The client gets a generated stub to call; the device gets a generated service base class to implement. Nobody writes wire code, so there is nothing to drift.

Where gRPC Came From

gRPC grew out of Stubby, Google's internal RPC framework, which was used between Google's own services and never released. Its open-source successor reached a stable 1.0 release in August 2016, and gRPC is now a Cloud Native Computing Foundation (CNCF) project, governed outside Google, with maintained implementations across many languages. Its design goals come from running services at scale: a strict contract, generated code, and a transport that multiplexes many calls over one connection.

Illustration of gRPC connecting a laptop engineering station (gRPC client) over TCP/IP and HTTP/2 to gRPC servers on a power plant and a robotic liquid handler, above a five-step pipeline: define, generate code, serialize and send, receive and deserialize, handle request.

The bottom half of that graphic is the whole pipeline in five steps. You define messages and services in a .proto file. The protoc compiler generates client and server code in each language you need. At runtime the client serializes a request object to compact protobuf binary and sends it over HTTP/2. The server receives and deserializes it back into an object of its own language, and your code handles the request. The top half makes the point that matters for us: the server on the other end of the wire could be a turbine controller or a medical instrument, and the client code does not change shape.

The Contract: Protocol Buffers

Protocol Buffers (protobuf) is both the interface definition language and the default serialization format for gRPC. Here is the complete service from the demo application, minus four trivial messages that have one field or none:

device.proto

syntax = "proto3";
package powerstation.v1;
option csharp_namespace = "PowerStation";

service PowerStation {
  rpc GetDeviceInfo (DeviceInfoRequest) returns (DeviceInfo);
  rpc StartPlant (StartRequest) returns (StartAck);
  rpc StopPlant  (StopRequest)  returns (StopAck);
  rpc SubscribeTelemetry (SubscribeRequest)
      returns (stream TelemetryFrame);   // the only difference
}

message DeviceInfo   { string firmware = 1; string interface_version = 2; }
message StartRequest { string operator_id = 1; }
message StartAck     { bool accepted = 1; string state = 2; }
message TelemetryFrame {
  uint32 sequence = 1;      float pressure_kpa = 2;
  float  temperature_c = 3; string state = 4;
}

There is not much vocabulary to learn. The package namespaces every type on the wire. Language option lines shape the generated code only; they never change a byte on the wire. A message is a typed record in which every field has a number. A service groups rpc methods, each of which takes exactly one message and returns exactly one message. That last rule feels fussy at first, but the message is your extension point: when a new requirement arrives, you add a field and no generated method signature changes anywhere.

Notice what separates the command path from the telemetry path: a single keyword. StartPlant is an ordinary request/response call. SubscribeTelemetry puts stream in front of its response type, and that one word changes the generated code on both sides.

Compact Binary, Not Self-Describing

Here is one real TelemetryFrame taken from a Wireshark capture of the demo (more on that below). On the wire it is 22 bytes. The same four values as compact JSON are 81 bytes.

One TelemetryFrame, decoded by hand

08 A3 7D                    field 1, varint     sequence      = 16035
15 70 DF 49 44              field 2, 32-bit     pressure_kpa  = 807.49
1D 7E 6C 9F 43              field 3, 32-bit     temperature_c = 318.85
22 07 52 55 4E 4E 49 4E 47  field 4, 7 bytes    state         = "RUNNING"

Each field starts with a single tag byte that packs the field number and the wire type (0x15 is field 2, wire type 5, a 32-bit value), followed by the value. There are no field names, no quotes and no punctuation. The trade-off is that protobuf is not self-describing: the receiver must have the same .proto to know that field 2 means pressure in kilopascals. That constraint is exactly what makes the contract real.

Field Numbers Are the Contract

This is the part architects should think hardest about. Field numbers, not names, are what travel on the wire. Renaming a field is free; changing its number is a breaking change.

Safe to shipBreaks the other side
Add a field with a new numberChange an existing field's number
Stop populating a fieldChange an existing field's type
Rename a field in the .protoReuse a retired number
Mark a retired number reservedDelete a field without reserving it

Suppose version 1 of a message sent pressure in psi as field 2, and version 2 switches to kilopascals:

message TelemetryFrame {
  uint32 sequence = 1;
  // v1: float pressure_psi = 2;
  reserved 2;
  reserved "pressure_psi";
  float pressure_kpa = 3;
}

The two reserved lines do two different jobs. reserved 2 protects the wire: an old device in the field still sends field 2 meaning psi, and if a new field ever took number 2, the receiver would decode those bytes as the new type with no error, just wrong values. reserved "pressure_psi" protects people: the name never travels, but reintroducing it under a new number would make old code, logs and JSON output silently mean something else. Both become compile errors for anyone who compiles the file afterwards.

Keeping Two Codebases on One Contract

In medical device work the .proto is frequently owned by another team or another company, typically the hardware vendor, and in a regulated product the GUI and firmware are often verified together as a pair. Three practices help:

  • Do not hash the file text. Line endings, whitespace and comments change a hash without changing a single byte on the wire. Compare a version string the vendor bumps on purpose.
  • Decide the older-firmware policy on paper. A new GUI will eventually meet a device that has not been updated. Refuse, warn or run degraded, and make the error say what to update.
  • Know whether a change is additive or breaking. Pull the .proto from a tagged release and diff it against the previous tag in CI (buf breaking does this). Additive means rebuild; breaking means client code changes.

The demo implements this as a startup handshake: GetDeviceInfo is the first call the client makes, and it checks the interface_version the device reports before it sends any command.

One Definition, Every Language

protoc, together with the gRPC plugin for each language, turns one .proto into two artifacts per language: a client stub with one method per rpc, which you instantiate and call, and an abstract service base class with one virtual method per rpc, which you inherit and override. Message types come out as ordinary classes.

In C#, the Grpc.Tools package runs code generation inside MSBuild on every compile, so the .proto is just another build input and no generated code is checked into source control. In Python, python -m grpc_tools.protoc writes device_pb2.py (messages) and device_pb2_grpc.py (the service).

On the client side there are three objects, and they come from two places. The channel comes from the gRPC library and owns the connection; the stub is generated from your .proto; a call is one method on the stub:

C# client (Grpc.Net.Client)

// CHANNEL: from the gRPC library. Create once, keep it.
var channel = GrpcChannel.ForAddress("http://127.0.0.1:5001");

// STUB: generated from device.proto. Cheap and thread-safe.
var client = new PowerStation.PowerStationClient(channel);

// CALL: one method per rpc
var ack = await client.StartPlantAsync(
    new StartRequest { OperatorId = "harry" });

Python client (grpcio)

channel = grpc.insecure_channel("127.0.0.1:5001")
stub = device_pb2_grpc.PowerStationStub(channel)
ack = stub.StartPlant(device_pb2.StartRequest(operator_id="harry"))

The shape is identical in both languages because both stubs came from the same file. If you take one operational rule from this section, it is this: do not create a channel per call. The channel owns the TCP connection, the HTTP/2 session and TLS, so it is expensive; one channel serves any number of stubs and concurrent calls.

The server side is the other half. You inherit the generated base and override one method per rpc. The extra ServerCallContext parameter carries the caller's deadline, a cancellation token and request metadata:

C# HAL (ASP.NET Core)

public class PowerStationService : PowerStation.PowerStationBase
{
    private readonly PlantSim _plant;          // the simulated hardware
    public PowerStationService(PlantSim plant) => _plant = plant;

    public override Task<StartAck> StartPlant(
        StartRequest req, ServerCallContext ctx)
    {
        _plant.Start();
        return Task.FromResult(
            new StartAck { Accepted = true, State = "STARTING" });
    }
}

That _plant field is the entire hardware abstraction layer. The generated base owns the wire; the only code you write is the hand-off to whatever actually drives the device.

Four Call Shapes on One Connection

You choose a call type per rpc by where you put the stream keyword:

  • Unary: one request, one response. Commands and queries; this is the default.
  • Server streaming: one request, many responses. Telemetry, progress, tailing a log.
  • Client streaming: many requests, one response. Uploads and batched samples pushed by the caller.
  • Bidirectional streaming: both sides send on one long-lived call.

Streaming in gRPC does not feel bolted on because of what sits underneath it: HTTP/2. HTTP/2 multiplexes many independent streams over a single TCP connection, so a long-lived telemetry subscription can stay open while commands come and go on the same socket. Messages travel as length-prefixed binary frames, so message boundaries are the transport's job, not yours. And HTTP/2 trailers let the final status arrive after the last message, which is what lets a stream report success or failure cleanly at the end.

What You Get for Free

These are the features a hand-rolled protocol could technically have and almost never does:

  • Deadlines: an absolute time budget that travels with every call, so the server can give up on work nobody is waiting for. In C#: deadline: DateTime.UtcNow.AddSeconds(5); in Python: timeout=5.
  • Cancellation: when the client cancels, the server's cancellation token fires.
  • Status codes: a standard set, not a string in a body.
  • Metadata: key/value headers and trailers per call, for correlation IDs and auth tokens.
  • TLS: configured once on the channel, not per message.

Status codes deserve emphasis because they are part of the contract. A client written by a different team, in a different language, already knows what each one means:

Status codeWhat it tells the caller
INVALID_ARGUMENTThe request was malformed. Retrying it unchanged will not help.
FAILED_PRECONDITIONThe system is not in a state where this operation is valid.
DEADLINE_EXCEEDEDThe caller's time budget ran out before a reply arrived.
UNAVAILABLEThe server is unreachable or the connection dropped. Safe to retry.
CANCELLEDThe caller ended the call.

On the client, a failure surfaces as an exception: RpcException in C#, RpcError in Python, carrying the code and an optional detail string. Find the full list of codes at grpc.io/docs/guides/status-codes.

In Part 2, we'll cover the application that ties all of this together. You can also listen to the information in our on-demand webinar.