Core Concepts

REST vs RPC vs gRPC

How APIs fetch the same report

Free~18 min

A report API can express the same lookup in two ways. It can give each report an address and let callers read from it. Or it can offer a GetReport operation that takes the report ID. Both can return the same answer: report r42 is still running. Where the request says what to do affects how clients call it and how tools log, cache, or diagnose it.

One lookup, three interfaces

We'll read from the report's address first, then call a named operation in two ways.

Read from the report's address

The request puts the report ID in the URL. The method GET asks to read it, just as it would ask to read an article or a user profile.

GET /v1/reports/r42 HTTP/1.1
Host: api.example.com

The server returns HTTP 200 OK. The response body contains the report ID and status.

{
  "reportId": "r42",
  "status": "running"
}

The report is the resource, the thing the API identifies. The JSON is a representation, the data about that report the API sends back. This is resource-oriented HTTP.

REST, short for Representational State Transfer, is a broader architectural style. Requests are stateless when each carries the information needed to handle it, such as the report ID and credentials. Responses indicate whether a cache can reuse them. Links can guide the caller to its next action. A finished report might include a download link. Fielding's REST chapter

Tell the server which operation to run

Now send a request to POST /rpc. Several operations can share that address. The JSON body tells the server to run reports.get with report ID r42. JSON-RPC puts the operation name and its inputs in a standard wrapper and includes a request ID when the caller expects a reply.

{
  "jsonrpc": "2.0",
  "method": "reports.get",
  "params": { "reportId": "r42" },
  "id": 7
}

The response wraps the report in result.

{
  "jsonrpc": "2.0",
  "result": { "reportId": "r42", "status": "running" },
  "id": 7
}

The reply repeats id: 7 so the caller can match it to this request. Here, r42 identifies the report and 7 identifies the call. A write such as reports.start needs its own safe retry rule to prevent a second job. A remote procedure call, or RPC, is this way of asking another machine to run a named operation. JSON-RPC is one format for making that request. JSON-RPC 2.0 specification

Call the same operation through a generated client

gRPC is another way to make an RPC. The client and the report service share a definition of the operation and the data it accepts and returns. Code generated from that definition gives the caller a local method called GetReport. That generated client is sometimes called a stub. Its method looks like a local function call, with the delay and failure modes of a network request.

Call GetReport with r42. The client decodes the reply into a Report. Shown as text, the returned fields look like this.

report_id: "r42"
status: "running"

The report's own status is running. The call finishes with a separate gRPC status of OK. Over the network, the report fields are sent as encoded bytes.

What the gRPC client sends

gRPC makes the call. In this example, Protocol Buffers, or Protobuf, describes its inputs and outputs and provides the format for encoding them. Google developed Protobuf so different programs could write and read the same structured data as bytes. A .proto file describes the message fields and types. The same file can specify which messages a gRPC method accepts and returns.

service ReportService {
  rpc GetReport(GetReportRequest) returns (Report);
}
 
message GetReportRequest {
  string report_id = 1;
}
 
message Report {
  string report_id = 1;
  string status = 2;
}

In string report_id = 1, string says the value is text, report_id is the name in the definition, and 1 identifies the field in the encoded message. A compiler generates code that can write and read those messages in the client and server's languages. When the caller supplies r42, the generated code writes a record for field 1 containing those three characters. The receiving code reads field 1 as the report ID. Protocol Buffers history · Protocol Buffers encoding

Those numbers matter when the client and server deploy separately. If we add an optional progress_percent field to Report at number 3, older Protobuf readers can still read fields 1 and 2 and ignore the new field. Newer callers need to handle its absence when talking to an older server. Keep each field's number stable. When removing a field, mark its number as reserved so a future definition cannot reuse it for another field.

When the report is missing

Suppose r42 is missing instead. Each interface tells the caller what happened in a different place. Native gRPC here means a client speaking gRPC over HTTP/2.

InterfaceWhere the caller sees the failure
Resource-oriented HTTPThe server returns HTTP 404 Not Found for the report URL.
JSON-RPC over HTTPThe response body contains an error and still includes id: 7. The API defines its report-missing error and how it uses HTTP status.
Native gRPCThe call reports NOT_FOUND in its gRPC status. The HTTP response can still have status 200.

For example, this JSON-RPC service could define its own error code, 1001, for a missing report.

{
  "jsonrpc": "2.0",
  "error": { "code": 1001, "message": "Report not found" },
  "id": 7
}

An HTTP access log can distinguish different report paths. A log that shows only POST /rpc needs the RPC method name to tell a lookup from a write. In native gRPC over HTTP/2, the request path names the service and method, as in POST /ReportService/GetReport. Read the gRPC status to count the method's failures. It's usually sent in trailers, metadata that follows the response body. A call that fails before it sends a response message can return the final status in its only set of headers. Native gRPC protocol

One result or several messages

A report lookup sends one request and receives one response. gRPC calls that a unary method. To watch a report's progress, a caller could send the report ID once and get an update whenever the status changes. That is server streaming.

service ReportService {
  rpc GetReport(GetReportRequest) returns (Report);
  rpc WatchReport(WatchReportRequest) returns (stream ReportProgress);
}

If the caller uploads report input in chunks and receives one receipt at the end, that is client streaming. If both sides need to send messages independently during the same call, that is bidirectional streaming. First decide which side needs to send multiple messages and when the other side needs to respond.

Native gRPC puts a small header before each encoded message, including its length. This is framing. The receiver can use the length to tell where one progress update ends and the next starts, even if the network carries them in several pieces.

What happens when the stream breaks

On WatchReport, suppose the client displays update 12 and loses the connection before updates 13 and 14 arrive. gRPC preserves message order in each direction of one call. A new call needs an application rule to recover updates from the old one. The service can retain the updates by sequence number so the client can reopen with afterSeq=12. If the earlier updates have expired, return a snapshot, the current report state, and its sequence from the same committed view. Open a watch after that sequence to replay updates that arrive during the reconnect.

An open call consumes capacity. When a client reads slowly, flow control limits how much data the sender can have in flight. Set a limit on the service's pending updates too. For report progress, the latest state may suffice when a client falls behind. A product that needs every event must retain enough history for replay.

Carry one deadline through the call

A deadline is the latest time a caller is prepared to wait. Suppose an HTTP gateway allows 200 ms to return report metadata. If authentication takes 30 ms, the gateway has at most 170 ms for everything that remains. It can set the gRPC call from its remaining budget and reserve some time to write the HTTP response.

If the reporting service calls another dependency 80 ms later, the original budget has at most 90 ms left. Propagate that deadline or a shorter one. Check your language's gRPC behavior and make the same choice explicitly at protocol boundaries. gRPC libraries can propagate a remaining timeout to avoid relying on synchronized clocks, but available behavior and defaults vary by implementation. gRPC deadlines and propagation

At expiry the client can receive DEADLINE_EXCEEDED. Handlers and downstream operations should observe cancellation and stop work where possible. Cancellation can arrive after the server saves a change. For a command such as StartReport, look up the existing job or, if the API supports it, retry with the same key that identifies the intended job.

Choose what the network path can support

For a public report lookup, direct HTTP gives the browser a URL it can read. Standard tools can inspect the method, status, and reuse rules. A shared cache can reuse a response when its cache policy permits it. Set explicit access and cache rules for private reports. For an API whose callers mostly ask the server to run named actions, JSON-RPC supplies a common request and reply format. When actions share POST /rpc, record the operation name in logs and define any per-operation caching in the application.

gRPC can fit services that control both ends, can distribute generated clients, and need the typed methods or native streaming modes. Check whether every intermediary can carry HTTP/2 streams and end-of-call status. Measure payload size and latency on the actual path. If a database lookup uses most of the time, changing just the message encoding may have little effect.

Browser clients have different constraints. The official JavaScript gRPC-Web client uses a browser-compatible protocol and commonly connects through a translating proxy. It supports unary calls and server streaming in grpcwebtext mode. Client streaming and bidirectional streaming are outside that client's supported modes. A service may keep gRPC internally and expose HTTP with server-sent events for browser progress. For two-way browser updates, evaluate a WebSocket interface and specify its own reconnect behavior. gRPC-Web streaming support

See also

  • Latency vs Throughput - measure the cost of request setup, streaming, and waiting under load.
  • Availability - decide how failed or late calls affect the service target.
  • Idempotency - protect writes when the response goes missing.
  • API Design - define the resource, state change, and allowed outcomes before choosing a wire interface.
  • Live Updates and Reconnects - choose browser delivery and recover missed events.

Used in

  • URL Shortener - a create operation and a public browser redirect use distinct HTTP methods and outcomes.
  • ChatGPT - the browser submits a turn over HTTP, then opens a one-way event stream for the reply and supplies a cursor when it reconnects.
  • Online Chess - a WebSocket carries player moves toward the server and game updates back toward the players.

Done reading? Mark it so it sticks in your dashboard.

Discussion