Micronaut gRPC

Integration between Micronaut and gRPC

Version: 5.2.1-SNAPSHOT

1 Introduction

This project allows building gRPC servers and clients with Micronaut.

Micronaut adds the following features to the gRPC experience:

  • Compile Time Dependency Injection (DI) and Aspect Oriented Programming (AOP)

  • Service Discovery and Registrations

  • Distributed Tracing

  • Cloud Native Configuration

2 Release History

For this project, you can find a list of releases (with release notes) here:

3 Getting Started

To get started you need first create a Micronaut project. The easiest way to do this is with the Micronaut Launch:

  • Go to Micronaut Launch

  • Select "gRPC Application" under "Application Type"

  • Choose a Language / Build System etc.

  • Click Generate

Replace java with kotlin or groovy to change language and the build flag with maven to use Maven instead.

Or alternatively you can create a project with curl:

curl --location --request GET 'https://launch.micronaut.io/create/grpc/demo?lang=JAVA&build=GRADLE' --output demo.zip
unzip demo.zip -d demo
cd demo

To manually setup gRPC you can create an application:

$ mn create-app helloworld
Add --lang kotlin or --lang groovy to create a Kotlin or Groovy application and --build maven to use Maven instead of Gradle.

Then follow the below steps depending on the build system and language chosen. The Gradle examples are shown for both the Groovy DSL (build.gradle) and the Kotlin DSL (build.gradle.kts).

Configuring Gradle

The com.google.protobuf plugin registers the generated sources with the corresponding source sets, so no additional sourceSets configuration is required.

Java and Groovy Projects

For Java or Groovy projects, add the com.google.protobuf plugin to your existing plugins block:

plugins {
    ...
    id 'com.google.protobuf' version '0.10.1'
}
plugins {
    ...
    id("com.google.protobuf") version "0.10.1"
}

Then configure protobuf source generation:

def grpcVersion = '1.84.2'
def protobufVersion = '4.36.2'

protobuf {
    protoc { artifact = "com.google.protobuf:protoc:$protobufVersion" }
    plugins {
        grpc { artifact = "io.grpc:protoc-gen-grpc-java:$grpcVersion" }
    }
    generateProtoTasks {
        all()*.plugins { grpc {} }
    }
}
val grpcVersion = "1.84.2"
val protobufVersion = "4.36.2"

protobuf {
    protoc { artifact = "com.google.protobuf:protoc:$protobufVersion" }
    plugins {
        create("grpc") { artifact = "io.grpc:protoc-gen-grpc-java:$grpcVersion" }
    }
    generateProtoTasks {
        all().configureEach {
            plugins {
                create("grpc")
            }
        }
    }
}
If you are using JDK 9 or above, provide the following compiler option to the gRPC plugin to skip javax.annotation.Generated stubs: option '@generated=omit' (added in gRPC Java v1.64.0). See issue 9179 for background.
protobuf {
    generateProtoTasks {
        all()*.plugins {
            grpc {
                option '@generated=omit'
            }
        }
    }
}
protobuf {
    generateProtoTasks {
        all().configureEach {
            plugins {
                named("grpc") {
                    option("@generated=omit")
                }
            }
        }
    }
}

Kotlin Projects

Kotlin projects additionally generate coroutine-based stubs with gRPC Kotlin. Use the following Gradle configuration:

plugins {
    ...
    id 'com.google.protobuf' version '0.10.1'
}

def grpcVersion = '1.84.2'
def grpcKotlinVersion = '1.5.0'
def protobufVersion = '4.36.2'

dependencies {
    ...
    implementation("io.grpc:grpc-kotlin-stub:$grpcKotlinVersion")
    implementation("io.grpc:grpc-services:$grpcVersion")
    compileOnly("io.grpc:grpc-stub:$grpcVersion")
    compileOnly("com.google.protobuf:protobuf-java:$protobufVersion")
    compileOnly("javax.annotation:javax.annotation-api:1.3.2")
}

protobuf {
    protoc { artifact = "com.google.protobuf:protoc:$protobufVersion" }
    plugins {
        grpc { artifact = "io.grpc:protoc-gen-grpc-java:$grpcVersion" }
        grpckt { artifact = "io.grpc:protoc-gen-grpc-kotlin:$grpcKotlinVersion:jdk8@jar" }
    }
    generateProtoTasks {
        all()*.plugins {
            grpc {}
            grpckt {}
        }
    }
}
plugins {
    ...
    id("com.google.protobuf") version "0.10.1"
}

val grpcVersion = "1.84.2"
val grpcKotlinVersion = "1.5.0"
val protobufVersion = "4.36.2"

dependencies {
    ...
    implementation("io.grpc:grpc-kotlin-stub:$grpcKotlinVersion")
    implementation("io.grpc:grpc-services:$grpcVersion")
    compileOnly("io.grpc:grpc-stub:$grpcVersion")
    compileOnly("com.google.protobuf:protobuf-java:$protobufVersion")
    compileOnly("javax.annotation:javax.annotation-api:1.3.2")
}

protobuf {
    protoc { artifact = "com.google.protobuf:protoc:$protobufVersion" }
    plugins {
        create("grpc") { artifact = "io.grpc:protoc-gen-grpc-java:$grpcVersion" }
        create("grpckt") { artifact = "io.grpc:protoc-gen-grpc-kotlin:$grpcKotlinVersion:jdk8@jar" }
    }
    generateProtoTasks {
        all().configureEach {
            plugins {
                create("grpc")
                create("grpckt")
            }
        }
    }
}

Reactor Stubs

If you want to generate Reactor-based stubs with reactive-grpc, add the generator plugin and stub dependency alongside the standard gRPC code generation:

def reactiveGrpcVersion = '1.2.4'

dependencies {
    ...
    implementation("com.salesforce.servicelibs:reactor-grpc-stub:$reactiveGrpcVersion")
    implementation("io.projectreactor:reactor-core")
}

protobuf {
    plugins {
        ...
        reactor { artifact = "com.salesforce.servicelibs:reactor-grpc:$reactiveGrpcVersion" }
    }
    generateProtoTasks {
        all()*.plugins {
            ...
            reactor {}
        }
    }
}
val reactiveGrpcVersion = "1.2.4"

dependencies {
    ...
    implementation("com.salesforce.servicelibs:reactor-grpc-stub:$reactiveGrpcVersion")
    implementation("io.projectreactor:reactor-core")
}

protobuf {
    plugins {
        ...
        create("reactor") { artifact = "com.salesforce.servicelibs:reactor-grpc:$reactiveGrpcVersion" }
    }
    generateProtoTasks {
        all().configureEach {
            plugins {
                ...
                create("reactor")
            }
        }
    }
}

Dependencies

Finally, add the following dependencies to your build:

For gRPC servers:

implementation("io.micronaut.grpc:micronaut-grpc-server-runtime")
<dependency>
    <groupId>io.micronaut.grpc</groupId>
    <artifactId>micronaut-grpc-server-runtime</artifactId>
</dependency>
[tool.pyronaut.dependencies]
runtime = [
    "io.micronaut.grpc:micronaut-grpc-server-runtime",
]

For gRPC clients:

implementation("io.micronaut.grpc:micronaut-grpc-client-runtime")
<dependency>
    <groupId>io.micronaut.grpc</groupId>
    <artifactId>micronaut-grpc-client-runtime</artifactId>
</dependency>
[tool.pyronaut.dependencies]
runtime = [
    "io.micronaut.grpc:micronaut-grpc-client-runtime",
]

If you wish to use gRPC standalone without the Micronaut HTTP server you should comment out the micronaut-http-server-netty dependency.

You can then run:

$ ./gradlew generateProto

To generate the Java (and, for Kotlin projects, Kotlin) sources from protobuf definitions in src/main/proto.

The generated sources are the service stubs, not the server implementation. Before starting the application, create a bean that extends the generated *ImplBase type (or *CoroutineImplBase for Kotlin) as shown in the next section.

Configuring Maven

For Maven create a Maven project first:

$ mn create-app helloworld --build maven

Add --lang kotlin or --lang groovy for a Kotlin or Groovy project.

Java and Groovy Projects

Define the gRPC and Protobuf versions in the properties section of your pom.xml:

<properties>
    <grpc.version>1.84.2</grpc.version>
    <protobuf.version>4.36.2</protobuf.version>
</properties>

Add the os-maven-plugin build extension, which detects the classifier of the protoc executable for the current platform:

<extensions>
    <extension>
        <groupId>kr.motd.maven</groupId>
        <artifactId>os-maven-plugin</artifactId>
        <version>1.7.1</version>
    </extension>
</extensions>

Then configure the Protobuf plugin appropriately:

<plugin>
    <groupId>org.xolstice.maven.plugins</groupId>
    <artifactId>protobuf-maven-plugin</artifactId>
    <version>0.6.1</version>
    <configuration>
        <protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact>
        <pluginId>grpc-java</pluginId>
        <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>compile</goal>
                <goal>compile-custom</goal>
            </goals>
        </execution>
    </executions>
</plugin>

The generated code requires the following dependencies, in addition to the Micronaut gRPC dependencies listed above:

<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-protobuf</artifactId>
    <version>${grpc.version}</version>
</dependency>
<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-stub</artifactId>
    <version>${grpc.version}</version>
</dependency>
<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java</artifactId>
    <version>${protobuf.version}</version>
</dependency>
<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
    <scope>provided</scope>
</dependency>

Kotlin Projects

Kotlin projects additionally generate coroutine-based stubs with gRPC Kotlin. Define the versions in the properties section of your pom.xml:

<properties>
    <grpc.version>1.84.2</grpc.version>
    <grpc.kotlin.version>1.5.0</grpc.kotlin.version>
    <protobuf.version>4.36.2</protobuf.version>
</properties>

Add the os-maven-plugin build extension:

<extensions>
    <extension>
        <groupId>kr.motd.maven</groupId>
        <artifactId>os-maven-plugin</artifactId>
        <version>1.7.1</version>
    </extension>
</extensions>

Configure the Protobuf plugin to run both the gRPC Java and the gRPC Kotlin generators:

<plugin>
    <groupId>org.xolstice.maven.plugins</groupId>
    <artifactId>protobuf-maven-plugin</artifactId>
    <version>0.6.1</version>
    <configuration>
        <protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact>
        <pluginId>grpc-java</pluginId>
        <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
        <protocPlugins>
            <protocPlugin>
                <id>grpc-kotlin</id>
                <groupId>io.grpc</groupId>
                <artifactId>protoc-gen-grpc-kotlin</artifactId>
                <version>${grpc.kotlin.version}</version>
                <classifier>jdk8</classifier>
                <mainClass>io.grpc.kotlin.generator.GeneratorRunner</mainClass>
            </protocPlugin>
        </protocPlugins>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>compile</goal>
                <goal>compile-custom</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Add the generated sources to the compile execution of the kotlin-maven-plugin (the kotlin.version property is defined by the Micronaut parent POM):

<plugin>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-maven-plugin</artifactId>
    <version>${kotlin.version}</version>
    <executions>
        <execution>
            <id>compile</id>
            <goals>
                <goal>compile</goal>
            </goals>
            <configuration>
                <sourceDirs>
                    <sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
                    <sourceDir>${project.build.directory}/generated-sources/protobuf/java</sourceDir>
                    <sourceDir>${project.build.directory}/generated-sources/protobuf/grpc-java</sourceDir>
                </sourceDirs>
            </configuration>
        </execution>
    </executions>
</plugin>

The generated code requires the following dependencies, in addition to the Micronaut gRPC dependencies listed above:

<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-kotlin-stub</artifactId>
    <version>${grpc.kotlin.version}</version>
</dependency>
<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-protobuf</artifactId>
    <version>${grpc.version}</version>
</dependency>
<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-stub</artifactId>
    <version>${grpc.version}</version>
</dependency>
<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java</artifactId>
    <version>${protobuf.version}</version>
</dependency>
<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
    <scope>provided</scope>
</dependency>

You can then run:

$ ./mvnw generate-sources

To generate the Java (and, for Kotlin projects, Kotlin) sources from protobuf definitions in src/main/proto.

Defining a Protobuf File

Once you have the build setup you can define a Protobuf file for your gRPC service. For example:

src/main/proto/helloworld.proto
// Copyright 2015 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
syntax = "proto3";

option java_multiple_files = true;
option java_package = "helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";

package helloworld;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}
With the Micronaut 1.1 or above CLI you can generate a service with mn create-grpc-service helloworld which will create the proto file and class that implements the stub.

4 gRPC Server

Writing a Simple gRPC Server

To implement a gRPC server for the previously defined helloworld.proto definition you first need to generate the Java stubs using Gradle or Maven then create a class that extends from GreeterGrpc.GreeterImplBase.

For example:

import io.grpc.stub.StreamObserver;

import jakarta.inject.Singleton;

@Singleton
public class GreetingEndpoint extends GreeterGrpc.GreeterImplBase { // (1)

    private final GreetingService greetingService;

    // (2)
    public GreetingEndpoint(GreetingService greetingService) {
        this.greetingService = greetingService;
    }

    @Override
    public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
        // (3)
        final String message = greetingService.sayHello(request.getName());
        HelloReply reply = HelloReply.newBuilder().setMessage(message).build();
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }
}
import java

from io.grpc.stub import StreamObserver
from jakarta.inject import Singleton

from .GreetingService import GreetingService

# `helloworld` is both the Java package of the generated gRPC classes and the package of these
# Python sources, so the generated types are looked up by name instead of imported.
GreeterGrpc = java.type("helloworld.GreeterGrpc")
HelloReply = java.type("helloworld.HelloReply")
HelloRequest = java.type("helloworld.HelloRequest")

@Singleton
class GreetingEndpoint(GreeterGrpc.GreeterImplBase):  # (1)

    # (2)
    def __init__(self, greeting_service: GreetingService):
        self.greeting_service = greeting_service

    def sayHello(self, request: HelloRequest, response_observer: StreamObserver[HelloReply]) -> None:
        # (3)
        message = self.greeting_service.say_hello(request.getName())
        reply = HelloReply.newBuilder().setMessage(message).build()
        response_observer.onNext(reply)
        response_observer.onCompleted()
import jakarta.inject.Singleton

@Singleton // (1)
class GreetingEndpoint(val greetingService: GreetingService) : GreeterGrpcKt.GreeterCoroutineImplBase() { // (2)
    override suspend fun sayHello(request: HelloRequest): HelloReply {
        // (3)
        val message = greetingService.sayHello(request.name)
        val reply = HelloReply.newBuilder().setMessage(message).build()
        return reply
    }
}
import groovy.transform.CompileStatic
import io.grpc.stub.StreamObserver
import jakarta.inject.Singleton


@CompileStatic
@Singleton
class GreetingEndpoint extends GreeterGrpc.GreeterImplBase { // (1)

    final GreetingService greetingService

    // (2)
    GreetingEndpoint(GreetingService greetingService) {
        this.greetingService = greetingService
    }

    @Override
    void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
        // (3)
        HelloReply.newBuilder().with {
            message = greetingService.sayHello(request.name)
            responseObserver.onNext(build())
            responseObserver.onCompleted()
        }
    }
}
1 The class extends from GreeterGrpc.GreeterImplBase and is annotated with jakarta.inject.Singleton
2 You can dependency inject other beans into the implementation. In this case GreetingService is dependency injected.
3 The StreamObserver is used to send a response to the client.

If you generate Reactor bindings with reactive-grpc, Micronaut can register the generated BindableService implementation in exactly the same way. Implement the generated Reactor base class as a singleton bean:

@Singleton
public class ReactiveGreetingEndpoint extends ReactorReactiveGreeterGrpc.ReactiveGreeterImplBase {

    private final GreetingService greetingService;

    public ReactiveGreetingEndpoint(GreetingService greetingService) {
        this.greetingService = greetingService;
    }

    @Override
    public Mono<HelloReply> sayHello(Mono<HelloRequest> request) {
        return request.map(helloRequest ->
            HelloReply.newBuilder()
                .setMessage(greetingService.sayHello(helloRequest.getName()))
                .build()
        );
    }
}
@Singleton
class ReactiveGreetingEndpoint(ReactorReactiveGreeterGrpc.ReactiveGreeterImplBase):

    def __init__(self, greeting_service: GreetingService):
        self.greeting_service = greeting_service

    def sayHello(self, request: Mono[HelloRequest]) -> Mono[HelloReply]:
        return request.map(
            lambda hello_request: HelloReply.newBuilder()
                .setMessage(self.greeting_service.say_hello(hello_request.getName()))
                .build()
        )
@Singleton
class ReactiveGreetingEndpoint(private val greetingService: GreetingService) : ReactorReactiveGreeterGrpc.ReactiveGreeterImplBase() {

    override fun sayHello(request: Mono<HelloRequest>): Mono<HelloReply> =
        request.map { helloRequest ->
            HelloReply.newBuilder()
                .setMessage(greetingService.sayHello(helloRequest.name))
                .build()
        }
}
@CompileStatic
@Singleton
class ReactiveGreetingEndpoint extends ReactorReactiveGreeterGrpc.ReactiveGreeterImplBase {

    private final GreetingService greetingService

    ReactiveGreetingEndpoint(GreetingService greetingService) {
        this.greetingService = greetingService
    }

    @Override
    Mono<HelloReply> sayHello(Mono<HelloRequest> request) {
        request.map(helloRequest ->
            HelloReply.newBuilder()
                .setMessage(greetingService.sayHello(helloRequest.name))
                .build()
        )
    }
}

Running the gRPC Server

To run the server use the Application class or run ./gradlew run for Gradle or ./mvnw compile exec:exec for Maven.

The server by default runs on port 50051, however you can configure which port the server runs on by setting grpc.server.port to whichever value you wish (a value of ${random.port} will use a random port).

Configuring the gRPC Server

The server can be configured in a number of different ways. By default, Micronaut configures gRPC’s NettyServerBuilder via application.yml.

For example:

Configuring the gRPC server
grpc.server.port=8080
grpc.server.keep-alive-time=3h
grpc.server.max-inbound-message-size=1024
grpc.server.ssl.cert-chain=file://path/to/my.cert
grpc.server.ssl.private-key=classpath:my.key
grpc:
    server:
        port: 8080
        keep-alive-time: 3h
        max-inbound-message-size: 1024
        ssl:
            cert-chain: 'file://path/to/my.cert' # (1)
            private-key: 'classpath:my.key' # (2)
[grpc.server]
port = 8080
keep-alive-time = "3h"
max-inbound-message-size = 1024

[grpc.server.ssl]
cert-chain = "file://path/to/my.cert"
private-key = "classpath:my.key"
grpc {
  server {
    port = 8080
    keepAliveTime = "3h"
    maxInboundMessageSize = 1024
    ssl {
      certChain = "file://path/to/my.cert"
      privateKey = "classpath:my.key"
    }
  }
}
{
  grpc {
    server {
      port = 8080
      keep-alive-time = "3h"
      max-inbound-message-size = 1024
      ssl {
        cert-chain = "file://path/to/my.cert"
        private-key = "classpath:my.key"
      }
    }
  }
}
{
  "grpc": {
    "server": {
      "port": 8080,
      "keep-alive-time": "3h",
      "max-inbound-message-size": 1024,
      "ssl": {
        "cert-chain": "file://path/to/my.cert",
        "private-key": "classpath:my.key"
      }
    }
  }
}
1 Load the certificate from /path/to/my.cert file.
2 Load the private key from the classpath. The file should be in src/main/resources/my.key.

Mutual TLS

To require clients to present a certificate, add the CA certificates that sign client certificates and set client-auth:

Requiring client certificates
grpc.server.ssl.cert-chain=classpath:server.crt
grpc.server.ssl.private-key=classpath:server.key
grpc.server.ssl.trust-certificates=classpath:ca.crt
grpc.server.ssl.client-auth=require
grpc:
    server:
        ssl:
            cert-chain: 'classpath:server.crt'
            private-key: 'classpath:server.key'
            trust-certificates: 'classpath:ca.crt' # (1)
            client-auth: require # (2)
[grpc.server.ssl]
cert-chain = "classpath:server.crt"
private-key = "classpath:server.key"
trust-certificates = "classpath:ca.crt"
client-auth = "require"
grpc {
  server {
    ssl {
      certChain = "classpath:server.crt"
      privateKey = "classpath:server.key"
      trustCertificates = "classpath:ca.crt"
      clientAuth = "require"
    }
  }
}
{
  grpc {
    server {
      ssl {
        cert-chain = "classpath:server.crt"
        private-key = "classpath:server.key"
        trust-certificates = "classpath:ca.crt"
        client-auth = "require"
      }
    }
  }
}
{
  "grpc": {
    "server": {
      "ssl": {
        "cert-chain": "classpath:server.crt",
        "private-key": "classpath:server.key",
        "trust-certificates": "classpath:ca.crt",
        "client-auth": "require"
      }
    }
  }
}
1 PEM-encoded CA certificates used to verify client certificates. Without it, the JVM’s default trust store is used.
2 none (the default), optional or require.

trust-certificates and client-auth need cert-chain and private-key to be configured.

By default, the gRPC server will be enabled. To disable the gRPC server, set grpc.server.enabled to false.

For tests, add the io.micronaut.grpc:micronaut-grpc-inprocess module and set grpc.server.in-process-name to switch the embedded server and the injected @GrpcChannel("grpc-server") test channel to gRPC’s in-process transport instead of opening a TCP port.

Using the in-process server for tests
grpc.server.in-process-name=test-grpc
grpc:
    server:
        in-process-name: test-grpc
[grpc.server]
in-process-name = "test-grpc"
grpc {
  server {
    inProcessName = "test-grpc"
  }
}
{
  grpc {
    server {
      in-process-name = "test-grpc"
    }
  }
}
{
  "grpc": {
    "server": {
      "in-process-name": "test-grpc"
    }
  }
}

The in-process transport avoids port management and is managed by the Micronaut application lifecycle. SSL is not supported in this mode, and the support lives in the optional micronaut-grpc-inprocess module so the Netty-based server runtime does not require the extra dependency.

Alternatively if you prefer programmatic configuration you can write a BeanCreatedEventListener for example:

Configuring the ServerBuilder
import io.grpc.ServerBuilder;
import io.micronaut.context.event.BeanCreatedEvent;
import io.micronaut.context.event.BeanCreatedEventListener;
import jakarta.inject.Singleton;

@Singleton
public class ServerBuilderListener implements BeanCreatedEventListener<ServerBuilder<?>> {

    @Override
    public ServerBuilder<?> onCreated(BeanCreatedEvent<ServerBuilder<?>> event) {
        final ServerBuilder<?> builder = event.getBean();
        builder.maxInboundMessageSize(1024);
        return builder;
    }
}
Configuring the ServerBuilder
from io.grpc import ServerBuilder
from jakarta.inject import Singleton
from micronaut.context.event import BeanCreatedEvent, BeanCreatedEventListener

@Singleton
class ServerBuilderListener(BeanCreatedEventListener[ServerBuilder]):

    def onCreated(self, event: BeanCreatedEvent[ServerBuilder]) -> ServerBuilder:
        builder = event.getBean()
        builder.maxInboundMessageSize(1024)
        return builder
Configuring the ServerBuilder
import io.grpc.ServerBuilder
import io.micronaut.context.event.BeanCreatedEvent
import io.micronaut.context.event.BeanCreatedEventListener
import jakarta.inject.Singleton

@Singleton
class ServerBuilderListener : BeanCreatedEventListener<ServerBuilder<*>> {

    override fun onCreated(event: BeanCreatedEvent<ServerBuilder<*>>): ServerBuilder<*> {
        val builder = event.bean
        builder.maxInboundMessageSize(1024)
        return builder
    }
}
Configuring the ServerBuilder
import groovy.transform.CompileStatic
import io.grpc.ServerBuilder
import io.micronaut.context.event.BeanCreatedEvent
import io.micronaut.context.event.BeanCreatedEventListener
import jakarta.inject.Singleton

@CompileStatic
@Singleton
class ServerBuilderListener implements BeanCreatedEventListener<ServerBuilder<?>> {

    @Override
    ServerBuilder<?> onCreated(BeanCreatedEvent<ServerBuilder<?>> event) {
        final ServerBuilder<?> builder = event.bean
        builder.maxInboundMessageSize(1024)
        builder
    }
}

Auto Injected Types

By default, the server will automatically be dependency injected with beans of the following types:

  • io.grpc.BindableService - Any services declared as beans

  • io.grpc.ServerInterceptor - Any interceptors declared as beans

  • io.grpc.ServerTransportFilter - Any transport filters declared as beans

In addition, by default the server will be setup to use Micronaut’s I/O executor service. Set grpc.server.executor to the name of an Executor bean to override that default from configuration.

To run service methods on virtual threads, use Micronaut’s blocking executor, which uses virtual threads when the JVM supports them:

Running gRPC service methods on virtual threads
grpc.server.executor=blocking
grpc:
    server:
        executor: blocking
[grpc.server]
executor = "blocking"
grpc {
  server {
    executor = "blocking"
  }
}
{
  grpc {
    server {
      executor = "blocking"
    }
  }
}
{
  "grpc": {
    "server": {
      "executor": "blocking"
    }
  }
}

Virtual threads suit blocking stubs and service methods that call databases or other services synchronously. Kotlin coroutine and Reactor services don’t need them.

Server Interceptor Ordering

To produce a consistent and predictable order of execution for server interceptors, it is required for the io.grpc.ServerInterceptor implementation to do one of the following:

Implement the io.micronaut.core.order.Ordered interface
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.micronaut.core.order.Ordered;
import jakarta.inject.Singleton;

@Singleton // (1)
public class CustomInterceptor implements ServerInterceptor, Ordered { // (2)
    @Override
    public <T, R> ServerCall.Listener<T> interceptCall(ServerCall<T, R> call,
                                                       Metadata headers,
                                                       ServerCallHandler<T, R> next) {
        return next.startCall(call, headers);
    }

    @Override
    public int getOrder() {
        return 10; // (3)
    }
}
Implement the io.micronaut.core.order.Ordered interface
from io.grpc import Metadata, ServerCall, ServerCallHandler, ServerInterceptor
from jakarta.inject import Singleton
from micronaut.core.order import Ordered

@Singleton  # (1)
class CustomInterceptor(ServerInterceptor, Ordered):  # (2)

    def interceptCall[T, R](
        self,
        call: ServerCall[T, R],
        headers: Metadata,
        next: ServerCallHandler[T, R],
    ) -> ServerCall.Listener[T]:
        return next.startCall(call, headers)

    def getOrder(self) -> int:
        return 10  # (3)
Implement the io.micronaut.core.order.Ordered interface
import io.grpc.Metadata
import io.grpc.ServerCall
import io.grpc.ServerCallHandler
import io.grpc.ServerInterceptor
import io.micronaut.core.order.Ordered
import jakarta.inject.Singleton

@Singleton // (1)
class CustomInterceptor : ServerInterceptor, Ordered { // (2)
    override fun <T, R> interceptCall(
        call: ServerCall<T, R>,
        headers: Metadata,
        next: ServerCallHandler<T, R>,
    ): ServerCall.Listener<T> {
        return next.startCall(call, headers)
    }

    override fun getOrder(): Int {
        return 10 // (3)
    }
}
Implement the io.micronaut.core.order.Ordered interface
import groovy.transform.CompileStatic
import io.grpc.Metadata
import io.grpc.ServerCall
import io.grpc.ServerCallHandler
import io.grpc.ServerInterceptor
import io.micronaut.core.order.Ordered
import jakarta.inject.Singleton

@CompileStatic
@Singleton // (1)
class CustomInterceptor implements ServerInterceptor, Ordered { // (2)
    @Override
    <T, R> ServerCall.Listener<T> interceptCall(ServerCall<T, R> call,
                                                Metadata headers,
                                                ServerCallHandler<T, R> next) {
        next.startCall(call, headers)
    }

    @Override
    int getOrder() {
        10 // (3)
    }
}
1 Declare the server interceptor as a bean to have it registered automatically
2 Implement Ordered in addition to ServerInterceptor
3 Provide the specified order of execution in the server interceptor chain
Wrap with io.micronaut.grpc.server.interceptor.OrderedServerInterceptor
import io.grpc.ServerInterceptor;
import io.micronaut.context.annotation.Bean;
import io.micronaut.context.annotation.Factory;
import io.micronaut.grpc.server.interceptor.OrderedServerInterceptor;
import jakarta.inject.Singleton;

@Factory // (1)
public class ServerInterceptorFactory {

    @Bean // (2)
    @Singleton
    public ServerInterceptor customServerInterceptor() {
        return new OrderedServerInterceptor(new CustomInterceptor(), 10); // (3)
    }
}
Wrap with io.micronaut.grpc.server.interceptor.OrderedServerInterceptor
from io.grpc import ServerInterceptor
from jakarta.inject import Singleton
from micronaut.context.annotation import Bean, Factory
from micronaut.grpc.server.interceptor import OrderedServerInterceptor

from .CustomInterceptor import CustomInterceptor

@Factory  # (1)
class ServerInterceptorFactory:

    @Bean  # (2)
    @Singleton
    def custom_server_interceptor(self) -> ServerInterceptor:
        return OrderedServerInterceptor(CustomInterceptor(), 10)  # (3)
Wrap with io.micronaut.grpc.server.interceptor.OrderedServerInterceptor
import io.grpc.ServerInterceptor
import io.micronaut.context.annotation.Bean
import io.micronaut.context.annotation.Factory
import io.micronaut.grpc.server.interceptor.OrderedServerInterceptor
import jakarta.inject.Singleton

@Factory // (1)
class ServerInterceptorFactory {

    @Bean // (2)
    @Singleton
    fun customServerInterceptor(): ServerInterceptor {
        return OrderedServerInterceptor(CustomInterceptor(), 10) // (3)
    }
}
Wrap with io.micronaut.grpc.server.interceptor.OrderedServerInterceptor
import groovy.transform.CompileStatic
import io.grpc.ServerInterceptor
import io.micronaut.context.annotation.Bean
import io.micronaut.context.annotation.Factory
import io.micronaut.grpc.server.interceptor.OrderedServerInterceptor
import jakarta.inject.Singleton

@CompileStatic
@Factory // (1)
class ServerInterceptorFactory {

    @Bean // (2)
    @Singleton
    ServerInterceptor customServerInterceptor() {
        new OrderedServerInterceptor(new CustomInterceptor(), 10) // (3)
    }
}
1 Use a @Factory to create an instance of ServerInterceptor bean
2 Register the created sever interceptor as a bean
3 Wrap the CustomInterceptor with OrderedServerInterceptor and provide the order of execution

The order which is provided will dictate the order of execution of the interceptors when receiving the request message, and then the order will be reversed when sending the response message.

3 interceptors, with respective orders, 1, 2, and 3:
Request -> 1 -> 2 -> 3 -> business logic -> 3 -> 2 -> 1 -> Response

Context Propagation

gRPC delivers each event of a call (messages, half-close, cancellation) as a separate task on the server executor, possibly on a different thread. A unary service method runs when the client half-closes the call, so a Micronaut PropagatedContext that a server interceptor makes current while it starts the call would otherwise be gone by the time the method runs.

Micronaut registers an interceptor that runs last, closest to the service, and makes that context current again for every later event of the call. A server interceptor can therefore add context elements, for example an authenticated user or MDC entries, and the service method sees them:

@Singleton
public class TenantInterceptor implements ServerInterceptor {
    private static final Metadata.Key<String> TENANT = Metadata.Key.of("x-tenant", Metadata.ASCII_STRING_MARSHALLER);

    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
                                                                 Metadata headers,
                                                                 ServerCallHandler<ReqT, RespT> next) {
        return PropagatedContext.getOrEmpty()
            .plus(new Tenant(headers.get(TENANT))) // your own PropagatedContextElement
            .propagate(() -> next.startCall(call, headers));
    }
}

This covers interceptors registered as beans. Interceptors applied to a single service with ServerInterceptors.intercept(..) run inside Micronaut’s interceptor, so a context they make current is not carried to later events. The captured context is only a fallback: if an interceptor makes a context current around a later event, for example around one message, that context takes precedence.

To turn this off, set grpc.server.context-propagation.enabled to false.

Health checks

gRPC Health checks

If the gRPC services dependency (io.grpc:grpc-services) is added, then gRPC health checks will be enabled.

To modify the status of a service, call the setStatus method on an instance of HealthServiceManager, for example:

import io.grpc.health.v1.HealthCheckResponse;
import io.grpc.protobuf.services.HealthStatusManager;
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.Nullable;

import jakarta.inject.Singleton;

@Singleton
public class HealthService {

    private final HealthStatusManager healthStatusManager;

    public HealthService(@Nullable HealthStatusManager healthStatusManager) {
        this.healthStatusManager = healthStatusManager;
    }

    public void setStatus(@NonNull String serviceName, HealthCheckResponse.@NonNull ServingStatus status) {
        if (healthStatusManager != null) {
            healthStatusManager.setStatus(serviceName, status);
        }
    }
}
from io.grpc.health.v1 import HealthCheckResponse
from io.grpc.protobuf.services import HealthStatusManager
from jakarta.inject import Singleton

@Singleton
class HealthService:

    def __init__(self, health_status_manager: HealthStatusManager | None):
        self.health_status_manager = health_status_manager

    def set_status(self, service_name: str, status: HealthCheckResponse.ServingStatus) -> None:
        if self.health_status_manager is not None:
            self.health_status_manager.setStatus(service_name, status)
import io.grpc.health.v1.HealthCheckResponse.ServingStatus
import io.grpc.protobuf.services.HealthStatusManager
import jakarta.inject.Singleton

@Singleton
class HealthService(private val healthStatusManager: HealthStatusManager?) {

    fun setStatus(serviceName: String, status: ServingStatus) {
        healthStatusManager?.setStatus(serviceName, status)
    }
}
import io.grpc.health.v1.HealthCheckResponse
import io.grpc.protobuf.services.HealthStatusManager
import io.micronaut.core.annotation.NonNull
import io.micronaut.core.annotation.Nullable
import jakarta.inject.Singleton


@Singleton
class HealthService {

    private final HealthStatusManager healthStatusManager

    HealthService(@Nullable HealthStatusManager healthStatusManager) {
        this.healthStatusManager = healthStatusManager
    }

    void setStatus(@NonNull String serviceName, @NonNull HealthCheckResponse.ServingStatus status) {
        healthStatusManager?.setStatus(serviceName, status)
    }
}

If you wish to disable the gRPC health check while still using the services dependency you can set the property grpc.server.health.enabled to false in your application configuration.

Management Health checks

If the management dependency (io.micronaut:micronaut-management) is added, then Micronaut’s Health Endpoint can be used to expose the health status of the gRPC server.

For example, if gRPC is running then the /health endpoint will return:

{
  "status": "UP",
  "details": {
     "grpc-server": {
       "name": "your-project-name",
       "status": "UP",
       "details": {
         "host": "localhost",
         "port": 5050
       }
     }
  },
 ...
}

If you wish to disable the Micronaut gRPC server health check while still using the management dependency you can set the property grpc.server.health.enabled to false in your application configuration.

Server Reflection

The gRPC server reflection service lets tools such as grpcurl, Postman and grpcui discover the services, methods and message types exposed by the server without a copy of the .proto files.

Reflection exposes your whole API surface, so it is disabled by default. To enable it, add the gRPC services dependency (io.grpc:grpc-services) and set grpc.server.reflection.enabled to true:

Enabling server reflection
grpc.server.reflection.enabled=true
grpc:
    server:
        reflection:
            enabled: true
[grpc.server.reflection]
enabled = true
grpc {
  server {
    reflection {
      enabled = true
    }
  }
}
{
  grpc {
    server {
      reflection {
        enabled = true
      }
    }
  }
}
{
  "grpc": {
    "server": {
      "reflection": {
        "enabled": true
      }
    }
  }
}

Micronaut registers the grpc.reflection.v1.ServerReflection service. It lists the services generated by protoc (whose descriptors carry the .proto schema), plus the health service when gRPC health checks are enabled. A service you build by hand as a ServerServiceDefinition without a schema descriptor still accepts calls but doesn’t appear in reflection results. You can then list the services with:

grpcurl -plaintext localhost:50051 list
Consider enabling reflection only in development, for example in application-dev.yml.

Testing the Server

To test the server it is recommended that you use Micronaut Test.

For detailed instructions on how to set up Micronaut Test for Spock, JUnit 5, or Kotest see the documentation on the subject.

You can then define a blocking stub bean in your test sources. For example:

Defining Test Clients
@Factory
class Clients {

    @Bean
    GreeterGrpc.GreeterBlockingStub blockingStub(
        @GrpcChannel(GrpcServerChannel.NAME) ManagedChannel channel) { // (1)
        return GreeterGrpc.newBlockingStub( // (2)
            channel
        );
    }
}
Defining Test Clients
@Factory
class Clients:

    @Bean
    def blocking_stub(self, channel: Annotated[ManagedChannel, GrpcChannel(GrpcServerChannel.NAME)]) -> GreeterGrpc.GreeterBlockingStub:  # (1)
        return GreeterGrpc.newBlockingStub(channel)  # (2)
Defining Test Clients
@Factory
class Clients {

    @Bean
    fun greetingClient(@GrpcChannel(GrpcServerChannel.NAME) channel: ManagedChannel): GreeterGrpcKt.GreeterCoroutineStub = // (1)
        GreeterGrpcKt.GreeterCoroutineStub(channel) // (2)
}
Defining Test Clients
@Factory
class Clients {

    @Bean
    GreeterGrpc.GreeterBlockingStub blockingStub(
            @GrpcChannel(GrpcServerChannel.NAME) ManagedChannel channel) { // (1)
        GreeterGrpc.newBlockingStub( // (2)
                channel
        )
    }
}
1 A ManagedChannel is injected that can communicate with the server.
2 The generated gRPC client blocking stub is created.

The above example uses the @GrpcChannel annotation to inject a gRPC ManagedChannel that can communicate with the running server. This channel will be automatically be shutdown when the application shuts down.

Now that you have a test client, writing the test becomes trivial:

import io.grpc.ManagedChannel;
import io.micronaut.context.annotation.Bean;
import io.micronaut.context.annotation.Factory;
import io.micronaut.grpc.annotation.GrpcChannel;
import io.micronaut.grpc.server.GrpcServerChannel;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;

import org.junit.jupiter.api.Test;

import jakarta.inject.Inject;

import static org.junit.jupiter.api.Assertions.assertEquals;

@MicronautTest // (1)
class GreetingEndpointTest {

    @Inject
    GreeterGrpc.GreeterBlockingStub blockingStub; // (2)

    @Test
    void testHelloWorld() {
        final HelloRequest request = HelloRequest.newBuilder() // (3)
            .setName("Fred")
            .build();
        assertEquals(
            "Hello Fred",
            blockingStub.sayHello(request)
                .getMessage()
        );
    }

}
import java
from typing import Annotated

from io.grpc import ManagedChannel
from jakarta.inject import Inject
from micronaut.context.annotation import Bean, Factory
from micronaut.grpc.annotation import GrpcChannel
from micronaut.grpc.server import GrpcServerChannel
from micronaut.test.extensions.junit5.annotation import MicronautTest
from org.junit.jupiter.api import Test

# `helloworld` is both the Java package of the generated gRPC classes and the package of these
# Python sources, so the generated types are looked up by name instead of imported.
GreeterGrpc = java.type("helloworld.GreeterGrpc")
HelloRequest = java.type("helloworld.HelloRequest")

@MicronautTest  # (1)
class GreetingEndpointTest:

    blocking_stub: Annotated[GreeterGrpc.GreeterBlockingStub, Inject]  # (2)

    @Test
    def test_hello_world(self):
        request = HelloRequest.newBuilder().setName("Fred").build()  # (3)
        assert self.blocking_stub.sayHello(request).getMessage() == "Hello Fred"
import io.grpc.ManagedChannel
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import io.micronaut.context.annotation.Bean
import io.micronaut.context.annotation.Factory
import io.micronaut.grpc.annotation.GrpcChannel
import io.micronaut.grpc.server.GrpcServerChannel
import io.micronaut.test.extensions.kotest5.annotation.MicronautTest

@MicronautTest // (1)
class GreetingEndpointTest(
    private val greetingClient: GreeterGrpcKt.GreeterCoroutineStub, // (2)
) : StringSpec({
    "returns a greeting response" {
        greetingClient.sayHello( // (3)
            HelloRequest.newBuilder().setName("Fred").build(),
        ).message shouldBe "Hello Fred"
    }
})
import io.grpc.ManagedChannel
import io.micronaut.context.annotation.Bean
import io.micronaut.context.annotation.Factory
import io.micronaut.grpc.annotation.GrpcChannel
import io.micronaut.grpc.server.GrpcServerChannel
import io.micronaut.test.extensions.spock.annotation.MicronautTest
import jakarta.inject.Inject
import spock.lang.Specification

@MicronautTest // (1)
class GreetingEndpointTest extends Specification {

    @Inject
    GreeterGrpc.GreeterBlockingStub blockingStub // (2)

    void "test greeting endpoint"() {
        given:
        HelloRequest request = HelloRequest.newBuilder().with { // (3)
            name = "Fred"
            build()
        }

        expect:
        blockingStub.sayHello(
                request
        ).message == 'Hello Fred'
    }
}
1 The test is annotated with @MicronautTest
2 The client stub is injected into the test
3 A request is sent and the response asserted.

5 gRPC Server Security

gRPC Server Security

Micronaut gRPC can integrate with Micronaut Security on the server side through io.grpc.ServerInterceptor beans.

For JWT-based authentication, add both dependencies:

  • implementation("io.micronaut.grpc:micronaut-grpc-server-security-jwt")
    <dependency>
        <groupId>io.micronaut.grpc</groupId>
        <artifactId>micronaut-grpc-server-security-jwt</artifactId>
    </dependency>
    [tool.pyronaut.dependencies]
    runtime = [
        "io.micronaut.grpc:micronaut-grpc-server-security-jwt",
    ]

  • implementation("io.micronaut.security:micronaut-security-jwt")
    <dependency>
        <groupId>io.micronaut.security</groupId>
        <artifactId>micronaut-security-jwt</artifactId>
    </dependency>
    [tool.pyronaut.dependencies]
    runtime = [
        "io.micronaut.security:micronaut-security-jwt",
    ]

The JWT module reads a token from gRPC metadata, validates it with Micronaut Security token validators, and then evaluates the configured grpc.server.security.intercept-method-map rules against the gRPC method name.

JWT Metadata

By default, the token is read from the JWT metadata key.

grpc.server.security.token.jwt.enabled=true
grpc.server.security.token.jwt.metadata-key-name=JWT
grpc:
  server:
    security:
      token:
        jwt:
          enabled: true
          metadata-key-name: JWT
[grpc.server.security.token.jwt]
enabled = true
metadata-key-name = "JWT"
grpc {
  server {
    security {
      token {
        jwt {
          enabled = true
          metadataKeyName = "JWT"
        }
      }
    }
  }
}
{
  grpc {
    server {
      security {
        token {
          jwt {
            enabled = true
            metadata-key-name = "JWT"
          }
        }
      }
    }
  }
}
{
  "grpc": {
    "server": {
      "security": {
        "token": {
          "jwt": {
            "enabled": true,
            "metadata-key-name": "JWT"
          }
        }
      }
    }
  }
}

If you want to use an Authorization metadata key instead, set metadata-key-name accordingly. The interceptor accepts both a raw token value and a Bearer <token> value.

Authorization Rules

Authorization rules for gRPC calls are configured with grpc.server.security.intercept-method-map. Each entry has a pattern, a regular expression matched against the fully qualified gRPC method name (for example helloworld.Greeter/SayHello), and the access rules required to invoke matching methods. Entries are evaluated in order and the first matching entry applies.

grpc.server.security.intercept-method-map[0].pattern=helloworld.Greeter/SayHello
grpc.server.security.intercept-method-map[0].access[0]=isAuthenticated()
grpc.server.security.intercept-method-map[1].pattern=helloworld.Admin/.*
grpc.server.security.intercept-method-map[1].access[0]=ROLE_ADMIN
grpc:
  server:
    security:
      intercept-method-map:
        - pattern: helloworld.Greeter/SayHello
          access:
            - isAuthenticated()
        - pattern: helloworld.Admin/.*
          access:
            - ROLE_ADMIN
[[grpc.server.security.intercept-method-map]]
pattern = "helloworld.Greeter/SayHello"
access = ["isAuthenticated()"]

[[grpc.server.security.intercept-method-map]]
pattern = "helloworld.Admin/.*"
access = ["ROLE_ADMIN"]
grpc {
  server {
    security {
      interceptMethodMap = [{
          pattern = "helloworld.Greeter/SayHello"
          access = ["isAuthenticated()"]
        }, {
          pattern = "helloworld.Admin/.*"
          access = ["ROLE_ADMIN"]
        }]
    }
  }
}
{
  grpc {
    server {
      security {
        intercept-method-map = [{
            pattern = "helloworld.Greeter/SayHello"
            access = ["isAuthenticated()"]
          }, {
            pattern = "helloworld.Admin/.*"
            access = ["ROLE_ADMIN"]
          }]
      }
    }
  }
}
{
  "grpc": {
    "server": {
      "security": {
        "intercept-method-map": [{
            "pattern": "helloworld.Greeter/SayHello",
            "access": ["isAuthenticated()"]
          }, {
            "pattern": "helloworld.Admin/.*",
            "access": ["ROLE_ADMIN"]
          }]
      }
    }
  }
}
Micronaut Security’s micronaut.security.intercept-url-map is not applied to gRPC calls. Its entries are Ant-style HTTP path patterns (such as /**), so an application exposing both HTTP and gRPC endpoints can keep its HTTP rules there and declare gRPC rules separately.

Granted roles are the roles exposed by the Authentication (Authentication#getRoles()) combined with the roles resolved from its attributes by the RolesFinder bean, so both JWT claims and authentications returned by a custom GrpcServerAuthenticationFetcher (for example Authentication.build("alice", List.of("ROLE_ADMIN"))) are matched against role-based rules.

If a rule requires authentication and no token is provided, the server responds with UNAUTHENTICATED. If a token is provided but validation fails, or the authenticated principal does not satisfy the configured access rules, the server responds with PERMISSION_DENIED.

With Micronaut Security’s default micronaut.security.reject-not-found=true, unmatched gRPC methods are rejected as well. Define explicit intercept-method-map patterns for the methods you want to secure, or set reject-not-found to false if unmatched methods should remain accessible.

Configuration Reference

🔗
Table 1. Configuration Properties for GrpcServerSecurityConfiguration
Property Type Description Default value

grpc.server.security.enabled

boolean

true

grpc.server.security.missing-authentication-status

io.grpc.Status$Code

The gRPC status returned when authentication is missing.

UNAUTHENTICATED

grpc.server.security.failed-authorization-status

io.grpc.Status$Code

The gRPC status returned when authorization fails.

PERMISSION_DENIED

grpc.server.security.intercept-method-map

java.util.List

The gRPC authorization rules. Each entry has a {@code pattern}, a regular expression matched against the fully qualified gRPC method name (for example {@code helloworld.Greeter/SayHello}), and the {@code access} rules required to invoke matching methods. The first matching entry applies.

<p>These rules are separate from {@code micronaut.security.intercept-url-map}, which holds HTTP path patterns.</p>

🔗
Table 2. Configuration Properties for GrpcServerSecurityJwtConfiguration
Property Type Description Default value

grpc.server.security.token.jwt.enabled

boolean

true

grpc.server.security.token.jwt.metadata-key-name

java.lang.String

The metadata key name that contains the JWT value.

JWT

6 gRPC Clients

By default, Micronaut for gRPC does not create client stub beans for you: you expose the stubs your application needs using a @Factory, as described below. Alternatively, add the micronaut-grpc-client-processor annotation processor and inject stubs directly (see Injecting Client Stubs).

You can dependency inject a io.grpc.ManagedChannel into the factory. Each injected io.grpc.ManagedChannel will automatically be shutdown when the application shuts down.

Configuring ManagedChannel Instances

The channel can be configured using properties defined under grpc.client by default.

For example, if you wish to disable secure communication:

grpc.client.plaintext=true
grpc.client.max-retry-attempts=10
grpc:
    client:
        plaintext: true
        max-retry-attempts: 10
[grpc.client]
plaintext = true
max-retry-attempts = 10
grpc {
  client {
    plaintext = true
    maxRetryAttempts = 10
  }
}
{
  grpc {
    client {
      plaintext = true
      max-retry-attempts = 10
    }
  }
}
{
  "grpc": {
    "client": {
      "plaintext": true,
      "max-retry-attempts": 10
    }
  }
}

Properties under grpc.client are global properties and are the defaults used unless named configuration exists under grpc.channels.[NAME].

Any property of the io.grpc.netty.NettyChannelBuilder type can be configured.

You can also disable all gRPC client channel injection, or disable a specific named client:

grpc.client.enabled=false
grpc:
    client:
        enabled: false
[grpc.client]
enabled = false
grpc {
  client {
    enabled = false
  }
}
{
  grpc {
    client {
      enabled = false
    }
  }
}
{
  "grpc": {
    "client": {
      "enabled": false
    }
  }
}
grpc.client.greeter.enabled=false
grpc:
    client:
        greeter:
            enabled: false
[grpc.client.greeter]
enabled = false
grpc {
  client {
    greeter {
      enabled = false
    }
  }
}
{
  grpc {
    client {
      greeter {
        enabled = false
      }
    }
  }
}
{
  "grpc": {
    "client": {
      "greeter": {
        "enabled": false
      }
    }
  }
}

When a client is disabled, optional or nullable @GrpcChannel injection points resolve to an empty value, while required injection points fail with a dependency injection error.

For gRPC service-config based retry and resiliency features, you can configure default-service-config as a nested map. The map is bound using Micronaut’s nested/raw map binding so gRPC service config keys such as methodConfig, retryPolicy, and hedgingPolicy are preserved as-is.

grpc.client.plaintext=true
grpc.client.enable-retry=true
grpc.client.max-retry-attempts=4
grpc.client.default-service-config.methodConfig[0].name[0].service=helloworld.Greeter
grpc.client.default-service-config.methodConfig[0].retryPolicy.maxAttempts=4
grpc.client.default-service-config.methodConfig[0].retryPolicy.initialBackoff=0.1s
grpc.client.default-service-config.methodConfig[0].retryPolicy.maxBackoff=1s
grpc.client.default-service-config.methodConfig[0].retryPolicy.backoffMultiplier=2
grpc.client.default-service-config.methodConfig[0].retryPolicy.retryableStatusCodes[0]=UNAVAILABLE
grpc:
    client:
        plaintext: true
        enable-retry: true
        max-retry-attempts: 4
        default-service-config:
            methodConfig:
                -
                    name:
                        -
                            service: helloworld.Greeter
                    retryPolicy:
                        maxAttempts: 4
                        initialBackoff: 0.1s
                        maxBackoff: 1s
                        backoffMultiplier: 2
                        retryableStatusCodes:
                            - UNAVAILABLE
[grpc.client]
plaintext = true
enable-retry = true
max-retry-attempts = 4

[[grpc.client.default-service-config.methodConfig]]

[grpc.client.default-service-config.methodConfig.retryPolicy]
maxAttempts = 4
initialBackoff = "0.1s"
maxBackoff = "1s"
backoffMultiplier = 2
retryableStatusCodes = ["UNAVAILABLE"]

[[grpc.client.default-service-config.methodConfig.name]]
service = "helloworld.Greeter"
grpc {
  client {
    plaintext = true
    enableRetry = true
    maxRetryAttempts = 4
    defaultServiceConfig {
      methodConfig = [{
          name = [{
              service = "helloworld.Greeter"
            }]
          retryPolicy {
            maxAttempts = 4
            initialBackoff = "0.1s"
            maxBackoff = "1s"
            backoffMultiplier = 2
            retryableStatusCodes = ["UNAVAILABLE"]
          }
        }]
    }
  }
}
{
  grpc {
    client {
      plaintext = true
      enable-retry = true
      max-retry-attempts = 4
      default-service-config {
        methodConfig = [{
            name = [{
                service = "helloworld.Greeter"
              }]
            retryPolicy {
              maxAttempts = 4
              initialBackoff = "0.1s"
              maxBackoff = "1s"
              backoffMultiplier = 2
              retryableStatusCodes = ["UNAVAILABLE"]
            }
          }]
      }
    }
  }
}
{
  "grpc": {
    "client": {
      "plaintext": true,
      "enable-retry": true,
      "max-retry-attempts": 4,
      "default-service-config": {
        "methodConfig": [{
            "name": [{
                "service": "helloworld.Greeter"
              }],
            "retryPolicy": {
              "maxAttempts": 4,
              "initialBackoff": "0.1s",
              "maxBackoff": "1s",
              "backoffMultiplier": 2,
              "retryableStatusCodes": ["UNAVAILABLE"]
            }
          }]
      }
    }
  }
}

The same structure can be defined per channel under grpc.channels.<name>.default-service-config.

Alternatively if you prefer programmatic configuration you can write a BeanCreatedEventListener for example:

Configuring the NettyChannelBuilder
import io.grpc.ManagedChannelBuilder;
import io.micronaut.context.event.BeanCreatedEvent;
import io.micronaut.context.event.BeanCreatedEventListener;
import jakarta.inject.Singleton;

@Singleton
public class ManagedChannelBuilderListener implements BeanCreatedEventListener<ManagedChannelBuilder<?>> {

    @Override
    public ManagedChannelBuilder<?> onCreated(BeanCreatedEvent<ManagedChannelBuilder<?>> event) {
        final ManagedChannelBuilder<?> channelBuilder = event.getBean();
        channelBuilder.maxInboundMessageSize(1024);
        return channelBuilder;
    }
}
Configuring the NettyChannelBuilder
from io.grpc import ManagedChannelBuilder
from jakarta.inject import Singleton
from micronaut.context.event import BeanCreatedEvent, BeanCreatedEventListener

@Singleton
class ManagedChannelBuilderListener(BeanCreatedEventListener[ManagedChannelBuilder]):

    def onCreated(self, event: BeanCreatedEvent[ManagedChannelBuilder]) -> ManagedChannelBuilder:
        channel_builder = event.getBean()
        channel_builder.maxInboundMessageSize(1024)
        return channel_builder
Configuring the NettyChannelBuilder
import io.grpc.ManagedChannelBuilder
import io.micronaut.context.event.BeanCreatedEvent
import io.micronaut.context.event.BeanCreatedEventListener
import jakarta.inject.Singleton

@Singleton
class ManagedChannelBuilderListener : BeanCreatedEventListener<ManagedChannelBuilder<*>> {

    override fun onCreated(event: BeanCreatedEvent<ManagedChannelBuilder<*>>): ManagedChannelBuilder<*> {
        val channelBuilder = event.bean
        channelBuilder.maxInboundMessageSize(1024)
        return channelBuilder
    }
}
Configuring the NettyChannelBuilder
import groovy.transform.CompileStatic
import io.grpc.ManagedChannelBuilder
import io.micronaut.context.event.BeanCreatedEvent
import io.micronaut.context.event.BeanCreatedEventListener
import jakarta.inject.Singleton

@CompileStatic
@Singleton
class ManagedChannelBuilderListener implements BeanCreatedEventListener<ManagedChannelBuilder<?>> {

    @Override
    ManagedChannelBuilder<?> onCreated(BeanCreatedEvent<ManagedChannelBuilder<?>> event) {
        final ManagedChannelBuilder<?> channelBuilder = event.bean
        channelBuilder.maxInboundMessageSize(1024)
        channelBuilder
    }
}

TLS and Mutual TLS

A channel can verify the server against your own CA certificates and present a client certificate to servers that require one:

Configuring TLS for a channel
grpc.channels.greeter.address=greeter.internal:50051
grpc.channels.greeter.ssl.trust-certificates=classpath:ca.crt
grpc.channels.greeter.ssl.cert-chain=classpath:client.crt
grpc.channels.greeter.ssl.private-key=classpath:client.key
grpc:
    channels:
        greeter:
            address: 'greeter.internal:50051'
            ssl:
                trust-certificates: 'classpath:ca.crt' # (1)
                cert-chain: 'classpath:client.crt' # (2)
                private-key: 'classpath:client.key'
[grpc.channels.greeter]
address = "greeter.internal:50051"

[grpc.channels.greeter.ssl]
trust-certificates = "classpath:ca.crt"
cert-chain = "classpath:client.crt"
private-key = "classpath:client.key"
grpc {
  channels {
    greeter {
      address = "greeter.internal:50051"
      ssl {
        trustCertificates = "classpath:ca.crt"
        certChain = "classpath:client.crt"
        privateKey = "classpath:client.key"
      }
    }
  }
}
{
  grpc {
    channels {
      greeter {
        address = "greeter.internal:50051"
        ssl {
          trust-certificates = "classpath:ca.crt"
          cert-chain = "classpath:client.crt"
          private-key = "classpath:client.key"
        }
      }
    }
  }
}
{
  "grpc": {
    "channels": {
      "greeter": {
        "address": "greeter.internal:50051",
        "ssl": {
          "trust-certificates": "classpath:ca.crt",
          "cert-chain": "classpath:client.crt",
          "private-key": "classpath:client.key"
        }
      }
    }
  }
}
1 PEM-encoded CA certificates that verify the server. Without it, the JVM’s default trust store is used.
2 The client certificate and its PKCS#8 private key, for mutual TLS. Configure both or neither.

Properties under grpc.client.ssl are defaults for channels that have no ssl settings of their own. Locations accept the classpath: and file: prefixes. Don’t combine these settings with plaintext: true.

Client Executors

Each channel runs its callbacks, such as StreamObserver.onNext of an async stub, on Micronaut’s I/O executor. Set grpc.client.executor for every channel, or grpc.channels.[NAME].executor for one, to the name of another Executor bean. For example, to run callbacks on virtual threads:

grpc.client.executor=blocking
grpc.channels.greeter.executor=io
grpc:
    client:
        executor: blocking
    channels:
        greeter:
            executor: io
[grpc.client]
executor = "blocking"

[grpc.channels.greeter]
executor = "io"
grpc {
  client {
    executor = "blocking"
  }
  channels {
    greeter {
      executor = "io"
    }
  }
}
{
  grpc {
    client {
      executor = "blocking"
    }
    channels {
      greeter {
        executor = "io"
      }
    }
  }
}
{
  "grpc": {
    "client": {
      "executor": "blocking"
    },
    "channels": {
      "greeter": {
        "executor": "io"
      }
    }
  }
}

The value can also be an Executor instance supplied by a programmatic property source. An unknown executor name fails when the channel is created. The built-in @GrpcChannel("grpc-server") channel to the embedded server, used in tests, always uses the I/O executor.

Auto Injected Types

By default, each channel will automatically be dependency injected with beans of the following types:

  • io.grpc.ClientInterceptor - Any client interceptors declared as beans

  • io.grpc.NameResolver - The configured name resolver

Context Propagation

gRPC runs a call’s response callbacks, such as StreamObserver.onNext of an async stub, on the channel’s executor. Micronaut captures the PropagatedContext of the thread that starts the call (when ClientCall.start runs, which a stub does for you) and makes it current again in those callbacks, so MDC entries, tracing context and other context elements of the caller are available there. Client interceptors see it in their response listeners too, including calls an interceptor completes itself without reaching the server. A callback that already runs inside a propagated context keeps it.

To turn this off, set grpc.client.context-propagation.enabled to false.

Injecting Client Stubs

Add the client processor to the annotation processor path of the module that compiles your .proto files:

annotationProcessor("io.micronaut.grpc:micronaut-grpc-client-processor")
<annotationProcessorPaths>
    <path>
        <groupId>io.micronaut.grpc</groupId>
        <artifactId>micronaut-grpc-client-processor</artifactId>
    </path>
</annotationProcessorPaths>
[tool.pyronaut.dependencies]
build = [
    "io.micronaut.grpc:micronaut-grpc-client-processor",
]

For every service class that protoc-gen-grpc-java generates, the processor generates a bean factory for its stubs. You can then inject the blocking, async and future stubs with @GrpcChannel, by field or constructor:

@Singleton
public class GreetingClient {

    private final GreeterGrpc.GreeterBlockingStub greeter;

    public GreetingClient(@GrpcChannel("greeter") GreeterGrpc.GreeterBlockingStub greeter) {
        this.greeter = greeter;
    }
}

The channel is resolved and configured exactly as for an injected ManagedChannel, including grpc.channels.[NAME] configuration, interceptors and service discovery. All stubs of the same channel share one ManagedChannel. A stub of a disabled channel behaves like a disabled channel: a @Nullable or Optional injection point receives no stub.

The generated factories are secondary beans, so a stub bean you define yourself in a @Factory takes precedence. Stubs of other code generators, such as the grpc-kotlin coroutine stubs, aren’t generated and still need a factory.

Creating Client Stub Beans

The value of the @GrpcChannel annotation can be used to specify the target server, the configuration for which can also be externalized:

@Factory
class ExternalizedClients {

    @Singleton
    GreeterGrpc.GreeterStub greeterStub(
        @GrpcChannel("https://${my.server}:${my.port}")
        ManagedChannel channel) {
        return GreeterGrpc.newStub(
            channel
        );
    }
}
@Factory
class ExternalizedClients:

    @Singleton
    def greeter_stub(
        self,
        channel: Annotated[ManagedChannel, GrpcChannel("https://${my.server}:${my.port}")]
    ) -> GreeterGrpc.GreeterStub:
        return GreeterGrpc.newStub(
            channel
        )
@Factory
class ExternalizedClients {

    @Singleton
    fun greeterStub(
        @GrpcChannel("https://\${my.server}:\${my.port}")
        channel: ManagedChannel,
    ): GreeterGrpc.GreeterStub {
        return GreeterGrpc.newStub(
            channel
        )
    }
}
@CompileStatic
@Factory
class ExternalizedClients {

    @Singleton
    GreeterGrpc.GreeterStub greeterStub(
            @GrpcChannel('https://${my.server}:${my.port}')
            ManagedChannel channel) {
        GreeterGrpc.newStub(
                channel
        )
    }
}

The above example requires that my.server and my.port are specified in application.yml (or via environment variables MY_SERVER and MY_PORT). You can also externalize this further into configuration and provide channel specific configuration.

For example given the following configuration:

grpc.channels.greeter.address=${my.server}:${my.port}
grpc.channels.greeter.plaintext=true
grpc.channels.greeter.enable-retry=true
grpc.channels.greeter.max-retry-attempts=4
grpc.channels.greeter.default-service-config.methodConfig[0].name[0].service=helloworld.Greeter
grpc.channels.greeter.default-service-config.methodConfig[0].retryPolicy.maxAttempts=4
grpc.channels.greeter.default-service-config.methodConfig[0].retryPolicy.initialBackoff=0.1s
grpc.channels.greeter.default-service-config.methodConfig[0].retryPolicy.maxBackoff=1s
grpc.channels.greeter.default-service-config.methodConfig[0].retryPolicy.backoffMultiplier=2
grpc.channels.greeter.default-service-config.methodConfig[0].retryPolicy.retryableStatusCodes[0]=UNAVAILABLE
grpc:
    channels:
        greeter:
            address: '${my.server}:${my.port}'
            plaintext: true
            enable-retry: true
            max-retry-attempts: 4
            default-service-config:
                methodConfig:
                    -
                        name:
                            -
                                service: helloworld.Greeter
                        retryPolicy:
                            maxAttempts: 4
                            initialBackoff: 0.1s
                            maxBackoff: 1s
                            backoffMultiplier: 2
                            retryableStatusCodes:
                                - UNAVAILABLE
[grpc.channels.greeter]
address = "${my.server}:${my.port}"
plaintext = true
enable-retry = true
max-retry-attempts = 4

[[grpc.channels.greeter.default-service-config.methodConfig]]

[grpc.channels.greeter.default-service-config.methodConfig.retryPolicy]
maxAttempts = 4
initialBackoff = "0.1s"
maxBackoff = "1s"
backoffMultiplier = 2
retryableStatusCodes = ["UNAVAILABLE"]

[[grpc.channels.greeter.default-service-config.methodConfig.name]]
service = "helloworld.Greeter"
grpc {
  channels {
    greeter {
      address = "${my.server}:${my.port}"
      plaintext = true
      enableRetry = true
      maxRetryAttempts = 4
      defaultServiceConfig {
        methodConfig = [{
            name = [{
                service = "helloworld.Greeter"
              }]
            retryPolicy {
              maxAttempts = 4
              initialBackoff = "0.1s"
              maxBackoff = "1s"
              backoffMultiplier = 2
              retryableStatusCodes = ["UNAVAILABLE"]
            }
          }]
      }
    }
  }
}
{
  grpc {
    channels {
      greeter {
        address = "${my.server}:${my.port}"
        plaintext = true
        enable-retry = true
        max-retry-attempts = 4
        default-service-config {
          methodConfig = [{
              name = [{
                  service = "helloworld.Greeter"
                }]
              retryPolicy {
                maxAttempts = 4
                initialBackoff = "0.1s"
                maxBackoff = "1s"
                backoffMultiplier = 2
                retryableStatusCodes = ["UNAVAILABLE"]
              }
            }]
        }
      }
    }
  }
}
{
  "grpc": {
    "channels": {
      "greeter": {
        "address": "${my.server}:${my.port}",
        "plaintext": true,
        "enable-retry": true,
        "max-retry-attempts": 4,
        "default-service-config": {
          "methodConfig": [{
              "name": [{
                  "service": "helloworld.Greeter"
                }],
              "retryPolicy": {
                "maxAttempts": 4,
                "initialBackoff": "0.1s",
                "maxBackoff": "1s",
                "backoffMultiplier": 2,
                "retryableStatusCodes": ["UNAVAILABLE"]
              }
            }]
        }
      }
    }
  }
}

You can then define the @GrpcChannel annotation as follows:

@Factory
class NamedChannelClients {

    @Singleton
    GreeterGrpc.GreeterStub greeterStub(
        @GrpcChannel("greeter")
        ManagedChannel channel) {
        return GreeterGrpc.newStub(
            channel
        );
    }
}
@Factory
class NamedChannelClients:

    @Singleton
    def greeter_stub(
        self,
        channel: Annotated[ManagedChannel, GrpcChannel("greeter")]
    ) -> GreeterGrpc.GreeterStub:
        return GreeterGrpc.newStub(
            channel
        )
@Factory
class NamedChannelClients {

    @Singleton
    fun greeterStub(
        @GrpcChannel("greeter")
        channel: ManagedChannel,
    ): GreeterGrpc.GreeterStub {
        return GreeterGrpc.newStub(
            channel
        )
    }
}
@CompileStatic
@Factory
class NamedChannelClients {

    @Singleton
    GreeterGrpc.GreeterStub greeterStub(
            @GrpcChannel("greeter")
            ManagedChannel channel) {
        GreeterGrpc.newStub(
                channel
        )
    }
}

The ID greeter is used to reference the configuration for grpc.channels.greeter.

Using service IDs in this way is the preferred way to set up gRPC clients, because it works nicely with Service Discovery (see the next section).

If you generate Reactor bindings with reactive-grpc, define the generated Reactor stub in the same kind of factory and inject the ManagedChannel with @GrpcChannel:

@Bean
ReactorReactiveGreeterGrpc.ReactorReactiveGreeterStub reactiveStub(
    @GrpcChannel(GrpcServerChannel.NAME) ManagedChannel channel) {
    return ReactorReactiveGreeterGrpc.newReactorStub(channel);
}
@Bean
def reactive_stub(self, channel: Annotated[ManagedChannel, GrpcChannel(GrpcServerChannel.NAME)]) -> ReactorReactiveGreeterGrpc.ReactorReactiveGreeterStub:
    return ReactorReactiveGreeterGrpc.newReactorStub(channel)
@Bean
fun reactiveStub(@GrpcChannel(GrpcServerChannel.NAME) channel: ManagedChannel): ReactorReactiveGreeterGrpc.ReactorReactiveGreeterStub =
    ReactorReactiveGreeterGrpc.newReactorStub(channel)
@Bean
ReactorReactiveGreeterGrpc.ReactorReactiveGreeterStub reactiveStub(
        @GrpcChannel(GrpcServerChannel.NAME) ManagedChannel channel) {
    ReactorReactiveGreeterGrpc.newReactorStub(channel)
}

The resulting stub can then be injected into your application or tests and used directly with Reactor operators:

@MicronautTest
class ReactiveGreetingEndpointTest {

    @Inject
    ReactorReactiveGreeterGrpc.ReactorReactiveGreeterStub reactiveStub;

    @Test
    void testReactiveHelloWorld() {
        String message = Mono.just(HelloRequest.newBuilder().setName("Fred").build())
            .transform(reactiveStub::sayHello)
            .map(HelloReply::getMessage)
            .block(Duration.ofSeconds(5));

        assertEquals("Hello Fred", message);
    }
}
@MicronautTest
class ReactiveGreetingEndpointTest:

    reactive_stub: Annotated[ReactorReactiveGreeterGrpc.ReactorReactiveGreeterStub, Inject]

    @Test
    def test_reactive_hello_world(self):
        message = self.reactive_stub.sayHello(Mono.just(HelloRequest.newBuilder().setName("Fred").build())) \
            .map(lambda reply: reply.getMessage()) \
            .block(Duration.ofSeconds(5))

        assert message == "Hello Fred"
@MicronautTest
class ReactiveGreetingEndpointTest {

    @Inject
    lateinit var reactiveStub: ReactorReactiveGreeterGrpc.ReactorReactiveGreeterStub

    @Test
    fun testReactiveHelloWorld() {
        val message = Mono.just(HelloRequest.newBuilder().setName("Fred").build())
            .transform(reactiveStub::sayHello)
            .map(HelloReply::getMessage)
            .block(Duration.ofSeconds(5))

        assertEquals("Hello Fred", message)
    }
}
@MicronautTest
class ReactiveGreetingEndpointTest extends Specification {

    @Inject
    ReactorReactiveGreeterGrpc.ReactorReactiveGreeterStub reactiveStub

    void "test reactive greeting endpoint"() {
        when:
        String message = Mono.just(HelloRequest.newBuilder().setName("Fred").build())
            .transform(reactiveStub::sayHello)
            .map(HelloReply::getMessage)
            .block(Duration.ofSeconds(5))

        then:
        message == "Hello Fred"
    }
}

Circuit Breakers

A named channel can be guarded by a circuit breaker built on Micronaut Retry. When the server keeps failing, the circuit opens and calls fail immediately with UNAVAILABLE instead of waiting for a connection or a deadline, which protects both the caller and the struggling server.

To use it, add the Micronaut Retry dependency:

implementation("io.micronaut:micronaut-retry")
<dependency>
    <groupId>io.micronaut</groupId>
    <artifactId>micronaut-retry</artifactId>
</dependency>
[tool.pyronaut.dependencies]
runtime = [
    "io.micronaut:micronaut-retry",
]

Then enable the circuit breaker for the channel:

Enabling a circuit breaker
grpc.channels.greeter.address=greeter.internal:50051
grpc.channels.greeter.plaintext=true
grpc.channels.greeter.circuit-breaker.enabled=true
grpc.channels.greeter.circuit-breaker.failure-threshold=5
grpc.channels.greeter.circuit-breaker.reset-timeout=20s
grpc.channels.greeter.circuit-breaker.failure-status-codes[0]=UNAVAILABLE
grpc.channels.greeter.circuit-breaker.failure-status-codes[1]=DEADLINE_EXCEEDED
grpc:
    channels:
        greeter:
            address: 'greeter.internal:50051'
            plaintext: true
            circuit-breaker:
                enabled: true
                failure-threshold: 5
                reset-timeout: 20s
                failure-status-codes:
                    - UNAVAILABLE
                    - DEADLINE_EXCEEDED
[grpc.channels.greeter]
address = "greeter.internal:50051"
plaintext = true

[grpc.channels.greeter.circuit-breaker]
enabled = true
failure-threshold = 5
reset-timeout = "20s"
failure-status-codes = ["UNAVAILABLE", "DEADLINE_EXCEEDED"]
grpc {
  channels {
    greeter {
      address = "greeter.internal:50051"
      plaintext = true
      circuitBreaker {
        enabled = true
        failureThreshold = 5
        resetTimeout = "20s"
        failureStatusCodes = ["UNAVAILABLE", "DEADLINE_EXCEEDED"]
      }
    }
  }
}
{
  grpc {
    channels {
      greeter {
        address = "greeter.internal:50051"
        plaintext = true
        circuit-breaker {
          enabled = true
          failure-threshold = 5
          reset-timeout = "20s"
          failure-status-codes = ["UNAVAILABLE", "DEADLINE_EXCEEDED"]
        }
      }
    }
  }
}
{
  "grpc": {
    "channels": {
      "greeter": {
        "address": "greeter.internal:50051",
        "plaintext": true,
        "circuit-breaker": {
          "enabled": true,
          "failure-threshold": 5,
          "reset-timeout": "20s",
          "failure-status-codes": ["UNAVAILABLE", "DEADLINE_EXCEEDED"]
        }
      }
    }
  }
}
Property Default Description

enabled

false

Whether the channel has a circuit breaker.

failure-threshold

5

The number of consecutive failed calls that opens the circuit.

reset-timeout

20s

How long the circuit stays open. After it, a single trial call is let through: it closes the circuit if it succeeds and opens it again if it fails. Calls made while the trial is in flight fail fast.

failure-status-codes

UNAVAILABLE, DEADLINE_EXCEEDED

The status codes that count as failures. Other codes, such as INVALID_ARGUMENT or NOT_FOUND, are application errors and reset the count.

While the circuit is open, a call ends with status UNAVAILABLE and the description Circuit breaker for gRPC channel [greeter] is open, without reaching the network. Client interceptor beans still see these calls, so tracing and metrics record them.

All stubs created from the same channel share one circuit breaker. Inject GrpcCircuitBreakerRegistry to read its state, for example in a health indicator:

CircuitState state = registry.currentState("greeter").orElse(CircuitState.CLOSED);
The circuit breaker never retries a call, because streaming calls cannot be replayed. To retry failed calls, enable retries in the channel’s gRPC service config, which applies before a call counts as failed.

7 Service Discovery

When using @GrpcChannel with a service ID without explicitly configuring the address of the service will trigger gRPC’s NameResolver and attempt to do service discovery.

The default strategy for this is to use DNS based discovery. So for example you can do:

@Factory
class DnsClients {

    @Singleton
    GreeterGrpc.GreeterStub greeterStub(
        @GrpcChannel("dns:///greeter")
        ManagedChannel channel) {
        return GreeterGrpc.newStub(
            channel
        );
    }
}
@Factory
class DnsClients:

    @Singleton
    def greeter_stub(
        self,
        channel: Annotated[ManagedChannel, GrpcChannel("dns:///greeter")]
    ) -> GreeterGrpc.GreeterStub:
        return GreeterGrpc.newStub(
            channel
        )
@Factory
class DnsClients {

    @Singleton
    fun greeterStub(
        @GrpcChannel("dns:///greeter")
        channel: ManagedChannel,
    ): GreeterGrpc.GreeterStub {
        return GreeterGrpc.newStub(
            channel
        )
    }
}
@CompileStatic
@Factory
class DnsClients {

    @Singleton
    GreeterGrpc.GreeterStub greeterStub(
            @GrpcChannel("dns:///greeter")
            ManagedChannel channel) {
        GreeterGrpc.newStub(
                channel
        )
    }
}

Where DNS has been configured to know the address of the greeter service.

Alternatively, if you prefer to use a service discovery server then you can use integration with Micronaut service discovery.

Service Discovery with Consul

You can use Micronaut’s built-in service discovery features with any supported server (Consul and Eureka currently).

The way in which this is done is the same as a regular Micronaut service.

Registering a gRPC Service with Consul

To register a gRPC service with Consul first add the micronaut-discovery-client dependency:

runtimeOnly("io.micronaut.discovery:micronaut-discovery-client")
<dependency>
    <groupId>io.micronaut.discovery</groupId>
    <artifactId>micronaut-discovery-client</artifactId>
    <scope>runtime</scope>
</dependency>
[tool.pyronaut.dependencies]
runtime = [
    "io.micronaut.discovery:micronaut-discovery-client",
]

Then setup Consul correctly:

micronaut.application.name=greeter
consul.client.registration.enabled=true
consul.client.defaultZone=${CONSUL_HOST:localhost}:${CONSUL_PORT:8500}
micronaut:
    application:
        name: greeter
consul:
    client:
        registration:
            enabled: true
        defaultZone: "${CONSUL_HOST:localhost}:${CONSUL_PORT:8500}"
[micronaut.application]
name = "greeter"

[consul.client]
defaultZone = "${CONSUL_HOST:localhost}:${CONSUL_PORT:8500}"

[consul.client.registration]
enabled = true
micronaut {
  application {
    name = "greeter"
  }
}
consul {
  client {
    registration {
      enabled = true
    }
    defaultZone = "${CONSUL_HOST:localhost}:${CONSUL_PORT:8500}"
  }
}
{
  micronaut {
    application {
      name = "greeter"
    }
  }
  consul {
    client {
      registration {
        enabled = true
      }
      defaultZone = "${CONSUL_HOST:localhost}:${CONSUL_PORT:8500}"
    }
  }
}
{
  "micronaut": {
    "application": {
      "name": "greeter"
    }
  },
  "consul": {
    "client": {
      "registration": {
        "enabled": true
      },
      "defaultZone": "${CONSUL_HOST:localhost}:${CONSUL_PORT:8500}"
    }
  }
}

When using Service Discovery, Micronaut will register the service in Consul using the name defined in micronaut.application.name. If the application also uses an HTTP Server (Netty, Tomcat,…​), Micronaut will register the application with the same name and a different port in Consul. In case you want to use a different name for the gRPC service in Consul:

micronaut.application.name=greeter
grpc.server.instance-id=hello-grpc
micronaut:
    application:
        name: greeter # (1)
grpc:
    server:
        instance-id: 'hello-grpc' # (2)
[micronaut.application]
name = "greeter"

[grpc.server]
instance-id = "hello-grpc"
micronaut {
  application {
    name = "greeter"
  }
}
grpc {
  server {
    instanceId = "hello-grpc"
  }
}
{
  micronaut {
    application {
      name = "greeter"
    }
  }
  grpc {
    server {
      instance-id = "hello-grpc"
    }
  }
}
{
  "micronaut": {
    "application": {
      "name": "greeter"
    }
  },
  "grpc": {
    "server": {
      "instance-id": "hello-grpc"
    }
  }
}
1 The HTTP port will be registered in Consul with the name greeter
2 The gRPC port will be registered in Consul with the name hello-grpc

Discoverying Services via Consul

To discovery services via Consul and the Micronaut DiscoveryClient abstraction enable Consul and gRPC service discovery:

grpc.client.discovery.enabled=true
consul.client.defaultZone=${CONSUL_HOST:localhost}:${CONSUL_PORT:8500}
grpc:
    client:
        discovery:
            enabled: true
consul:
    client:
        defaultZone: "${CONSUL_HOST:localhost}:${CONSUL_PORT:8500}"
[grpc.client.discovery]
enabled = true

[consul.client]
defaultZone = "${CONSUL_HOST:localhost}:${CONSUL_PORT:8500}"
grpc {
  client {
    discovery {
      enabled = true
    }
  }
}
consul {
  client {
    defaultZone = "${CONSUL_HOST:localhost}:${CONSUL_PORT:8500}"
  }
}
{
  grpc {
    client {
      discovery {
        enabled = true
      }
    }
  }
  consul {
    client {
      defaultZone = "${CONSUL_HOST:localhost}:${CONSUL_PORT:8500}"
    }
  }
}
{
  "grpc": {
    "client": {
      "discovery": {
        "enabled": true
      }
    }
  },
  "consul": {
    "client": {
      "defaultZone": "${CONSUL_HOST:localhost}:${CONSUL_PORT:8500}"
    }
  }
}

Then use the value greeter to discover the service when injecting the channel:

@Factory
class DiscoveryClients {

    @Singleton
    @Bean
    GreeterGrpc.GreeterStub greeterStub(
        @GrpcChannel("greeter")
        ManagedChannel channel) {
        return GreeterGrpc.newStub(
            channel
        );
    }
}
@Factory
class DiscoveryClients:

    @Singleton
    @Bean
    def greeter_stub(
        self,
        channel: Annotated[ManagedChannel, GrpcChannel("greeter")]
    ) -> GreeterGrpc.GreeterStub:
        return GreeterGrpc.newStub(
            channel
        )
@Factory
class DiscoveryClients {

    @Singleton
    @Bean
    fun greeterStub(
        @GrpcChannel("greeter")
        channel: ManagedChannel,
    ): GreeterGrpc.GreeterStub {
        return GreeterGrpc.newStub(
            channel
        )
    }
}
@CompileStatic
@Factory
class DiscoveryClients {

    @Singleton
    @Bean
    GreeterGrpc.GreeterStub greeterStub(
            @GrpcChannel("greeter")
            ManagedChannel channel) {
        GreeterGrpc.newStub(
                channel
        )
    }
}

8 Distributed Tracing

Micronaut gRPC includes legacy OpenTracing-based tracing support. For new applications using Micronaut Tracing, add the OpenTelemetry gRPC integration:

implementation("io.micronaut.tracing:micronaut-tracing-opentelemetry-grpc")
<dependency>
    <groupId>io.micronaut.tracing</groupId>
    <artifactId>micronaut-tracing-opentelemetry-grpc</artifactId>
</dependency>
[tool.pyronaut.dependencies]
runtime = [
    "io.micronaut.tracing:micronaut-tracing-opentelemetry-grpc",
]

Micronaut Tracing will then create spans for gRPC client requests, server requests, client responses, and server responses.

To export traces to Google Cloud Trace, add the Google Cloud OpenTelemetry exporter:

runtimeOnly("com.google.cloud.opentelemetry:exporter-auto")
<dependency>
    <groupId>com.google.cloud.opentelemetry</groupId>
    <artifactId>exporter-auto</artifactId>
    <scope>runtime</scope>
</dependency>
[tool.pyronaut.dependencies]
runtime = [
    "com.google.cloud.opentelemetry:exporter-auto",
]

Then configure OpenTelemetry to use the google_cloud_trace exporter:

otel.traces.exporter=google_cloud_trace
otel:
  traces:
    exporter: google_cloud_trace
[otel.traces]
exporter = "google_cloud_trace"
otel {
  traces {
    exporter = "google_cloud_trace"
  }
}
{
  otel {
    traces {
      exporter = "google_cloud_trace"
    }
  }
}
{
  "otel": {
    "traces": {
      "exporter": "google_cloud_trace"
    }
  }
}

When running outside Google Cloud, provide Application Default Credentials with the GOOGLE_APPLICATION_CREDENTIALS environment variable (or gcloud auth application-default login) and set GOOGLE_CLOUD_PROJECT if the project cannot be detected automatically.

For additional exporter options and authentication details, see the Micronaut Tracing OpenTelemetry exporter documentation.

9 Protocol Buffers Support

This project also includes a module that adds the ability to encode and decode Protocol buffers messages with the Micronaut HTTP server.

To use this adds the micronaut-protobuff-support dependency:

implementation("io.micronaut.grpc:micronaut-protobuff-support")
<dependency>
    <groupId>io.micronaut.grpc</groupId>
    <artifactId>micronaut-protobuff-support</artifactId>
</dependency>
[tool.pyronaut.dependencies]
runtime = [
    "io.micronaut.grpc:micronaut-protobuff-support",
]

Micronaut will now support the encoding and decoding requests / responses of type application/x-protobuf.

Avoiding Reflection

To create a message from a request body, Micronaut needs a builder for the message type. Add the micronaut-protobuff-processor annotation processor to generate a factory for every message class compiled in your project, so that builders are created without reflection:

annotationProcessor("io.micronaut.grpc:micronaut-protobuff-processor")
<annotationProcessorPaths>
    <path>
        <groupId>io.micronaut.grpc</groupId>
        <artifactId>micronaut-protobuff-processor</artifactId>
    </path>
</annotationProcessorPaths>
[tool.pyronaut.dependencies]
build = [
    "io.micronaut.grpc:micronaut-protobuff-processor",
]

The processor brings Micronaut’s annotation processing (micronaut-inject-java) with it, so nothing else is needed on the annotation processor path. The project must have micronaut-protobuff-support on its compile classpath, directly or through micronaut-protobuff-json-support.

The processor runs on the Java sources that protoc generates. It finds message classes by the @com.google.protobuf.Generated annotation and writes a small factory for each one, which Micronaut registers like its own generated services, so GraalVM native images need no extra reflection configuration for them. The JSON support in micronaut-protobuff-json-support uses the same factories.

For compatibility, messages without a generated factory still work: Micronaut falls back to calling their static newBuilder() method by reflection. This applies to messages compiled elsewhere, for example in a shared library of .proto definitions built without the processor, and to messages in the default Java package, which the processor skips.

10 Protocol Buffers Json Support (Experimental)

This project also includes a module that adds the ability to send json-serialized messages via a POST HTTP 1.1 call with the Micronaut HTTP server.

To use this add the micronaut-protobuff-json-support dependency:

implementation("io.micronaut.grpc:micronaut-protobuff-json-support")
<dependency>
    <groupId>io.micronaut.grpc</groupId>
    <artifactId>micronaut-protobuff-json-support</artifactId>
</dependency>
[tool.pyronaut.dependencies]
runtime = [
    "io.micronaut.grpc:micronaut-protobuff-json-support",
]

grpc.rest.json.exposed=true

And then include the @GrpcRestJsonExposed annotation on your gRPC service definition:

import io.grpc.stub.StreamObserver;
import io.micronaut.grpc.annotation.GrpcRestJsonExposed;
import jakarta.inject.Singleton;
import org.example.grpc.GreeterGrpc;
import org.example.grpc.HelloRequest;
import org.example.grpc.HelloResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Singleton
public class GreeterService extends GreeterGrpc.GreeterImplBase {
    private static final Logger LOG = LoggerFactory.getLogger(GreeterService.class);

    @GrpcRestJsonExposed
    @Override
    public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
        LOG.debug("Received request: {}", request);
        String name = request.getName();
        String greeting = "Hello, " + name;

        HelloResponse reply = HelloResponse.newBuilder()
            .setGreeting(greeting)
            .build();

        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }
}
import logging

from io.grpc.stub import StreamObserver
from jakarta.inject import Singleton
from micronaut.grpc.annotation import GrpcRestJsonExposed
from org.example.grpc import GreeterGrpc, HelloRequest, HelloResponse

LOG = logging.getLogger(__name__)

@Singleton
class GreeterService(GreeterGrpc.GreeterImplBase):

    @GrpcRestJsonExposed
    def sayHello(self, request: HelloRequest, response_observer: StreamObserver[HelloResponse]) -> None:
        LOG.debug("Received request: %s", request)
        name = request.getName()
        greeting = "Hello, " + name

        reply = HelloResponse.newBuilder().setGreeting(greeting).build()

        response_observer.onNext(reply)
        response_observer.onCompleted()
import io.grpc.stub.StreamObserver
import io.micronaut.grpc.annotation.GrpcRestJsonExposed
import jakarta.inject.Singleton
import org.example.grpc.GreeterGrpc
import org.example.grpc.HelloRequest
import org.example.grpc.HelloResponse
import org.slf4j.LoggerFactory

@Singleton
class GreeterService : GreeterGrpc.GreeterImplBase() {

    @GrpcRestJsonExposed
    override fun sayHello(request: HelloRequest, responseObserver: StreamObserver<HelloResponse>) {
        LOG.debug("Received request: {}", request)
        val name = request.name
        val greeting = "Hello, $name"

        val reply = HelloResponse.newBuilder()
            .setGreeting(greeting)
            .build()

        responseObserver.onNext(reply)
        responseObserver.onCompleted()
    }

    companion object {
        private val LOG = LoggerFactory.getLogger(GreeterService::class.java)
    }
}
import groovy.transform.CompileStatic
import io.grpc.stub.StreamObserver
import io.micronaut.grpc.annotation.GrpcRestJsonExposed
import jakarta.inject.Singleton
import org.example.grpc.GreeterGrpc
import org.example.grpc.HelloRequest
import org.example.grpc.HelloResponse
import org.slf4j.Logger
import org.slf4j.LoggerFactory

@CompileStatic
@Singleton
class GreeterService extends GreeterGrpc.GreeterImplBase {
    private static final Logger LOG = LoggerFactory.getLogger(GreeterService)

    @GrpcRestJsonExposed
    @Override
    void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
        LOG.debug("Received request: {}", request)
        String name = request.name
        String greeting = "Hello, " + name

        HelloResponse reply = HelloResponse.newBuilder()
            .setGreeting(greeting)
            .build()

        responseObserver.onNext(reply)
        responseObserver.onCompleted()
    }
}

Micronaut will now support the encoding and decoding requests / responses of type application/json via http 1.1. For browser-oriented gRPC-Web support, see the dedicated guide section at gRPC-Web.

How this works

Controller Creation

  1. After the controller is created, the post creation annotation will traverse the beans created with the @GrpcRestJsonExposed annotation on the service method.

  2. For each bean, peek into the gRPC allocated methods created.

  3. Register the bean in a cache

The controller endpoint will use google’s built-in JSON/ProtocolBuffer serialization. Unfortunately, there is not yet a way to print a full API schema for a request. However, to create a json request output one can take any gRPC request protocol buffer and convert it to json using the io.micronaut.protobuf.json.ProtobufJsonTranscoder class.

Usage

Request comes in and matches as:

/grpc-json/{serviceName}/{method}

where the serviceName is the name of the gRPC service and the method is the name of the method.

Here’s an example of a gRPC service definition.

For example:

syntax = "proto3";
package greeter;

option java_package = "org.example.grpc";
option java_outer_classname = "GreeterProto";
option java_multiple_files = true;

message HelloRequest {
  string name = 1;
}

message HelloResponse {
  string greeting = 1;
}

service Greeter {
  rpc sayHello (HelloRequest) returns (HelloResponse);
}

Mapping this to a grpc service, the request would look like this:

Where GreeterService is the service name and sayHello is the method name.

The payload would look like this:

{"name": "YourName"}

Take in a POST as application/json and the request should cleanly map as a grpc response.

Example client usage with cURL

If you run the test-suite-protobuff-json-java project and issue the following cURL call:

curl -X POST http://localhost:8080/grpc-json/GreeterService/sayHello \
-H "Content-Type: application/json" \
-d '{"name": "YourName"}'

11 REST Transcoding (Experimental)

The micronaut-protobuff-json-support module can expose unary gRPC methods as REST endpoints, following the HTTP to gRPC transcoding rules in the google.api.http annotations of your .proto files. This feature is experimental.

Enable it with:

grpc.rest.transcoding.enabled=true
grpc.rest.transcoding.timeout=30s
grpc:
  rest:
    transcoding:
      enabled: true
      timeout: 30s
[grpc.rest.transcoding]
enabled = true
timeout = "30s"
grpc {
  rest {
    transcoding {
      enabled = true
      timeout = "30s"
    }
  }
}
{
  grpc {
    rest {
      transcoding {
        enabled = true
        timeout = "30s"
      }
    }
  }
}
{
  "grpc": {
    "rest": {
      "transcoding": {
        "enabled": true,
        "timeout": "30s"
      }
    }
  }
}

Annotate the methods you want to expose:

import "google/api/annotations.proto";

service LibraryService {
  rpc GetShelf(GetShelfRequest) returns (Shelf) {
    option (google.api.http) = { get: "/v1/{name=shelves/*}" };
  }
  rpc UpdateBook(UpdateBookRequest) returns (Book) {
    option (google.api.http) = {
      put: "/v1/books/{book.id}"
      body: "book"
      additional_bindings { patch: "/v1/books/{book.id}" body: "book" }
    };
  }
  rpc GetBookTitle(GetBookRequest) returns (Book) {
    option (google.api.http) = { get: "/v1/books/{id}/title" response_body: "title" };
  }
}

The rules are read from the service’s protobuf descriptors when the application starts. The module uses no reflection and needs no generated code. It supports the following:

  • The get, post, put, patch and delete methods, custom methods (custom: { kind: "…​" }, where kind: "*" matches any HTTP method unless a rule for that method also matches) and additional_bindings.

  • Path templates with literal segments, and * wildcards, variables with or without a sub-template ({name=shelves/*}), nested field paths ({book.id}) and a verb suffix (/v1/books/{id}:archive).

  • body: "", body: "<field>" or no body. When the body is not , query parameters set the remaining fields. Query parameters may use proto field names or JSON names, including nested paths like paging.token, and a repeated field takes repeated parameters. A field bound by the path or the body is not overridden by a query parameter, whichever name the parameter uses.

  • response_body, which returns a single field of the response instead of the whole message.

A request is matched against the rules before routing. Requests that match no rule continue to your controllers. A matching request is dispatched in-process to the gRPC service, through the ServerInterceptor beans of the application. The HTTP request headers become gRPC metadata, except for hop-by-hop and transport headers, grpc-* headers and binary (-bin) headers. Interceptors that authenticate from metadata therefore also apply to REST calls.

The request and response bodies use the protobuf JSON mapping. When a call fails, the gRPC status is mapped to an HTTP status in the same way as Google APIs: INVALID_ARGUMENT becomes 400, NOT_FOUND becomes 404, UNAUTHENTICATED becomes 401, and so on. The body has the following form:

{"error": {"code": 404, "message": "Shelf not found", "status": "NOT_FOUND"}}

A request body that is not valid JSON, or that does not match the request message, is rejected with 400.

The following are not supported:

  • Streaming methods: rules on client, server or bidirectional streaming methods are skipped with a warning.

  • google.protobuf.Any fields, because no type registry is configured.

  • Unknown query parameters are ignored, not rejected.

Unlike the /grpc-json endpoints described above, transcoding does not use the @GrpcRestJsonExposed annotation. It exposes only the methods annotated with google.api.http, with the paths and HTTP methods those annotations define.

12 gRPC-Web

Micronaut can also expose @GrpcRestJsonExposed methods through the gRPC-Web wire protocol over HTTP/1.1.

This is useful when a browser or browser-facing proxy needs protobuf-native unary calls instead of the JSON transcoding endpoint described in Protocol Buffers Json Support.

Setup

Add the JSON support module:

implementation("io.micronaut.grpc:micronaut-protobuff-json-support")
<dependency>
    <groupId>io.micronaut.grpc</groupId>
    <artifactId>micronaut-protobuff-json-support</artifactId>
</dependency>
[tool.pyronaut.dependencies]
runtime = [
    "io.micronaut.grpc:micronaut-protobuff-json-support",
]

Then annotate the gRPC service method you want to expose:

package com.example.services;

import io.grpc.stub.StreamObserver;
import io.micronaut.grpc.annotation.GrpcRestJsonExposed;
import jakarta.inject.Singleton;
import org.example.grpc.GreeterGrpc;
import org.example.grpc.HelloRequest;
import org.example.grpc.HelloResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Singleton
public class GreeterService extends GreeterGrpc.GreeterImplBase {
    private static final Logger log = LoggerFactory.getLogger(GreeterService.class);

    @GrpcRestJsonExposed
    @Override
    public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
        log.debug("Received request: {}", request);
        String name = request.getName();
        String greeting = "Hello, " + name;

        HelloResponse reply = HelloResponse.newBuilder()
                .setGreeting(greeting)
                .build();

        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }
}

The same annotation enables both:

  • the JSON endpoint at /grpc-json/{serviceName}/{method}

  • the gRPC-Web endpoint at /grpc-web/{serviceName}/{method}

Endpoint Shape

Unary gRPC-Web requests are served from:

/grpc-web/{serviceName}/{method}

For the sample GreeterService#sayHello method this becomes:

The path prefix defaults to grpc-web and can be changed with:

micronaut:
    grpc:
        web:
            path: custom-grpc-web

Supported Content Types

The endpoint accepts the following media types, ignoring case and parameters, and answers with the media type of the request:

  • application/grpc-web and application/grpc-web+proto

  • application/grpc-web-text and application/grpc-web-text+proto

Binary requests use the standard gRPC-Web frame format. Text requests use the same frames, base64-encoded for browser compatibility.

Request Format

Each request body must contain a framed protobuf message:

  1. One byte of flags.

  2. Four bytes of message length.

  3. The serialized protobuf payload.

The current implementation supports unary requests with an uncompressed data frame. Compressed request frames are rejected.

Response Format

Successful responses include:

  • one protobuf data frame containing the unary response message

  • one trailers frame containing grpc-status: 0

The status is only sent in the trailers frame, not as response headers.

Error responses are also returned using gRPC-Web framing, with a trailers frame containing grpc-status and grpc-message:

  • A status raised by the service, passed to onError or thrown as a StatusRuntimeException, is sent as is.

  • An unknown service or method is sent as UNIMPLEMENTED (12), and a malformed request as INVALID_ARGUMENT (3).

  • Any other failure is sent as INTERNAL (13) with a generic message, so that internal error details are not exposed. The failure is logged.

Example Flow

With this proto definition:

syntax = "proto3";
package helloworld;

option java_package = "org.example.grpc";
option java_outer_classname = "HelloworldProto";
option java_multiple_files = true;

message HelloRequest {
  string name = 1;
}

message HelloResponse {
  string greeting = 1;
}

service Greeter {
  rpc sayHello (HelloRequest) returns (HelloResponse);
}

the gRPC-Web endpoint expects a framed HelloRequest protobuf payload and returns a framed HelloResponse protobuf payload.

In practice, a browser application will usually rely on a gRPC-Web client library or proxy to construct these frames rather than building them manually.

13 Repository

You can find the source code of this project in this repository: