A backend serves gRPC and calls gRPC services, with all four RPC shapes: unary, server streaming, client streaming and bidirectional streaming. Calls travel over the server’s HTTP/2 listener, so a stock gRPC client in any language can call a backend service. The same services also answer gRPC-Web over HTTP/1.1, which is what the application’s @GrpcClient and browsers send.

Messages

A message is a @ProtoMessage class whose fields carry @ProtoField tags, the same classes an application uses. The build writes a codec for each one, <Message>ProtoCodec, with a shared INSTANCE. Nothing is read by reflection at run time.

Serving a service

A @GrpcService bean serves one service. Each @Rpc method serves one RPC, and its signature says which shape the RPC has:

@GrpcService("demo.Greeter")
public class Greeter {
    @Rpc("SayHello")                       // unary
    public HelloReply sayHello(HelloRequest request) {
        return reply("Hello " + request.name);
    }

    @Rpc("Countdown")                      // server streaming
    public void countdown(HelloRequest request, StreamObserver<HelloReply> out) {
        for (int i = 3; i > 0; i--) {
            out.onNext(reply(request.name + " " + i));
        }
    }

    @Rpc("Collect")                        // client streaming
    public HelloReply collect(Iterator<HelloRequest> requests) {
        StringBuilder names = new StringBuilder();
        while (requests.hasNext()) {
            names.append(requests.next().name).append(' ');
        }
        return reply(names.toString().trim());
    }

    @Rpc("Chat")                           // bidirectional streaming
    public void chat(Iterator<HelloRequest> in, StreamObserver<HelloReply> out) {
        while (in.hasNext()) {
            out.onNext(reply("Hi " + in.next().name));
        }
    }
}
  • A method may also take a trailing GrpcContext. It reads the request metadata and the deadline, says whether the client has gone, and adds response headers and trailers.

  • Throwing GrpcException ends the call with its status and message. Any other exception ends it UNKNOWN. The exception is logged, and its message isn’t sent to the client.

  • A streaming method returns when its stream is done: the call ends OK then.

  • An RPC that no bean serves is answered UNIMPLEMENTED. A signature that isn’t one of the four shapes, and two methods serving the same RPC, are build errors.

The bean is an ordinary bean: it’s injected, takes @Transactional and the other aspects, and is wired to the server by the build.

Generating from a .proto file

cn1:generate-grpc writes the messages from a .proto file. With -Dcn1.grpc.target=backend, it writes each service for a backend:

mvn cn1:generate-grpc -Dcn1.grpc.proto=src/main/proto/greeter.proto \
    -Dcn1.grpc.basePackage=com.example.greeter -Dcn1.grpc.target=backend
  • GreeterService, an interface with one @Rpc method per RPC. A @GrpcService("demo.Greeter") class that implements it serves the service.

  • GreeterClient, a class that calls the service through a GrpcChannel.

stream is accepted on either side of an RPC in this mode.

Calling a service

GrpcChannel calls a gRPC server: another backend, or any other implementation. It’s immutable, so one channel can be shared:

GrpcChannel channel = GrpcChannel.forTarget("https://greeter.internal:8443")
        .withMetadata("authorization", "Bearer " + token)
        .withDeadlineMillis(2000);
HelloReply reply = channel.unary("/demo.Greeter/SayHello",
        HelloRequestProtoCodec.INSTANCE, HelloReplyProtoCodec.INSTANCE, request);
  • serverStreaming answers a GrpcChannel.Call, an Iterator of the responses as they arrive.

  • clientStreaming sends every message of an Iterator and answers the one response.

  • bidiStreaming answers an open Call: send and complete write the request stream, and the iterator reads responses meanwhile.

  • A call that fails throws GrpcException. A server that can’t be reached is UNAVAILABLE, and a call past its deadline is DEADLINE_EXCEEDED.

http:// targets are spoken as HTTP/2 without TLS (h2c), and https:// targets negotiate HTTP/2 through ALPN.

Protocol details

  • Messages may be compressed with gzip in either direction. withGzip(true) compresses a channel’s requests.

  • -bin metadata is base64 encoded on the wire and read as bytes by GrpcContext.getBinary.

  • grpc-timeout sets the call’s deadline. A handler that’s still running at the deadline isn’t interrupted: it should check GrpcContext.isDeadlineExceeded between units of work.

  • Messages larger than 4 MiB are refused with RESOURCE_EXHAUSTED, in either direction; GrpcServer.setMaxMessageSize and GrpcChannel.withMaxMessageSize change it.

  • The calls of one HTTP/2 connection are served one at a time, in the order they arrive. Separate connections are served in parallel. Clients such as grpc-java put every call of a channel on one connection, so a long-lived streaming call (a watch or a subscription) holds back every call queued behind it. Give such calls a channel of their own.

  • Over gRPC-Web on HTTP/1.1, the response headers are sent before the handler runs, so headers a handler adds through GrpcContext aren’t sent; trailers are. GrpcContext.isCancelled is answered only over HTTP/2; over gRPC-Web a departed client shows up as a failed write.

  • A server-streaming call holds its connection until the stream is read to the end or the call is closed: a caller that stops early calls close().

OpenTelemetry over gRPC

cn1.otel.protocol=grpc exports traces and metrics with OTLP over gRPC, to the collector’s TraceService/Export and MetricsService/Export. The endpoint defaults to http://localhost:4317, the collector’s gRPC port, and cn1.otel.headers travel as call metadata. UNAVAILABLE, RESOURCE_EXHAUSTED and DEADLINE_EXCEEDED are retried as the HTTP exporter retries a 503; see Distributed tracing with OpenTelemetry.