Working with Keep-Alive
1. Configuring Client Keep-Alive
| Field | Default | Description |
Time | ∞ (disabled) | Idle interval before ping |
Timeout | 20s | Pong wait |
PermitWithoutStream | false | Ping with no active RPCs |
2. Setting Keep-Alive Time
| Recommendation | Detail |
| Production | 10–30s |
| Behind LB | Less than LB idle timeout |
| Mobile | 30–60s to save battery |
3. Setting Keep-Alive Timeout
| Value | Effect |
| Too short | False disconnects under load |
| Too long | Slow dead-peer detection |
| Typical | 3–5s |
4. Allowing Pings Without Stream
Example: Idle pings
kp := keepalive.ClientParameters{
Time: 10*time.Second, Timeout: 3*time.Second,
PermitWithoutStream: true,
}
Warning: Server enforcement may close connections sending too many pings. Coordinate client + server values.
5. Configuring Server Keep-Alive
Example: Server keep-alive
srv := grpc.NewServer(
grpc.KeepaliveParams(keepalive.ServerParameters{
MaxConnectionIdle: 5 * time.Minute,
MaxConnectionAge: 30 * time.Minute,
MaxConnectionAgeGrace: 30 * time.Second,
Time: 10 * time.Second,
Timeout: 3 * time.Second,
}),
)
| Field | Purpose |
MaxConnectionIdle | Close idle connections |
MaxConnectionAge | Force re-LB by closing old connections |
MaxConnectionAgeGrace | Drain time before close |
6. Setting Enforcement Policy
Example: Enforcement
grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
MinTime: 5 * time.Second,
PermitWithoutStream: true,
})
| Field | Effect |
MinTime | Min interval between client pings |
PermitWithoutStream | Allow client pings during idle |
7. Setting Min Time Between Pings
| Symptom | Cause |
| Client ENHANCE_YOUR_CALM | Server enforced ping limit exceeded |
| Fix | Increase client Time ≥ server MinTime |
8. Permitting Without Stream on Server
| Setting | When |
| true | Server allows pings on idle connections |
| false (default) | Server only accepts pings with active stream |
9. Detecting Connection Loss
| Side | Detection |
| Client | Ping timeout → close + reconnect |
| Server | HTTP/2 frame errors / TCP RST |
10. Tuning Keep-Alive for Production
| Scenario | Recommended |
| Internal mesh | Time 10s / Timeout 3s |
| Behind L4 LB | Time < LB idle (typically 60–300s) |
| Mobile | Time 30–60s |
| MinTime alignment | Server MinTime ≤ client Time |