Search code examples
kotlinprotocol-buffersgrpcgrpc-java

How to extract amount of retries that happened from rpc call?


I have a simple rpc call with configured retrying that should fail with error UNAVAILABLE. At the DEBUG level in logs I can see that request was sent exactly N times as it should.

serviceStub.sayHello(request)

How can I extract the number of retries occured while this rpc call?

I tried extracting headers but seems like there is no value for retries count


Solution

  • As mentioned in the gRFC A6, the metatdata grpc-previous-rpc-attempts is set in the request headers for the server to see. And grpc-java does set it in the response headers for the client to see.

    So for client side, you could adapt the metadata example:

    public class RetryLoggingInterceptor implements ClientInterceptor {
      private static final Logger logger = Logger.getLogger(RetryLoggingInterceptor.class.getName());
    
      private static final Metadata.Key<String> RPC_ATTEMPTS_KEY =
          Metadata.Key.of("grpc-previous-rpc-attempts", Metadata.ASCII_STRING_MARSHALLER);
    
      @Override
      public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method,
          CallOptions callOptions, Channel next) {
        return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
          @Override
          public void start(Listener<RespT> responseListener, Metadata headers) {
            super.start(new SimpleForwardingClientCallListener<RespT>(responseListener) {
              @Override
              public void onHeaders(Metadata headers) {
                String retries = headers.get(RPC_ATTEMPTS_KEY);
                if (retries != null) {
                  logger.info("retries:" + retries);
                }
                super.onHeaders(headers);
              }
            }, headers);
          }
        };
      }
    }