Idempotent webhook handlers
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.
Idempotent handler example
Section titled “Idempotent handler example”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 },});pq.create_task( "orders", task_id="fulfil-order-1234", path="/hooks/fulfil-order", json_body={"order_id": 1234},)_, err := pq.CreateTask(ctx, "orders", pushq.TaskCreate{ TaskID: "fulfil-order-1234", Path: "/hooks/fulfil-order", JSONBody: map[string]any{"order_id": 1234},})pq.createTask("orders", TaskCreate.builder() .taskId("fulfil-order-1234") .path("/hooks/fulfil-order") .jsonBody(Map.of("order_id", 1234)) .build());await pq.CreateTaskAsync("orders", new TaskCreate{ TaskId = "fulfil-order-1234", Path = "/hooks/fulfil-order", JsonBody = new { order_id = 1234 },});curl -X POST https://api.pushqueue.dev/v1/queues/orders/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{"task_id":"fulfil-order-1234","path":"/hooks/fulfil-order","json_body":{"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});import jsonimport os
import psycopgfrom fastapi import FastAPI, HTTPException, Request, Responsefrom pushq import WebhookVerificationError, verify_signature
app = FastAPI()SECRET = os.environ["PUSHQ_SIGNING_SECRET"]
@app.post("/hooks/fulfil-order")async def fulfil_order(request: Request): body = await request.body() # raw bytes try: # "orders/fulfil-order-1234": the same on every retry of this task delivery_id = verify_signature(SECRET, request.headers, body) except WebhookVerificationError: raise HTTPException(status_code=401) order_id = json.loads(body)["order_id"]
async with await psycopg.AsyncConnection.connect(os.environ["DATABASE_URL"]) as conn: async with conn.transaction(): claim = await conn.execute( "INSERT INTO processed_tasks (id) VALUES (%s) ON CONFLICT DO NOTHING", (delivery_id,), ) if claim.rowcount == 1: # First delivery: do the work in the same transaction. await conn.execute( "UPDATE orders SET status = 'fulfilled' WHERE id = %s", (order_id,) ) # An exception above rolls back and returns 500, so pushq retries. return Response(status_code=204) # also for duplicates: the work is donefunc fulfilOrder(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(r.Body) if err != nil { http.Error(w, "read error", http.StatusBadRequest) return } // "orders/fulfil-order-1234": the same on every retry of this task deliveryID, err := pushq.VerifySignature(secret, r.Header, body, 5*time.Minute) if err != nil { http.Error(w, "invalid signature", http.StatusUnauthorized) return } var p struct { OrderID int64 `json:"order_id"` } if err := json.Unmarshal(body, &p); err != nil { http.Error(w, "bad payload", http.StatusBadRequest) // retried: see /docs/patterns/stop-retrying/ return }
ctx := r.Context() tx, err := db.BeginTx(ctx, nil) if err != nil { http.Error(w, "db error", http.StatusInternalServerError) return } defer tx.Rollback()
res, err := tx.ExecContext(ctx, `INSERT INTO processed_tasks (id) VALUES ($1) ON CONFLICT DO NOTHING`, deliveryID) if err != nil { http.Error(w, "db error", http.StatusInternalServerError) // pushq retries return } if n, _ := res.RowsAffected(); n == 1 { // First delivery: do the work in the same transaction. if _, err := tx.ExecContext(ctx, `UPDATE orders SET status = 'fulfilled' WHERE id = $1`, p.OrderID); err != nil { http.Error(w, "db error", http.StatusInternalServerError) return } } if err := tx.Commit(); err != nil { http.Error(w, "db error", http.StatusInternalServerError) return } w.WriteHeader(http.StatusNoContent) // also for duplicates: the work is done}@RestControllerpublic class FulfilOrderHook { private final String secret = System.getenv("PUSHQ_SIGNING_SECRET"); private final ObjectMapper json = new ObjectMapper(); private final JdbcTemplate jdbc; private final TransactionTemplate tx;
public FulfilOrderHook(JdbcTemplate jdbc, TransactionTemplate tx) { this.jdbc = jdbc; this.tx = tx; }
@PostMapping("/hooks/fulfil-order") public ResponseEntity<Void> fulfil(@RequestBody byte[] payload, @RequestHeader("webhook-id") String deliveryId, @RequestHeader("webhook-timestamp") long ts, @RequestHeader("webhook-signature") String sig) throws IOException { try { // deliveryId is "orders/fulfil-order-1234": the same on every retry Webhooks.verifySignature(secret, deliveryId, ts, payload, sig, 300); } catch (WebhookVerificationException e) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } long orderId = json.readTree(payload).get("order_id").asLong();
// An exception rolls back and returns 500, so pushq retries. tx.executeWithoutResult(status -> { int claimed = jdbc.update( "INSERT INTO processed_tasks (id) VALUES (?) ON CONFLICT DO NOTHING", deliveryId); if (claimed == 1) { // First delivery: do the work in the same transaction. jdbc.update("UPDATE orders SET status = 'fulfilled' WHERE id = ?", orderId); } }); return ResponseEntity.noContent().build(); // also for duplicates }}app.MapPost("/hooks/fulfil-order", async (HttpRequest req, NpgsqlDataSource db) =>{ using var ms = new MemoryStream(); await req.Body.CopyToAsync(ms); var body = ms.ToArray();
string deliveryId; try { // "orders/fulfil-order-1234": the same on every retry of this task deliveryId = Webhooks.VerifySignature(signingSecret, name => req.Headers[name].FirstOrDefault(), body); } catch (WebhookVerificationException) { return Results.Unauthorized(); } var orderId = JsonDocument.Parse(body).RootElement.GetProperty("order_id").GetInt64();
// An exception rolls back and returns 500, so pushq retries. await using var conn = await db.OpenConnectionAsync(); await using var tx = await conn.BeginTransactionAsync();
await using var claim = new NpgsqlCommand( "INSERT INTO processed_tasks (id) VALUES ($1) ON CONFLICT DO NOTHING", conn, tx); claim.Parameters.AddWithValue(deliveryId); if (await claim.ExecuteNonQueryAsync() == 1) { // First delivery: do the work in the same transaction. await using var update = new NpgsqlCommand( "UPDATE orders SET status = 'fulfilled' WHERE id = $1", conn, tx); update.Parameters.AddWithValue(orderId); await update.ExecuteNonQueryAsync(); } await tx.CommitAsync(); return Results.NoContent(); // 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 thewebhook-idheader afterverifySignaturepasses). - 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-QueueandX-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
2xxresponse and retries on anything else, so a duplicate must also get a2xx. 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.
When duplicate deliveries happen
Section titled “When duplicate deliveries happen”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.
Idempotency for external side effects
Section titled “Idempotency for external side effects”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.
Pitfalls
Section titled “Pitfalls”- 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-idis different. The original queue and task ID are in theX-Pushq-Deadletter-Source-QueueandX-Pushq-Deadletter-Task-Idheaders; 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.