gRPC and Service-to-Service Communication Questions
Efficient inter-service communication using RPC-style contracts: gRPC, Protocol Buffers, and HTTP/2 transport. Covers unary and streaming modes (server, client, bidirectional), flow control, backpressure and cancellation, protobuf schema evolution and field compatibility (reserved field numbers, oneof, unknown fields), binary serialization trade-offs versus JSON/REST, deadlines and timeout propagation, status codes, retries on idempotent calls, interceptors and metadata, long-lived streams behind proxies and load balancers, gRPC-web and gateway exposure, upload and chat contract design, phased migration from REST, and choosing a transport for internal versus public-facing traffic. Excludes REST resource design, GraphQL, mTLS and mesh security, service discovery infrastructure, and broker-based messaging, which are covered elsewhere.
A team is considering gRPC server streaming to push real-time notifications to mobile apps and server clients. What would you evaluate before committing: how long-lived streams behave behind proxies and load balancers, how the design scales to millions of concurrent clients, what you do when a stream is unavailable, and how you guarantee delivery to a client that was offline?
Sample Answer
The idea in plain words
gRPC server streaming means a client opens one call, sends one request ("subscribe"), and the server keeps writing messages on that same call for as long as it likes. It is a natural fit for pushing notifications, and it works for native mobile apps and server clients. The risks are not in the API but in the world around the long-lived call: proxies and load balancers that close idle connections, millions of open connections that each cost memory, clients that vanish without telling you, and the fact that a stream is a live pipe, not a mailbox. A stream drops messages sent while nobody is listening, so "guarantee delivery to an offline client" needs a stored log behind the stream.
My recommendation, for the constraints in the question: use a server-streaming Subscribe call as the live path, backed by a durable per-user event log with sequence numbers, plus a normal unary catch-up call and the phone platform's push service to wake apps that are offline. The stream is an optimisation for latency; the log is what provides the guarantee. The sequence-numbered log (section 4) is the central idea; sections 1 to 3 are the operational checks that decide whether the live path survives real networks and real load.
What I would evaluate, in order
1. Behaviour behind proxies and load balancers
- HTTP/2 end to end. gRPC needs a proxy that speaks HTTP/2 and forwards trailers (headers sent after the body, which carry the final gRPC status). A layer-4 balancer (one that only forwards TCP connections) pins each long-lived connection to one backend, so load stays uneven after deployments; use a layer-7 (HTTP-aware) balancer or client-side balancing.
- Idle timeouts. Proxies and balancers commonly close connections that carry no traffic for a configured period, and mobile networks and NAT devices (network address translation: routers that share one public address among many devices and forget a connection's mapping once it has been idle for a while) can drop idle connections silently. Find every idle timeout on the path and send HTTP/2 PING keepalives (small frames sent on an otherwise idle connection to prove it is alive and keep middleboxes from discarding it; configured through gRPC keepalive settings) at an interval comfortably below the smallest one. The server must allow that ping rate (a server permitting no frequent pings answers an over-eager client with a GOAWAY frame carrying
ENHANCE_YOUR_CALM, the HTTP/2 error code meaning "you are asking too much of me", and the debug texttoo_many_pings), so client and server keepalive settings are tuned together. - Rebalancing. A stream never moves by itself. Set a maximum connection age on the server so it periodically sends GOAWAY (a frame telling the client to finish current calls and reconnect elsewhere), with a grace period; clients reconnect and resubscribe with their last sequence number.
- Browsers. If browser clients matter, gRPC-web supports server streaming but not client or bidirectional streaming from the browser, and needs a translating proxy. The question names mobile apps and server clients, so native gRPC applies.
2. Scaling to millions of concurrent clients (assumptions stated)
Assume 1,000,000 concurrent streams and about 40 KiB of memory per open stream (connection, TLS state, buffers, subscription record); that figure is an assumption to be replaced by a load-test measurement.
- Memory: 1,000,000 x 40 KiB = 40,000,000 KiB, which is 40,000,000 / 1,048,576 = about 38.1 GiB across the fleet.
- Nodes: if one node is tested to hold 50,000 streams, 1,000,000 / 50,000 = 20 nodes at full load. Plan for headroom so losing a node does not overload the rest; 20 nodes plus spare capacity, not 20.
- Reconnect storms. If one node fails, its 50,000 clients reconnect at once. If the whole fleet restarts during a deploy, all 1,000,000 do. Clients must reconnect with exponential backoff and full jitter (a random delay between 0 and the current backoff cap, so clients do not retry in lockstep). If the 1,000,000 spread uniformly over 60 s, the arrival rate is 1,000,000 / 60 = about 16,667 connections per second; over 30 s, a single failed node's 50,000 clients arrive at 50,000 / 30 = about 1,667 per second. Size connection setup capacity (TLS handshakes, the exchange that starts an encrypted connection and costs CPU and round trips, plus authentication) for that rate, and roll deployments node by node so the storm is one node's worth.
- Fan-out. Fan-out means delivering one event to many recipients. One event to one user is one write. A broadcast to all 1,000,000 is 1,000,000 writes; send it through a sharded publish path (the work is split into shards, each handled by a different node) and not through a single hot process. Concretely: publish the event once to a feed that every node reads. Each node holds about 50,000 streams and writes the event only to the users connected to it, so 20 nodes x 50,000 = 1,000,000 writes happen in parallel rather than in one process. For an event addressed to one user, partition the feed by user id so only the node holding that user's stream does any work.
- Slow consumers. Give each stream a bounded send queue (a buffer of messages waiting to be written to that client; for example the last 100 messages). If a client falls behind, close the stream with an error status and let it resume from its sequence number. Never let one slow client grow server memory without limit; HTTP/2 flow control stops the bytes, but your own queue must be bounded.
3. When the stream is unavailable
The stream will fail: network change, GOAWAY, deploy, client in a tunnel. Define the client behaviour: reconnect with backoff and jitter, and on each reconnect send the highest sequence number it processed. While disconnected, the client can poll a unary call ListEvents(after_seq, limit) on a slower timer if the stream stays down, using the same cursor, so the two paths cannot disagree. On the server, a stream that cannot be established returns UNAVAILABLE (the gRPC status meaning the service is temporarily unreachable and the call may be retried), and the client treats that as retry-with-backoff, not as a permanent error.
4. Guaranteeing delivery to a client that was offline
A stream cannot hold messages for someone who is not connected, so the guarantee comes from a store:
- Every event is appended to a per-user log with a monotonically increasing sequence number (each new number is larger than every earlier one, so order is unambiguous) before it is pushed anywhere.
Subscribe(from_seq)first replays everything afterfrom_seqfrom the log, then switches to live events. Do the switch without a gap by holding events that arrive during replay and releasing them in order after the replay ends. Worked example with sequence numbers: the user's log holds events 1 to 10 and the client reconnects withfrom_seq = 7. The server first registers for live events for this user, holding them in a side buffer, and only then reads the log. It sends events 8, 9 and 10 from the log. While that happens, events 11 and 12 are produced; they are stored in the log and also land in the side buffer. When the replay ends, the server releases the buffer in order, skipping anything not above the last sequence number it sent (10), so it sends 11 and 12, and from then on live events 13, 14 and so on go straight to the client. Registering for live events before reading the log is what closes the gap: done the other way round, event 11 could be produced after the log was read and before the registration, and would be missed.- The client acknowledges the highest sequence it processed (as a field on the next call or a separate unary
Ack). Delivery is at-least-once, meaning an event may arrive twice after a reconnect; the client discards any sequence number it has already seen, so processing becomes effectively once. - Retention is a product decision: events older than the retention period are gone, so a client offline longer than that must do a full refresh instead of a replay. State the period to the client team.
- For a phone that the operating system has suspended or closed, a live gRPC connection may not be possible in the background; the usual route is the platform's push service to show an alert or wake the app, which then opens the stream and catches up from the log. Check each platform's current background rules in its documentation before promising behaviour.
Storage arithmetic (assumptions: 20 events per user per day, 7-day retention, 300 bytes per stored event): per user 20 x 7 x 300 = 42,000 bytes. For 1,000,000 active users that is 42,000,000,000 bytes = 42 GB (decimal); for 10,000,000 registered users, 420 GB. This is the real cost of the delivery guarantee, and it scales with retention and event rate, not with the number of open streams.
The decision and what would flip it
Commit to gRPC server streaming plus the sequence-numbered log when: clients are native apps and services, event rates per user are modest, and the team already runs gRPC with an HTTP/2-capable edge. It would flip toward something else when:
- most clients are browsers and need the same real-time feed (consider WebSocket or Server-Sent Events, both of which browsers support directly);
- the edge cannot pass HTTP/2 and trailers end to end and cannot be changed;
- clients are battery-constrained devices where a long-lived TCP connection is too costly, and platform push or a lightweight device protocol is the better primary path;
- the delivery requirement is strict ordering across users or exactly-once effects, which needs an application-level idempotency design regardless of transport.
How I would know it works
Track: concurrent streams per node, stream age distribution, reconnect rate per minute, reconnect-storm peak per second, the age of the oldest unacknowledged event per user, replay length on reconnect, and the share of events delivered live versus by catch-up. Test by killing a node and by rolling a deploy in a staging environment, and by running a client offline for longer than retention.
Common mistakes
- Treating the stream as the guarantee. Messages sent while the client is away are lost without a log.
- No jitter on reconnect, turning every deploy into a self-inflicted outage.
- Forgetting an idle timeout somewhere on the path, then chasing "random" disconnects at exactly the same interval.
- An unbounded per-client send queue.
- Using an L4 balancer and discovering all streams sit on the oldest nodes.
Running the code
No program is required for this design question. The memory per stream, streams per node, event rate and retention are stated assumptions used for arithmetic, to be replaced with measured values from a load test.
Your organization runs internal services on JSON/REST and wants to move to gRPC, but some teams resist. How would you decide whether it is worth it, and how would you migrate in phases while keeping polyglot clients working, preserving compatibility, observability, and measuring the real gain against the cost?
Sample Answer
The idea in plain words
Do not migrate because gRPC is modern. Migrate an internal call path when a measured benefit (CPU, tail latency, a feature you need such as streaming or deadlines, or fewer integration bugs from a generated contract) is larger than the cost (engineering time, new tooling, harder debugging). Then do it in small, reversible phases (polyglot, meaning many programming languages, is the normal case for internal services, so every phase must keep non-gRPC-capable callers working): measure first, serve both protocols from the same business logic, move callers one edge at a time, and delete the old path only when its traffic is zero. A cheap, honest pilot settles the argument with the resisting teams' own numbers.
Step 1: decide whether it is worth it (evaluation criteria)
Score each candidate call edge (one caller service to one callee service) on three groups of criteria.
Interoperability
- Does every language in use have a maintained gRPC library and code generator? List them; any gap is a reason to keep a REST facade for that caller.
- Who calls the service: only internal services, or also browsers and partners? Browsers need gRPC-web and a proxy; partners usually need REST.
- Are there proxies, load balancers or gateways on the path that handle HTTP/2 end to end? An L4 balancer (it forwards TCP connections and cannot see individual requests) pins long-lived connections to one backend, so you may need an L7 balancer (one that understands HTTP/2 and spreads individual calls) or client-side balancing (the client library chooses a backend per call).
Developer experience
- Gains: one
.protofile generates typed clients in every language, so hand-written client drift disappears; breaking-change linters in CI turn "did we break anyone" into a check; new engineers get a precise contract to read. - Costs: binary payloads need
grpcurlor a UI tool instead ofcurl; engineers must learn field numbers and evolution rules; local setup needs the code generator. - Eased onboarding: publish the protos in one repository, a make target that regenerates stubs, a copy-paste
grpcurlcheat sheet, and enable server reflection in non-production (a feature where the server describes its own services and methods on request, so tools such asgrpcurlwork without the.protofile in hand).
Operational cost
- Observability must be rebuilt: metrics by method and gRPC status code, tracing context passed in metadata (an identifier for the whole request, copied onto every call it causes, so a tracing tool can join the hops), logs that include method and status. HTTP-level dashboards will show gRPC errors as HTTP 200 unless you record
grpc-status. - Health checks (the standard gRPC health-checking protocol, a small built-in service a load balancer can call to ask whether the server is ready), deadline defaults, retry policy and connection settings need owners.
- Two protocols run in parallel during the migration; that is a real, temporary cost.
Step 2: measure the real gain against the cost
Take a baseline of the candidate edge: calls per second, payload sizes, p50 and p99 latency (p99 is the time 99% of calls beat), CPU per 1,000 calls, error rate. Then run a canary (a small share of real traffic sent to the new path first, so a problem affects few users): send a small share of the edge's traffic over gRPC (for example 5% to 10%) and compare the same metrics over the same period.
Worked example (stated assumptions, not measurements): an edge handles 5,000 calls per second. The canary shows gRPC saves 0.3 ms of CPU per call.
- CPU saved = 5,000 calls/s x 0.3 ms = 1,500 ms of CPU per second = 1.5 cores.
- Suppose the edge's migration costs 3 engineer-weeks. To compare the two, put them in one unit, money per week. Let E be what one engineer-week costs and C what one core costs for a week. The weekly saving is 1.5 x C, the cost is 3 x E, and the payback time is 3E / (1.5C) = 2E/C weeks. Assume, as a stated example (use your own rates), that an engineer-week costs 100 times a core-week, so E/C = 100: payback = 2 x 100 = 200 weeks, nearly four years (200 / 52 = 3.8). On CPU alone I would not migrate this edge.
- Now suppose the same edge also needs server streaming for a new feature, or its callers are written in four languages with hand-built clients that keep drifting. Those benefits are not in the CPU number, and they could justify the work.
An illustrative ship rule (it covers only the inputs above and is not a complete policy): migrate an edge on cost grounds if the payback computed above is under 52 weeks, a threshold the organisation sets and that is used here only as an example; the 200-week edge above fails it. Migrate regardless of payback if the edge needs a capability REST does not give (streaming, propagated deadlines), or if a generated contract removes a recurring class of integration bug, for example one drifted hand-written client causing an incident each quarter. A real process must also weigh team capacity, other roadmap work, and risk to the service's reliability.
Step 3: the phased plan
- Baseline and choose the pilot. Rank edges by call volume and by how much they would gain. Pick one internal edge with an owner who is willing, not the most critical one.
- Define the contract backend-first. Write the
.protofrom the existing JSON shapes (or OpenAPI file). Keep field names aligned with the JSON names so mapping is obvious. Add breaking-change checks to CI (continuous integration, the automated build that runs on every change) before anything ships. An example of the conversion, for an existing response{"id": 150, "name": "Ada", "active": true, "tags": ["a", "b"], "created_at": "2026-01-05T10:00:00Z"}:
syntax = "proto3";
import "google/protobuf/timestamp.proto";
message User {
int64 id = 1;
string name = 2;
bool active = 3;
repeated string tags = 4;
google.protobuf.Timestamp created_at = 5 [json_name = "created_at"];
}
Each JSON key becomes a field with a number you choose now and never change; a JSON array becomes repeated; a timestamp string becomes the standard Timestamp message. The protobuf JSON mapping writes lowerCamelCase keys by default (createdAt), so json_name pins the existing key where a JSON surface is kept.
3. Serve both from one implementation. Put business logic behind an internal interface; add a gRPC handler beside the REST handler (a facade: a thin adapter exposing the same capability through the old interface). Alternatively generate the REST/JSON surface from annotations on the proto using a transcoding gateway (a proxy that turns an incoming REST/JSON request into a gRPC call and the reply back into JSON, following HTTP mappings written in the .proto file), so there is one implementation. Either way nothing is rewritten twice. One caution on compatibility: a transcoding gateway returns the protobuf JSON mapping, which is not always identical to the old hand-written JSON. 64-bit integers such as id are written as strings ("150" instead of 150), and fields holding their default value (active: false, an empty tags) are omitted unless the gateway is configured to print them. Lenient parsers cope with this; a strict old client may not. Replay recorded traffic from each old client against the gateway's output, and keep the hand-written REST facade for any caller that fails that check.
4. Add observability before moving traffic. Server and client interceptors (hooks that run around every call, before and after the handler) record latency histograms and status counts per method and propagate trace context in metadata. Dashboards and alerts must exist for the gRPC path before the first caller moves.
5. Move callers edge by edge, starting with callers in languages that have good gRPC support. Use a canary percentage and a flag to roll back in one change. Callers in languages that lack support stay on REST for now.
6. Fix infrastructure issues the pilot reveals, typically load balancing of long-lived connections, proxy timeouts and idle-connection settings.
7. Retire the old path. When the REST endpoint's traffic is zero over a period longer than the slowest caller's release cycle, mark it deprecated, then remove it. Keep the REST facade at the public edge permanently.
Compatibility during the migration is protected by additive-only proto changes, the CI check, and keeping both protocols live until traffic proves the old one is unused.
Handling the resisting teams
Resistance is information. Ask what they fear: debugging, learning curve, tooling gaps. Address each with something concrete (reflection and grpcurl for debugging, a pilot on an edge they own, a written rollback). Let their canary numbers decide, including a decision not to migrate their edge.
Common mistakes
- A big-bang rewrite of every service at once.
- Migrating without baseline numbers, then being unable to show any gain.
- Dropping the REST facade before browsers and partners have an alternative.
- Skipping observability work, so the first incident is hard to diagnose.
- Assuming that moving to gRPC fixes slow handlers; if time goes to the database, nothing changes.
A platform has internal services that call each other at high volume and also exposes endpoints to third-party clients. Where would you use gRPC, where REST/JSON, and where an asynchronous message-based interface? Explain how latency, throughput, failure behavior and schema versioning affect each choice.
Sample Answer
The idea in plain words
Pick the interface style by who the caller is and what happens when the call fails, not by fashion. Between your own high-volume services, use gRPC (RPC calls over HTTP/2 with protobuf, a compact binary format, and a generated contract). For third-party clients, use REST/JSON over HTTP, because it works in every language, browser and tool, and because you can document, cache and throttle it with standard machinery. For work that does not need an answer in the same moment, or that several consumers should react to independently, use an asynchronous message-based interface (the caller hands a message to an intermediary and moves on; consumers process it later). The decision hangs on three questions, which matter more than the detail below: who controls the caller (schema versioning), what the caller experiences when the other side is slow or down (failure behavior), and whether the caller needs the answer now (sync versus async).
Where each one goes
Assumed platform for the example (an illustration, not a real system): a storefront. A third-party partner places an order over the public API. Inside the platform, an order service calls pricing and inventory services thousands of times per second, and after an order is placed, email, analytics and fulfilment must react. The gateway in the table below is the front-door server that authenticates outside callers and applies rate limits (caps on how many requests a caller may make per period).
| Boundary | Choice | Why |
|---|---|---|
Partner to platform edge: POST /orders | REST/JSON | Unknown clients and languages, browsers possible, standard authentication, rate limits and caching headers, easy to try with curl |
| Order service to pricing and inventory | gRPC | Hot path, many calls per order, one generated contract for every team's language, deadlines that shrink as they pass down the chain |
| Order placed, then email, analytics, fulfilment | Async messages | The order does not need to wait for them; they can be down for a while and catch up; new consumers can be added without changing the order service |
How the four forces apply to each choice
Latency
- gRPC: lowest per-call overhead. Reused HTTP/2 connections avoid repeated connection setup, and binary encoding is cheap to process. It helps most where one request triggers many internal calls.
- REST/JSON: slightly higher per-call overhead, usually acceptable at the edge where a human or partner is on the other end and network time dominates.
- Async: the caller gets control back after handing over the message, so caller latency is low, but the end-to-end time until the work completes is longer and variable.
Throughput
- gRPC: multiplexed streams on few connections, and streaming calls for bulk transfers, give high sustained throughput per instance.
- REST/JSON: scales well horizontally; a gateway can add rate limits, which protect the platform from a partner's burst.
- Async: an intermediary absorbs spikes by queueing, so consumers process at their own steady rate; throughput on the consumer side is limited by how fast it drains, and lag is the thing to watch.
Failure behavior
- gRPC: synchronous, so the caller is blocked on the callee. Each call needs a deadline (an absolute time limit that travels with the call), retry rules only for idempotent calls (calls safe to repeat), and a circuit breaker (a wrapper that, after repeated failures, stops calling the failing service for a cool-off period and fails immediately instead, so callers do not pile up waiting). If inventory is slow, order service threads pile up unless deadlines cut them off. Errors arrive as gRPC status codes such as
UNAVAILABLE(safe to retry) orINVALID_ARGUMENT(not). - REST/JSON (public): the failure contract is HTTP status codes, so partners get
429 Too Many RequestswithRetry-After,503for overload, and anIdempotency-Keyheader convention so a retriedPOSTdoes not create two orders. How the key works: the partner generates a unique value, sayK-7f3a, and sends it on the firstPOST /orders. The server saves the key together with the response it produced (order 9001). If the network drops the response and the partner retries with the sameK-7f3a, the server finds the saved key and returns the saved response for order 9001 instead of creating a second order. - Async: a consumer outage does not break the producer; messages wait. The price is at-least-once delivery (a message may arrive twice), so consumers must deduplicate, and poisoned messages (ones that fail every time they are processed, for example because of malformed content) need a dead-letter path (a separate queue where a message is parked after a set number of failed attempts, so it stops blocking the rest and a person can inspect it). A concrete flow: the order service publishes
OrderPlaced{order_id: 9001}once and returns. The broker keeps a copy for each of three consumers. Email processes it and acknowledges. Analytics processes it and acknowledges. Fulfilment fails three times in a row because of a bad address, so after the third attempt the broker moves the message to the dead-letter queue, and the other two consumers are unaffected. Consumer lag (how many messages are waiting, not yet processed, behind a consumer) is the number to watch: if fulfilment is down for an hour, its lag grows and then drains when it returns.
Schema versioning
- gRPC/protobuf: fields are matched by number, so adding a field is safe, and removing one needs its number reserved (declared in the
.protofile asreserved 5;so nobody can assign that number to a different field later). You control all callers, so you can set a rule such as "no breaking change within a package version, and a newv2package for a break", and enforce it in CI. - REST/JSON (public): you do not control callers, so you need long-lived versions, a deprecation and sunset process, and tolerant readers (clients ignore unknown fields). Treat anything the partner can observe as a contract. A tolerant reader is a client written to ignore fields it does not recognise instead of failing; a sunset process is the published schedule on which an old version stops working (announce, warn, then switch off on a stated date).
- Async: messages are stored and replayed, so old and new message shapes coexist for as long as the intermediary retains them. Consumers must handle every version still in flight, which usually means additive-only changes.
A before and after example of the same additive change in each style: the platform wants to carry a coupon code on an order. In gRPC, the message gains one new field, string coupon_code = 5; (before: fields 1 to 4; after: field 5 added), and old clients simply never set it. In the public REST API the response JSON gains "coupon_code": null or the request accepts an optional coupon_code; old partners ignore the extra key, and the old version stays available through the deprecation process. In the async message, OrderPlaced gains an optional coupon_code field, and consumers written before the change keep working because they ignore it, while messages already stored in the queue (without the field) must still be read by new consumers.
Worked deadline example (stated assumptions)
The partner's client allows 1,000 ms for POST /orders. The gateway spends 20 ms on authentication and routing and calls the order service with 980 ms left (1,000 - 20). The order service sets aside 100 ms for its own work and database write, leaving 980 - 100 = 880 ms for dependencies. It calls pricing and inventory in parallel and gives each call a 400 ms deadline, well inside the 880 ms, so that one slow dependency cannot eat the whole budget. If inventory takes 450 ms, its call fails with DEADLINE_EXCEEDED at 400 ms, and the order service can still answer the partner after 20 + 400 + 100 = 520 ms with a clean error, instead of letting the partner time out at 1,000 ms. In an async step, there is no such chain: the order service publishes OrderPlaced and returns.
My recommendation
Use all three, each at its own boundary: REST/JSON at the public edge, gRPC for internal request/response on the hot path, and async messages for reactions that do not gate the user's answer. I would not expose gRPC directly to partners unless they are few, known and agree to it, and I would not use async for anything the caller must have in the response (a price quote).
What would change this: a partner base that is only a few internal-like teams (gRPC at the edge is fine); an internal call that is rare and low volume (REST is fine and simpler); a reaction that must finish before the user sees a result (make it a synchronous call, not an event).
Common mistakes
- Using one style everywhere "for consistency", then paying the cost of the wrong style at one boundary.
- Making a synchronous call chain deep without deadlines, so one slow service stalls everything upstream.
- Using async messages for something that needs an immediate answer, then inventing polling to fake a response.
- Forgetting that at-least-once async delivery requires a deduplicating consumer.
You are choosing how latency-sensitive microservices inside one data center should call each other. Would you pick gRPC over HTTP/2 with protobuf, or REST with JSON, and what would you weigh to decide? Where would the gap not matter?
Sample Answer
The idea in plain words
Both options can meet a latency target inside one data center. gRPC (calls over HTTP/2 with protobuf, a compact binary encoding) removes some per-call costs: smaller messages, cheaper encode and decode, one reused connection with many calls multiplexed on it, and deadlines built into the call. REST with JSON removes friction: every tool can call it, and anyone can read a message. The decision is whether those per-call savings are a meaningful share of your latency budget or CPU bill. Where handlers are dominated by databases or other slow work, the gap does not matter, and the simpler option wins.
What to weigh, in the order I would check
- Where the time goes. Take a traced request and split its latency into network, serialization, queueing and handler work. Serialization is only worth optimising if it is a visible slice. Measure with your own payloads; published benchmarks use other payloads and hardware.
- Call count per user request. The saving is per call, so it scales with the number of calls in the path. Fan-out means one incoming request causing many outgoing calls; sequential hops add their per-call cost to the user's latency, while calls made in parallel mostly add CPU cost across the fleet rather than waiting time.
- Payload size and shape. Many small numeric fields compress well in protobuf; large strings or blobs cost about the same in both.
- Features you need. Streaming, per-call deadlines that propagate down the chain, and a contract that generates clients in every language favour gRPC.
- Operational cost. Binary payloads need schema-aware tools to inspect; HTTP/2 needs an L7-aware load balancer (one that understands individual HTTP requests, unlike an L4 balancer that only forwards TCP connections) or client-side balancing (the client library holds the list of servers and picks one per call); the team must learn proto evolution rules (the rules for changing a
.protofile without breaking old clients: never reuse a field number, and so on). REST fits the tooling you already have. - Connection handling. A gRPC client should create one channel (a managed connection to a server, or a set of servers, that carries many calls) and reuse it. Creating a new channel per call pays the TCP and TLS setup every time, and can make gRPC slower than a well-configured REST client that uses keep-alive (a setting that keeps a connection open between requests so the next request skips the setup).
Worked example (all inputs are stated assumptions)
Assume each REST/JSON call costs 0.3 ms more CPU time than the equivalent gRPC call, counting encode and decode on both sides, and that a user request has a 50 ms latency budget. These are illustrative figures to show the method; replace them with your own measurements. To measure the 0.3 ms for real, take a sample of your actual request and response bodies, time encoding and decoding them in both formats in a loop on the same machine, and divide the total CPU time by the number of calls; then confirm it in a staging load test by comparing CPU per 1,000 calls for the two transports.
Two different quantities follow, and they should not be added together. Latency is time a single user request spends waiting, and only calls made one after another add to it. CPU cost is processor time spent across all servers, which depends on how many calls per second the fleet makes, regardless of whether any one user waits for it.
Case A, a shallow chain: 4 sequential calls per request.
Added latency = 4 x 0.3 ms = 1.2 ms. Share of budget = 1.2 / 50 = 0.024, which is 2.4%. Not a reason to change transports.
Case B, a heavy fan-out: 40 calls per request made sequentially by a legacy aggregator.
Added latency = 40 x 0.3 ms = 12 ms. Share of budget = 12 / 50 = 0.24, which is 24%. Now the transport matters.
CPU view, assuming 20,000 calls per second across the fleet: 20,000 x 0.3 ms = 6,000 ms of CPU per second = 6 CPU cores. Six cores is real money at large scale and trivial at small scale; compare it with the engineering cost of the migration, not with zero.
My recommendation
For a platform with many internal services, several languages, and any fan-out or streaming, I would choose gRPC as the default internal transport, with a REST/JSON facade only at the public edge. For a small team with a few services, modest call volume, and handlers dominated by database time, I would stay on REST/JSON, keep connections alive, and revisit if measurements change.
What would flip the decision toward gRPC: a trace showing serialization or connection setup as a double-digit share of latency; a need for server streaming; many languages drifting out of sync with hand-written clients. What would flip it toward REST: a need for HTTP caching, direct browser calls, or heavy use of ad hoc debugging by people without schema-aware tools.
Where the gap does not matter
- Handler time is large (database queries, calls to external vendors): a sub-millisecond saving disappears.
- Call volume is low, so CPU savings are a fraction of one core.
- Payloads are dominated by long strings or binary blobs, which both formats carry at about the same cost.
- The path crosses a slow link or a queue anyway.
- Calls are rare administrative operations where debuggability beats speed.
So "is gRPC always faster" has the answer no: it is usually cheaper per call, but whether that is faster end to end depends on how large the per-call cost is relative to everything else on the path, and a misconfigured gRPC client (a new connection per call) can lose to a tuned REST client.
Common mistakes
- Quoting a benchmark ratio instead of measuring the actual service.
- Comparing gRPC over HTTP/2 with REST over HTTP/1.1 without keep-alive and concluding the encoding caused the whole difference.
- Ignoring tail latency (p99, the time that 99% of requests beat; the slowest 1% are the tail): connection pinning behind an L4 balancer can create hot backends that hurt p99 more than any serialization saving helps. Pinning means that, because a gRPC connection is long-lived and an L4 balancer chooses a backend only when the connection opens, all calls on that connection keep going to the same server. A hot backend is a server that ends up with more than its share of calls, so its queue (requests waiting for a free worker) grows and requests on it wait longer. An L7-aware balancer avoids this by choosing a backend per call.
Your internal services speak gRPC, and a web app in the browser needs to call them. Design how you would expose them, and explain what browsers cannot do natively, what the translation layer costs, and what you would do about streaming and legacy browsers.
Sample Answer
The idea in plain words
A browser cannot speak native gRPC. gRPC needs full control of HTTP/2 framing and the ability to read trailers (headers sent after the body; gRPC puts its final status there), and the browser's fetch and XHR APIs expose neither. The fix is gRPC-web, a slightly different wire format that browsers can produce, plus a translation layer that converts between gRPC-web and native gRPC in front of your services. That layer is either a proxy (for example a filter, a plug-in step in a proxy such as Envoy, built for it) or a library inside the server. You pay for it with an extra component to run, a fixed set of limits on streaming, and some browser-specific configuration.
What browsers cannot do natively
- Send arbitrary HTTP/2 frames (HTTP/2 splits traffic into small typed frames, and gRPC depends on controlling them) or read trailers, so the
grpc-statustrailer is unreachable. gRPC-web sends the trailers as a final frame inside the response body instead. - Reliably stream a request body from the page. As a result browser gRPC-web clients support unary and server streaming calls only.
- Skip the same-origin rules. A page on
https://app.example.comcallinghttps://api.example.comis cross-origin, so the browser enforces CORS (cross-origin resource sharing) and sends a preflight (anOPTIONSrequest asking permission) before a POST that carries a non-simple content type or custom headers.
The design
Browser, then an edge gateway that terminates TLS (it ends the encrypted connection from the browser, so what it forwards inward is decrypted), then the translation layer, then the internal gRPC services.
Browser (gRPC-web over HTTP/1.1 or HTTP/2)
-> edge gateway / proxy (TLS, CORS, auth check, translation to native gRPC)
-> internal services (native gRPC over HTTP/2)
My choices:
- Serve the web app and the gRPC-web endpoint from one origin (
https://app.example.com, with the proxy routing the path prefix/chat.v1.ChatService/to the backend). Same-origin calls need no CORS and no preflight, which removes both a configuration burden and a round trip per call. - The default I would ship: gRPC-web through this layer with unary and server-streaming calls. The other options named under streaming below are fallbacks for specific needs.
- Keep the translation layer stateless and horizontally scaled behind the load balancer.
- Authenticate at the edge (validate the session or bearer token) and forward identity to services in metadata, so services keep one auth path.
- For third-party developers, do not hand out gRPC-web. Expose a documented REST/JSON API that a transcoding gateway (a proxy that turns a REST/JSON request into a gRPC call and back, using HTTP mappings written in the
.protofile) generates from proto annotations.
An illustrative exchange
Illustrative unary call from the page (the page is served from app.example.com, so this is same-origin) to ChatService.SendMessage (gRPC-web, binary format):
POST /chat.v1.ChatService/SendMessage HTTP/1.1
Host: app.example.com
Content-Type: application/grpc-web+proto
X-Grpc-Web: 1
Authorization: Bearer eyJ...example
Grpc-Timeout: 5S
Accept: application/grpc-web+proto
(5-byte frame prefix: flag 0x00, 4-byte length) + protobuf bytes of SendMessageRequest
The 5-byte prefix is the same framing native gRPC uses. Byte 0 is a flag: 0x00 means an uncompressed data frame, and in gRPC-web a flag with the top bit set (0x80) means the frame holds trailers. Bytes 1 to 4 are the length of the frame's content, a 32-bit number in big-endian order. For example, a 30-byte message is prefixed 00 00 00 00 1E (30 = 0x1E). The browser sends this framing inside the HTTP body.
Content-Type: application/grpc-web+protosays this is gRPC-web with protobuf (application/grpc-web-textis the base64 text variant).X-Grpc-Web: 1marks the request as gRPC-web; browser clients send it by convention.Authorizationcarries the credential; the proxy turns it into call metadata.Grpc-Timeout: 5Sis the deadline: 5 seconds.
Illustrative response:
HTTP/1.1 200 OK
Content-Type: application/grpc-web+proto
Transfer-Encoding: chunked
(data frame, flag 0x00) SendMessageResponse bytes
(trailer frame, flag 0x80) "grpc-status: 0\r\n"
The trailer frame's content is the text grpc-status: 0 followed by a carriage return and line feed, 16 bytes, so its prefix is 80 00 00 00 10 (16 = 0x10).
The HTTP status is 200 even when the call fails; the failure is in the trailer frame as grpc-status and grpc-message.
If the page and API were on different origins, the browser would first send a preflight like this (illustrative):
OPTIONS /chat.v1.ChatService/SendMessage HTTP/1.1
Host: api.example.com
Origin: https://app.example.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type,x-grpc-web,authorization,grpc-timeout
and need an answer such as 204, Access-Control-Allow-Origin: https://app.example.com, Access-Control-Allow-Methods: POST, Access-Control-Allow-Headers: content-type,x-grpc-web,authorization,grpc-timeout, Access-Control-Max-Age: 600, plus Access-Control-Expose-Headers: grpc-status,grpc-message on the real responses so page code can read them. Header by header: Access-Control-Allow-Origin names the one origin whose page code may read the response; Access-Control-Allow-Methods lists the HTTP methods the browser may use; Access-Control-Allow-Headers lists the request headers the page may send beyond the simple ones; Access-Control-Max-Age is how many seconds (here 600) the browser may remember the preflight reply before asking again; Access-Control-Expose-Headers lists the response headers that page code is allowed to read. Access-Control-Allow-Origin: * cannot be combined with credentialed requests (requests that carry cookies or HTTP authentication).
What the translation layer costs
- Latency: one extra hop per call. If the proxy runs near the services, assume it adds a small fixed delay (measure it; do not guess), and the preflight adds a full round trip per distinct call in cross-origin setups unless
Access-Control-Max-Agelets the browser cache it (browsers cap the maximum). - Operations: another tier to deploy, scale, patch and alert on. It must handle long-lived server-streaming responses without idle timeouts cutting them.
- Monitoring: a gRPC-web failure arrives as HTTP 200, so edge dashboards built on HTTP status will show success. Record
grpc-statusper method at the proxy and at the services, tag traces with the request id, and alert on status code rates. - Payload debugging: binary bodies in browser dev tools are unreadable without a plug-in; the text variant helps in development.
- Feature gaps: no client or bidirectional streaming, and some features of native gRPC (for example fine control of connection behavior) are not available.
Streaming and legacy browsers
The usual choice is the one in the recommendation: server streaming for downstream and unary calls for upstream. The bullets below are the fallbacks for the less common needs, each with a one-line gloss.
- Server streaming works with gRPC-web in browsers that can read a streamed response body. Use it for feeds and progress updates.
- Client streaming and bidirectional streaming do not exist in gRPC-web. Pick one of: replace client streaming with repeated unary calls carrying offsets or sequence numbers; use server streaming for downstream plus unary calls for upstream (this covers most chat-style needs); or add a separate WebSocket (a long-lived two-way connection started from an HTTP request) or WebTransport (a newer browser API for two-way streams over HTTP/3, whose browser support you must check) endpoint for true two-way sessions, with an adapter service that talks gRPC behind it.
- Legacy browsers that cannot stream a fetch response need the base64 text mode (response bytes encoded as base64 text, which older browser APIs can read) over XHR where the client library supports it (check the library's supported-browser matrix), or a fallback to a REST/JSON or server-sent-events endpoint (a one-way stream of text events from server to browser over plain HTTP) for streaming features. Decide a minimum browser support level with product up front, because every fallback is code to maintain.
- A protocol such as Connect (an RPC protocol designed to be called from browsers with plain
fetch, using JSON or protobuf bodies), is an alternative worth evaluating if you want to avoid a dedicated proxy; it has its own tradeoffs.
My recommendation
Same-origin gRPC-web through the edge proxy for the first-party web app, unary plus server streaming only, authentication enforced at the edge, grpc-status monitoring from day one, and a REST/JSON transcoded API for outside developers. If product insists on browser-to-server bidirectional streaming, treat it as a separate WebSocket adapter decision.
Common mistakes
- Expecting a browser to call a native gRPC port directly.
- Trusting HTTP 200 as success in dashboards.
- Using
Access-Control-Allow-Origin: *while sending credentials. - Designing a feature that needs client streaming for the web app and discovering the gap late.
- Letting a proxy idle timeout cut a long server stream and reporting it as a client bug.
That is every published gRPC and Service-to-Service Communication question for Cloud Architect so far. Browse the other topics in this category, or practice this one interactively.