# Production checklist for pushq

> A pushq production checklist for API keys, webhook signature verification, idempotent handlers, rate limits, retries, dead-letter queues and monitoring.

Source: https://pushqueue.dev/docs/guides/going-to-production/

This production checklist lists what to set up before real traffic goes through pushq, whether you use the hosted API or run your own server. Each item is one or two lines with a link to the page that has the details. The self-hosting items are at the end.

Most of the app-side work fits in a few lines: one shared client with its API key read from the environment and a timeout set, plus a deterministic `task_id` so that a retried enqueue can't create a duplicate.


**TypeScript**

```ts

// Create one client at startup and reuse it.
export const pq = new Pushq({ apiKey: process.env.PUSHQ_API_KEY, timeoutMs: 10_000 });

export async function enqueueWelcome(userId: number) {
  try {
    await pq.createTask("emails", {
      taskId: `welcome-user-${userId}`,
      path: "/hooks/send-welcome",
      jsonBody: { userId },
    });
  } catch (err) {
    if (err instanceof PushqError && err.code === "already_exists") return; // already enqueued
    throw err;
  }
}
```

**Python**

```python
import os
from pushq import Pushq, PushqError

# Create one client at startup and reuse it.
pq = Pushq(api_key=os.environ["PUSHQ_API_KEY"], timeout=10.0)

def enqueue_welcome(user_id: int) -> None:
    try:
        pq.create_task(
            "emails",
            task_id=f"welcome-user-{user_id}",
            path="/hooks/send-welcome",
            json_body={"user_id": user_id},
        )
    except PushqError as e:
        if e.code != "already_exists":  # already_exists = already enqueued
            raise
```

**Go**

```go
// Create one client at startup and share it across goroutines.
var pq = pushq.New("", os.Getenv("PUSHQ_API_KEY"),
	pushq.WithHTTPClient(&http.Client{Timeout: 10 * time.Second}))

func enqueueWelcome(ctx context.Context, userID int) error {
	_, err := pq.CreateTask(ctx, "emails", pushq.TaskCreate{
		TaskID:   fmt.Sprintf("welcome-user-%d", userID),
		Path:     "/hooks/send-welcome",
		JSONBody: map[string]any{"user_id": userID},
	})
	if pushq.IsCode(err, "already_exists") {
		return nil // already enqueued
	}
	return err
}
```

**Java**

```java
// Build one client at startup and share it (thread-safe).
static final Pushq pq = Pushq.builder()
    .apiKey(System.getenv("PUSHQ_API_KEY"))
    .timeout(Duration.ofSeconds(10))
    .build();

static void enqueueWelcome(long userId) {
    try {
        pq.createTask("emails", TaskCreate.builder()
            .taskId("welcome-user-" + userId)
            .path("/hooks/send-welcome")
            .jsonBody(Map.of("user_id", userId))
            .build());
    } catch (PushqException e) {
        if (!"already_exists".equals(e.getCode())) throw e; // already_exists = already enqueued
    }
}
```

**.NET**

```csharp
// Create one client for the app's lifetime (thread-safe).
var pq = new PushqClient(new PushqClientOptions
{
    ApiKey = Environment.GetEnvironmentVariable("PUSHQ_API_KEY"),
    Timeout = TimeSpan.FromSeconds(10),
});

async Task EnqueueWelcomeAsync(long userId)
{
    try
    {
        await pq.CreateTaskAsync("emails", new TaskCreate
        {
            TaskId = $"welcome-user-{userId}",
            Path = "/hooks/send-welcome",
            JsonBody = new { user_id = userId },
        });
    }
    catch (PushqException e) when (e.Code == "already_exists")
    {
        // Already enqueued: treat as success.
    }
}
```

**curl**

```bash
# 201 = created; 409 with "code": "already_exists" = already enqueued. Both mean success.
curl -sS --max-time 10 -X POST https://api.pushqueue.dev/v1/queues/emails/tasks \
  -H "Authorization: Bearer $PUSHQ_API_KEY" \
  -d '{"task_id": "welcome-user-42", "path": "/hooks/send-welcome", "json_body": {"user_id": 42}}'
```

Field names on this page are the JSON names (`rate_limits.max_dispatches_per_second`). The SDKs use their language's casing: camelCase in TypeScript and Java, snake_case in Python, PascalCase in Go and .NET.

## Store and scope API keys

### Keep API keys in environment variables

Load the key from an environment variable such as `PUSHQ_API_KEY`, set by your secret manager or deployment platform, and keep it out of source control. The SDKs don't read environment variables themselves, so pass the key explicitly. Never ship a key to a browser or mobile app. See [store keys safely](https://pushqueue.dev/docs/guides/api-keys/#store-keys-safely).

### Use writer keys in app code, admin keys for tooling

A writer key can enqueue tasks and manage queues it knows by name, but can't list or delete queues or manage keys. That is all most services need. Keep admin keys for people and ops tooling, and give each service and environment its own key. See [API key roles](https://pushqueue.dev/docs/guides/api-keys/#key-roles).

### Rotate API keys without downtime

pushq accepts any number of keys at once: create the new key, deploy it, wait until the old key's `last_used_at` stops moving, then revoke the old one. See [rotate a key with zero downtime](https://pushqueue.dev/docs/guides/api-keys/#rotate-a-key-with-zero-downtime).

## Secure webhook deliveries

### Sign every delivery with a signing secret

Set `target.signing_secret` on each queue so every delivery carries Standard Webhooks `webhook-id`, `webhook-timestamp` and `webhook-signature` headers. Generate a fresh secret per environment, for example `echo "whsec_$(openssl rand -base64 32)"`. See [the target settings](https://pushqueue.dev/docs/concepts/queues/#target-settings-base-url-method-headers-and-signing-secret).

:::caution
The server doesn't check that a `whsec_` secret is valid base64 when you save it. If it isn't, every delivery fails with `error_kind: config` and keeps retrying. Generate the secret with a tool like the command above rather than typing it.
:::

### Verify webhook signatures on the raw body

Reject any request whose signature doesn't verify, and verify the body exactly as received, before any JSON parsing. A framework that parses and re-serializes the body breaks verification. Every SDK ships a verifier; see [verify signatures](https://pushqueue.dev/docs/getting-started/sdks/#verify-signatures).

### Make handlers idempotent

Delivery is at least once: a timeout, a crash or a lost lease can deliver the same task again. Use the `webhook-id` header (`<queue>/<task_id>`, stable across retries) or `X-Pushq-Task-Id` as an idempotency key. See [idempotent handlers](https://pushqueue.dev/docs/patterns/idempotent-handlers/) and [delivery guarantees](https://pushqueue.dev/docs/concepts/delivery/).

### Return 2xx when a task can never succeed

pushq retries every non-2xx response, including `400` and `404`. If your handler knows a task is permanently bad, record the problem and return a 2xx to stop the retries. See [what counts as a failure](https://pushqueue.dev/docs/concepts/retries/#what-counts-as-a-failed-delivery) and [stop retrying a task](https://pushqueue.dev/docs/patterns/stop-retrying/).

## Enqueue tasks safely

### Deduplicate with a task ID and treat already_exists as success

Build `task_id` from your own record ID. A second create with the same ID returns `409 already_exists`, which means the task is already queued, so treat it as success (as in the example above). The ID stays reserved after the task finishes: 24 hours after success and 7 days after failure by default. See [task IDs and deduplication](https://pushqueue.dev/docs/concepts/tasks/#task-ids-and-deduplication) and the [deduplication pattern](https://pushqueue.dev/docs/patterns/deduplication/).

### Retry failed API calls yourself

No SDK retries API calls on its own. Network errors and timeouts surface as the HTTP library's own exceptions rather than the pushq error type (in Java, as a `PushqException` with status `0`), so handle both and retry with backoff. Because of `task_id`, retrying a create is safe. See [error handling](https://pushqueue.dev/docs/getting-started/sdks/#error-handling).

### Reuse one SDK client and set a timeout

Create the client once at startup and share it, rather than building one per request, so connections are reused. The default request timeout is 30 seconds; lower it if an enqueue sits on a user-facing request path. See [SDK client options](https://pushqueue.dev/docs/getting-started/sdks/#client-options).

### Check every result of a batch enqueue

`POST .../tasks:batch` returns `200` even when some items fail. Each item has its own `task` or `error` (`already_exists`, `invalid_argument`, ...), so inspect every result. See [batch enqueue](https://pushqueue.dev/docs/concepts/tasks/#batch-enqueue-up-to-500-tasks) and the [bulk enqueue pattern](https://pushqueue.dev/docs/patterns/bulk-enqueue/).

## Configure queues for production

### Use PATCH for single changes; PUT replaces the whole queue config

:::danger
`PUT /v1/queues/{queue}` (upsert) is a full replace. Every field you leave out goes back to its default: `target.base_url` and `target.headers` are cleared and `dead_letter_queue` is removed. Only `signing_secret` is kept when omitted. Always send the complete config with PUT, or use PATCH to change one field.
:::

Keeping the full config in code and upserting it at deploy time works well. See [create or update a queue with PUT](https://pushqueue.dev/docs/concepts/queues/#create-or-update-a-queue-with-put-upsert) and [update part of a queue](https://pushqueue.dev/docs/concepts/queues/#update-queue-settings-with-patch).

### Choose rate limits your endpoint can handle

The defaults are 500 dispatches per second and 1,000 concurrent requests per queue, more than most endpoints can absorb. Set `max_dispatches_per_second` and `max_concurrent_dispatches` to what the receiving service (or the third-party API behind it) can take, and answer `429` with `Retry-After` when overloaded. See the [rate limits guide](https://pushqueue.dev/docs/guides/rate-limits/) and [throttle a third-party API](https://pushqueue.dev/docs/patterns/throttle-a-third-party-api/).

### Set retry limits that fit the job

By default a task gets 100 attempts and keeps retrying for about 3.5 days. Lower `max_attempts` for work that goes stale, and raise `min_backoff_seconds` to a few seconds if failures usually mean a deploy or an outage. When you set both `max_attempts` and `max_retry_duration_seconds`, retries stop only when **both** are reached. See [retry backoff and when retries stop](https://pushqueue.dev/docs/concepts/retries/#what-happens-when-retries-run-out).

### Add a dead-letter queue

Set `dead_letter_queue` so tasks that run out of retries are copied somewhere you can inspect and replay them. Create the dead-letter queue itself first, with its own `target.base_url` if your tasks use relative paths: if it doesn't exist, the copy fails and is only logged. See [dead-letter queues](https://pushqueue.dev/docs/concepts/dead-letter-queues/) and [replay dead letters](https://pushqueue.dev/docs/patterns/replay-dead-letters/).

### Match the dispatch deadline to handler time

Each attempt waits up to `dispatch_deadline_seconds` (default 600, range 15 to 1800) for a response; past that it counts as a `timeout` and is retried, even if your handler finishes later. Set it above your slowest handler's time, or acknowledge quickly and do slow work elsewhere. See [dispatch deadline](https://pushqueue.dev/docs/concepts/tasks/#dispatch-deadline-request-timeout) and [long-running work](https://pushqueue.dev/docs/patterns/long-running-work/).

## Monitor queues and deliveries

### Watch queue stats

`GET /v1/queues/{queue}/stats` returns `pending`, `running`, `failed`, `scheduled_future`, `oldest_due_age_seconds` and error counts for the last minute and hour. Alert when `oldest_due_age_seconds` keeps growing (a backlog) or `errors_last_1m` climbs. See [queue stats](https://pushqueue.dev/docs/concepts/queues/#queue-stats-and-monitoring) and the [dashboard](https://pushqueue.dev/docs/guides/dashboard/).

### Scrape /metrics on a self-hosted server

`GET /metrics` serves Prometheus counters for dispatch results, errors by kind, latency, in-flight deliveries, retries and dead-lettered tasks. They are aggregate, without per-queue labels; use the stats endpoint for per-queue numbers. See [Prometheus metrics](https://pushqueue.dev/docs/self-hosting/operations/#prometheus-metrics).

## Self-hosting pushq in production

### Close the unauthenticated first-run window

A new server with no `api_keys` and no dashboard accounts accepts every request without credentials. Create the first admin account (or set `api_keys`) before the server is reachable from anywhere else. See [create the first admin account](https://pushqueue.dev/docs/self-hosting/install/#create-the-first-admin-account). Never expose a `pushq dev` server.

### Run two replicas on Postgres for high availability

SQLite is single-node. With Postgres, run two or more replicas: all serve the API, one holds the dispatcher lock, and another takes over if it dies. Probe `/healthz` for liveness and `/readyz` for readiness. See [high availability and leader election](https://pushqueue.dev/docs/self-hosting/operations/#high-availability-and-leader-election) and [deploy with docker-compose](https://pushqueue.dev/docs/self-hosting/deploy/#run-multiple-replicas-with-docker-compose-and-postgres).

### Terminate TLS at a reverse proxy

Bind pushq to a private address and put a TLS-terminating proxy in front. The proxy must send `X-Forwarded-Proto: https` so the session cookie is marked `Secure`, and must allow request bodies up to 8 MiB for batch enqueues. See [reverse proxy setup](https://pushqueue.dev/docs/self-hosting/deploy/#put-pushq-behind-a-reverse-proxy).

### Pass %2F through your proxy unchanged

Queue names with folders travel as one encoded segment (`/v1/queues/user%2Finstagram`). If the proxy decodes `%2F` into `/`, pushq answers `404`. With nginx, write `proxy_pass` with no URI part. See [forward the path unmodified](https://pushqueue.dev/docs/self-hosting/deploy/#forward-encoded-queue-names-unmodified).

### Restrict the metrics endpoint

`/metrics` is public by default and lists aggregate numbers for the whole server. Set `metrics.public: false` (`PUSHQ_METRICS_PUBLIC=false`) to require an admin key, or block it at the proxy. See [metrics settings](https://pushqueue.dev/docs/self-hosting/configuration/#metrics).

### Back up the database

All state lives in the database: queues, tasks, accounts and API keys. Use `sqlite3 .backup` or `pg_dump` (or managed Postgres snapshots), and back up before every upgrade, since there are no down migrations. See [backups](https://pushqueue.dev/docs/self-hosting/operations/#back-up-the-database) and [upgrading](https://pushqueue.dev/docs/self-hosting/operations/#upgrade-to-a-new-version).

### Set task retention

Succeeded tasks are kept 24 hours and failed tasks 7 days by default, never less than the 1-hour dedup window. Longer retention gives you more history but more rows to scan. See [retention and cleanup](https://pushqueue.dev/docs/self-hosting/operations/#task-retention-and-cleanup).

### Pin the server version

Run an exact image tag or release binary in production so upgrades happen when you choose. `:edge` moves on every release. See [upgrading pushq](https://pushqueue.dev/docs/self-hosting/operations/#upgrade-to-a-new-version).

## Read more

- [Troubleshooting pushq](https://pushqueue.dev/docs/guides/troubleshooting/): symptoms, causes and fixes for common failures.
- [Retries and backoff](https://pushqueue.dev/docs/concepts/retries/): the exact retry schedule.
- [Rate limits guide](https://pushqueue.dev/docs/guides/rate-limits/): how rate, burst and concurrency interact.
- [Deploy a self-hosted server](https://pushqueue.dev/docs/self-hosting/deploy/): systemd, docker-compose and reverse proxies.
- [Errors reference](https://pushqueue.dev/docs/reference/errors/): every error code and what to do about it.
