Opening your learning path
Progress is saved as you study.
Opening your learning path
Progress is saved as you study.
Opening your learning path
Progress is saved as you study.
gRPC Deep Dive is a depth lesson in the Networking & APIs family of the Thita system design course.
Protocols (REST, gRPC, WebSocket, SSE), API design, pagination, and idempotency.
It sits on the Deep Dive path — worth reading once the Interview Soon lessons are solid, or when a role names this area explicitly.
A gRPC API usually fails where teams share a contract: schema changes, request shape, connection behavior, streaming behavior, deadlines, retries, and mesh policy.
gRPC is a high-performance RPC framework. It usually runs over HTTP/2 and uses Protocol Buffers as its default serialization format.
The interview point is concrete: gRPC gives you typed contracts, binary encoding, multiplexed connections, deadlines, cancellation, and streaming.
Use gRPC when engineering teams can share schemas and generated clients. Use REST or GraphQL when the API is public, browser-facing, or needs easy human inspection.
| Decision point | Pick gRPC when | Pick REST/JSON when |
|---|---|---|
| Clients | Internal services, mobile apps with generated SDKs | Public third-party clients, browsers, scripts |
| Contract | Strong schema and version discipline matter | Flexible payloads and ad hoc integration matter |
| Latency/CPU | High QPS or large payload volume | Lower QPS or human debugging matters more |
| Streaming | Server, client, or bidirectional streaming helps | Simple request/response is enough |
| Operations | You can enforce deadlines, retries, and mTLS centrally | You need simple HTTP tooling everywhere |
Treating gRPC as a direct REST replacement causes bad designs. gRPC works best as a contract-first service interface. That contract becomes a liability when teams reuse field numbers, change field meaning, or skip compatibility planning.
A protobuf schema defines messages, fields, numeric tags, and services. Generated code turns the schema into typed clients and servers. That removes many runtime parsing bugs.
Schema changes need care because old and new binaries run at the same time during rolling deploys.
A minimal service looks like this:
1syntax = "proto3";
2
3service OrderService {
4 rpc GetOrder(GetOrderRequest) returns (GetOrderResponse);
5 rpc WatchOrders(WatchOrdersRequest) returns (stream OrderEvent);
6}
7
8message GetOrderRequest {
9 string order_id = 1;
10}
11
12message GetOrderResponse {
13 string order_id = 1;
14 string status = 2;
15 int64 updated_at_ms = 3;
16}Protobuf encodes field numbers on the wire. Field names affect generated code.
If status = 2 reaches production, field number 2 now means status for that message forever.
Many interview answers fail here. A candidate says, “We can rename fields later,” which is true for generated code. The wire format still uses field numbers and values.
Field numbers are the stable identifiers in protobuf encoding. You may rename status to state if field number 2 keeps the same meaning. Old and new binaries still agree that field 2 carries the same data.
Never reuse field number 2 for a different meaning after deleting status.
Once a field number has existed in production, reserve it after removal. Reservation prevents a future engineer from assigning the same number to a different field and corrupting data across mixed-version clients.
1message GetOrderResponse {
2 string order_id = 1;
3 reserved 2;
4 reserved "status";
5
6 int64 updated_at_ms = 3;
7 string state = 4;
8}reserved 2 protects the wire tag. reserved "status" protects the field name. Use both when deleting a field because they prevent different mistakes.
Field numbers from 1 to 15 encode more compactly than larger numbers. Use low numbers for hot, frequently populated fields. In interviews, spend more time on permanence, reservation, and rolling deploy compatibility.
Protobuf sends field numbers, not names. Renaming field 2 is safe, but reusing number 2 for a new meaning makes old data decode wrongly. Reserve removed numbers and names.
Backward compatibility means a new server can still understand old clients. Forward compatibility means an old server or client can tolerate messages produced by newer code.
Distributed systems need both because deploys happen across services, regions, mobile apps, and background workers over time.
Protobuf gives useful defaults. It does not make every schema change safe.
Older readers usually skip unknown fields, so adding a new optional field is usually safe. Changing a field’s type or meaning is unsafe because old binaries may decode the same field number incorrectly or apply stale business logic.
| Schema change | Safe? | Why |
|---|---|---|
| Add a new optional field with a new number | Yes | Old readers ignore unknown fields; new readers see a default when absent |
| Rename a field while keeping the same number and meaning | Yes | Wire encoding uses the field number |
| Delete a field and reserve the number/name | Usually | Old senders may still send it; new readers ignore it if removed |
| Reuse a deleted field number | No | Old data can be decoded with a new meaning |
Change string user_id = 1 to int64 user_id = 1 | No | The same tag now carries incompatible encoding and meaning |
| Change business meaning of a field | No | Wire compatibility does not protect semantic compatibility |
| Add a new required concept to request handling | Risky | Old clients will omit it, so the server needs a default or a new method |
Proto3 removed explicit required fields because required fields break rolling upgrades. If a new server needs a field that old clients omit, choose one of three paths:
For interviews, prefer additive optional fields and server-side defaults unless the business operation needs a new contract.
A clean evolution looks like this:
1message CreatePaymentRequest {
2 string account_id = 1;
3 int64 amount_cents = 2;
4 string currency = 3;
5 string idempotency_key = 4; // added later
6}Adding idempotency_key is safe at the wire level. The server still needs behavior for old clients that omit it.
A reasonable answer: “For old clients, use a weaker dedupe key or require a client upgrade before enabling retries that depend on idempotency.”
Avoid versioning until the contract meaning changes. Add fields, keep old fields readable, and phase behavior behind server logic. Create v2 when old and new semantics cannot safely share one message.
Separate wire compatibility from product compatibility.
Adding discount_code = 5 is wire-compatible. Changing amount_cents from pre-tax to post-tax is semantically incompatible, even though the type remains int64.
Use this decision tree:
| Situation | Recommendation |
|---|---|
| Need extra data while old clients keep working | Add an optional field with a new number |
| Need to stop using a field | Stop writing it, keep reading it, then reserve it after clients migrate |
| Need a new meaning for an existing field | Add a new field |
| Need a different operation with different invariants | Add a new RPC method |
| Need a different API model | Create a new service or versioned package |
Interviewers expect migration thinking. Say how old clients behave, how new clients behave, and what happens during a rolling deploy.
A unary RPC has one request and one response. Start there unless the problem needs streaming. Unary calls are easier to retry, load balance, observe, and reason about under failure.
Example:
1service InventoryService {
2 rpc GetStock(GetStockRequest) returns (GetStockResponse);
3}Unary is the right default for fetching an entity, submitting a command, checking authorization, or writing a transaction. High-QPS services can still use unary behind load balancing and connection pooling.
Avoid streaming when pagination gives clear checkpoints and retry behavior. Use streaming when one logical operation benefits from staying open.
Server streaming means the client sends one request and receives a sequence of responses. Use it when the client subscribes to updates, downloads a large result incrementally, or needs partial results before the full operation completes.
Example:
1service FeedService {
2 rpc WatchFeed(WatchFeedRequest) returns (stream FeedEvent);
3}A clear use case is watching order status changes. The client sends order_id, and the server streams OrderEvent messages until the order completes, the deadline expires, or the client cancels. The design avoids polling and reduces unnecessary requests.
A streaming call holds server memory, connection state, and usually a subscription handle. Mention deadlines, cancellation, heartbeat behavior, and backpressure.
Pick server streaming when updates naturally flow from server to client. Use paginated unary for ordinary list endpoints unless partial delivery improves latency or memory use.
Client streaming means the client sends a sequence of messages and receives one response after finishing the upload. Use it for uploads, batching, telemetry ingestion, and cases where the server aggregates many client events into one result.
Example:
1service MetricsService {
2 rpc UploadMetrics(stream MetricPoint) returns (UploadSummary);
3}A mobile client can upload many metric points over one RPC. The server validates each point, aggregates counts, and returns one summary. That reduces per-request overhead compared with thousands of unary calls.
Failure recovery needs a clear rule. If a client streams 10,000 events and the connection fails after 8,000, both sides need to know what was accepted. Use idempotency keys, sequence numbers, or chunk acknowledgments when duplicate or missing events matter.
Pick client streaming when batching reduces overhead and the operation can handle partial failure. If every item needs an independent success or failure result, a unary batch RPC with per-item statuses is usually simpler.
Bidirectional streaming means both client and server send message sequences over the same RPC. Use it when both sides need independent, ongoing communication. Common examples include chat, collaborative editing, multiplayer coordination, interactive control planes, and proxy tunnels.
Example:
1service ChatService {
2 rpc Chat(stream ChatMessage) returns (stream ChatMessage);
3}Bidirectional streams have two independent directions. You must reason about ordering, flow control, cancellation, and half-closed streams. They are harder to test and harder to recover after failure.
Pick bidirectional streaming only when the interaction is conversational. If the client sends one request and waits for updates, use server streaming. If the client uploads many items and waits for one result, use client streaming.
Most interview systems do not need streaming. Start with unary. Change the shape only when the use case needs it. Unary keeps the design easier to debug and makes failure handling easier to explain.
| API need | Best gRPC shape | Reason |
|---|---|---|
| Fetch user profile | Unary | One request maps to one response |
| Submit payment | Unary | Easier idempotency, deadlines, and retries |
| Watch delivery location | Server streaming | One subscription produces many updates |
| Upload telemetry batch | Client streaming | Many events become one summary |
| Real-time chat | Bidirectional streaming | Both sides send independently |
| Large export | Server streaming or paginated unary | Streaming lowers memory use; pagination improves retries |
Name the failure semantics of the chosen shape. For streaming, say what happens on disconnect. For unary writes, say whether retries are safe and which idempotency key prevents duplicates.
gRPC makes deadlines part of the call. A deadline tells downstream services when the request is no longer useful. A slow request should stop consuming CPU after the caller times out.
Set deadlines at the edge and propagate them downstream. If the user request has a 300 ms budget, a downstream inventory call might get 50 ms. Avoid unbounded timeouts. Unbounded timeouts cause retry storms and thread starvation during partial outages.
Retries are safe for idempotent reads and idempotent writes with keys. Retries are dangerous for non-idempotent operations such as “charge card” unless the server deduplicates by idempotency key.
In interviews, state which calls are safe to retry.
For streaming calls, retries usually mean reconnect and resume. Resume requires an offset, sequence number, cursor, timestamp, or version. Without a resume token, the client may receive duplicates or miss events, and the application must tolerate that.
A service mesh moves shared network behavior out of application code and into a managed proxy layer. In an Istio-style deployment, each service instance has an Envoy sidecar that intercepts inbound and outbound traffic.
Istio’s control plane configures those sidecars with routing, identity, certificates, telemetry, retries, and policy.
The concrete benefit is operational consistency. The mesh applies common mTLS, retries, circuit breaking, traffic splitting, and metrics at the network layer. Without a mesh, each service team may implement those behaviors differently.
The cost is extra complexity, proxy overhead, and another control plane that can fail or be misconfigured.
Envoy fits gRPC well because gRPC uses HTTP/2. Envoy understands HTTP/2 routing, request metadata, status codes, deadlines, and load balancing. That gives the platform team traffic control without changing generated gRPC clients.
mTLS gives both client and server cryptographic identity. It also encrypts transport.
In a mesh, service A connects to a workload identity such as payments.default.svc.cluster.local. Envoy validates certificates and enforces whether that identity can call the target.
“Internal network” is a weak security boundary. If one service is compromised, mTLS plus authorization policy limits which other services it can call. Encryption protects traffic. Identity and policy protect service-to-service access.
A good answer: “Use mesh-managed mTLS for service-to-service gRPC inside the cluster, then enforce authorization by service identity.”
Do not put certificate rotation logic in every application unless you are building the platform.
Debugging and bootstrapping are harder with mTLS. If certificates expire or sidecars cannot get config, traffic can fail before reaching the application. Monitor mesh health, certificate rotation, and policy rollout because these failures look like network errors to application teams.
A mesh gives traffic control below application code. For gRPC, this includes service discovery, load balancing, timeouts, retries, circuit breaking, canaries, shadow traffic, and fault injection.
Operators can change traffic behavior without rebuilding every client.
Common traffic controls:
| Capability | What it does | Interview recommendation |
|---|---|---|
| Canary release | Send 1%, then 5%, then 25% of traffic to a new version | Use for risky server changes |
| Traffic splitting | Route by percentage, header, or service version | Use for gradual migration |
| Circuit breaking | Stop sending requests to unhealthy or overloaded instances | Use to prevent cascading failure |
| Outlier detection | Eject instances with high error rates | Use for noisy bad pods |
| Request timeout | Bound how long a proxy waits | Align with application deadlines |
| Retry policy | Retry selected transient failures | Retry only idempotent calls |
Avoid retry amplification. If the client retries three times, Envoy retries three times, and the downstream service retries its database call, one user request can become dozens of backend operations.
Pick one retry layer for each failure domain and keep the total retry budget explicit.
For gRPC status codes, retry UNAVAILABLE or selected transient failures when the method is idempotent. Do not retry INVALID_ARGUMENT, PERMISSION_DENIED, or failed business validations. For writes, require idempotency keys before enabling retries.
Use a service mesh when you have many services, multiple teams, strict security requirements, or frequent traffic shifting.
Do not introduce a full mesh for a five-service system unless compliance or platform standards require it. The cost is real: sidecar resources, more moving parts, harder debugging, and policy mistakes that can break healthy services.
For a small system, start without a mesh and design the gRPC services so they can run behind Envoy later. Keep deadlines, health checks, clear status codes, and idempotency in the application. The mesh improves enforcement. It does not fix unclear API semantics.
If the design already assumes Kubernetes, many internal services, and zero-trust requirements, choose Istio or another mature mesh. If the design is a simpler internal tool with a low service count, use standard load balancing, TLS, and application-level observability first.
The deciding factors are service count, team count, security requirements, and traffic-release complexity.
gRPC needs method-level metrics. Host CPU and memory are insufficient.
Track request count, latency, error rate, deadline exceeded count, payload size, and per-method status codes. For streaming, also track active streams, stream duration, messages per stream, and disconnect reason.
Use structured logs with request IDs and trace IDs. Distributed tracing helps because one user operation may cross five services and fail in the fourth.
A mesh can emit proxy-level telemetry. The application still needs business context.
Interview-safe answer: “I would monitor gRPC method latency, error codes, deadline exceeded rate, retry rate, and active streams. For mesh-managed traffic, I would also watch Envoy upstream errors and mTLS certificate health.”
Default: Use unary gRPC with protobuf for internal service-to-service APIs. Evolve schemas through additive fields with permanent field numbers. Reserve deleted field numbers and names. Use server streaming for subscriptions or large incremental responses. Use client streaming for uploads or telemetry batches. Use bidirectional streaming only for interactive sessions. For a multi-team Kubernetes environment, run gRPC through Envoy/Istio with mesh-managed mTLS, method-level observability, explicit deadlines, conservative retries, and canary traffic control.
Warning:
- They say protobuf is backward-compatible without explaining field numbers. Field numbers are the wire contract and must never be reused.
- They delete fields without reserving numbers and names. That creates a future corruption bug when another engineer reuses the old tag.
- They confuse renaming a field with changing a field’s meaning. Renaming can be safe. Changing semantics is unsafe.
- They make new fields logically required and forget old clients. During rolling deploys, old clients omit the field, so the server needs a default, compatibility path, or new method.
- They use bidirectional streaming when server streaming is enough. Bidirectional streams add ordering, flow control, and recovery complexity.
- They describe streaming without disconnect behavior. Every stream needs cancellation, timeout, heartbeat, and resume or duplicate-handling behavior.
- They enable retries without idempotency. Retrying a non-idempotent write can duplicate payments, orders, messages, or side effects.
- They treat a service mesh as magic reliability. Mesh retries, timeouts, and mTLS help. Bad API semantics still fail.
- They forget retry amplification. Client retries plus proxy retries plus database retries can turn one request into many backend operations.
- They explain mTLS only as encryption. The interview-relevant point is service identity and authorization between workloads.
| Category | 2026 number | How to use it in gRPC design |
|---|---|---|
| General-purpose machine RAM | 512 GiB | A single service instance can hold large connection pools and hot metadata, while active streams still need limits |
| Memory-optimized RAM | 4 TB | Useful for high-fanout routing, caching, or large in-memory indexes |
| High-memory machine RAM | 24 TB | Rare and expensive; mention only for specialized workloads |
| General-purpose CPU | 128 vCPUs | High-QPS gRPC services can scale vertically, while CPU still burns on serialization, TLS, compression, and business logic |
| Local SSD | 60 TB | Useful for local queues, logs, or cache; unsafe as the only durable store |
| Local HDD | 336 TB | Cheap local capacity; poor fit for low-latency RPC serving paths |
| Datacenter network | 25-100 Gbps | Network bandwidth is usually not the first bottleneck for small protobuf messages; CPU, fanout, and downstream latency often dominate |
| Same-AZ latency | < 1 ms | Service-to-service gRPC inside one AZ can be fast, so set tight realistic deadlines |
| Cross-AZ latency | 1-2 ms | Cross-AZ calls are acceptable for availability, while fanout multiplies tail latency |
| US-EU latency | 70-90 ms | Avoid synchronous gRPC calls across continents on a user-critical path unless the latency budget allows it |
| US-India latency | 150-250 ms | Prefer async replication or regional serving for interactive flows |
| Redis GET | < 1 ms | Cache lookups can be faster than network fanout; add cache only when read load or latency requires it |
| Postgres indexed read | 1-5 ms | A database read may be comparable to several internal RPC hops; avoid unnecessary service fanout |
| S3 first byte | 50-100 ms | Use streaming or async workflows for object-backed responses |
| Kafka throughput | 1M+ msg/sec per cluster | Prefer Kafka over gRPC streams for durable high-volume event distribution |
| Postgres single primary | 10K-50K TPS | A single primary handles many interview-scale workloads |
| Redis throughput | 100K-500K ops/sec per instance | Good for hot metadata, rate limits, and ephemeral state |
| QPS estimate | DAU × actions/user ÷ 86,400; peak 2-3× average | Use this before claiming gRPC, cache, or sharding is required |
| Bandwidth estimate | QPS × average response size | Use protobuf response size to check whether network is material |