Skip to content
Docs

Recipes

Process each event once

Use the event id and confirmed flag as a unique key so retries never double-process.

Overview

Retries mean a message can arrive more than once. The pair of id and confirmed is unique for each message, so use it as a key.

Table

sql
CREATE TABLE gray3_events (
  event_id   text        NOT NULL,
  confirmed  boolean     NOT NULL,
  body       jsonb       NOT NULL,
  received_at timestamptz NOT NULL DEFAULT now(),
  processed_at timestamptz,
  PRIMARY KEY (event_id, confirmed)
);

Insert once

javascript
async function saveEventOnce(event) {
  const { rowCount } = await pg.query(
    `INSERT INTO gray3_events (event_id, confirmed, body)
     VALUES ($1, $2, $3)
     ON CONFLICT DO NOTHING`,
    [event.id, event.confirmed, event],
  );
  return rowCount === 1; // false = already received, skip it
}

Save the event in the request handler, reply 2xx, then process rows where processed_at is empty in a background worker. If the worker crashes, the row is still there to pick up again.

Out-of-order messages

A confirmed message can arrive before its unconfirmed one if the first try of the unconfirmed one failed. When the confirmed row exists, skip the unconfirmed one.