Unary RPC in gRPC

A unary RPC sends exactly one request from the client and receives exactly one response from the server for a remote operation. It is the simplest and most common gRPC communication pattern.

In gRPC, a unary RPC follows a request-response model: the client sends one serialized request message, and the server returns one response message. The interaction resembles a normal method call, except the method executes remotely and communication happens over the network.

The RPC contract is defined in a Protocol Buffers (`.proto`) service. A unary method has one request type and one response type, without streaming on either side. gRPC generates client and server APIs from this contract.

On the Java server, an implementation typically extends the generated service base class and overrides the RPC method. The server receives the request, performs the required work, and completes the response through the provided observer or generated API, depending on the gRPC Java API being used.

Unary RPCs are appropriate when the operation naturally has one input and one result, such as fetching a user by ID or creating an order. They are less suitable when the server must continuously send results, the client sends a sequence of messages, or both sides exchange streams of messages.

Key points

Interview questions

What failure concerns should you consider with a unary gRPC call?

A unary call is still a network operation, so it can fail because of connectivity problems, server errors, or deadlines. The client should use an appropriate deadline rather than waiting indefinitely. gRPC communicates failures through status information, which the client can inspect and handle. Retry behavior should be designed carefully because retrying an operation may duplicate side effects.

What is a unary RPC in gRPC?

A unary RPC is the basic gRPC request-response pattern. The client sends exactly one request message and receives exactly one response message. The RPC is declared in a Protocol Buffers service definition. It is useful for operations such as retrieving or creating a single resource.

How do you define a unary RPC in a `.proto` file?

You declare an RPC inside a service using one request type and one response type. Neither side uses the `stream` keyword. For example, `rpc GetUser(GetUserRequest) returns (User);` defines a unary method. The gRPC tooling can then generate the corresponding Java APIs.

When would you choose unary RPC instead of streaming?

I would choose unary RPC when one request naturally maps to one result. It keeps the API simple and is a good fit for operations such as fetching a resource or submitting a command. Streaming is better when the result arrives incrementally or when either side needs to exchange multiple messages. The choice should follow the communication pattern required by the operation.