Format run webhook plus polling: one idempotent finalize in SQLite

A webhook and a poll can both see the same terminal run. Insert the run id with insert or ignore, and do the work only when a row was added.

4 min readSume
All posts

Run both a webhook and a poll for every Format run, and send both to the same function that finalizes by run id. A SQLite insert or ignore on the id makes the second arrival a no-op, so the work happens once.

Webhooks deliver the terminal event at least once and can arrive late or twice, and polling can catch a run the webhook never delivered.

Which path carries what

From the Run webhooks page (read 2026-10-03).

Webhook event and poll for a Format run (read 2026-10-03)
PathWhat you getGap
Webhook format.run.terminalEnvelope with request_id equal to the run id, status, outcome and payloadpayload is null when over 1 MiB
Poll GET /v1/format-runs/{run_id}The receiptOnly as often as you ask, within the read budget
GET /v1/format-runs/{run_id}/resultThe output409 run_not_completed before the run ends

The finalizer

The function takes a run id and an optional payload. When the webhook payload is null, it fetches the result from the API instead.

import sqlite3

db = sqlite3.connect("done.db")
db.execute("create table if not exists done(id text primary key)")

def finalize(run_id, payload=None, fetch=lambda i: {"fetched": i}):
    cur = db.execute("insert or ignore into done values(?)", (run_id,))
    db.commit()
    if cur.rowcount == 0:
        return "duplicate"
    data = payload if payload is not None else fetch(run_id)
    print("deliver", run_id, data)
    return "done"

print(finalize("run_1", {"ok": True}))
print(finalize("run_1"))

Failure ordering

If the delivery step can fail, insert the id after it succeeds, or delete the row on failure, since a row that is written first would mark a failed delivery as finished. Verify the signature before this function runs, as in the Flask receiver, and see dedupe on request_id for ordering.

Sources

Related posts

More in Formats

All Formats posts

Written by Sume