golang: grpc call timeout

Viewed 7821

I am using the below 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
    }
1 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
}
Related