Skip to content
pushqdocs
Get started

pushq delivers every task at least once, so the same task can reach your endpoint more than once. An idempotent webhook handler records which tasks it has already processed and does the work only the first time, using the task’s webhook-id (or X-Pushq-Queue + X-Pushq-Task-Id) as the idempotency key.

Enqueue the task as usual. Give it a task ID when you have a natural one; the handler works with server-generated IDs too.

await pq.createTask("orders", {
taskId: "fulfil-order-1234",
path: "/hooks/fulfil-order",
jsonBody: { order_id: 1234 },
});

The handler verifies the webhook signature, then claims the webhook-id and applies the change in one database transaction. A primary key on the processed-tasks table makes the claim atomic, so two concurrent deliveries of the same task can’t both do the work.

CREATE TABLE processed_tasks (
id text PRIMARY KEY, -- webhook-id: "<queue>/<task_id>"
processed_at timestamptz NOT NULL DEFAULT now()
);
import express from "express";
import pg from "pg";
import { verifySignature, WebhookVerificationError } from "pushq";
const app = express();
const db = new pg.Pool();
app.post("/hooks/fulfil-order", express.raw({ type: "*/*" }), async (req, res) => {
let deliveryId: string;
try {
// "orders/fulfil-order-1234": the same on every retry of this task
deliveryId = await verifySignature({
secret: process.env.PUSHQ_SIGNING_SECRET!,
headers: req.headers,
payload: req.body,
});
} catch (err) {
if (err instanceof WebhookVerificationError) return res.sendStatus(401);
throw err;
}
const { order_id } = JSON.parse(req.body.toString("utf8"));
const client = await db.connect();
try {
await client.query("BEGIN");
const claim = await client.query(
"INSERT INTO processed_tasks (id) VALUES ($1) ON CONFLICT DO NOTHING",
[deliveryId],
);
if (claim.rowCount === 1) {
// First delivery: do the work in the same transaction.
await client.query("UPDATE orders SET status = 'fulfilled' WHERE id = $1", [order_id]);
}
await client.query("COMMIT");
} catch (err) {
await client.query("ROLLBACK");
console.error(err);
return res.sendStatus(500); // pushq retries
} finally {
client.release();
}
res.sendStatus(204); // also for duplicates: the work is done
});

Use this when a task changes state you own (a database row, a balance, an order status) and running it twice would be wrong.

Why the webhook-id works as an idempotency key

Section titled “Why the webhook-id works as an idempotency key”
  • It is stable across retries. When the queue has a signing secret, pushq sends webhook-id: <queue>/<task_id> on every attempt of a task. Every SDK’s verify function returns it after checking the signature (in Java, read the webhook-id header after verifySignature passes).
  • It is unique per task. Task IDs are unique within a queue, and the queue name is part of the key, so the same task ID in two queues gives two different keys.
  • Without signing, build the same key yourself. Every delivery carries X-Pushq-Queue and X-Pushq-Task-Id; join them with / to get the identical string. Only trust these headers on a request you have authenticated (with a signature or a static auth header), since anyone can send them.
  • Success is any 2xx. pushq marks the task succeeded on any 2xx response and retries on anything else, so a duplicate must also get a 2xx. Returning an error for “already processed” makes pushq retry a task that is already done.

X-Pushq-Attempt tells you which attempt this is (starting at 1). It is useful in logs, but don’t use X-Pushq-Attempt > 1 as your duplicate check: attempt 2 can arrive while attempt 1 is still running.

pushq retries a task whenever it doesn’t see a 2xx, even if your handler already did the work. In practice that means:

  • The response is lost. Your handler committed, then the connection dropped, a proxy returned 502, or your process crashed before responding.
  • The dispatch deadline passes. pushq gives up on the request after dispatch_deadline_seconds (default 600) and schedules a retry, but your handler may still be running. The retry can then run at the same time as the first attempt. See long-running tasks.
  • The dispatcher stops mid-request. If a pushq server is restarted or crashes during a delivery, the attempt is counted as failed (lease_lost, or aborted after the shutdown drain timeout on self-hosted servers) and the task is retried, although your endpoint may have received the first request.
  • Your handler returns non-2xx after a partial side effect, for example it sent the email and then failed to write to its database.

Each of these delivers the same task again, with the same webhook-id. A second task created for the same work (for example, a client retrying an enqueue call without a task_id) is a different task with a different key; prevent that on the enqueue side with task deduplication.

The transaction pattern works when the work and the processed-IDs table live in the same database. For side effects outside it (sending an email, charging a card, calling another API):

  • Pass the key downstream. Many APIs accept an idempotency key header. Send the webhook-id (or a value derived from it) so the provider drops the duplicate for you.
  • Record progress per step. Store a status per key (started, email_sent, done) and skip steps that are already recorded. A crash between the side effect and the record can still repeat that one step, so keep steps small.
  • Split the work into separate tasks, one side effect each, so a retry repeats only the step that failed. See chaining steps.
  • Don’t record the key before the work commits. If you insert the key in its own transaction and then the work fails, the retry sees the key and skips work that never happened.
  • Dead-lettered copies have new IDs. When retries run out and the queue has a dead-letter queue, pushq copies the task into it with a new, server-generated ID, so its webhook-id is different. The original queue and task ID are in the X-Pushq-Deadletter-Source-Queue and X-Pushq-Deadletter-Task-Id headers; use those if the dead-letter handler must recognise work that was already done.
  • Task IDs are reusable later. pushq frees a task ID after the task’s record is cleaned up (24 hours after success and 7 days after failure on self-hosted defaults). If you deliberately reuse an ID for new work after that, your processed-tasks table will treat it as a duplicate. Include something that changes per piece of work in the ID (a date, a version), or expire old keys.
  • Keep keys at least as long as a task can retry. With the default retry settings (100 attempts, backoff up to an hour) a task can retry for days. Don’t delete processed keys while their task can still be delivered.