# rpc 错误：code = DeadlineExceeded desc = 上下文超时

- **ID:** `go/grpc-deadline-exceeded-server-slow`
- **领域:** go
- **类别:** network_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

客户端上下文截止时间在服务器响应之前耗尽。通常是因为服务器处理程序较慢（数据库查询、下游调用）或截止时间设置过于激进。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| google.golang.org/grpc v1.55+ | active | — | — |

## 解决方案

1. **** (90% 成功率)
   ```
   func (s *server) Get(ctx context.Context, req *pb.GetReq) (*pb.GetResp, error) {
    ctx, span := trace.StartSpan(ctx, "Get")
    defer span.End()
    if dl, ok := ctx.Deadline(); ok {
        log.Printf("deadline in %v", time.Until(dl))
    }
    return s.db.Query(ctx, req.Id) // pass ctx through
}
   ```
2. **** (85% 成功率)
   ```
   b := backoff.NewExponentialBackOff()
b.MaxElapsedTime = 5 * time.Second
b.InitialInterval = 100 * time.Millisecond
return backoff.Retry(func() error {
    _, err := client.Get(ctx, req)
    return err
}, backoff.WithContext(b, ctx))
   ```

## 无效尝试

- **** — Removes the timeout but leaves slow handlers blocking goroutines indefinitely; cascading failures. (80% 失败率)
- **** — Synchronized retries amplify load on an already-overloaded server (thundering herd). (75% 失败率)
