My Retry Wrote the Row Twice, and the Idempotency Key Was the Bug

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

My Retry Wrote the Row Twice, and the Idempotency Key Was the Bug

My Retry Wrote the Row Twice, and the Idempotency Key Was the Bug Here is a failure shape I keep meeting in batch jobs: one input, two writes to the database, and a clean 200 on every log line I check. Which attempt actually did the work? Did the queue hand me the same job twice? Did my own retry fire while the first call was still in flight, so two workers raced to the same finish line? None of those questions can be answered from timing alone, because a duplicate looks exactly like a success. So for 48 hours I stopped adding retries and started counting duplicates instead. I worked it in three passes: where a duplicate is born, how to fingerprint a unit of work, and how to prove the guard holds when I inject faults. These are the field notes from that pass, including the parts that broke.

我的重试机制导致了重复写入,而幂等键正是罪魁祸首。在批处理作业中,我经常遇到这样一种故障模式:一个输入,两次数据库写入,且我检查的每一行日志都显示正常的 200 状态码。到底是哪一次尝试真正完成了工作?是队列把同一个任务给了我两次吗?还是我的重试机制在第一次调用尚未结束时就触发了,导致两个工作进程竞相到达终点?仅凭时间戳无法回答这些问题,因为重复执行看起来和成功执行一模一样。因此,我花了 48 小时停止添加重试逻辑,转而开始统计重复项。我分三个阶段进行了处理:重复项是如何产生的、如何为工作单元生成指纹,以及当我注入故障时如何证明防护机制有效。以下是该过程的现场记录,包括那些失败的部分。

Pass 1: Three places a duplicate is born Before writing any code I listed the birthplaces, because each one needs a different fix. Skipping this step is how people end up with three half-guards that each cover the wrong layer. The producer enqueues twice. A form submit, a cron overlap, or a webhook redelivery creates two jobs with the same payload and different job IDs. The broker redelivers. Visibility timeouts, at-least-once queues, and worker crashes all cause the same job to be handed to a second worker mid-flight. Your own retry wrapper fires. A timeout does not mean the server did nothing; it means you stopped waiting for the answer. Only the third one lives in my code, and it was the one I had been “fixing” for months. That is the trap, isn’t it? You patch the layer you can see and assume the other two are somebody else’s problem.

第一阶段:重复项产生的三个源头。在编写任何代码之前,我列出了重复项的产生源头,因为每一个都需要不同的修复方案。跳过这一步,人们最终会得到三个半吊子的防护措施,且每个都覆盖了错误的层级。生产者重复入队:表单提交、定时任务重叠或 Webhook 重复投递,都会创建两个具有相同负载但不同任务 ID 的作业。消息代理重复投递:可见性超时、至少一次投递队列以及工作进程崩溃,都会导致同一个任务在执行过程中被交给第二个工作进程。你自己的重试包装器触发:超时并不意味着服务器什么都没做,它只意味着你停止等待响应了。只有第三种情况存在于我的代码中,而这正是我几个月来一直在“修复”的问题。这就是陷阱,不是吗?你修补了你能看到的层级,并假设另外两个是别人的问题。

Pass 2: Fingerprint the work, not the attempt The worst bug in this whole exercise was mine, and it was one line long. My idempotency key was built from the job ID plus the attempt counter, which guaranteed that every retry looked like brand new work. Nothing deduplicated, ever, and the logs looked perfectly healthy. The key has to describe the input, not the history. Here is the fingerprint function I settled on, which normalizes the payload so cosmetic differences do not create new work:

第二阶段:为工作生成指纹,而非为尝试生成指纹。在整个过程中,最严重的 Bug 出在我自己身上,而且只有一行代码。我的幂等键是由任务 ID 加上尝试计数器生成的,这保证了每一次重试看起来都像是全新的工作。没有任何东西被去重,日志看起来也完全正常。幂等键必须描述输入,而不是历史记录。这是我最终确定的指纹函数,它对负载进行了标准化,从而确保表面上的差异不会产生新的工作:

import hashlib, json
def fingerprint(model: str, messages: list[dict], params: dict) -> str:
    payload = {
        "model": model,
        "messages": [{"role": m["role"], "content": m["content"]} for m in messages],
        "params": {k: params[k] for k in sorted(params) if k != "idempotency_key"},
    }
    blob = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
    return hashlib.sha256(blob).hexdigest()

The rules I follow for that function are boring and they matter: Include every field that changes the output, and exclude every field that changes between attempts (timestamps, attempt counters, request IDs). Normalize whitespace and key order before hashing, or the same prompt in two formats becomes two units of work. Hash the whole conversation, not just the last message, or a multi-turn job collapses into a single key by accident. Write the fingerprint to the log line, so the next duplicate is one grep away instead of one afternoon away. A cache key is not a claim I also had to separate two ideas that I had been conflating. A cache key answers “have I seen this input before, and can I reuse the output?” A claim answers “is someone working on this input right now, and should I back off?” Those are different questions with different lifetimes, and a single table serving both was the reason my stale entries kept resurrecting finished work.

我遵循的函数规则虽然枯燥但至关重要:包含所有会改变输出的字段,排除所有在尝试之间会改变的字段(时间戳、尝试计数器、请求 ID)。在哈希之前标准化空格和键的顺序,否则同一提示词的两种格式会变成两个工作单元。对整个对话进行哈希,而不仅仅是最后一条消息,否则多轮任务会意外地合并成同一个键。将指纹写入日志行,这样下次查找重复项时只需一个 grep 命令,而不是浪费一下午时间。缓存键不是声明,我还必须区分我一直混淆的两个概念。缓存键回答的是“我以前见过这个输入吗,可以重用输出吗?”而声明回答的是“现在有人在处理这个输入吗,我应该退出吗?”这是两个生命周期不同的问题,用一张表同时处理两者,就是我的过期条目不断复活已完成工作的原因。

Pass 3: A claim table with a state machine The smallest guard that survives a crash is a table with a primary key on the fingerprint and a status column. The insert either wins or it does not, and the database does the arguing for you.

第三阶段:带有状态机的声明表。能够从崩溃中恢复的最小防护措施是一张表,其中指纹作为主键,并包含一个状态列。插入操作要么成功,要么失败,数据库会为你处理争用问题。

CREATE TABLE work_claims (
    fingerprint TEXT PRIMARY KEY,
    state TEXT NOT NULL CHECK (state IN ('claimed','done','failed')),
    attempt INTEGER NOT NULL DEFAULT 1,
    claimed_at REAL NOT NULL,
    updated_at REAL NOT NULL
);

The claim path is short, and every branch is explicit:

声明路径很短,且每个分支都是明确的:

import sqlite3, time
STALE_AFTER = 900 # seconds; must exceed your worst p99 call latency
def claim(db: sqlite3.Connection, fp: str) -> str:
    now = time.time()
    db.execute("BEGIN IMMEDIATE")
    try:
        row = db.execute(
            "SELECT state, claimed_at FROM work_claims WHERE fingerprint = ?", (fp,)
        ).fetchone()
        if row is None:
            db.execute(
                "INSERT INTO work_claims(fingerprint, state, attempt, claimed_at, updated_at)"
                " VALUES (?, 'claimed', 1, ?, ?)", (fp, now, now)
            )
            db.execute("COMMIT")
            return "claimed"
        state, claimed_at = row
        if state == "done":
            db.execute("COMMIT")
            return "skip"
        if state == "claimed" and now - claimed_at > STALE_AFTER:
            db.execute(
                "UPDATE work_claims SET attempt = attempt + 1, claimed_at = ?, updated_at = ?"
                " WHERE fingerprint = ?", (now, now, fp)
            )
            db.execute("COMMIT")
            return "reclaimed"
        db.execute("COMMIT")
        return "busy"
    except Exception:
        db.execute("ROLLBACK")
        raise

Two details I got wrong at first. A process-level threading.Lock is useless once you run two workers, so the atomicity has to live in the database, and BEGIN IMMEDIATE is what stops two writers from both seeing “no row” in SQLite. And the side effect and the state = ‘done’ update belong in one transaction, or you will produce exactly the duplicate you were preventing. How I would prove it: three fault injections A guard you have not attacked is a guard you do not know. My test plan kills the worker at three specific points and asserts that the effect count stays at one. Crash after send, before commit. The model has been called, the row is still claimed, and no output was written. Expected result: the next run returns reclaimed only after STALE_AFTER, and the effect count stays at one if you also store the output before committing. Duplicate delivery. Two workers claim the same fingerprint in parallel with no injected delay. Expected result: one claimed, one busy, and the busy worker exits without calling anything. Retry storm. Wrap the call so it raises a timeout three times while the serve

起初我有两个细节弄错了。一旦运行两个工作进程,进程级的 threading.Lock 就没用了,所以原子性必须存在于数据库中,而 BEGIN IMMEDIATE 正是防止 SQLite 中两个写入者同时看到“无行”的关键。此外,副作用和 state = ‘done’ 的更新必须属于同一个事务,否则你最终会产生你试图防止的重复项。我将如何证明它:三次故障注入。没有经过攻击的防护措施就不是真正的防护。我的测试计划在三个特定点杀死工作进程,并断言效果计数保持为一。发送后、提交前崩溃:模型已被调用,行仍处于已声明状态,且没有写入输出。预期结果:下一次运行仅在 STALE_AFTER 之后返回 reclaimed,如果在此之前存储了输出,效果计数保持为一。重复投递:两个工作进程并行声明同一个指纹,没有注入延迟。预期结果:一个声明成功,一个显示忙碌,忙碌的工作进程在不调用任何内容的情况下退出。重试风暴:包装调用,使其在服务器响应时抛出三次超时。