架构与系统设计 / 系统课时

设置 Deadline 与取消传播

设置 Deadline 与取消传播

这节解决一个生产环境常见问题:调用已经超时,服务端和下游却还在继续消耗线程、连接与数据库资源。你会用 Deadline 给整条 RPC 链路设置时间预算,并让取消信号沿调用链传播,做到超时后尽快停止无效工作。

学习目标

  • 在 gRPC 客户端为单次调用设置明确的 Deadline,而不是无界等待
  • 在服务端响应请求 Context 的取消,并把同一时间预算继续传给下游 RPC
  • 区分 DEADLINE_EXCEEDED 与 CANCELLED,避免超时后继续产生不必要的副作用

Deadline 是整条调用链的时间预算

Deadline 表示“最晚允许这次 RPC 活到什么时候”。客户端达到截止时间后会结束本地等待;gRPC 会把剩余时长编码并传播给服务端。服务端继续调用下游时,应复用当前请求的 Context,让剩余预算自然递减,而不是为每一跳重新创建一个完整超时。

Deadline 与取消信号沿 gRPC 调用链传播

Deadline 不等于“服务端进程被强制终止”。业务代码必须主动响应 Context 取消;如果忽略 ctx.Done(),耗时计算、外部请求甚至部分数据库操作仍可能继续。对有副作用的写操作,还要额外配合事务或幂等设计,因为客户端看到超时并不能证明服务端什么都没做。

用一个最小程序观察取消传播

下面用 grpc-go 自带的 Health RPC 做一个可运行示例,不需要自己生成 protobuf。服务端故意等待 2 秒,客户端只给 300ms;Deadline 到期后,客户端返回 DeadlineExceeded,服务端则从请求 Context 的 Done 通道得知这次调用已经结束。

go
package main

import (
    "context"
    "fmt"
    "net"
    "time"

    "google.golang.org/grpc"
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/credentials/insecure"
    healthpb "google.golang.org/grpc/health/grpc_health_v1"
    "google.golang.org/grpc/status"
)

type slowHealthServer struct {
    healthpb.UnimplementedHealthServer
    canceled chan struct{}
}

func (s *slowHealthServer) Check(ctx context.Context, _ *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {
    select {
    case <-time.After(2 * time.Second):
        return &healthpb.HealthCheckResponse{Status: healthpb.HealthCheckResponse_SERVING}, nil
    case <-ctx.Done():
        // 请求结束后立即停止昂贵工作,并通知 main 等待逻辑。
        fmt.Println("server stopped after context cancellation")
        close(s.canceled)
        return nil, status.FromContextError(ctx.Err()).Err()
    }
}

func main() {
    lis, err := net.Listen("tcp", "127.0.0.1:0")
    if err != nil {
        panic(err)
    }

    server := grpc.NewServer()
    slow := &slowHealthServer{canceled: make(chan struct{})}
    healthpb.RegisterHealthServer(server, slow)
    go func() {
        _ = server.Serve(lis)
    }()
    defer server.Stop()

    conn, err := grpc.NewClient(
        lis.Addr().String(),
        grpc.WithTransportCredentials(insecure.NewCredentials()),
    )
    if err != nil {
        panic(err)
    }
    defer conn.Close()

    client := healthpb.NewHealthClient(conn)
    ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
    defer cancel()

    _, err = client.Check(ctx, &healthpb.HealthCheckRequest{})
    fmt.Printf("client code: %s\n", status.Code(err))
    if status.Code(err) != codes.DeadlineExceeded {
        panic("unexpected status code")
    }

    // 等到服务端确认看到取消,避免进程过早退出导致日志偶发缺失。
    select {
    case <-slow.canceled:
    case <-time.After(time.Second):
        panic("server did not observe cancellation")
    }
}

在空目录中保存为 main.go 后执行:

bash
go mod init deadline-demo
go get google.golang.org/grpc
go run .

预期输出包含下面两条信息;先后顺序可能因调度略有不同:

text
server stopped after context cancellation
client code: DeadlineExceeded

这说明客户端停止等待后,服务端也观察到了请求 Context 的结束,并提前退出了原本 2 秒的等待。实际依赖下载日志可能不同,不影响这两条验证信息。

把剩余时间继续传给下游

在 grpc-go 的服务端处理函数中,默认应把入站 ctx 直接传给下游 gRPC Client。下游调用会继承父 Context 的截止时间;如果某一跳还需要更短的局部预算,可以基于父 Context 派生更短的子 Context,但不能把整体截止时间延长。

go
// 片段示例:假设 inventoryClient 已由 protobuf 生成。
func reserveInventory(ctx context.Context, inventoryClient pb.InventoryClient) error {
    deadline, ok := ctx.Deadline()
    if !ok {
        return status.Error(codes.Internal, "missing request deadline")
    }
    if time.Until(deadline) < 50*time.Millisecond {
        return status.Error(codes.DeadlineExceeded, "insufficient remaining budget")
    }

    _, err := inventoryClient.Reserve(
        ctx,
        &pb.ReserveRequest{Sku: "sku-42"},
    )
    return err
}

该片段依赖当前请求的 context.Context、生成后的 pb.InventoryClient,以及 time、codes、status 包。验证时让下游故意延迟,确认它获得的 Deadline 不晚于上游请求的 Deadline;不要在每一跳重新使用 context.WithTimeout(context.Background(), ...),否则父调用的取消无法继续传播。

处理 Deadline 与主动取消

DEADLINE_EXCEEDED 表示时间预算耗尽;CANCELLED 通常表示调用方主动取消,例如用户终止请求、上游连接关闭或父 Context 被取消。两者都意味着当前调用不应继续投入昂贵工作,但重试策略不同:Deadline 到期后即使准备重试,也要先检查整体预算是否仍允许;主动取消通常应立即停止并把取消语义返回上游。

把 Deadline 当成整条调用链共享的预算,再让 Context 取消贯穿每一跳,才能同时控制尾延迟和资源浪费;单纯在客户端“等 300ms 就放弃”并不足以治理服务端的无效工作。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

设置 Deadline 与取消传播

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通