Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I implement a timeout in a GRPC call?

Tags:

go

grpc

I am using this code to connect to a grpc server and clientConn object is used for all subsequent rpc calls. maxDelay is set to 5 seconds. Now because of some issue at server, it is not responding for a grpc call. So my client is waiting for a long time for each rpc call. Do I need to set timeout in a different way?

b := grpc.BackoffConfig{
        MaxDelay: maxDelay,
}

clientConn, err := grpc.Dial(serverAddress, grpc.WithBackoffConfig(b), grpc.WithInsecure())

if err != nil {
        log.Println("Dial failed!")
        return err
}
like image 314
aniztar Avatar asked Sep 07 '25 11:09

aniztar


2 Answers

You can modify your code to add a timeout using grpc.WithTimeout(5 * time.Second) instead of using MaxDelay and grpc.WithBackoffConfig(b) which are for retries and retries delay.

clientConn, err := grpc.Dial(serverAddress, grpc.WithTimeout(5 * time.Second), grpc.WithInsecure())
if err != nil {
        log.Println("Dial failed!")
        return err
}

However the above is deprecated, alternatively you can use DialContext and context.WithTimeout

ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)

clientConn, err := grpc.DialContext(ctx, serverAddress, grpc.WithInsecure())
if err != nil {
    log.Println("Dial failed!")
    return err
}
like image 125
KitchenSpoon Avatar answered Sep 10 '25 07:09

KitchenSpoon


The doc of WithTimeout says that it is used to set timeout of connection initializing, and not to set timeout to the calls. context in the DialContext is the same.

WithTimeout returns a DialOption that configures a timeout for dialing a ClientConn initially. This is valid if and only if WithBlock() is present. Deprecated: use DialContext instead of Dial and context.WithTimeout instead. Will be supported throughout 1.x.

To set timeout to the calls you can pass context to invoke like:

ctx, cancel := context.WithDeadline(ctx, time.Now().Add(time.Duration(2000)*time.Millisecond))
defer cancel()
clientConn.Invoke(ctx, "/YourEndpoint", in, out, opts...)
like image 29
Gabriel Jacquier Avatar answered Sep 10 '25 06:09

Gabriel Jacquier