> ## Content Index
> Fetch the complete content index at: https://zyx322.xyz/llms.txt
> Use this file to discover other available public pages before exploring further.

# gRPC 请求超时却不返回：deadline 没传到服务端的 4 个断链点
- URL: https://zyx322.xyz/csdn-2026-10-13-ced435be5d21/
- Published: 2026-10-13T04:00:00.000Z
- Updated: 2026-11-26T07:02:13.000Z
- Author: ZYX
- Tags: Golang

### 一、一个典型的现象

客户端设了 3 秒超时：

```go
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()

resp, err := client.GetUser(ctx, &pb.GetUserReq{Id: 123})
if err != nil {
    log.Printf("rpc failed: %v", err)   // context deadline exceeded
}

```

客户端确实在 3 秒后返回了 `context deadline exceeded`。但你去服务端看日志，发现那个请求**还在跑**，又跑了两秒才结束，而且服务端日志里没有任何"超时"的记录。

结果就是：**客户端放弃了，服务端不知道**，白白消耗了资源。更糟的是，如果这个请求慢是因为下游慢，那么每次客户端超时重试一次，服务端就多背一份负载。

这不是 gRPC 的 bug，是 deadline 在传递链路上断了。断点通常有四个。

### 二、断链点 1：服务端根本没读 `ctx`

这是最常见的一个。服务端 handler 拿到了 `ctx`，但**没有把它往下传**：

```go
// 错误：ctx 被丢掉了
func (s *Server) GetUser(ctx context.Context, req *pb.GetUserReq) (*pb.User, error) {
    // 直接用了一个新 context，deadline 信息全丢了
    return s.repo.FindByID(context.Background(), req.Id)
}

```

`context.Background()` 是一切的起点，它**没有 deadline**。这样写之后，客户端的 3 秒超时完全传不到数据库那一层。

正确写法是**把入参的 ctx 一路传下去**：

```go
func (s *Server) GetUser(ctx context.Context, req *pb.GetUserReq) (*pb.User, error) {
    // ctx 带着客户端的 deadline，直接往下传
    return s.repo.FindByID(ctx, req.Id)
}

func (r *Repo) FindByID(ctx context.Context, id int64) (*User, error) {
    // 数据库驱动认识 ctx，deadline 到了会主动取消查询
    row := r.db.QueryRowContext(ctx, "SELECT ... WHERE id = ?", id)
    // ...
}

```

**检查办法**：全局搜 `context.Background()` 和 `context.TODO()`，凡是出现在请求处理链路上的（而不是 main 或者定时任务入口），基本都是 bug。

### 三、断链点 2：新起 goroutine，deadline 不继承

```go
// 错误：goroutine 里用了新的 context
func (s *Server) GetUser(ctx context.Context, req *pb.GetUserReq) (*pb.User, error) {
    result := make(chan *User, 1)
    go func() {
        u, _ := s.repo.FindByID(context.Background(), req.Id)  // 断链
        result <- u
    }()
    select {
    case u := <-result:
        return u, nil
    case <-ctx.Done():
        return nil, ctx.Err()
    }
}

```

这段代码看起来"处理了超时"——`select` 里监听了 `ctx.Done()`，超时后函数会返回。但**那个 goroutine 还在跑**，而且它用的是没有 deadline 的 context，会一直跑到结束。

正确写法是让 goroutine 继承 ctx：

```go
func (s *Server) GetUser(ctx context.Context, req *pb.GetUserReq) (*pb.User, error) {
    result := make(chan *User, 1)
    go func() {
        // 继承 ctx：deadline 到了，查询会被取消，goroutine 能退出
        u, _ := s.repo.FindByID(ctx, req.Id)
        result <- u
    }()
    select {
    case u := <-result:
        return u, nil
    case <-ctx.Done():
        return nil, ctx.Err()   // goroutine 里的查询也会随之取消
    }
}

```

**判断标准**：`go func()` 里面如果出现了 `context.Background()`，那这个 goroutine 就脱离了请求生命周期，既不会被取消，也可能泄漏。

更彻底一点，可以基于父 ctx 派生一个带自己超时的子 ctx：

```go
go func() {
    // 继承父 ctx（保留 deadline），同时给自己加一个更短的超时
    child, cancel := context.WithTimeout(ctx, 2*time.Second)
    defer cancel()
    u, _ := s.repo.FindByID(child, req.Id)
    result <- u
}()

```

### 四、断链点 3：中间层自己造了个新 timeout

```go
// 错误：用 Background 重造了一个 ctx
func (s *Server) GetUser(ctx context.Context, req *pb.GetUserReq) (*pb.User, error) {
    c, cancel := context.WithTimeout(context.Background(), 5*time.Second)  // 断链
    defer cancel()
    return s.repo.FindByID(c, req.Id)
}

```

这个写法比前两个更隐蔽：**它看起来"设置了超时"，所以很容易通过 code review**。但它的父是 `Background()`，客户端的 3 秒 deadline 被完全丢掉了，服务端自己给自己定了 5 秒。

正确写法是从**入参 ctx** 派生：

```go
func (s *Server) GetUser(ctx context.Context, req *pb.GetUserReq) (*pb.User, error) {
    c, cancel := context.WithTimeout(ctx, 2*time.Second)  // 从入参派生
    defer cancel()
    return s.repo.FindByID(c, req.Id)
}

```

`context.WithTimeout(ctx, ...)` 的语义是"取父的 deadline 和新的 deadline 里**更早**的那个"。所以即使客户端给 3 秒、服务端本地想限 2 秒，最终生效的是 2 秒——**这就是想要的"逐层收敛"**。

### 五、断链点 4：跨服务调用时没把 deadline 带过去

这一层是微服务里最容易断的。

**gRPC 客户端**：只要把 ctx 传进去，deadline 会通过 HTTP/2 的 `grpc-timeout` header 自动带到服务端，服务端收到的 ctx 就带 deadline。**这一环是自动的**。

```go
// 正确：ctx 传进去，grpc-timeout 自动带上
resp, err := downstream.GetOrder(ctx, req)

```

**但如果中间夹了 HTTP 调用，就不会自动带**：

```go
// 错误：http.NewRequest 用的是 Background
req, _ := http.NewRequest("GET", url, nil)
resp, err := http.DefaultClient.Do(req)    // 没有超时，也没继承 ctx

// 正确：WithContext + 显式 Timeout
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
client := &http.Client{Timeout: 3 * time.Second}
resp, err := client.Do(req)

```

**两个都要**：`NewRequestWithContext` 保证 ctx 取消时请求中断，`client.Timeout` 保证即使 ctx 没有 deadline 也不会永久挂着。

同理，MySQL、Redis、MongoDB 的驱动都有 `XxxContext` 版本，一律用带 ctx 的那个：

```go
db.QueryContext(ctx, ...)       // 而不是 db.Query(...)
rdb.Get(ctx, key)               // go-redis 本来就是 ctx 优先
coll.FindOne(ctx, filter)       // mongo-go-driver

```

### 六、还有一类：deadline 传过去了，但服务端不看

即使 ctx 一路传到位，如果服务端代码里**没有任何一处检查 `ctx.Done()`**，那么耗时操作（比如一个不查 ctx 的循环）依然会跑完。

```go
// 长循环要主动检查取消
func aggregate(ctx context.Context, items []Item) (*Result, error) {
    r := &Result{}
    for _, it := range items {
        select {
        case <-ctx.Done():
            return nil, ctx.Err()    // 主动让出
        default:
        }
        r.Add(process(it))
    }
    return r, nil
}

```

对数据库/redis 这类 IO，驱动内部已经处理了取消，不用你检查；**只有纯 CPU 的长循环需要自己检查**。

### 七、怎么验证修好了

一个可复现的验证方法：服务端 handler 里加一行日志，打印 ctx 的 deadline：

```go
func (s *Server) GetUser(ctx context.Context, req *pb.GetUserReq) (*pb.User, error) {
    if dl, ok := ctx.Deadline(); ok {
        log.Printf("deadline 已传到，剩余 %v", time.Until(dl))
    } else {
        log.Printf("⚠ ctx 没有 deadline —— 链路上有断点")
    }
    // ...
}

```

客户端带 3 秒超时打一次，服务端如果打印"没有 deadline"，说明四个断链点里至少有一个还堵着。

再做一个"强制慢"的验证：让 handler 睡 10 秒，客户端 3 秒超时。修好之后，服务端日志应该在 3 秒左右就出现取消（数据库查询被中断、goroutine 退出），而不是跑满 10 秒。

### 八、带走物

| 断链点                         | 症状                   | 修法                                                        |
| --------------------------- | -------------------- | --------------------------------------------------------- |
| 1\. 服务端没读 ctx               | 服务端请求跑满才结束           | 把入参 ctx 一路传到底                                             |
| 2\. goroutine 里用新 ctx       | 主流程返回了，goroutine 还在跑 | goroutine 继承父 ctx                                         |
| 3\. 从 Background 派生 timeout | 服务端超时比客户端还长          | 从**入参 ctx** 派生子 ctx                                       |
| 4\. 跨 HTTP/DB 没带 ctx        | 下游调用不响应取消            | NewRequestWithContext \+ client.Timeout；DB 用 QueryContext |

一条全局可用的检查命令：

```bash
# 在请求处理链路里找这两个，基本都是 bug
grep -rn "context.Background()\|context.TODO()" --include="*.go" ./internal ./service ./handler

```

最后一句结论：**gRPC 会自动帮你把 deadline 从客户端传到服务端，但它只负责"这一跳"。链路上每一层你是不是接着往下传，它管不了。**