Most webhook tutorials stop right after signature verification and a seen_events table. You add a primary key on event_id, run INSERT OR IGNORE, and figure duplicates are solved.
Then a real outage hits your downstream API, or a worker gets killed right after sending a confirmation message, and that simple table starts either dropping paid events silently or running the same side effect twice.
We hit both failure modes while hardening payment and bot webhook handlers in a small open Telegram Mini App backend (https://github.com/angeldev-tech/ton-alpha-tma). Neither bug showed up in unit tests because happy-path tests never crash halfway between the database write and the HTTP response.
The two traps inside a naive seen_events table
A single-column webhook_events (event_id PRIMARY KEY) table forces you to choose when to insert the row, and both choices break under partial failures.
If you insert event_id first and run your side effect second, a crash or timeout mid-handler leaves event_id permanently marked as seen. When Stripe, GitHub, or Telegram retries sixty seconds later, INSERT OR IGNORE sees the existing row, returns 200 OK, and drops the event forever.
If you run the side effect first and insert event_id second, a crash between the external call and the database commit leaves no record behind. The next retry executes the side effect a second time.
A 3-state claim with an expiring lease
You can close the silent-drop hole without adding a message broker by replacing the boolean seen row with a small state machine: processing (with a lease_until timestamp) and completed.
The key rules are simple. First, claim the event atomically in BEGIN IMMEDIATE before doing work. Second, if a concurrent retry arrives while the lease is still valid, return a retryable status like 503 (not 200 OK) so the provider comes back if the first worker died. Third, once the lease expires, a retry atomically reclaims the row and finishes the job.
Here is a self-contained Python script using only sqlite3 that compares the naive mark-first pattern against a lease-based claim across a crash, a concurrent retry, a reclaim, and a late duplicate.
import sqlite3
def make_db() -> sqlite3.Connection:
conn = sqlite3.connect(":memory:", isolation_level=None)
conn.execute(
"""
CREATE TABLE webhook_events (
event_id TEXT PRIMARY KEY,
status TEXT NOT NULL,
lease_until INTEGER NOT NULL,
attempts INTEGER NOT NULL DEFAULT 1
)
"""
)
return conn
def claim_with_lease(conn: sqlite3.Connection, event_id: str, now: int, lease_s: int = 30) -> str:
conn.execute("BEGIN IMMEDIATE")
row = conn.execute(
"SELECT status, lease_until FROM webhook_events WHERE event_id = ?",
(event_id,),
).fetchone()
if row is None:
conn.execute(
"INSERT INTO webhook_events (event_id, status, lease_until, attempts) VALUES (?, 'processing', ?, 1)",
(event_id, now + lease_s),
)
conn.execute("COMMIT")
return "claimed"
status, lease_until = row
if status == "completed":
conn.execute("COMMIT")
return "already_completed"
if lease_until > now:
conn.execute("COMMIT")
return "in_flight"
conn.execute(
"UPDATE webhook_events SET lease_until = ?, attempts = attempts + 1 WHERE event_id = ?",
(now + lease_s, event_id),
)
conn.execute("COMMIT")
return "reclaimed"
def mark_completed(conn: sqlite3.Connection, event_id: str) -> None:
conn.execute("BEGIN IMMEDIATE")
conn.execute("UPDATE webhook_events SET status = 'completed' WHERE event_id = ?", (event_id,))
conn.execute("COMMIT")
def run_demo() -> None:
naive = sqlite3.connect(":memory:")
naive.execute("CREATE TABLE seen (event_id TEXT PRIMARY KEY)")
naive_runs = 0
for attempt in (1, 2):
cur = naive.execute("INSERT OR IGNORE INTO seen VALUES (?)", ("evt_901",))
if cur.rowcount == 1:
if attempt == 1:
continue # simulated crash before side effect finished
naive_runs += 1
print(f"naive_mark_first runs={naive_runs}")
conn = make_db()
lease_runs = 0
timeline = [
(1000, True), # delivery 1: claims lease, crashes before finishing
(1005, False), # delivery 2: arrives during active lease -> blocked
(1035, False), # delivery 3: lease expired -> reclaimed and completed
(1040, False), # delivery 4: late retry -> skipped cleanly
]
for ts, crash in timeline:
state = claim_with_lease(conn, "evt_901", now=ts, lease_s=30)
if state in ("claimed", "reclaimed"):
if not crash:
lease_runs += 1
mark_completed(conn, "evt_901")
print(f"t={ts} state={state} runs={lease_runs}")
if __name__ == "__main__":
run_demo()
Running this locally outputs:
naive_mark_first runs=0
t=1000 state=claimed runs=0
t=1005 state=in_flight runs=0
t=1035 state=reclaimed runs=1
t=1040 state=already_completed runs=1
Honest limits of a database lease
A lease fixes silent drops and stops overlapping retries during normal crashes, yet it still cannot guarantee exactly-once delivery across an external network call on its own.
If worker 1 stalls past lease_s without actually dying, worker 2 can reclaim the row while worker 1's outbound request is still in flight. Keeping lease_s comfortably above your outbound HTTP timeout narrows that window, and passing event_id downstream as an Idempotency-Key header is what actually prevents duplicate external side effects.
For local database updates (crediting a balance, unlocking a plan, creating an order), the cleaner rule is to write both the business row and status = 'completed' inside the same transaction, then push any slow email or API notification into an outbox table that a background worker drains asynchronously.
For teams running webhook receivers in Python, Node, or Go: do you stick with an inline lease table and downstream idempotency keys, or did a real duplicate-delivery bug push you to a full transactional outbox and queue?
Top comments (0)