gRPC Interview Questions & Answers
A comprehensive guide for backend developers learning gRPC
Table of Contents
1. Basic Level
Introduction to gRPC
Q1: What is gRPC and why was it created?
Answer: gRPC (Google Remote Procedure Call) is a modern, high-performance RPC framework that can run in any environment. It was created by Google to overcome the limitations of REST/JSON in internal service-to-service communication.
Key Technical Foundations:
- HTTP/2 Transport: Uses advanced features like multiplexing (multiple requests over one connection), header compression (HPACK), and server push.
- Protocol Buffers (Protobuf): Uses a binary serialization format that is much smaller and faster to process than JSON.
- Interface Definition Language (IDL): You define your service and message structures in a
.protofile, and gRPC generates client/server code in almost any language.
Why it was created: To provide a more efficient, strictly-typed alternative to REST for microservices. It solves problems of performance, latency, and "contract drift" (where API documentation doesn't match the actual implementation).
Q2: What are the main differences between REST and gRPC?
Answer: gRPC and REST represent different philosophies for service communication.
| Feature | REST | gRPC |
|---|---|---|
| Protocol | HTTP/1.1 (usually) | HTTP/2 |
| Payload | JSON/XML (Text) | Protobuf (Binary) |
| Contract | Implicit (Swagger/OpenAPI) | Explicit (.proto file) |
| Communication | Request/Response | Unary & Streaming (4 types) |
| Browser Support | Native | Via gRPC-Web proxy |
| Latency | Higher (Header overhead) | Extremely low |
| Language Support | Universal | Via Code Generation |
Comparison Example:
- In REST, if you change a field name in the database, the client might crash because the JSON changed.
- In gRPC, the contract is enforced at compile-time. If the
.protofile changes, both client and server code must be regenerated, catching errors before deployment.
Q3: What is Protocol Buffers (Protobuf)?
Answer: Protobuf is gRPC's default serialization format. It is language-neutral and platform-neutral.
How it works:
Instead of sending text like {"id": 123, "name": "John"}, Protobuf serializes data into a compact binary format. It doesn't send the field names (like "id" or "name") over the wire; it only sends the field numbers (tags) defined in the .proto file.
Example .proto file:
syntax = "proto3";
message User {
int32 id = 1; // Field tag 1
string name = 2; // Field tag 2
string email = 3;
repeated string tags = 4; // A list of strings
}
Advantages:
- Size: Binary format is 3-10 times smaller than JSON.
- Speed: 20-100 times faster to serialize/deserialize than JSON/XML.
- Backward Compatibility: You can add new fields without breaking old clients (as long as you don't change field tags).
Q4: What are the different gRPC service methods?
Answer: gRPC supports four types of service methods:
1. Unary RPC - Single request, single response (like a normal function call):
rpc GetUser (GetUserRequest) returns (User);
This works like a regular function call where the client sends one request and gets one response back.
2. Server Streaming RPC - Single request, stream of responses:
rpc GetUserPosts (GetUserPostsRequest) returns (stream Post);
The server can send multiple responses to a single request, useful for real-time updates or streaming data.
3. Client Streaming RPC - Stream of requests, single response:
rpc UploadPosts (stream Post) returns (UploadResponse);
The client sends multiple requests and gets one consolidated response at the end, useful for batch uploads.
Q5: What are the four types of gRPC Service Methods?
Answer: gRPC supports four different communication patterns between a client and a server.
-
Unary RPC (Request-Response):
- The most common pattern. The client sends a single request and gets a single response.
- Analogue to a standard HTTP call.
rpc GetUser(UserRequest) returns (UserResponse);
-
Server Streaming RPC:
- The client sends one request and the server returns a stream of messages.
- Perfect for fetching a large list of data or real-time feeds.
rpc ListUsers(ListRequest) returns (stream User);
-
Client Streaming RPC:
- The client sends a stream of messages and the server returns a single response at the end.
- Useful for uploading large files or batch data.
rpc UploadLogs(stream Log) returns (UploadStatus);
-
Bidirectional Streaming RPC:
- Both client and server send a stream of messages over the same connection.
- The two streams operate independently, allowing complex real-time interactions (like chat).
rpc ChatRoom(stream Message) returns (stream Message);
Q6: What is the role of HTTP/2 in gRPC?
Answer: HTTP/2 is the transport backbone of gRPC. It provides several critical features that enable gRPC's high performance:
- Multiplexing: Unlike HTTP/1.1 (which requires a new connection for each request), HTTP/2 allows multiple requests and responses to be sent over a single TCP connection simultaneously. This reduces latency significantly.
- Binary Framing: Messages are broken into small binary frames, making them easier to parse and more efficient to transmit.
- Header Compression (HPACK): HTTP headers are often repetitive. HTTP/2 compresses these headers, saving bandwidth.
- Full Duplex: Both sides can send data at the same time without waiting for each other, enabling the native streaming features of gRPC.
Comparison:
- REST (HTTP/1.1): One request = One connection (or sequential requests). Heavy headers.
- gRPC (HTTP/2): Many requests = One connection. Compressed headers. Binary speed.
Both client and server can send multiple messages independently, perfect for chat applications and real-time collaboration.
Q7: What is a .proto file?
Answer: A .proto file is where you define your gRPC service and message structures. It serves as the contract between client and server, ensuring both sides know exactly what data will be sent and received.
A complete example looks like:
syntax = "proto3";
package user_service;
option go_package = "github.com/example/userpb";
option java_package = "com.example.user";
service UserService {
rpc GetUser (GetUserRequest) returns (User);
rpc CreateUser (CreateUserRequest) returns (CreateUserResponse);
rpc GetUserPosts (GetUserRequest) returns (stream Post);
}
message GetUserRequest {
string id = 1;
}
message CreateUserRequest {
string name = 1;
string email = 2;
int32 age = 3;
}
message CreateUserResponse {
User user = 1;
bool success = 2;
string message = 3;
}
message User {
string id = 1;
string name = 2;
string email = 3;
int32 age = 4;
bool is_active = 5;
}
Q8: How do you generate code from .proto files?
Answer: Use the protoc compiler with language-specific plugins. For Python, you would install grpcio-tools and then generate code using:
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. user.proto
This generates two files: user_pb2.py containing protocol buffer message classes and user_pb2_grpc.py containing gRPC service stubs that you use to implement servers and clients.
Q9: What are the benefits of HTTP/2 in gRPC?
Answer: HTTP/2 provides several significant advantages for gRPC. Multiplexing allows multiple requests and responses over a single TCP connection without head-of-line blocking, unlike HTTP/1.1 where each request had to wait for the previous one to complete. Binary framing is more efficient than text-based HTTP/1.1, resulting in lower latency and better compression. Header compression using HPACK reduces overhead from repeated headers, which is significant for API calls with similar headers. Server push enables the server to send resources before the client requests them, useful for preloading related data. Bidirectional communication allows both client and server to initiate requests, enabling streaming without workarounds.
Q10: What are gRPC channels?
Answer: A gRPC channel provides a connection to a gRPC server and is used to create client stubs. You can create a basic insecure channel with grpc.insecure_channel('localhost:50051'), a secure channel with TLS using grpc.secure_channel('myserver:50051', credentials), or configure various options. Common options include grpc.max_receive_message_length for maximum message size, grpc.enable_retries to enable retry logic, and grpc.keepalive_time_ms for keepalive intervals. Channels should be closed when done to free resources.
Q11: What is gRPC metadata?
Answer: Metadata in gRPC is similar to HTTP headers and allows passing additional context with requests like authentication tokens, correlation IDs, and custom headers. On the server side, you can read metadata from context.invocation_metadata() and send metadata back using context.send_initial_metadata(). On the client side, you pass metadata as a parameter: stub.GetUser(request, metadata=[('authorization', 'Bearer token')]).
Q12: What are gRPC interceptors?
Answer: Interceptors allow you to add cross-cutting functionality like logging, authentication, and monitoring to all service methods. Server interceptors process requests before they reach the handler, while client interceptors process responses before they reach the caller. They are useful for implementing authentication, logging, metrics collection, error handling, and rate limiting across all service methods without modifying each individual service implementation.
2. Intermediate Level
Advanced gRPC Concepts
Q13: How do you handle errors in gRPC?
Answer: gRPC uses a set of standardized Status Codes (like OK, CANCELLED, NOT_FOUND, UNAUTHENTICATED) instead of HTTP status codes.
Key Detail: Since gRPC runs over HTTP/2, the HTTP level response is almost always 200 OK. The actual gRPC error is sent in the HTTP/2 Trailers.
Error Object: A gRPC error consists of:
- Code: The integer status code.
- Message: A human-readable error description.
- Details (Optional): A list of Protobuf messages that can contain structured error data (like field violations for validation).
Example Code (Python):
if not user_exists:
context.abort(grpc.StatusCode.NOT_FOUND, f"User {id} not found")
Q14: How do you implement gRPC authentication?
Answer: gRPC provides several ways to secure communication:
- SSL/TLS (Transport Security): Encrypts all data between client and server.
- ALTS: Application Layer Transport Security (used within Google's infrastructure).
- Token-based Authentication (e.g., JWT):
- The client sends the token in the Metadata (headers).
- The server uses an Interceptor (middleware) to validate the token before processing the request.
Example (Client sending JWT):
metadata = [('authorization', f'Bearer {token}')]
response = stub.MyMethod(request, metadata=metadata)
Q15: What are gRPC Deadlines and why are they better than Timeouts?
Answer: A Deadline allows a client to specify how long it is willing to wait for an RPC to complete.
The Difference:
- Timeout: "Wait 5 seconds from now."
- Deadline: "Finish this work by 10:00:05 AM."
Why Deadlines are better (Deadline Propagation): In a chain of microservices (A -> B -> C), if Service A sets a deadline of 5 seconds, Service B knows how much of that time is left after its own processing. It passes the remaining time to Service C. If the time runs out, the entire chain can stop immediately, saving resources.
Example (Server checking remaining time):
if context.time_remaining() < 0.1:
# Not enough time left to call the next service
context.abort(grpc.StatusCode.DEADLINE_EXCEEDED, "Insufficient time")
Q16: How do you implement gRPC retries?
Answer: gRPC supports automatic retry configuration through service config JSON. You specify maxAttempts, initialBackoff, maxBackoff, backoffMultiplier, and retryableStatusCodes like UNAVAILABLE and DEADLINE_EXCEEDED.
Q17: What is gRPC health checking?
Answer: gRPC includes a built-in health checking protocol. You implement a HealthServicer that responds to Check and Watch requests with states like SERVING and NOT_SERVING. Kubernetes and load balancers use this for routing traffic.
Q18: How do you implement gRPC versioning?
Answer: There are several strategies for API versioning. Package-based versioning uses different proto packages like myservice.v1 and myservice.v2. Method-based versioning adds version suffixes. Field-based evolution adds new optional fields while maintaining backward compatibility.
Q19: What are gRPC best practices for production?
Answer: Production best practices include using connection pooling, setting message size limits, enabling keepalive, implementing retries, using health checks, enabling TLS, and monitoring with distributed tracing.
Q20: What is gRPC reflection?
Answer: gRPC reflection allows clients to discover services at runtime. You enable it on the server and clients can query available services and their methods without having the .proto files. Useful for debugging tools and dynamic clients.
3. Advanced Level (Expanded)
Enterprise gRPC
Q21: What are the four types of gRPC streaming?
Answer: (1) Unary: single request, single response. (2) Server streaming: single request, stream of responses. (3) Client streaming: stream of requests, single response. (4) Bidirectional streaming: both sides stream simultaneously.
service Chat {
rpc SendMessage(stream Message) returns (stream Message);
}
🔍 Behind the Question: Streaming use cases and when to use each. ❌ The Red Flags: Using unary for everything; not understanding streaming.
Q22: What is protocol buffer versioning and how do you handle it?
Answer: Protobuf supports forward/backward compatibility through field tags. Never reuse field numbers; new fields are optional; old fields are ignored by new clients. Use reserved for deleted fields. For breaking changes, create new message types.
🔍 Behind the Question: Schema evolution and backward compatibility. ❌ The Red Flags: Changing field numbers; breaking existing clients.
Q23: What is the difference between proto2 and proto3?
Answer: proto3 is simpler: all fields optional by default, no required keyword, better cross-language support. proto2 has required/optional/repeated, default values, and richer features. proto3 is recommended for new projects.
🔍 Behind the Question: Protobuf version selection. ❌ The Red Flags: Using proto2 for new projects without reason.
Q24: How does gRPC handle load balancing?
Answer: gRPC uses HTTP/2, so traditional L7 load balancers don't work well. Options: (1) Client-side LB with service discovery. (2) Proxy-based LB (Envoy) at L4. (3) gRPC-LB protocol. (4) Kubernetes L4 with externalTrafficPolicy: Local.
🔍 Behind the Question: HTTP/2 constraints and LB strategies. ❌ The Red Flags: Using HTTP/1.1 LB logic for gRPC.
Q25: How do you handle large messages in gRPC?
Answer: Increase max message size with grpc.max_send_message_length and grpc.max_receive_message_length. For very large data, use streaming. Consider compression (gzip). For files, use chunked streaming.
🔍 Behind the Question: Message size limits and streaming alternatives. ❌ The Red Flags: Sending 100MB in a unary call.
Q26: How does gRPC handle authentication?
Answer: gRPC supports: (1) TLS for transport security. (2) Token-based auth (JWT, OAuth2) via metadata interceptors. (3) mTLS for mutual authentication. (4) Custom auth via interceptors. Tokens passed in metadata (authorization key).
🔍 Behind the Question: Security layers and auth patterns. ❌ The Red Flags: Plaintext gRPC; auth in message body.
Q27: What are gRPC interceptors and how do you use them?
Answer: Interceptors are middleware for gRPC calls. Server interceptors handle auth, logging, metrics. Client interceptors add retries, timeouts, tracing. Implement UnaryServerInterceptor or StreamServerInterceptor.
🔍 Behind the Question: Cross-cutting concerns and AOP. ❌ The Red Flags: Logging/auth in every service method manually.
Q28: How do you implement retries in gRPC?
Answer: Use client interceptors with retry policies. Configure max attempts, backoff (initial interval, multiplier, max interval), and retryable status codes (UNAVAILABLE, DEADLINE_EXCEEDED). gRPC has built-in retry support via service config.
🔍 Behind the Question: Resilience and retry strategies. ❌ The Red Flags: Retrying idempotent and non-idempotent calls the same way.
Q29: What is gRPC keepalive and when should you configure it?
Answer: Keepalive pings detect dead connections and keep NAT/firewall state alive. Configure grpc.keepalive_time_ms, grpc.keepalive_timeout_ms, and grpc.keepalive_permit_without_calls.
🔍 Behind the Question: Network reliability and connection management. ❌ The Red Flags: Default keepalive causing issues with load balancers.
Q30: How do you debug gRPC applications?
Answer: Use grpcurl for CLI debugging, gRPC UI for web-based exploration, enable tracing (OpenTelemetry), check server logs, use Wireshark for network-level debugging, and enable gRPC logging (GRPC_TRACE env var).
🔍 Behind the Question: Tooling and observability. ❌ The Red Flags: No debugging tools; guessing from client errors.
Q31: What is gRPC deadline propagation?
Answer: Deadlines propagate across service calls. If service A calls B with a 500ms deadline, and B takes 400ms, A only has 100ms left. Propagate via context. Set deadlines at the edge and let them flow through the system.
🔍 Behind the Question: Distributed system timeouts and cascading failures. ❌ The Red Flags: Not propagating deadlines; setting new deadlines at each hop.
Q32: How do you test gRPC services?
Answer: Use grpc_testing for unit tests with in-process server. Use test containers for integration tests. Use grpcurl or custom test clients for contract tests. Test error cases, timeouts, and streaming behavior.
🔍 Behind the Question: Testing strategies for RPC services. ❌ The Red Flags: Only testing happy path; no error case tests.
Q33: How do you handle gRPC deadline exceeded errors?
Answer: Handle DEADLINE_EXCEEDED status in interceptors. Return appropriate error to client. Consider retrying with backoff if idempotent. Log for debugging. Set reasonable deadlines at edge (e.g., 5s for UI APIs, 30s for batch).
🔍 Behind the Question: Timeout handling and user experience. ❌ The Red Flags: Infinite timeouts; no retry on transient failures.
Q34: What is gRPC request coalescing?
Answer: When multiple clients request the same data simultaneously, coalesce into one backend call. Implement in client interceptors or service mesh. Reduces duplicate work for hot keys.
🔍 Behind the Question: Cache efficiency and load reduction. ❌ The Red Flags: Thundering herd on hot endpoints.
Q35: How do you version gRPC APIs?
Answer: Strategies: (1) New service version: UserServiceV2. (2) New method: GetUserV2. (3) New fields in message: old clients ignore new fields. (4) Deprecate old methods. Use package naming or service naming for major versions.
🔍 Behind the Question: API evolution and backward compatibility. ❌ The Red Flags: Breaking existing clients without versioning.
Q36: How does gRPC compare to Apache Thrift?
Answer: Both are RPC frameworks with IDL and code generation. gRPC uses HTTP/2 and Protobuf; Thrift has more transport options. gRPC has better streaming and ecosystem (Envoy, Istio). Thrift is older and more flexible in transports.
🔍 Behind the Question: RPC framework comparison. ❌ The Red Flags: Not knowing when to choose Thrift over gRPC.
Q37: What is gRPC load balancing with service mesh?
Answer: Service mesh (Istio, Linkerd) handles load balancing at the sidecar proxy level. Uses round-robin, least connections, or consistent hashing. Handles retries, timeouts, and circuit breaking. Transparent to application code.
🔍 Behind the Question: Modern infrastructure patterns. ❌ The Red Flags: Implementing custom LB when service mesh exists.
Q38: How do you handle gRPC message compression?
Answer: Enable compression per RPC or globally. gRPC supports gzip by default. Set grpc.default_compression_algorithm or per-call. Trade-off: CPU for bandwidth. Good for large payloads; bad for small messages.
response = stub.GetUser(request, compression=grpc.Compression.Gzip)
🔍 Behind the Question: Performance trade-offs. ❌ The Red Flags: Compressing everything regardless of size.
Q39: What is gRPC-Web and when do you need it?
Answer: gRPC-Web is a protocol for browser clients to communicate with gRPC servers. Browsers don't support raw HTTP/2 with TLS and binary frames. gRPC-Web uses HTTP/1.1 or HTTP/2 with a proxy (Envoy) that translates between gRPC-Web and gRPC.
🔍 Behind the Question: Browser compatibility and gRPC adoption. ❌ The Red Flags: Expecting gRPC to work natively in browsers.
Q40: How do you handle file uploads in gRPC?
Answer: Use client streaming: client streams chunks, server receives and assembles. Or use a hybrid: metadata with file info + stream of bytes. For large files, chunk size matters (default 4MB max message size). Consider resumable uploads.
🔍 Behind the Question: Streaming patterns and large data handling. ❌ The Red Flags: Sending large files in unary calls.
Q41: What is gRPC name resolution?
Answer: gRPC resolves service names to addresses via name resolvers (DNS, etcd, Consul). The default is DNS. For service meshes, use xDS-based resolution. Custom resolvers can be implemented via the resolver package.
🔍 Behind the Question: Service discovery integration. ❌ The Red Flags: Hardcoding IPs; no service discovery.
Q42: How do you implement request/response logging in gRPC?
Answer: Use unary interceptors to log request/response metadata and status. For streaming, use stream interceptors. Be careful with large messages and PII. Log to structured format (JSON) with trace IDs.
🔍 Behind the Question: Observability and debugging. ❌ The Red Flags: Logging full message bodies in production.
Q43: How do you handle gRPC connection pooling?
Answer: gRPC clients maintain connection pools. Configure grpc.client_idle_timeout, grpc.connection_idle_timeout, and max connections per endpoint. Reuse channels instead of creating per-request. Monitor connection count.
🔍 Behind the Question: Connection management and resource efficiency. ❌ The Red Flags: Creating new channel per request.
Q44: What is gRPC client-side load balancing?
Answer: gRPC supports client-side LB via the round_robin policy. Configure in service config or via channel args. Client picks endpoint from resolver. Works with DNS or custom resolvers.
channel = grpc.insecure_channel(
'dns:///user-service',
[('grpc.lb_policy_name', 'round_robin')]
)
🔍 Behind the Question: Client-side LB and service discovery. ❌ The Red Flags: Single hardcoded endpoint; no failover.
Q45: How do you implement gRPC health checks for Kubernetes?
Answer: Implement the gRPC health checking protocol. Kubernetes probes gRPC services via the health endpoint. Configure grpc.health.v1.Health service. Use readiness and liveness probes.
# Kubernetes probe
livenessProbe:
grpc:
port: 50051
service: user.UserService
🔍 Behind the Question: Kubernetes integration and HA. ❌ The Red Flags: HTTP health checks for gRPC services.
Q46: What is gRPC reflection and when is it useful?
Answer: Server reflection allows clients to query what methods and types a server supports. Useful for debugging, generic clients, and tools like grpcurl or gRPC UI. Enable with grpc.reflection.v1alpha.ServerReflection server.
🔍 Behind the Question: Dynamic discovery and tooling. ❌ The Red Flags: Disabling reflection and wondering why generic clients don't work.
Q47: How do you handle gRPC errors gracefully?
Answer: Map gRPC status codes to application errors. Return INVALID_ARGUMENT for bad input, NOT_FOUND for missing resources, ALREADY_EXISTS for duplicates, PERMISSION_DENIED for auth failures, UNAVAILABLE for downstream errors. Don't return INTERNAL for expected errors.
🔍 Behind the Question: Error handling and API design.
❌ The Red Flags: Returning INTERNAL for all errors.
Q48: How do you implement gRPC tracing with OpenTelemetry?
Answer: Use OpenTelemetry gRPC instrumentation. Propagate trace context via gRPC metadata. Each interceptor creates spans for incoming/outgoing calls. Export to Jaeger, Zipkin, or OTLP collector.
server = grpc.server(interceptors=[OpenTelemetryServerInterceptor()])
🔍 Behind the Question: Observability in microservices. ❌ The Red Flags: No trace propagation across services.
Q49: What is gRPC gateway and when should you use it?
Answer: gRPC Gateway generates a RESTful reverse proxy from gRPC service definitions. Add HTTP annotations to .proto files. Allows HTTP clients to interact with gRPC services. Useful for browser clients or third-party integrations.
google.api.http {
post: "/v1/users"
body: "*"
}
🔍 Behind the Question: API gateway patterns and backward compatibility. ❌ The Red Flags: Maintaining separate REST and gRPC APIs manually.
Q50: How do you secure gRPC in production?
Answer: Enable TLS with valid certificates. Use mTLS for mutual authentication. Implement auth interceptors for JWT/OAuth2. Rate limit at gateway. Validate all inputs. Rotate certificates regularly. Use service mesh for automatic mTLS.
🔍 Behind the Question: Production security posture. ❌ The Red Flags: Plaintext gRPC; no certificate rotation.
4. Real-World Scenarios (Expanded)
Q51: Design a real-time gaming leaderboard
Answer: Use gRPC bidirectional streaming for live score updates. Server maintains sorted set of scores, pushes top-K changes to connected clients. Use Redis for score storage. Clients stream heartbeats to detect disconnections.
🔍 Behind the Question: Real-time systems and streaming. ❌ The Red Flags: Polling for leaderboard updates.
Q52: Design a gRPC-based file processing pipeline
Answer: Client streams files to server. Server processes chunks (transcode, analyze) and streams progress back. Use client streaming for upload, server streaming for progress. Implement checkpoint/resume for large files.
🔍 Behind the Question: Streaming patterns and large data. ❌ The Red Flags: Loading entire file into memory.
Q53: Design a gRPC microservices architecture for e-commerce
Answer: Services: User, Product, Cart, Order, Payment, Notification. Each exposes gRPC API. API Gateway handles external traffic. Service mesh for observability and security. Event-driven via Kafka for async operations.
🔍 Behind the Question: Microservice design and gRPC orchestration. ❌ The Red Flags: Chatty synchronous calls between all services.
Q54: Design a gRPC-based IoT data ingestion system
Answer: Devices use bidirectional streaming to send telemetry. Server validates, enriches, and writes to time-series DB. Use device authentication via mTLS. Implement backpressure when server is overloaded.
🔍 Behind the Question: IoT patterns and streaming at scale. ❌ The Red Flags: Unary calls per sensor reading.
Q55: Design a gRPC caching layer for product catalog
Answer: gRPC service checks Redis cache first. On miss, fetches from DB and populates cache. Use hash-based cache keys. Implement cache invalidation on product updates. Return cached response for hot products.
🔍 Behind the Question: Caching strategies and gRPC integration. ❌ The Red Flags: No cache invalidation; stale product data.
Q56: Design a gRPC-based real-time collaboration tool
Answer: Use bidirectional streaming for operation flow (OT/CRDT). Server broadcasts operations to all clients. Implement presence via heartbeats. Use Redis pub/sub for multi-instance broadcasting.
🔍 Behind the Question: Real-time collaboration and conflict resolution. ❌ The Red Flags: Last-write-wins; no conflict resolution.
Q57: Design a gRPC monitoring and alerting system
Answer: gRPC interceptors collect metrics (request count, latency, errors). Export to Prometheus. Alert on error rate > 1%, p99 latency > 500ms. Dashboards in Grafana. Trace slow requests with OpenTelemetry.
🔍 Behind the Question: Observability and SRE practices. ❌ The Red Flags: No metrics; alerting on p50 only.
Q58: Design a gRPC-based authentication and authorization system
Answer: gRPC interceptors validate JWT tokens. Extract user ID from context. Implement RBAC in interceptor: check user roles against required permissions. Use mTLS for service-to-service auth. Refresh tokens via separate endpoint.
🔍 Behind the Question: Security architecture and interceptors. ❌ The Red Flags: Auth in every service method; no centralized interceptor.
Q59: Design a gRPC-based logging aggregation system
Answer: Services stream logs to a central logging service via gRPC. Logging service buffers, indexes, and stores logs. Use client streaming for high-volume log ingestion. Implement backpressure and batching.
🔍 Behind the Question: Log aggregation and streaming ingestion. ❌ The Red Flags: Synchronous logging; no batching.
Q60: Design a gRPC-based metrics collection system
Answer: Services push metrics to a metrics service via gRPC. Metrics service aggregates and exports to Prometheus. Use client streaming for high-frequency metrics. Implement sampling for high-cardinality metrics.
🔍 Behind the Question: Metrics collection and streaming. ❌ The Red Flags: Pulling metrics; no streaming aggregation.
Q61: Design a gRPC-based CI/CD pipeline trigger system
Answer: CI/CD system calls gRPC service to trigger deployments. Service validates, queues, and executes deployment. Streams logs and status back to CI/CD. Implement retries and circuit breaker for resilience.
🔍 Behind the Question: CI/CD integration and streaming logs. ❌ The Red Flags: Polling for deployment status.
Q62: Design a gRPC-based feature flag system
Answer: Feature flag service exposes gRPC API for flag evaluation. Clients stream flag keys and get batch responses. Use streaming for real-time flag updates. Implement targeting rules in service.
🔍 Behind the Question: Feature flags and streaming evaluation. ❌ The Red Flags: Polling for flag changes; no batching.
Q63: Design a gRPC-based A/B testing system
Answer: A/B testing service assigns variants via gRPC. Clients stream experiment assignments. Server tracks metrics per variant. Use consistent hashing for assignment. Stream real-time results.
🔍 Behind the Question: A/B testing and streaming metrics. ❌ The Red Flags: Random assignment per request; no statistical rigor.
5. Quick Reference (Expanded)
gRPC Status Codes
| Code | Meaning | Common Cause |
|---|---|---|
OK | Success | - |
INVALID_ARGUMENT | Bad input | Validation failure |
NOT_FOUND | Resource missing | ID not found |
ALREADY_EXISTS | Duplicate | Unique constraint |
PERMISSION_DENIED | Auth failed | Invalid token |
RESOURCE_EXHAUSTED | Quota exceeded | Rate limit |
FAILED_PRECONDITION | Bad state | Invalid state transition |
ABORTED | Conflict | Concurrent modification |
OUT_OF_RANGE | Range error | Pagination overflow |
UNIMPLEMENTED | Not supported | Method missing |
INTERNAL | Server error | Unexpected error |
UNAVAILABLE | Service down | Network, overloaded |
DATA_LOSS | Corruption | Invalid data |
DEADLINE_EXCEEDED | Timeout | Slow backend |
gRPC CLI Tools
# grpcurl - like curl for gRPC
grpcurl -plaintext localhost:50051 list
grpcurl -plaintext -d '{"id": 1}' localhost:50051 user.UserService/GetUser
# gRPC UI - web-based explorer
grpcui -plaintext localhost:50051
# ghz - benchmarking
ghz --insecure -n 1000 -c 10 -d '{"id": 1}' \
localhost:50051 user.UserService/GetUser
gRPC Best Practices
- Always set deadlines on client calls
- Use streaming for large or real-time data
- Implement proper error handling with status codes
- Use interceptors for auth, logging, metrics
- Enable TLS in production
- Use mTLS for service-to-service
- Version APIs carefully
- Test error cases and timeouts
- Monitor with distributed tracing
- Use service mesh for complex deployments
- Compress large messages
- Implement health checks
- Use protoc for code generation
- Document proto files
- Handle connection failures gracefully
End of Guide
3. Advanced Level
Enterprise gRPC
Q64: How do you implement distributed tracing with gRPC?
Answer: Use OpenTelemetry for distributed tracing. Configure a tracer provider with exporters like Jaeger or Zipkin, and use grpc_instrumentation for automatic span creation. This enables tracking requests across multiple services.
Q65: What is gRPC gateway?
Answer: gRPC Gateway creates RESTful APIs from gRPC service definitions. Add HTTP annotations to .proto files, generate gateway code, and run both gRPC server and REST gateway. Allows HTTP clients to interact with gRPC services.
Q66: How do you migrate from REST to gRPC?
Answer: Migration involves creating proto definitions, implementing gRPC services, creating REST-to-gRPC adapters, updating clients gradually, and removing REST endpoints. The adapter approach lets you run both APIs during migration.
Q67: What are gRPC interceptors for monitoring?
Answer: Create monitoring interceptors to collect metrics like request count, latency histograms, active requests gauge, and error rates. Use Prometheus client libraries to expose metrics for visualization with Grafana.
Q68: How do you implement circuit breaker for gRPC?
Answer: Use the circuit breaker pattern with three states: CLOSED (normal operation), OPEN (failing fast), and HALF_OPEN (testing recovery). Track failures and open the circuit when threshold is exceeded.
Q69: What are gRPC patterns for microservices?
Answer: Common patterns include event-driven architecture using pub/sub, the aggregator pattern for combining results, the chain pattern for sequential calls, and the ambassador pattern for cross-cutting concerns.
Q70: How do you secure gRPC in production?
Answer: Production security includes TLS encryption, mTLS for mutual authentication, authentication interceptors, authorization checks, rate limiting, input validation, and regular security audits.
Q71: What is gRPC performance tuning?
Answer: Performance tuning includes TCP settings like TCP_NODELAY, HTTP/2 settings, keepalive configuration, message size limits, compression, connection pooling, and load testing to identify bottlenecks.
4. Real-World Scenarios
Q72: Design a microservice communication system
Answer: A typical microservices setup has separate services for users, orders, products, and notifications, each with gRPC servers. Services communicate via gRPC clients with an API gateway handling external requests. Use service discovery for dynamic addresses.
Q73: Design a real-time notification system
Answer: A notification service uses bidirectional streaming for persistent client connections. When events occur, services publish to a message queue, the notification service consumes and streams to connected clients in real-time.
5. Quick Reference
Common .proto Types
// Primitive types
int32, int64, float, double, bool, string, bytes
// Repeated and optional
repeated string tags = 1;
optional string name = 2;
gRPC Commands
# Generate code
protoc --go_out=. --go-grpc_out=. user.proto
# Python
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. user.proto
Best Practices
- Always use protoc for code generation
- Set appropriate timeouts for all RPCs
- Implement proper error handling with status codes
- Use streaming for large data or real-time needs
- Enable TLS in production
- Implement health checks for load balancer integration
- Use interceptors for cross-cutting concerns
- Monitor with distributed tracing
End of Guide
Senior / Principal — Real World gRPC Scenarios
Q74: gRPC service down after deploy — breaking proto change
Level: Senior
Scenario: A service updates its .proto file (removes a field, changes a type) and redeploys. Client calls start failing with UNIMPLEMENTED or decoding errors. The client and server are now incompatible.
Impact: Service-to-service calls fail. Partial outage. Rollback needed.
Root Cause: Breaking protobuf schema change deployed without backward compatibility. Old clients can't parse new messages; new server rejects old field tags.
Simple explanation: You change the language of a form mid-stream. People filling out the old form can't be understood by the new processor.
Technical Answer:
- Protobuf backward compatibility: only add fields (with new field numbers), never remove or renumber. Mark deprecated fields instead of deleting.
- Use
optionalkeyword (proto3) for new fields so old clients ignore unknown fields. - Version the service endpoint (e.g.,
/v1/,/v2/) when breaking change is unavoidable. - Run schema compatibility checks in CI (buf breaking).
- Deploy server first (backward-compatible with old clients), then clients.
Code/Syntax Justification:
// Backward-compatible: add new field with new number
message User {
string id = 1;
string name = 2;
string phone = 3; // new field, old clients ignore
optional string email = 4; // optional, proto3
}
// Never: renumber or delete field 2
Workflow Diagram:
Breaking proto change
|
v
Old client sends field 2 New server expects new schema
| |
v v
Decoding error / UNIMPLEMENTED |
| v
Rollback or versioned endpoint Deploy backward-compatible change first
🔍 Behind the Question: Protobuf backward compatibility, field numbers, optional fields, versioning, buf breaking.
❌ The Red Flags: Removing/renumbering fields; deploying client and server simultaneously with breaking change; no schema compatibility CI.
Q75: High latency in gRPC service-to-service calls
Level: Principal
Scenario: Internal gRPC calls between microservices average 200ms. Under load, p99 spikes to 5 seconds. CPU is low. The team suspects network but can't pinpoint.
Impact: Slow user-facing API. Timeout cascades. Poor UX.
Root Cause: No connection pooling (new TCP/TLS handshake per request), no keep-alive, no load balancing, or large message serialization overhead. Each gRPC call opens a new connection.
Simple explanation: Dialing a phone number for every sentence in a conversation instead of staying on the line.
Technical Answer:
- Reuse gRPC channels (connection pooling) — create channel once, reuse across calls.
- Enable keep-alive and connection pooling on client.
- Use round-robin / DNS load balancing across service instances.
- Compress messages (
gzipcompression) for large payloads. - Profile with
grpcurland distributed tracing to find slow methods. - Consider binary protobuf already helps; avoid JSON-in-protobuf wrappers.
Code/Syntax Justification:
# Reuse channel (create once at app startup)
channel = grpc.insecure_channel("localhost:50051")
stub = user_pb2_grpc.UserStub(channel)
# Per call: reuse stub, no new connection
response = stub.GetUser(user_pb2.UserRequest(id=user_id))
Workflow Diagram:
New connection per call: Reused channel:
dial + TLS handshake + call dial once + TLS once
| |
v v
200ms base latency 5ms base latency
under load: 5s p99 under load: 50ms p99
🔍 Behind the Question: Connection pooling, channel reuse, keep-alive, load balancing, compression, tracing.
❌ The Red Flags: New channel per gRPC call; no keep-alive; no load balancing; no tracing.