Spring / Spring gRPC Interview Questions
1. What is gRPC and why would you use it in a Spring application?
gRPC is an open-source, high-performance remote procedure call (RPC) framework built on HTTP/2, originally developed by Google. It uses Protocol Buffers as its interface definition language and wire format. In a Spring application, gRPC is chosen when a service needs low-latency, strongly-typed c...
2. How does gRPC differ from traditional REST APIs?
The two differ at both the transport and payload layers. gRPC runs on HTTP/2 , which multiplexes many logical streams over a single TCP connection and compresses headers; classic REST implementations typically run on HTTP/1.1, opening more connections and repeating full headers per request. On th...
3. What are the four types of service methods gRPC supports?
A gRPC service method can be declared as one of four call shapes in the .proto file: Unary RPC - one request, one response, like a normal method call. Server streaming RPC - one request, a stream of responses. Client streaming RPC - a stream of requests, one final response. Bidirectional streamin...
4. What role does HTTP/2 play in gRPC?
HTTP/2 is the transport layer gRPC is built on, and several of its features are what make gRPC's performance and streaming model possible. Multiplexing lets many independent request/response streams share a single TCP connection without one slow call blocking others (no head-of-line blocking at t...
5. What is a.proto file and what is it used for?
A .proto file is a Protocol Buffers interface definition file . It declares two things: message types, which describe the shape of data exchanged, and service definitions, which list the RPC methods a service exposes along with each method's request and response message types. syntax = "proto3"; ...
6. What is the role of the protoc compiler and code-generation plugins in a Spring project?
protoc is the Protocol Buffers compiler; it parses .proto files and emits generated source code - message classes with immutable builders, and gRPC service base classes plus client stub classes (blocking, async, and future variants). In a Spring/Maven project this is usually wired through the pro...
7. What is a gRPC channel, and how does it differ from a single HTTP connection?
A ManagedChannel is a virtual, logical connection to a gRPC endpoint. It is not tied to exactly one TCP socket - internally it can manage connection setup, reconnection, and (with the right resolver/balancer configuration) distribute calls across multiple backend addresses. Application code never...
8. What are gRPC status codes, and how do they compare to HTTP status codes?
gRPC defines its own enumerated Status codes - values like OK , NOT_FOUND , INVALID_ARGUMENT , DEADLINE_EXCEEDED , UNAVAILABLE , PERMISSION_DENIED , and UNAUTHENTICATED - that map conceptually to HTTP status ranges but are tailored specifically to RPC semantics rather than generic web resource se...
9. What are the advantages of Protocol Buffers over JSON for service payloads?
Protobuf messages are binary and compact , which means smaller payloads on the wire and faster serialization/deserialization than text-based JSON - meaningful at high request volumes or for large messages. Protobuf also enforces a strict, versioned schema at compile time: field types and structur...
10. Explain field numbering in a.proto message and why it matters?
Every field inside a protobuf message declaration carries a unique integer tag, for example string name = 1; . That number , not the field name, is what actually gets encoded on the wire. This matters because it is the basis of protobuf's binary compatibility guarantees: once a message is used in...
11. How does protobuf handle backward and forward compatibility?
Protobuf is designed so that old and new versions of a message can coexist safely, provided a few rules are followed. Adding a new field with a fresh, unused tag number is safe: older code simply ignores the field it doesn't recognize, and newer code sees the field's default when talking to an ol...
12. What is the difference between proto2 and proto3 syntax?
proto2 distinguishes required , optional , and repeated fields explicitly, and lets you customize default values per field. proto3 simplified this: it dropped the required qualifier entirely (all singular fields behave as implicitly optional, taking a language-specific default such as 0 , empty s...
13. What Java types do common protobuf scalar types map to?
Protobuf type Generated Java type int32 / int64 int / long bool boolean string String bytes ByteString double / float double / float repeated T List
14. How do you handle optional vs unset primitive fields in proto3?
By default in proto3, a scalar field like int32 count = 1; cannot distinguish between 'the client never set this' and 'the client explicitly set it to zero' - both serialize to the same absent-on-the-wire representation, and the generated getter simply returns the default. Two common solutions: d...
15. What are the main ways to integrate gRPC into a Spring Boot application?
Two approaches are common. The first is the community-maintained grpc-spring-boot-starter (originally by devh/yidongnan, now continued under the grpc-ecosystem/grpc-spring project), which provides @GrpcService and @GrpcClient annotations plus autoconfiguration for an embedded Netty-based gRPC ser...
16. What does the @GrpcService annotation do?
@GrpcService marks a class - one that extends a generated *ImplBase base class from your .proto definition - as both a regular Spring-managed bean and a gRPC service that should be registered on the embedded gRPC server. @GrpcService public class GreetingService extends GreeterGrpc . GreeterImplB...
17. How do you configure the gRPC server port in a Spring Boot app using the community starter?
The port is set through standard Spring configuration properties, separate from the servlet/reactive HTTP port: grpc: server: port: 9090 By default, the community starter runs an embedded Netty-based gRPC server that is entirely independent of Spring MVC/WebFlux's HTTP port (commonly 8080). This ...
18. How do you create and inject a gRPC client stub in Spring?
With the community starter, you declare a stub field annotated with @GrpcClient("service-name") : @GrpcClient ( "order-service" ) private OrderServiceGrpc . OrderServiceBlockingStub orderStub; The target address is configured separately, e.g. grpc.client.order-service.address=static://localhost:9...
19. What is the difference between a blocking stub, a non-blocking async stub, and a future stub in generated gRPC client code?
Stub type Behavior Blocking stub Synchronous call; calling thread waits for the response Async stub Takes a StreamObserver callback; non-blocking, supports all four call types Future stub Unary calls return a ListenableFuture, useful for async/reactive composition Choosing between them depends on...
20. How does Spring's dependency injection interact with generated gRPC service classes?
Generated *ImplBase classes coming out of protoc are plain Java classes with no knowledge of Spring - they are not beans on their own. The integration point is your own class, which extends the generated base class and is annotated with @GrpcService . Because that subclass is a normal Spring bean...
21. Can gRPC and Spring MVC or WebFlux REST endpoints run in the same application?
Yes. It's common to run both in a single Spring Boot process: the gRPC server (usually an embedded Netty server bound to something like port 9090) and the standard servlet or reactive web server (typically port 8080) start up side by side, sharing the same application context, beans, configuratio...
22. How do you enable gRPC server reflection in Spring Boot, and why would you?
Reflection is enabled by adding the grpc-services dependency and turning on the reflection service, e.g. with the community starter: grpc.server.reflection-service-enabled=true . Once enabled, tools such as grpcurl or Postman's gRPC support can query the running server to discover which services ...
23. How would you expose actuator-style health checks for a gRPC service?
gRPC has a standardized Health Checking Protocol (the grpc.health.v1.Health service, from io.grpc:grpc-services ), and most Spring gRPC starters can auto-register an implementation of it alongside your own services. This gives load balancers, service meshes, and Kubernetes readiness/liveness prob...
24. How do you handle configuration for multiple gRPC clients pointing to different backend services?
Each backend gets its own named client configuration block: grpc: client: order-service: address: static://order-service:9090 payment-service: address: static://payment-service:9091 Each matching @GrpcClient("order-service") / @GrpcClient("payment-service") field then resolves independently, and ...
25. How do you implement a server-streaming RPC in a Spring @GrpcService?
The generated method signature takes the request plus a StreamObserver
26. How do you implement a bidirectional streaming RPC?
The service method itself returns a StreamObserver
27. What thread-safety considerations apply to StreamObserver in gRPC?
A given StreamObserver instance's onNext / onError / onCompleted methods are not guaranteed thread-safe for concurrent invocation from multiple threads - grpc-java expects calls on one observer to be serialized (one at a time). If multiple threads (say, worker threads reacting to events from diff...
28. How does backpressure work in gRPC streaming, and how would you handle a slow consumer?
gRPC relies on HTTP/2's built-in flow control, but on the server side you can also cooperate with it explicitly using a ServerCallStreamObserver . Before writing each message you can check isReady() ; if the client hasn't caught up yet, you hold off on further onNext() calls rather than buffering...
29. When would you choose client streaming over unary calls in a Spring service?
Client streaming fits scenarios where the client needs to send a sequence of related items and only cares about a single aggregated response at the end - for example, uploading chunks of a large file, or submitting a batch of telemetry events - rather than the server responding to each item indiv...
30. How would you test streaming gRPC endpoints in a Spring Boot integration test?
The standard approach uses io.grpc:grpc-testing 's GrpcCleanupRule (JUnit 4) or the equivalent extension (JUnit 5), together with InProcessServerBuilder / InProcessChannelBuilder to run a real server and stub pair without opening actual network sockets. To assert on a streamed response, you imple...
31. What is a ServerInterceptor in gRPC, and what is it typically used for?
A ServerInterceptor wraps every incoming call before it reaches your service method, similar in role to a servlet filter in a traditional web stack. It's the natural place for cross-cutting concerns: authentication/authorization checks, structured logging, metrics collection, or metadata inspecti...
32. How do you propagate contextual data such as a request ID or authenticated user through a gRPC call in Spring?
gRPC provides its own io.grpc.Context API, which behaves like a ThreadLocal but is designed to propagate correctly across the async, callback-driven code paths that streaming calls use (where a plain ThreadLocal would often lose its value across thread hops). The typical pattern is: an intercepto...
33. How should errors be communicated back to the client in gRPC, and how does this differ from throwing a plain exception?
Errors should be surfaced explicitly through gRPC's Status / StatusRuntimeException mechanism, e.g. Status.INVALID_ARGUMENT.withDescription("customerId is required").asRuntimeException() , optionally enriched with structured google.rpc.Status details for machine-readable error payloads. If an unc...
34. How do you implement centralized exception handling for gRPC services in Spring, analogous to @ControllerAdvice for REST?
There is no built-in gRPC equivalent of @ControllerAdvice in core Spring. The common workaround is a ServerInterceptor that wraps the call's ServerCall.Listener , catching exceptions thrown while handling the call and translating them consistently into the right Status code before closing the cal...
35. What is gRPC Metadata, and how does it compare to HTTP headers?
Metadata is gRPC's key-value container for out-of-band information sent alongside a call - things like authentication tokens, correlation/request IDs, or client version info - conceptually the same role HTTP headers play for REST, and in fact implemented on top of actual HTTP/2 headers and traile...
36. How would you implement deadline/timeout handling for gRPC calls from a Spring client?
A deadline is set on the stub before making the call, e.g. stub.withDeadlineAfter(500, TimeUnit.MILLISECONDS).getOrder(request) . If the server hasn't responded by then, the call fails on the client with Status.DEADLINE_EXCEEDED rather than hanging indefinitely. Deadlines are most effective when ...
37. How do you enable TLS for a gRPC server in a Spring Boot application?
TLS is configured by supplying certificate and private key material to the server's SSL context. With the community starter this is typically done through properties such as: grpc: server: security: enabled: true certificate-chain: file:server.crt private-key: file:server.key Under the hood these...
38. How does authentication typically work in a gRPC plus Spring setup?
Two common patterns dominate. The first is token-based : a bearer token (often a JWT) is attached via Metadata on each call, and a ServerInterceptor validates it and populates Spring Security's SecurityContext before the service method runs - conceptually similar to a REST filter validating an Au...
39. What is mTLS and why is it commonly used for internal gRPC service-to-service communication?
Mutual TLS extends normal TLS so that both parties present and validate certificates, not just the server. This gives two-way authentication (each side proves who it is) plus the usual encryption-in-transit guarantees of TLS. sequenceDiagram participant C as Client Service participant S as Server...
40. How would you restrict which gRPC methods a caller can access, i.e. authorization?
Authorization is typically implemented in a ServerInterceptor that runs after authentication has already populated the caller's identity (whether from a validated JWT or from an mTLS client certificate). The interceptor inspects the method being called (available from the call's descriptor) again...
41. How do you unit test a gRPC service implementation without starting a real server?
Since a @GrpcService class is ultimately just a plain Java class implementing the generated interface, it can be instantiated directly in a unit test like any other object - no Spring context or network layer required. GreetingService service = new GreetingService(mockDependency); TestStreamObser...
42. What is the purpose of InProcessServerBuilder and InProcessChannelBuilder in gRPC testing?
These classes let a test run a full, real gRPC server and a matching client stub entirely in-process, without opening any actual network sockets. You register your service on an InProcessServerBuilder -built server under a unique name, and build a channel with InProcessChannelBuilder.forName(same...
43. How would you write a Spring Boot integration test that spins up the embedded gRPC server?
Using @SpringBootTest , you can let the starter bind the gRPC server to a fixed or dynamically-assigned test port, then build a real stub pointed at that port to exercise the service end-to-end, including any registered interceptors and the actual Spring-managed bean graph. A common variation avo...
44. How do you assert on streaming responses in a test without blocking indefinitely?
The key is to bound how long the test is willing to wait. A CountDownLatch initialized to 1 is counted down inside the test observer's onCompleted() (and typically also on onError() , capturing the error for later assertion), and the test calls latch.await(timeout, TimeUnit.SECONDS) with a real t...
45. How does gRPC support client-side load balancing across multiple server instances?
gRPC's channel layer is pluggable at two points: a NameResolver , which turns a logical target name into a set of backend addresses (for example via DNS), and a LoadBalancer , which decides how to distribute calls across those addresses - common built-in policies include pick_first (stick to one ...
46. Why can gRPC load balancing be trickier in Kubernetes than for plain HTTP/1.1 services?
gRPC multiplexes many logical calls over a single long-lived HTTP/2 connection. A plain L4 (TCP) load balancer, or Kubernetes' default kube-proxy -based Service, balances at the connection level - so once a client establishes one long-lived HTTP/2 connection to a pod, all its calls stick to that ...
47. What connection or channel pooling considerations apply when calling gRPC services from Spring?
Because setting up a ManagedChannel involves real connection-establishment cost (DNS resolution, TCP/TLS handshake), the general rule is to create one long-lived channel per target service and reuse it for many calls, rather than building a fresh channel per request - a single HTTP/2 connection c...
48. How would you monitor gRPC service performance in a Spring Boot application?
A common approach layers a metrics-recording ServerInterceptor (or uses one provided by the starter, where available) that captures per-call latency, status codes, and message counts, and publishes them through Micrometer - the same metrics facade Spring Boot Actuator already uses for REST endpoi...
49. When would you choose gRPC over REST for a new Spring microservice, and when would you stick with REST?
Favor gRPC Favor REST/JSON Internal service-to-service calls you control on both ends Public APIs consumed by browsers or third parties Need for streaming (server, client, or bidirectional) Need for easy manual inspection (curl, browser dev tools) Strict, versioned, contract-first schemas Broad, ...
50. What are some best practices for evolving gRPC service contracts in a Spring microservices system over time?
The most important rule is protobuf-specific: never reuse or renumber an existing field tag . Add new fields with fresh tag numbers instead of repurposing old ones, and mark retired tags/names as reserved so nobody accidentally reintroduces the mistake later. At the API level, prefer additive cha...