gRPC UNAVAILABLE on the First Call After Idle: Load Balancer Timeouts and Keepalive Settings in Go

TechLab Editorial TeamPublished 79 views1 answer
0

Editorial Q&A · This problem and its answer were written by the TechLab editorial team to document a common issue. It isn't a question from a community member. If you've hit a variation of it or know a better approach, add a reply below.

The problem

Two Go services talk over gRPC: an order service (client) calls an inventory service (server) to reserve stock before confirming an order. The inventory service runs on Kubernetes in AWS, and the order service, running in a different cluster, reaches it through an internal AWS Network Load Balancer (NLB).

After 5–10 minutes without calls, the first RPC fails with UNAVAILABLE. Calls immediately afterwards succeed. The inventory pods are healthy and haven't restarted. The suspicion is that something between the two services closes the idle TCP connection and the client only notices when it next sends a request.

Environment:

  • Client and server: Go with google.golang.org/grpc
  • Network path: client pod → internal NLB → inventory service pods

Code Snippets:

OrderProcessingService (Client-side connection setup):

Go
package main

import (
	"log"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	pb "your/proto/package" // Assume pb is defined for generated gRPC client
)

var inventoryServiceClient pb.InventoryServiceClient

func init() {
	// Internal NLB in front of the inventory service
	inventoryServiceAddr := "inventory-nlb.internal.example.com:50051"

	conn, err := grpc.Dial(
		inventoryServiceAddr,
		grpc.WithTransportCredentials(insecure.NewCredentials()), // For simplicity in internal cluster comms
	)
	if err != nil {
		log.Fatalf("did not connect to inventory service: %v", err)
	}
	inventoryServiceClient = pb.NewInventoryServiceClient(conn)
	log.Printf("Successfully connected to inventory service at %s", inventoryServiceAddr)
}

func main() {
	// ... application logic ...
	// Example RPC call later in the code (simplified):
	// _, err := inventoryServiceClient.ReserveStock(context.Background(), &pb.ReserveStockRequest{ProductId: "prod1", Quantity: 1})
	// if err != nil {
	//     log.Printf("Error reserving stock: %v", err) // This is where UNAVAILABLE errors appear
	// }
}

InventoryService (Server-side setup):

Go
package main

import (
	"context"
	"log"
	"net"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	pb "your/proto/package" // Assume pb is defined for generated gRPC server
)

// server implements your/proto/package.InventoryServiceServer
type server struct {
	pb.UnimplementedInventoryServiceServer
}

func (s *server) ReserveStock(ctx context.Context, req *pb.ReserveStockRequest) (*pb.ReserveStockResponse, error) {
	log.Printf("Received ReserveStock request for product %s, quantity %d", req.ProductId, req.Quantity)
	// Simulate stock reservation logic
	if req.ProductId == "non-existent" {
		return nil, status.Errorf(codes.NotFound, "Product %s not found", req.ProductId)
	}
	return &pb.ReserveStockResponse{Success: true, Message: "Stock reserved"}, nil
}

func main() {
	lis, err := net.Listen("tcp", ":50051")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	pb.RegisterInventoryServiceServer(s, &server{})
	log.Printf("server listening at %v", lis.Addr())
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}

Expected behaviour: gRPC keeps the connection usable, or reconnects transparently, so the application never sees an error caused by an idle period.

Actual behaviour: After about 5–10 minutes without traffic, the first ReserveStock call fails with an error like:

Code
rpc error: code = Unavailable desc = error reading from server: read tcp 10.0.12.34:41872->10.0.40.7:50051: read: connection reset by peer

The next call succeeds on a fresh connection.

The question: why does the idle connection fail, and how should client and server be configured so it doesn't?

Advertisement

1 Answer

0

Explanation of the Problem (Root Cause):

This is the classic signature of an intermediary (load balancer, firewall or NAT gateway) dropping an idle TCP connection without telling either end.

  1. Idle timeouts: stateful network devices forget connections that carry no traffic for a while. An AWS NLB's TCP idle timeout defaults to 350 seconds (just under 6 minutes, configurable per listener since 2024), which matches the observed 5–10 minute window. NAT gateways and many firewalls behave similarly.

  2. Both ends still think the connection is open. The NLB removes its flow entry silently. Neither the client nor the server receives anything, so both keep the connection as if nothing happened.

  3. The first request gets a reset. The next RPC is sent on the old connection. The NLB no longer knows that flow and answers with a TCP RST, which the client's kernel reports as "connection reset by peer". gRPC fails the in-flight RPC with UNAVAILABLE.

  4. Then it reconnects. The reset marks the connection as broken, gRPC dials a new one, and later calls succeed until the next idle period. gRPC can't safely retry the failed call on its own: the request bytes had already been written, so as far as the client knows the server might have processed it.

  5. Keepalive pings are off by default. gRPC-Go clients don't send HTTP/2 keepalive pings unless configured to. Go does enable TCP keepalives on dialed connections (every 15 seconds by default in recent versions), and those usually also keep NLB flows alive. But they can be disabled by a custom dialer, they detect dead peers slowly, and they don't help with proxies that only count application data. gRPC keepalives are the explicit, portable fix.

The Fix:

Configure the client to send HTTP/2 PING frames more often than the shortest idle timeout on the path, and configure the server to accept them. The server half is easy to miss and is required: by default a gRPC-Go server only accepts pings at most every 5 minutes, and none at all when no RPC is active. A client that pings every 60 seconds is treated as abusive, and the server closes the connection with a GOAWAY frame (ENHANCE_YOUR_CALM, "too_many_pings"), which produces more UNAVAILABLE errors than before.

Corrected Code Blocks:

OrderProcessingService (Client-side connection setup with keepalives):

Go
package main

import (
	"log"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/keepalive" // Import the keepalive package
	pb "your/proto/package"
)

var inventoryServiceClient pb.InventoryServiceClient

func init() {
	inventoryServiceAddr := "inventory-nlb.internal.example.com:50051"

	// Configure client-side keepalive parameters
	// Send a ping if the connection has been idle for 60 seconds (shorter than NLB's 350s timeout)
	// Wait up to 20 seconds for a ping response before considering the connection broken
	clientKeepaliveParams := keepalive.ClientParameters{
		Time:                60 * time.Second, // Send pings every 60 seconds of inactivity
		Timeout:             20 * time.Second, // Wait 20 seconds for ping acknowledgement
		PermitWithoutStream: true,             // Crucial: Allow pings even if no active RPCs are in flight
	}

	// grpc.NewClient replaces the deprecated grpc.Dial (grpc-go v1.63+)
	conn, err := grpc.NewClient(
		inventoryServiceAddr,
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithKeepaliveParams(clientKeepaliveParams), // Apply client keepalive settings
	)
	if err != nil {
		log.Fatalf("did not connect to inventory service: %v", err)
	}
	inventoryServiceClient = pb.NewInventoryServiceClient(conn)
	log.Printf("Successfully connected to inventory service at %s", inventoryServiceAddr)
}

func main() {
	// ... application logic ...
}

InventoryService (Server-side setup with keepalives):

The server's EnforcementPolicy must allow the client's ping rate. Its ServerParameters additionally let the server ping idle clients and recycle long-lived connections.

Go
package main

import (
	"context"
	"log"
	"net"
	"time" // Import time for durations

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/keepalive" // Import the keepalive package
	"google.golang.org/grpc/status"
	pb "your/proto/package"
)

type server struct {
	pb.UnimplementedInventoryServiceServer
}

func (s *server) ReserveStock(ctx context.Context, req *pb.ReserveStockRequest) (*pb.ReserveStockResponse, error) {
	log.Printf("Received ReserveStock request for product %s, quantity %d", req.ProductId, req.Quantity)
	if req.ProductId == "non-existent" {
		return nil, status.Errorf(codes.NotFound, "Product %s not found", req.ProductId)
	}
	return &pb.ReserveStockResponse{Success: true, Message: "Stock reserved"}, nil
}

func main() {
	lis, err := net.Listen("tcp", ":50051")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}

	// Configure server-side keepalive enforcement policy
	// MinTime: Minimum duration a client should wait before sending a ping. If client pings more
	//          frequently, the connection will be terminated to prevent resource exhaustion.
	// PermitWithoutStream: If true, allows clients to send pings without any active RPCs. This MUST be
	//                      true for the client-side `PermitWithoutStream` to be effective.
	kaep := keepalive.EnforcementPolicy{
		MinTime:             30 * time.Second, // Must be <= the client's Time (60s); default is 5 minutes
		PermitWithoutStream: true,            // VERY IMPORTANT: Allow pings from idle clients
	}

	// Server-side keepalive parameters
	// These define how the *server* initiates keepalive pings to clients, and how it handles idle connections.
	// While client pings address your immediate issue, these are good for overall robustness.
	kasp := keepalive.ServerParameters{
		MaxConnectionIdle:     30 * time.Minute, // Close a connection if it's idle (no RPCs or pings) for 30 minutes
		MaxConnectionAge:      30 * time.Minute, // Recycle connections so clients rebalance across new pods
		MaxConnectionAgeGrace: 30 * time.Second, // Let in-flight RPCs finish before closing
		Time:                  2 * time.Minute,  // Server pings an idle client after 2 minutes
		Timeout:               20 * time.Second, // and drops it if there's no ack within 20s
	}

	s := grpc.NewServer(
		grpc.KeepaliveEnforcementPolicy(kaep), // Apply server keepalive enforcement
		grpc.KeepaliveParams(kasp),            // Apply server keepalive parameters
	)
	pb.RegisterInventoryServiceServer(s, &server{})
	log.Printf("server listening at %v", lis.Addr())
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}

The two settings that fix this incident are the client's Time (shorter than the NLB's 350-second timeout) with PermitWithoutStream: true, and the server's EnforcementPolicy permitting that rate. MaxConnectionAge is a separate improvement: gRPC holds long-lived connections, so without it, clients stay attached to the pods that existed when they connected, and new pods added by autoscaling get no traffic.

  1. Overly Aggressive Keepalives: Setting keepalive.ClientParameters.Time or keepalive.ServerParameters.Time values too low (e.g., a few seconds) can lead to excessive network traffic. If you have many idle connections, frequent pings consume unnecessary bandwidth and CPU resources on both client and server, potentially creating a "noisy" network. Choose a Time value that is comfortably shorter than your network's idle timeout (e.g., 60s for a 5-minute timeout), but not excessively short.
  2. Mismatched policies: a client Time shorter than the server's MinTime, or client PermitWithoutStream: true against a server that doesn't permit it, gets the connection closed with too_many_pings. Look for that string in client logs (with GRPC_GO_LOG_SEVERITY_LEVEL=info) after enabling keepalives.
  3. Proxies in the middle: if traffic passes through an L7 proxy (Envoy, an ALB, a service mesh sidecar), the proxy terminates HTTP/2 and keepalive pings only cover the client-to-proxy hop. Configure the proxy's own idle timeouts and upstream keepalives as well.

💡 Bonus Tip:

Keepalives prevent this failure, but deploys and network blips still produce occasional UNAVAILABLE errors. gRPC has built-in retries configured through the service config, so no middleware is needed:

Go
const serviceConfig = `{
  "methodConfig": [{
    "name": [{"service": "inventory.InventoryService"}],
    "retryPolicy": {
      "maxAttempts": 3,
      "initialBackoff": "0.1s",
      "maxBackoff": "1s",
      "backoffMultiplier": 2,
      "retryableStatusCodes": ["UNAVAILABLE"]
    }
  }]
}`

conn, err := grpc.NewClient(addr,
	grpc.WithTransportCredentials(insecure.NewCredentials()),
	grpc.WithKeepaliveParams(clientKeepaliveParams),
	grpc.WithDefaultServiceConfig(serviceConfig),
)

Retry only UNAVAILABLE, which means the request probably didn't reach the server, and only for operations that are safe to repeat. Reserving stock isn't idempotent: if the first attempt did reach the server, a retry could reserve twice. Give ReserveStock an idempotency key (for example, the order ID) that the server uses to ignore duplicates, and then retries are safe. Don't retry DEADLINE_EXCEEDED or CANCELLED automatically: the work may have happened, and a cancelled call means the caller no longer wants the result.

TechLab Editorial TeamAuthorAnswered

Know the answer?

Posting answers needs a TechLab plan. Reading every discussion stays free.