# Delivery and webhook signatures

> The HTTP request pushq sends to your endpoint: X-Pushq headers, success and timeouts, at-least-once delivery, idempotency and webhook signature checks.

Source: https://pushqueue.dev/docs/concepts/delivery/

Delivering a task means making one HTTP request to your endpoint. This page describes the request pushq sends and its headers, what your endpoint has to return, at-least-once delivery and idempotency keys, and webhook signature verification so you know a request really came from pushq.

## The HTTP request pushq sends

### Target URL resolution

- A task created with `url` is sent to that URL.
- A task created with `path` is sent to the queue's `target.base_url` with the path appended, at the moment of delivery. A trailing `/` on `base_url` is dropped, so `https://api.example.com/` + `/hooks/send` becomes `https://api.example.com/hooks/send`. A `base_url` with a path works as a prefix: `https://api.example.com/v2` + `/hooks/send` becomes `https://api.example.com/v2/hooks/send`.

### HTTP method

The task's `method` (default `POST`), unless the queue sets `target.method`, which overrides it for every task. If the resulting method is `GET`, `HEAD`, `DELETE` or `OPTIONS`, no body is sent.

### Request body and Content-Type

The task's body exactly as stored: the serialized `json_body`, or the decoded bytes of `body_base64`. `Content-Type` is `application/json` for `json_body` tasks (unless you set your own), whatever you set in the task or queue headers, or `application/octet-stream` for a raw body with no `Content-Type`.

### X-Pushq headers

Every delivery carries these headers:

| Header | Example | Meaning |
|---|---|---|
| `X-Pushq-Queue` | `user/instagram` | Queue name, including folders. |
| `X-Pushq-Task-Id` | `welcome-user-42` | Task ID. |
| `X-Pushq-Attempt` | `1` | Which attempt this is, starting at 1. Counts every attempt, including ones that got no response. |
| `X-Pushq-Execution-Count` | `0` | How many earlier attempts got an HTTP response (any status). `0` on the first attempt. |
| `X-Pushq-Scheduled-Time` | `2026-11-28T10:00:00Z` | The time this attempt was scheduled for (the task's schedule time, or the retry time), in UTC. |
| `User-Agent` | `pushq/1.2.3` | pushq and its version. |

When the queue has a [signing secret](#webhook-signing), three more are added: `webhook-id`, `webhook-timestamp` and `webhook-signature`.

Your own headers are merged in this order, with later ones winning (names are case-insensitive):

1. The task's `headers`.
2. The queue's `target.headers`.
3. pushq's headers above (`User-Agent`, `X-Pushq-*`, `webhook-*`). These can't be overridden.

A delivery looks like this:

```http
POST /hooks/send-welcome HTTP/1.1
Host: api.example.com
User-Agent: pushq/1.2.3
Content-Type: application/json
X-Pushq-Queue: emails
X-Pushq-Task-Id: welcome-user-42
X-Pushq-Attempt: 2
X-Pushq-Execution-Count: 1
X-Pushq-Scheduled-Time: 2026-11-28T10:00:01.2Z
webhook-id: emails/welcome-user-42
webhook-timestamp: 1764324001
webhook-signature: v1,N3JUvzf91hHCiXb5bhN9twIeDfIkfeYWvh/VeI+TSH0=

{"user_id":42}
```

## Respond with 2xx to acknowledge a task

- **Any 2xx** marks the task `succeeded`. The response body is ignored.
- **Anything else** is a failed attempt and is [retried](https://pushqueue.dev/docs/concepts/retries/): non-2xx statuses (including every 4xx), no response within the task's `dispatch_deadline_seconds` (default 600, range 15 to 1800), and connection, DNS or TLS errors. Redirects are followed and count as one attempt.
- **429 or 503 with `Retry-After`** also tells pushq to back off: the task waits for the given delay and the queue pauses new deliveries for up to 30 seconds. See [Retry-After](https://pushqueue.dev/docs/concepts/retries/#retry-after-and-the-queue-cool-down).

For failed attempts, pushq records the start of the response body (up to 4 KiB) in the task's [attempt log](https://pushqueue.dev/docs/concepts/tasks/#delivery-attempts-history), so returning a short error message helps debugging.

If your handler runs longer than the deadline, pushq counts a timeout and retries while the first run may still be going. Either raise `dispatch_deadline_seconds`, or accept the task quickly and do slow work elsewhere; see [long-running work](https://pushqueue.dev/docs/patterns/long-running-work/).

## At-least-once delivery and idempotency keys

pushq delivers every task **at least once**, not exactly once. Your endpoint can receive the same task more than once, for example when:

- it did the work but the response was lost or arrived after the deadline, so pushq retried;
- the pushq server restarted while a request was in flight, so the outcome was never recorded and the task was retried;
- the task was purged or deleted while its request was already on the way.

Make handlers idempotent. The pair of `X-Pushq-Queue` and `X-Pushq-Task-Id` (or `webhook-id`, which is `<queue>/<task_id>`) is the same on every attempt of a task, so use it as an idempotency key: record it when you finish the work and skip requests you have already handled. The [idempotent handlers pattern](https://pushqueue.dev/docs/patterns/idempotent-handlers/) shows how in each language.

## Webhook signing

Set a signing secret on the queue and every delivery is signed with HMAC-SHA256 using the [Standard Webhooks](https://www.standardwebhooks.com) format. Your endpoint verifies the signature to be sure the request came from pushq and wasn't modified.

### Set a signing secret

Generate a secret of the form `whsec_` followed by base64-encoded random bytes:

```bash
echo "whsec_$(openssl rand -base64 32)"
```

Then set it on the queue:


**TypeScript**

```ts
await pq.patchQueue("emails", { target: { signingSecret: process.env.PUSHQ_SIGNING_SECRET } });
```

**Python**

```python
from pushq import Target

pq.patch_queue("emails", target=Target(signing_secret=os.environ["PUSHQ_SIGNING_SECRET"]))
```

**Go**

```go
_, err := pq.PatchQueue(ctx, "emails", pushq.QueueConfig{
	Target: &pushq.Target{SigningSecret: os.Getenv("PUSHQ_SIGNING_SECRET")},
}, "")
```

**Java**

```java
pq.patchQueue("emails", QueuePatch.builder()
    .target(Target.builder().signingSecret(System.getenv("PUSHQ_SIGNING_SECRET")).build())
    .build());
```

**.NET**

```csharp
await pq.PatchQueueAsync("emails", new QueuePatch
{
    Target = new Target { SigningSecret = Environment.GetEnvironmentVariable("PUSHQ_SIGNING_SECRET") },
});
```

**curl**

```bash
curl -X PATCH https://api.pushqueue.dev/v1/queues/emails \
  -H "Authorization: Bearer $PUSHQ_API_KEY" \
  -d "{\"target\": {\"signing_secret\": \"$PUSHQ_SIGNING_SECRET\"}}"
```

The secret is never returned by the API; queue responses show `"has_signing_secret": true`. A PUT that omits `signing_secret` keeps the stored one. Send `""` to remove it (in Go, set `ClearSigningSecret: true`).

A secret that doesn't start with `whsec_` is also accepted and used as raw bytes, but `whsec_` secrets work with every Standard Webhooks library.

The new secret applies from the next delivery, including tasks already queued. pushq signs with one secret at a time, so to rotate without rejecting requests, have your endpoint accept both the old and the new secret for a few minutes, then switch the queue, then drop the old one.

### How the signature is computed

Signed deliveries carry three headers:

| Header | Value |
|---|---|
| `webhook-id` | `<queue>/<task_id>`, for example `emails/welcome-user-42`. The same on every attempt. |
| `webhook-timestamp` | Unix time in seconds when this attempt was sent. New on every attempt. |
| `webhook-signature` | `v1,` followed by the base64 HMAC-SHA256 signature. |

The signature is computed as:

```text
key       = base64-decode(secret without the "whsec_" prefix)
content   = webhook-id + "." + webhook-timestamp + "." + raw request body
signature = base64(HMAC-SHA256(key, content))
header    = "v1," + signature
```

The body is the exact bytes sent; for methods that send no body, it is empty.

### Verify webhook signatures in your handler

Every SDK includes a verification helper. Pass it the secret, the request headers and the **raw** request body, exactly as received; a body that has been parsed and re-serialized won't match. On success it returns (or, in Java, accepts) the webhook ID; on failure it throws or returns an error, and you should answer `401`.


**TypeScript**

```ts

const app = express();

// express.raw keeps the body unparsed; don't use express.json() on this route.
app.post("/hooks/send-welcome", express.raw({ type: "*/*" }), async (req, res) => {
  let webhookId: string;
  try {
    webhookId = 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 { user_id } = JSON.parse(req.body.toString("utf8"));
  // ... do the work, using webhookId as an idempotency key ...
  res.sendStatus(204);
});
```

**Python**

```python
import os
from fastapi import FastAPI, HTTPException, Request
from pushq import WebhookVerificationError, verify_signature

SECRET = os.environ["PUSHQ_SIGNING_SECRET"]
app = FastAPI()

@app.post("/hooks/send-welcome")
async def send_welcome(request: Request):
    body = await request.body()  # raw bytes, not parsed JSON
    try:
        webhook_id = verify_signature(SECRET, request.headers, body)
    except WebhookVerificationError:
        raise HTTPException(status_code=401)
    # ... do the work, using webhook_id as an idempotency key ...
    return {"ok": True}
```

**Go**

```go
var secret = os.Getenv("PUSHQ_SIGNING_SECRET")

func handleSendWelcome(w http.ResponseWriter, r *http.Request) {
	body, err := io.ReadAll(r.Body) // raw bytes, before any JSON decoding
	if err != nil {
		http.Error(w, "read error", http.StatusBadRequest)
		return
	}
	webhookID, err := pushq.VerifySignature(secret, r.Header, body, 5*time.Minute)
	if err != nil {
		http.Error(w, "invalid signature", http.StatusUnauthorized)
		return
	}
	_ = webhookID // use as an idempotency key
	// ... json.Unmarshal(body, &payload) and do the work ...
	w.WriteHeader(http.StatusNoContent)
}
```

**Java**

```java
@RestController
public class PushqHooks {
    private final String secret = System.getenv("PUSHQ_SIGNING_SECRET");

    @PostMapping("/hooks/send-welcome")
    public ResponseEntity<Void> sendWelcome(@RequestBody byte[] payload,   // raw body, unparsed
                                            @RequestHeader("webhook-id") String id,
                                            @RequestHeader("webhook-timestamp") long ts,
                                            @RequestHeader("webhook-signature") String sig) {
        try {
            Webhooks.verifySignature(secret, id, ts, payload, sig, 300);
        } catch (WebhookVerificationException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        // ... parse payload and do the work, using id as an idempotency key ...
        return ResponseEntity.noContent().build();
    }
}
```

**.NET**

```csharp
var secret = Environment.GetEnvironmentVariable("PUSHQ_SIGNING_SECRET")!;

app.MapPost("/hooks/send-welcome", async (HttpRequest req) =>
{
    using var ms = new MemoryStream();
    await req.Body.CopyToAsync(ms);
    var body = ms.ToArray(); // raw bytes, not model-bound
    try
    {
        string webhookId = Webhooks.VerifySignature(secret, name => req.Headers[name].FirstOrDefault(), body);
        // ... deserialize body and do the work, using webhookId as an idempotency key ...
        return Results.NoContent();
    }
    catch (WebhookVerificationException)
    {
        return Results.Unauthorized();
    }
});
```

Verification happens in your endpoint, so there is no curl version; to check a signature from the shell, see [verify a signature manually](#verify-a-signature-manually).

The helpers compare signatures in constant time, accept any `v1` entry in a space-separated `webhook-signature` list, and reject timestamps too far from the current time to block replayed requests. The tolerance defaults to 5 minutes in TypeScript (`toleranceSeconds`), Python (`tolerance_seconds`) and .NET (`tolerance`); Go and Java take it as a required argument. A tolerance of 0 disables the check in TypeScript, Python, .NET and Go. Keep your server's clock in sync (NTP) so valid requests aren't rejected.

Any Standard Webhooks library also verifies pushq deliveries, since the format is the same.

### Verify a signature manually

To check a signature by hand, recompute it from the headers and the raw body. This shell example uses `openssl`:

```bash
SECRET="whsec_..."                       # the queue's signing secret
ID="emails/welcome-user-42"              # webhook-id header
TS="1764324001"                          # webhook-timestamp header
BODY='{"user_id":42}'                    # raw request body

KEY_HEX=$(printf '%s' "${SECRET#whsec_}" | base64 -d | xxd -p -c 256)
printf '%s.%s.%s' "$ID" "$TS" "$BODY" \
  | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$KEY_HEX" -binary | base64
```

The output must equal the part after `v1,` in `webhook-signature`. In your own code, also compare in constant time and check that `webhook-timestamp` is within a few minutes of the current time.

## Static header authentication

If your endpoint already checks a shared secret or bearer token, put it in the queue's `target.headers` and pushq sends it with every delivery:


**TypeScript**

```ts
await pq.patchQueue("emails", {
  target: { headers: { Authorization: `Bearer ${process.env.INTERNAL_TOKEN}` } },
});
```

**Python**

```python
pq.patch_queue("emails", target=Target(headers={"Authorization": f"Bearer {os.environ['INTERNAL_TOKEN']}"}))
```

**Go**

```go
_, err := pq.PatchQueue(ctx, "emails", pushq.QueueConfig{
	Target: &pushq.Target{Headers: map[string]string{"Authorization": "Bearer " + os.Getenv("INTERNAL_TOKEN")}},
}, "")
```

**Java**

```java
pq.patchQueue("emails", QueuePatch.builder()
    .target(Target.builder().header("Authorization", "Bearer " + System.getenv("INTERNAL_TOKEN")).build())
    .build());
```

**.NET**

```csharp
await pq.PatchQueueAsync("emails", new QueuePatch
{
    Target = new Target
    {
        Headers = new Dictionary<string, string> { ["Authorization"] = "Bearer " + Environment.GetEnvironmentVariable("INTERNAL_TOKEN") },
    },
});
```

**curl**

```bash
curl -X PATCH https://api.pushqueue.dev/v1/queues/emails \
  -H "Authorization: Bearer $PUSHQ_API_KEY" \
  -d "{\"target\": {\"headers\": {\"Authorization\": \"Bearer $INTERNAL_TOKEN\"}}}"
```

A PATCH that sends `target.headers` replaces the queue's whole header map. Queue headers override task headers with the same name.

:::caution
Unlike the signing secret, queue headers are returned in queue responses, so anyone who can read the queue (including viewer-role users and writer keys) can see the token. Prefer signing where you can; static headers suit endpoints you can't change, such as an internal service that already expects an API key.
:::

You can combine both: send a static header for an existing gateway and verify the signature in your handler.

## Read more

- [Idempotent handlers](https://pushqueue.dev/docs/patterns/idempotent-handlers/): handle duplicate deliveries safely.
- [Long-running work](https://pushqueue.dev/docs/patterns/long-running-work/): handlers that take longer than the dispatch deadline.
- [Retry backoff and max attempts](https://pushqueue.dev/docs/concepts/retries/): what happens after a failed delivery.
- [Going to production](https://pushqueue.dev/docs/guides/going-to-production/): signing, monitoring and limits checklist.
