Skip to content

Webhook Idempotency: Dedupe Retries on update_id

Webhooks retry, so your receiver will see some deliveries twice. How to make an AyeWatch receiver idempotent with a Postgres or Redis claim on update_id, and when to answer 200 or 500.

By AyeWatch Team5 min read

Short answer: Webhook idempotency means a delivery that arrives twice has the same effect as one that arrives once. AyeWatch makes up to 10 attempts per delivery, all with the same update_id, so store each update_id under a unique constraint, skip any you have already handled and answer 2xx, and return 500 only when you want the retry.

Why the same alert arrives twice

AyeWatch retries a delivery that gets an error status or no answer within 10 seconds, with exponential backoff, up to 10 attempts. Every attempt carries the same update_id. Duplicates happen when your side did the work but AyeWatch never saw the success:

  • Your handler finished after the 10-second timeout.
  • A deploy or restart dropped the connection after the work but before the response.
  • A proxy in front of your app returned a 502 although the app processed the request.

Deliveries can also arrive out of order, so sort by created_at when order matters. The fix for duplicates is a claim: record update_id under a unique constraint before acting, and act only if the record is new.

A Postgres table that doubles as a queue

CREATE TABLE ayewatch_deliveries (
  update_id    bigint PRIMARY KEY,
  topic_id     bigint NOT NULL,
  payload      jsonb NOT NULL,
  received_at  timestamptz NOT NULL DEFAULT now(),
  processed_at timestamptz
);

The receiver verifies the signature, inserts the row and answers 200. A repeat hits the primary key and does nothing. This is the fast-ack pattern, and it keeps every response well inside 10 seconds:

# receiver.py (Flask, psycopg 3)
import json
import os
import psycopg
from flask import Flask, request
from ayewatch_signature import valid_signature

app = Flask(__name__)
SECRET = os.environ["AYEWATCH_WEBHOOK_SECRET"]
DSN = os.environ["DATABASE_URL"]

CLAIM = """
INSERT INTO ayewatch_deliveries (update_id, topic_id, payload)
VALUES (%s, %s, %s::jsonb)
ON CONFLICT (update_id) DO NOTHING
"""

@app.post("/ayewatch")
def ayewatch():
    raw = request.get_data()
    if not valid_signature(SECRET, raw, request.headers.get("X-AyeWatch-Signature", "")):
        return "", 401
    update = json.loads(raw)
    with psycopg.connect(DSN) as conn:  # use a connection pool in production
        conn.execute(CLAIM, (update["update_id"], update["topic_id"], raw.decode("utf-8")))
    return "", 200

A separate worker takes unprocessed rows. FOR UPDATE SKIP LOCKED lets several workers run without taking the same row:

# worker.py
import os
import time
import psycopg

BATCH = """
SELECT update_id, payload FROM ayewatch_deliveries
WHERE processed_at IS NULL
ORDER BY received_at
LIMIT 10
FOR UPDATE SKIP LOCKED
"""

def handle(update):
    print(update["update_id"], update["topic_name"])

with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
    while True:
        with conn.transaction():
            rows = conn.execute(BATCH).fetchall()
            for update_id, payload in rows:
                handle(payload)  # psycopg returns jsonb as a dict
                conn.execute("UPDATE ayewatch_deliveries SET processed_at = now() WHERE update_id = %s", (update_id,))
        if not rows:
            time.sleep(2)

If handle() raises, the transaction rolls back and the rows stay unprocessed for the next pass. The ayewatch_signature module is the one from verifying signatures in Python.

Doing the work inline

If the work is quick, do it in the request, inside the same transaction as the claim. When it fails, the claim rolls back and a 500 asks AyeWatch to retry:

def create_ticket(update):
    print("ticket for", update["update_id"], update.get("headline"))

@app.post("/ayewatch-inline")
def ayewatch_inline():
    raw = request.get_data()
    if not valid_signature(SECRET, raw, request.headers.get("X-AyeWatch-Signature", "")):
        return "", 401
    update = json.loads(raw)
    try:
        with psycopg.connect(DSN) as conn:  # commits on success, rolls back on error
            claimed = conn.execute(
                CLAIM + " RETURNING update_id",
                (update["update_id"], update["topic_id"], raw.decode("utf-8")),
            ).fetchone()
            if claimed:
                create_ticket(update)  # keep this well under 10 seconds
    except Exception:
        app.logger.exception("delivery %s failed", update["update_id"])
        return "", 500
    return "", 200

A database rollback can't undo a call to another system. If create_ticket posts to an outside API, pass update_id as that API's idempotency key too, where it has one.

The same claim in Redis

// claim.mjs: node-redis 4 or later. npm install redis
import { createClient } from "redis";

const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

const TTL_SECONDS = 14 * 24 * 3600;

export async function claim(updateId) {
  const result = await redis.set("ayewatch:update:" + updateId, "1", { NX: true, EX: TTL_SECONDS });
  return result === "OK";
}

export async function release(updateId) {
  await redis.del("ayewatch:update:" + updateId);
}

SET with NX writes the key only if it is new and returns "OK"; a repeat gets null. In the route, after the signature check: if claim() is false, answer 200 and stop. If your work then fails, call release() and answer 500 so the retry can claim it again. Keep keys for at least 14 days; each costs a few bytes.

What dedupe won't fix

  • Redirects. A 3xx answer is not followed and not retried, so the delivery fails at once. Register the final HTTPS URL.
  • Deliveries that fail every attempt. They are not sent again, and the API has no endpoint for past alerts. The alert still shows in the app's feed, so check it after an outage.
  • Different alerts about the same story. Two checks can each find something new about one event. They have different update_ids by design; dedupe on evidence[].source_url as well if you want one row per link.

AyeWatch Pro is $9/mo with 50 topics and hourly checks; Pro+ is $19/mo with 200 topics and ASAP mode. Every plan starts with a 7-day free trial. Deliveries don't use credits; checks do.

Make a receiver idempotent

  1. Create the ayewatch_deliveries table with update_id as the primary key.
  2. Verify the signature, then insert with ON CONFLICT DO NOTHING before any other work.
  3. Answer 200 for new and repeated deliveries alike, and 500 only when you want a retry.
  4. Move slow work to a worker that reads unprocessed rows with FOR UPDATE SKIP LOCKED.
  5. Sort by created_at wherever order matters, since deliveries can arrive out of order.
  6. Check the app's feed after any outage longer than the retries.
StoreSurvives restartsShared by instancesBest for
In-memory SetNoNoLocal testing
Postgres primary keyYesYesReceivers that keep every alert
Redis SET NX with expiryYes, with persistence onYesFast claims when the data lives elsewhere

Start a monitor in under a minute

Describe a topic or paste a URL. Cancel before the trial ends and you pay nothing.

Try it free for 7 days

The bottom line

Add the table and the ON CONFLICT insert before anything else in your receiver. Once claims are in place, retries stop being a risk and become the reason you don't lose alerts.

FAQ

What is webhook idempotency?

It means processing the same delivery twice has the same effect as processing it once. Receivers get there by recording each delivery's ID and skipping IDs they have seen.

Which field should I dedupe AyeWatch webhooks on?

update_id. Every retry of a delivery carries the same update_id, and different alerts carry different ones.

Should a duplicate delivery get a 200 or an error?

A 200. An error asks AyeWatch to retry, which only sends the duplicate again.

How long should I keep webhook IDs?

At least 14 days if they expire, as in Redis. In Postgres, keep the row with the alert and you never need to expire it.

Are AyeWatch webhooks delivered in order?

Not guaranteed. Retries and backoff can reorder them, so sort by created_at when order matters.

What happens if my server is down for a day?

AyeWatch retries with backoff, up to 10 attempts. Deliveries that fail every attempt aren't sent again, but the alerts remain in the app's feed.

webhook idempotency dedupe retrieswebhook idempotency keydedupe webhook retries postgresredis set nx webhookidempotent webhook receiver

Related articles