Engineering Resilient Webhook Systems: Retries, Backoff, and Queue Mechanics

本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。

Engineering Resilient Webhook Systems: Retries, Backoff, and Queue Mechanics

Webhook delivery sits at the boundary between decoupled distributed systems. Basic queue-and-retry tutorials cover exponential backoff and dead-letter queues. Production webhook infrastructure fails at the edges: system clocks that disagree across containerized workers, batched payloads that fail partially, and retry schedules that outlive the business windows they exist to serve.

Webhook 交付位于解耦分布式系统的边界。基础的队列与重试教程涵盖了指数退避和死信队列。生产环境中的 Webhook 基础设施往往在边缘地带失效:容器化工作节点之间系统时钟不一致、批量负载部分失败,以及重试计划超出了其原本服务的业务窗口。

Provider practice varies widely. GitHub does not automatically redeliver failed webhook deliveries and leaves redelivery to manual action or your own scripts. Stripe retries live-mode events with exponential backoff for up to three days. Svix publishes a fixed schedule of immediate, 5 seconds, 5 minutes, 30 minutes, 2 hours, 5 hours, then 10 hours twice, with each period starting after the previous failure. That schedule spans roughly 27.5 hours. If you build a sender, you have to choose where on this spectrum to sit, and the choice has consequences beyond the backoff formula.

服务提供商的做法差异巨大。GitHub 不会自动重新发送失败的 Webhook,而是将重试留给手动操作或用户自己的脚本。Stripe 会对实时模式事件进行长达三天的指数退避重试。Svix 则发布了一个固定的重试计划:立即重试,随后依次为 5 秒、5 分钟、30 分钟、2 小时、5 小时,以及两次 10 小时,每个周期从上一次失败后开始计算。该计划总时长约为 27.5 小时。如果你要构建一个发送端,你必须选择在这个谱系中的位置,而这种选择带来的后果远不止退避公式那么简单。

  1. Clock Skew and Drift in Delayed Webhook Schedulers Delayed webhook retries rely on time-ordered data structures. The most common are Redis sorted sets (ZSET), relational scheduled_at indexes, and broker-side delays or visibility timeouts such as those in Amazon SQS. Any design that mixes timestamps produced by different machines assumes those machines agree on the time.

  2. 延迟 Webhook 调度器中的时钟偏差与漂移 延迟 Webhook 重试依赖于按时间排序的数据结构。最常见的是 Redis 有序集合 (ZSET)、关系型数据库的 scheduled_at 索引,以及诸如 Amazon SQS 中的代理端延迟或可见性超时。任何混合使用由不同机器产生的时间戳的设计,都假设这些机器在时间上达成了一致。

How Wall-Clock Assumptions Break Distributed Schedulers Linux exposes several clocks, and two matter here. The clock_gettime(3) manual page describes them: Wall-clock time (CLOCK_REALTIME): Calendar time that can be set by an administrator or adjusted by NTP. It is affected by discontinuous jumps and by incremental adjtime/NTP adjustments, so it can step backward. Monotonic time (CLOCK_MONOTONIC): Not affected by discontinuous jumps such as a manual clock change, but still affected by incremental adjtime/NTP slewing. On Linux it does not count time the system is suspended. CLOCK_BOOTTIME is identical except that it includes suspended time, and CLOCK_MONOTONIC_RAW is not subject to NTP frequency adjustments.

墙上时钟假设如何破坏分布式调度器 Linux 提供了多种时钟,其中两种至关重要。clock_gettime(3) 手册页对其进行了描述:墙上时钟时间 (CLOCK_REALTIME):可由管理员设置或通过 NTP 调整的日历时间。它会受到不连续跳变和增量 adjtime/NTP 调整的影响,因此可能会向后回跳。单调时间 (CLOCK_MONOTONIC):不受手动更改时钟等不连续跳变的影响,但仍会受到增量 adjtime/NTP 调整的影响。在 Linux 上,它不计算系统挂起的时间。CLOCK_BOOTTIME 与之相同,但包含挂起时间,而 CLOCK_MONOTONIC_RAW 不受 NTP 频率调整的影响。

When a webhook worker computes a retry timestamp as now() + backoff and writes it into shared state, several failure modes appear: Premature retries (enqueuer clock behind the poller): If the enqueuing worker’s clock lags the polling scheduler’s by 45 seconds, a retry scheduled at worker_now + 30s is already in the past from the scheduler’s point of view. The backoff collapses into an immediate retry, which is the opposite of what you want during a downstream outage.

当 Webhook 工作节点计算重试时间戳为 now() + backoff 并将其写入共享状态时,会出现几种故障模式:过早重试(入队时钟滞后于轮询器):如果入队工作节点的时钟比轮询调度器慢 45 秒,那么在 worker_now + 30s 计划的重试在调度器看来已经成为过去。退避失效并演变为立即重试,这与你在下游中断期间想要的结果背道而驰。

Stalled retries (enqueuer clock ahead of the poller): If the enqueuer runs ahead, retries stay invisible for longer than intended. The same happens when a scheduler node’s clock steps backward after an NTP correction, because tasks are not due until the local clock catches up. Premature lease expiry in homegrown lease queues: If one process writes lease_expires_at using its own clock and a separate reaper compares it with a different clock, a few seconds of skew can make a live lease look expired. Two workers then dispatch the same webhook concurrently.

重试停滞(入队时钟超前于轮询器):如果入队节点运行超前,重试将比预期更长时间处于不可见状态。当调度器节点的时钟在 NTP 校正后向后跳变时也会发生同样的情况,因为任务必须等到本地时钟追上后才算到期。自研租约队列中的过早租约过期:如果一个进程使用自己的时钟写入 lease_expires_at,而另一个清理进程使用不同的时钟进行比较,几秒钟的偏差就可能使有效的租约看起来已过期。随后,两个工作节点会同时分发同一个 Webhook。

Managed brokers largely avoid the third problem by judging expiry on the broker side. In Amazon SQS, the visibility timeout starts when a message is returned to a consumer, and the broker enforces it. The remaining risk is that your worker’s belief about how much lease time is left diverges from the broker’s, for example during a long pause. SQS also does not guarantee that a message won’t be delivered more than once within the visibility timeout, so duplicate-safe processing is required regardless.

托管代理通过在代理端判断过期时间,在很大程度上避免了第三个问题。在 Amazon SQS 中,可见性超时从消息返回给消费者时开始,并由代理强制执行。剩下的风险在于,你的工作节点对剩余租约时间的判断可能与代理不一致,例如在长时间暂停期间。此外,SQS 不保证消息在可见性超时内不会被多次投递,因此无论如何都需要进行去重处理。

Architectural Mitigations The fix is to stop using uncoordinated node wall clocks as the source of truth for retry scheduling.

架构缓解措施 解决方案是停止使用未协调的节点墙上时钟作为重试调度的真理来源。

[Table omitted for brevity]

[表格省略]

Centralizing the Time Oracle in Redis For Redis-backed schedulers, avoid passing a client-generated Unix timestamp as the sorted-set score. Compute it inside a Lua script from Redis’s own clock. TIME returns a two-element array of Unix seconds and microseconds. Scripts that call TIME and then write used to be rejected because Redis replicated the whole script. Since Redis 5, scripts are replicated as their effects rather than verbatim, so this pattern works on any current version.

在 Redis 中集中化时间预言机 对于基于 Redis 的调度器,应避免将客户端生成的 Unix 时间戳作为有序集合的分数。应在 Lua 脚本内部使用 Redis 自身的时钟进行计算。TIME 命令返回一个包含 Unix 秒和微秒的两个元素的数组。过去,调用 TIME 后进行写入的脚本会被拒绝,因为 Redis 会复制整个脚本。从 Redis 5 开始,脚本以其执行效果而非原文进行复制,因此这种模式在当前任何版本中均适用。

— KEYS[1]: delayed_webhooks sorted set — ARGV[1]: webhook ID — ARGV[2]: relative backoff delay in milliseconds local t = redis.call(‘TIME’) local now_ms = (tonumber(t[1]) * 1000) + math.floor(tonumber(t[2]) / 1000) local execute_at = now_ms + tonumber(ARGV[2]) redis.call(‘ZADD’, KEYS[1], execute_at, ARGV[1]) return execute_at The claim step should use the same clock. This script moves due items into an in-fl

— KEYS[1]: delayed_webhooks 有序集合 — ARGV[1]: Webhook ID — ARGV[2]: 相对退避延迟(毫秒) local t = redis.call(‘TIME’) local now_ms = (tonumber(t[1]) * 1000) + math.floor(tonumber(t[2]) / 1000) local execute_at = now_ms + tonumber(ARGV[2]) redis.call(‘ZADD’, KEYS[1], execute_at, ARGV[1]) return execute_at 认领步骤应使用相同的时钟。此脚本将到期项移入处理中…