# Quickstart: send your first HTTP task > Get started with pushq in five minutes. Create an API key, create a queue, enqueue an HTTP task and receive it on your endpoint with signature checks. Source: https://pushqueue.dev/docs/getting-started/quickstart/ This quickstart takes you from zero to a delivered task with the hosted pushq API at `https://api.pushqueue.dev`: you create an API key, create a queue, enqueue an HTTP task and receive it on your own endpoint. Every step works the same against a server you run yourself; to try pushq on your machine without an account, see [local development with `pushq dev`](https://pushqueue.dev/docs/getting-started/local-development/). ## Create an API key Sign in to the [pushq console](https://console.pushqueue.dev/) and create a key under **Settings → API keys**. The key is shown once, so store it as an environment variable: ```bash export PUSHQ_API_KEY="pq_..." ``` Every request sends it as a bearer token (`Authorization: Bearer pq_...`). [API keys](https://pushqueue.dev/docs/guides/api-keys/) explains roles, rotation and revocation. ## Install an SDK Pick your language. Every SDK talks to the hosted API by default, and the docs remember the language you pick. **TypeScript** ```bash npm install pushq ``` **Python** ```bash pip install pushq ``` **Go** ```bash go get github.com/blissfulrays/pushq/sdks/go ``` **Java** ```xml io.github.blissfulrays pushq 1.0.0-SNAPSHOT ``` **.NET** ```bash dotnet add package Pushq ``` **curl** ```bash # No install needed: call the REST API directly. curl https://api.pushqueue.dev/v1/version -H "Authorization: Bearer $PUSHQ_API_KEY" ``` [Install & configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/) covers client options, errors and versions for each language. ## Create a client **TypeScript** ```ts const pq = new Pushq({ apiKey: process.env.PUSHQ_API_KEY }); ``` **Python** ```python import os from pushq import Pushq pq = Pushq(api_key=os.environ["PUSHQ_API_KEY"]) ``` **Go** ```go import ( "context" "os" pushq "github.com/blissfulrays/pushq/sdks/go" ) pq := pushq.New("", os.Getenv("PUSHQ_API_KEY")) // "" = https://api.pushqueue.dev ctx := context.Background() ``` **Java** ```java import io.pushq.*; Pushq pq = Pushq.builder() .apiKey(System.getenv("PUSHQ_API_KEY")) .build(); ``` **.NET** ```csharp using Pushq; using var pq = new PushqClient(apiKey: Environment.GetEnvironmentVariable("PUSHQ_API_KEY")); ``` **curl** ```bash export PUSHQ_URL="https://api.pushqueue.dev" ``` ## Create a queue A queue holds tasks and says where to deliver them and how fast. This one delivers to `https://api.example.com` at up to 10 requests per second, 5 at a time, and signs every delivery. **TypeScript** ```ts await pq.upsertQueue("emails", { rateLimits: { maxDispatchesPerSecond: 10, maxConcurrentDispatches: 5 }, target: { baseUrl: "https://api.example.com", signingSecret: process.env.PUSHQ_SIGNING_SECRET }, }); ``` **Python** ```python from pushq import RateLimits, Target pq.upsert_queue( "emails", rate_limits=RateLimits(max_dispatches_per_second=10, max_concurrent_dispatches=5), target=Target(base_url="https://api.example.com", signing_secret=os.environ["PUSHQ_SIGNING_SECRET"]), ) ``` **Go** ```go _, err := pq.UpsertQueue(ctx, "emails", pushq.QueueConfig{ RateLimits: &pushq.RateLimits{ MaxDispatchesPerSecond: pushq.Float64(10), MaxConcurrentDispatches: pushq.Int(5), }, Target: &pushq.Target{ BaseURL: "https://api.example.com", SigningSecret: os.Getenv("PUSHQ_SIGNING_SECRET"), }, }) ``` **Java** ```java pq.upsertQueue("emails", QueueConfig.builder() .rateLimits(RateLimits.builder() .maxDispatchesPerSecond(10) .maxConcurrentDispatches(5) .build()) .target(Target.builder() .baseUrl("https://api.example.com") .signingSecret(System.getenv("PUSHQ_SIGNING_SECRET")) .build()) .build()); ``` **.NET** ```csharp await pq.UpsertQueueAsync("emails", new QueueConfig { RateLimits = new RateLimits { MaxDispatchesPerSecond = 10, MaxConcurrentDispatches = 5 }, Target = new Target { BaseUrl = "https://api.example.com", SigningSecret = Environment.GetEnvironmentVariable("PUSHQ_SIGNING_SECRET"), }, }); ``` **curl** ```bash curl -X PUT "$PUSHQ_URL/v1/queues/emails" \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{ "rate_limits": {"max_dispatches_per_second": 10, "max_concurrent_dispatches": 5}, "target": {"base_url": "https://api.example.com", "signing_secret": "whsec_..."} }' ``` :::caution[Upsert replaces the whole configuration] Creating or updating a queue with upsert (`PUT`) replaces its configuration: any field you leave out goes back to its default, and only the signing secret is kept. Send the full configuration every time, or change single settings with a patch. See [queues](https://pushqueue.dev/docs/concepts/queues/). ::: ## Enqueue a task A task is one HTTP request pushq makes for you. `path` is resolved against the queue's base URL, so this task becomes `POST https://api.example.com/hooks/send-welcome`, delivered in an hour. **TypeScript** ```ts await pq.createTask("emails", { taskId: "welcome-user-42", // optional: a second create with this ID is rejected path: "/hooks/send-welcome", jsonBody: { user_id: 42 }, delaySeconds: 3600, // omit to deliver now }); ``` **Python** ```python pq.create_task( "emails", task_id="welcome-user-42", path="/hooks/send-welcome", json_body={"user_id": 42}, delay_seconds=3600, ) ``` **Go** ```go _, err = pq.CreateTask(ctx, "emails", pushq.TaskCreate{ TaskID: "welcome-user-42", Path: "/hooks/send-welcome", JSONBody: map[string]any{"user_id": 42}, DelaySeconds: pushq.Float64(3600), }) ``` **Java** ```java pq.createTask("emails", TaskCreate.builder() .taskId("welcome-user-42") .path("/hooks/send-welcome") .jsonBody(Map.of("user_id", 42)) .delaySeconds(3600) .build()); ``` **.NET** ```csharp await pq.CreateTaskAsync("emails", new TaskCreate { TaskId = "welcome-user-42", Path = "/hooks/send-welcome", JsonBody = new Dictionary { ["user_id"] = 42 }, Delay = TimeSpan.FromHours(1), }); ``` **curl** ```bash curl -X POST "$PUSHQ_URL/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}, "delay_seconds": 3600}' ``` A second create with the same `task_id` fails with `409 already_exists`, which makes enqueueing safe to retry. See [deduplicate tasks](https://pushqueue.dev/docs/patterns/deduplication/). ## Receive the task and verify its signature pushq calls your endpoint with the task's body and `X-Pushq-*` headers. **Return any 2xx** to mark the task done; any other status, or a timeout, is retried with backoff. Because the queue has a signing secret, verify each delivery against the raw request body before trusting it: **TypeScript** ```ts const app = express(); // express.raw keeps the exact bytes; don't run 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.status(401).end(); throw err; } const { user_id } = JSON.parse(req.body.toString("utf8")); await sendWelcomeEmail(user_id, webhookId); // webhookId is stable across retries res.sendStatus(204); }); ``` **Python** ```python import os from fastapi import FastAPI, HTTPException, Request from pushq import WebhookVerificationError, verify_signature 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(os.environ["PUSHQ_SIGNING_SECRET"], request.headers, body) except WebhookVerificationError: raise HTTPException(status_code=401) # webhook_id ("emails/welcome-user-42") is stable across retries return {"ok": True} ``` **Go** ```go 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 } id, err := pushq.VerifySignature(os.Getenv("PUSHQ_SIGNING_SECRET"), r.Header, body, 5*time.Minute) if err != nil { http.Error(w, "invalid signature", http.StatusUnauthorized) return } _ = id // "emails/welcome-user-42", stable across retries w.WriteHeader(http.StatusNoContent) } ``` **Java** ```java @PostMapping("/hooks/send-welcome") public ResponseEntity 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(System.getenv("PUSHQ_SIGNING_SECRET"), id, ts, payload, sig, 300); } catch (WebhookVerificationException e) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } // trusted: parse the payload and do the work return ResponseEntity.ok().build(); } ``` **.NET** ```csharp app.MapPost("/hooks/send-welcome", async (HttpRequest req) => { using var ms = new MemoryStream(); await req.Body.CopyToAsync(ms); var body = ms.ToArray(); try { // "emails/welcome-user-42": stable across retries string webhookId = Webhooks.VerifySignature( Environment.GetEnvironmentVariable("PUSHQ_SIGNING_SECRET")!, name => req.Headers[name].FirstOrDefault(), body); return Results.Ok(); } catch (WebhookVerificationException) { return Results.Unauthorized(); } }); ``` Delivery is at-least-once, so make the handler safe to run twice: the verified ID (`queue/task_id`) stays the same across retries and works as an idempotency key. See [delivery and signing](https://pushqueue.dev/docs/concepts/delivery/) and [idempotent handlers](https://pushqueue.dev/docs/patterns/idempotent-handlers/). ## Check the task's status and attempts ```bash curl "$PUSHQ_URL/v1/queues/emails/stats" -H "Authorization: Bearer $PUSHQ_API_KEY" curl "$PUSHQ_URL/v1/queues/emails/tasks/welcome-user-42/attempts" -H "Authorization: Bearer $PUSHQ_API_KEY" ``` Or open the [console](https://console.pushqueue.dev/) to see every queue with live stats and each task's attempt history. ## Read more - [Queues](https://pushqueue.dev/docs/concepts/queues/): rate limits, concurrency, folders, pause and purge. - [Tasks](https://pushqueue.dev/docs/concepts/tasks/): scheduling, deduplication and batch enqueue. - [Retries and backoff](https://pushqueue.dev/docs/concepts/retries/): what happens when a delivery fails. - [Rate limits](https://pushqueue.dev/docs/guides/rate-limits/): protect a downstream API. - [Going to production](https://pushqueue.dev/docs/guides/going-to-production/): the checklist before you ship. --- # Install and configure an SDK > Install the pushq SDK for TypeScript, Python, Go, Java or .NET, create a client, and handle errors, pagination and webhook signatures. Source: https://pushqueue.dev/docs/getting-started/sdks/ pushq has official SDKs for TypeScript/JavaScript, Python, Go, Java and .NET. Each one is a thin, typed wrapper over the [REST API](https://pushqueue.dev/docs/reference/api/). They cover every queue and task endpoint and include a helper to verify signed deliveries. This page covers what is the same everywhere: installing, creating a client, client options, errors, pagination and signature verification. The rest of the docs show every example in all five languages, plus `curl`. Parameter tables across the docs use the API's JSON field names, such as `rate_limits.max_dispatches_per_second`. Each SDK uses its own language's casing for those names. See [Naming conventions](#naming-conventions). ## Install **TypeScript** ```bash npm install pushq ``` **Python** ```bash pip install pushq ``` **Go** ```bash go get github.com/blissfulrays/pushq/sdks/go ``` **Java** ```bash git clone https://github.com/blissfulrays/pushq.git cd pushq/sdks/java mvn install -DskipTests ``` **.NET** ```bash dotnet add package Pushq ``` - **TypeScript:** `pnpm add pushq` and `bun add pushq` work too. In Deno, import `npm:pushq`. - **Go:** the import path ends in `/go`, so import the package with an explicit name: `import pushq "github.com/blissfulrays/pushq/sdks/go"`. - **Java:** the SDK is not on Maven Central yet; that is coming. Until then, `mvn install` builds it and puts it in your local Maven repository (`~/.m2`). Then add the dependency: **Maven** ```xml io.github.blissfulrays pushq 1.0.0-SNAPSHOT ``` **Gradle** ```kotlin repositories { mavenLocal() // needed until the SDK is on Maven Central mavenCentral() } dependencies { implementation("io.github.blissfulrays:pushq:1.0.0-SNAPSHOT") } ``` The Maven group is `io.github.blissfulrays`, but the Java package is `io.pushq`. ## Create a client ### Hosted API Create an API key in the [console](https://console.pushqueue.dev/) (see [API keys](https://pushqueue.dev/docs/guides/api-keys/)) and pass it to the client. With no base URL, every SDK talks to the hosted API at `https://api.pushqueue.dev`. **TypeScript** ```ts const pq = new Pushq({ apiKey: process.env.PUSHQ_API_KEY }); ``` **Python** ```python import os from pushq import Pushq pq = Pushq(api_key=os.environ["PUSHQ_API_KEY"]) ``` **Go** ```go import ( "context" "os" pushq "github.com/blissfulrays/pushq/sdks/go" ) pq := pushq.New("", os.Getenv("PUSHQ_API_KEY")) // "" = https://api.pushqueue.dev ctx := context.Background() ``` **Java** ```java import io.pushq.*; Pushq pq = Pushq.builder() .apiKey(System.getenv("PUSHQ_API_KEY")) .build(); ``` **.NET** ```csharp using Pushq; using var pq = new PushqClient(apiKey: Environment.GetEnvironmentVariable("PUSHQ_API_KEY")); ``` **curl** ```bash curl https://api.pushqueue.dev/v1/queues/emails \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` The SDKs send the key as `Authorization: Bearer `. None of them reads environment variables on its own, so pass the key in explicitly. Every SDK exports the default URL as a constant: `DEFAULT_BASE_URL` in TypeScript and Python, `pushq.DefaultBaseURL` in Go, `Pushq.DEFAULT_BASE_URL` in Java and `PushqClient.DefaultBaseUrl` in .NET. Create one client and reuse it. The Go, Java and .NET clients are documented as safe to share across threads and goroutines. ### Self-hosted server Pass your server's URL. If you run [`pushq dev`](https://pushqueue.dev/docs/getting-started/local-development/) locally, which has no API keys, leave the key out. Every SDK then sends no `Authorization` header. **TypeScript** ```ts const pq = new Pushq({ baseUrl: "https://pushq.internal.example.com", apiKey: process.env.PUSHQ_API_KEY }); // `pushq dev`: no key needed const local = new Pushq({ baseUrl: "http://localhost:8080" }); ``` **Python** ```python import os from pushq import Pushq pq = Pushq("https://pushq.internal.example.com", api_key=os.environ["PUSHQ_API_KEY"]) # `pushq dev`: no key needed local = Pushq("http://localhost:8080") ``` **Go** ```go pq := pushq.New("https://pushq.internal.example.com", os.Getenv("PUSHQ_API_KEY")) // `pushq dev`: pass an empty key local := pushq.New("http://localhost:8080", "") ``` **Java** ```java Pushq pq = Pushq.builder() .baseUrl("https://pushq.internal.example.com") .apiKey(System.getenv("PUSHQ_API_KEY")) .build(); // `pushq dev`: no key needed Pushq local = Pushq.builder().baseUrl("http://localhost:8080").build(); ``` **.NET** ```csharp using Pushq; using var pq = new PushqClient("https://pushq.internal.example.com", apiKey: Environment.GetEnvironmentVariable("PUSHQ_API_KEY")); // `pushq dev`: no key needed using var local = new PushqClient("http://localhost:8080"); ``` **curl** ```bash curl http://localhost:8080/v1/queues/emails ``` Every SDK strips trailing slashes from the base URL. An empty or whitespace-only base URL falls back to the hosted API. ## Client options Apart from the base URL and API key, the SDKs let you set a request timeout and, in most of them, supply your own HTTP client: **TypeScript** ```ts const pq = new Pushq({ baseUrl: "https://api.pushqueue.dev", apiKey: process.env.PUSHQ_API_KEY, timeoutMs: 10_000, // per request; default 30_000 fetch: async (input, init) => { // custom fetch: logging, tracing, proxies, tests const res = await fetch(input, init); console.log(init?.method, String(input), res.status); return res; }, }); ``` **Python** ```python import httpx from pushq import Pushq # timeout in seconds, default 30.0 pq = Pushq("https://api.pushqueue.dev", api_key="pq_...", timeout=10.0) # or bring your own httpx.Client (proxies, TLS, transport retries, event hooks) http = httpx.Client( base_url="https://api.pushqueue.dev", headers={"Authorization": "Bearer pq_..."}, timeout=10.0, transport=httpx.HTTPTransport(retries=2), ) pq = Pushq(client=http) # close the connection pool when done, or use a with-block pq.close() with Pushq(api_key="pq_...") as pq: pq.get_queue("emails") ``` **Go** ```go hc := &http.Client{ Timeout: 10 * time.Second, Transport: &http.Transport{MaxIdleConnsPerHost: 50}, } pq := pushq.New("", os.Getenv("PUSHQ_API_KEY"), pushq.WithHTTPClient(hc)) ``` **Java** ```java import java.time.Duration; Pushq pq = Pushq.builder() .baseUrl("https://api.pushqueue.dev") .apiKey(System.getenv("PUSHQ_API_KEY")) .timeout(Duration.ofSeconds(10)) // default 30s; connect and per-request timeout .build(); ``` **.NET** ```csharp using Pushq; // Standalone, with a custom timeout using var pq = new PushqClient(new PushqClientOptions { BaseUrl = "https://api.pushqueue.dev", ApiKey = Environment.GetEnvironmentVariable("PUSHQ_API_KEY"), Timeout = TimeSpan.FromSeconds(10), // default 30s; ignored when HttpClient is set }); // ASP.NET Core with IHttpClientFactory builder.Services.AddHttpClient("pushq", http => http.Timeout = TimeSpan.FromSeconds(15)); builder.Services.AddSingleton(sp => new PushqClient(new PushqClientOptions { BaseUrl = builder.Configuration["Pushq:Url"] ?? PushqClient.DefaultBaseUrl, ApiKey = builder.Configuration["Pushq:ApiKey"], HttpClient = sp.GetRequiredService().CreateClient("pushq"), })); ``` | SDK | Timeout | Custom HTTP client | Notes | | --- | --- | --- | --- | | TypeScript | `timeoutMs`, default `30000` | `fetch` (defaults to the global `fetch`) | The constructor throws if no `fetch` is available. | | Python | `timeout` (seconds), default `30.0` | `client=httpx.Client(...)`, or `httpx.AsyncClient` for `AsyncPushq` | When you pass `client`, the SDK ignores `base_url`, `api_key` and `timeout`; set them on the httpx client. `close()` also closes a client you passed in. | | Go | from the `http.Client`, default 30 s | `pushq.WithHTTPClient(hc)` | This replaces the whole client. Per-call deadlines come from the `context.Context` that every method takes first. | | Java | `timeout(Duration)`, default 30 s | not supported | The SDK uses its own `java.net.http.HttpClient` and does not follow redirects. | | .NET | `Timeout`, default 30 s | `HttpClient` | `Timeout` is ignored when you supply `HttpClient`. The SDK never disposes an `HttpClient` you supply. Every method takes an optional `CancellationToken`. | None of the SDKs retries failed API calls. If you add retries, set a `task_id` on every task you create. A retried create then fails with `already_exists` instead of enqueueing the task twice. ## Naming conventions The SDKs follow their language's conventions, so the same call looks different in each: | | TypeScript | Python | Go | Java | .NET | | --- | --- | --- | --- | --- | --- | | Create a task | `createTask` | `create_task` | `CreateTask` | `createTask` | `CreateTaskAsync` | | Batch create | `createTasks` | `create_tasks` | `CreateTasks` | `createTasks` | `CreateTasksAsync` | | Queue stats | `queueStats` | `queue_stats` | `QueueStats` | `queueStats` | `GetQueueStatsAsync` | | Fields | camelCase (`maxDispatchesPerSecond`) | snake_case (`max_dispatches_per_second`) | PascalCase (`MaxDispatchesPerSecond`) | camelCase builder methods and getters | PascalCase properties | | Building input | object literals | keyword arguments and config classes (`RateLimits`, `Retry`, `Target`) | structs; optional numbers are pointers (`pushq.Int(3)`, `pushq.Float64(3600)`) | builders (`TaskCreate.builder()...build()`) | object initializers | | Sync or async | all methods return a `Promise` | `Pushq` (sync) and `AsyncPushq` (async) | blocking; `ctx` first | synchronous | `...Async` methods | | Timestamps | `Date` | `datetime` | `time.Time` | `Instant` | `DateTimeOffset` | | Raw body (`body_base64`) | `body: string \| Uint8Array` | `body: bytes` | `Body []byte` | `body(byte[])` | `Body` (`byte[]`) | | Delay and deadline | seconds (`delaySeconds`) | seconds | seconds (`*float64`) | seconds | `TimeSpan` (`Delay`, `DispatchDeadline`) | | Task type | `Task` | `Task` | `pushq.Task` | `Task` | `PushqTask` | Every SDK base64-encodes raw bodies for you, so you never build `body_base64` yourself. Queue names that contain `/`, such as `user/instagram`, are URL-encoded automatically. See [queue folders](https://pushqueue.dev/docs/concepts/queues/). ## Error handling Every non-2xx API response becomes an error that carries the HTTP status, a stable machine-readable `code`, and a human-readable `detail`. Branch on `code`, not on the message text. **TypeScript** ```ts try { await pq.createTask("emails", { taskId: "welcome-user-42", path: "/hooks/send-welcome" }); } catch (err) { if (err instanceof PushqError && err.code === "already_exists") { // already enqueued: nothing to do } else if (err instanceof PushqError) { console.error(err.status, err.code, err.detail); throw err; } else { throw err; // timeout or network error } } ``` **Python** ```python from pushq import PushqError try: pq.create_task("emails", path="/hooks/send-welcome", task_id="welcome-user-42") except PushqError as e: if e.code == "already_exists": pass # already enqueued: nothing to do else: print(e.status, e.code, e.detail) raise ``` **Go** ```go _, err := pq.CreateTask(ctx, "emails", pushq.TaskCreate{ TaskID: "welcome-user-42", Path: "/hooks/send-welcome", }) if pushq.IsCode(err, "already_exists") { // already enqueued: nothing to do } else if err != nil { var pe *pushq.Error if errors.As(err, &pe) { log.Printf("pushq %d %s: %s", pe.Status, pe.Code, pe.Detail) } return err } ``` **Java** ```java try { pq.createTask("emails", TaskCreate.builder() .taskId("welcome-user-42") .path("/hooks/send-welcome") .build()); } catch (PushqException e) { if ("already_exists".equals(e.getCode())) { // already enqueued: nothing to do } else { System.err.println(e.getStatus() + " " + e.getCode() + ": " + e.getDetail()); throw e; } } ``` **.NET** ```csharp try { await pq.CreateTaskAsync("emails", new TaskCreate { TaskId = "welcome-user-42", Path = "/hooks/send-welcome" }); } catch (PushqException e) when (e.Code == "already_exists") { // already enqueued: nothing to do } catch (PushqException e) { Console.WriteLine($"{e.Status} {e.Code}: {e.Detail}"); throw; } ``` **curl** ```bash curl -i -X POST https://api.pushqueue.dev/v1/queues/emails/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{"task_id":"welcome-user-42","path":"/hooks/send-welcome"}' ``` Over raw HTTP, errors come back as [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) `application/problem+json`, and the SDKs read the same fields: ```json { "type": "about:blank", "title": "Conflict", "status": 409, "code": "already_exists", "detail": "...", "instance": "/v1/queues/emails/tasks" } ``` The [error reference](https://pushqueue.dev/docs/reference/errors/) lists every code, its HTTP status and what to do about it. API errors and transport failures (timeouts, refused connections, DNS) surface differently: | SDK | API error | Transport failure | Invalid input caught before sending | | --- | --- | --- | --- | | TypeScript | `PushqError` (`status`, `code`, `detail`) | `DOMException` named `TimeoutError` on timeout; otherwise what `fetch` throws (`TypeError`) | `Error` when both `body` and `jsonBody` are set | | Python | `PushqError` (`status`, `code`, `detail`) | httpx exceptions, such as `httpx.TimeoutException` and `httpx.ConnectError` | `ValueError` when both `body` and `json_body` are set | | Go | `*pushq.Error` (`Status`, `Code`, `Detail`); test with `pushq.IsCode(err, code)` | the `net/http` or `context` error, unwrapped | none | | Java | unchecked `PushqException` (`getStatus()`, `getCode()`, `getDetail()`) | `PushqException` with `getStatus() == 0`; the cause holds the `IOException` | `IllegalStateException` from `TaskCreate.build()` for conflicting fields | | .NET | `PushqException` (`Status`, `Code`, `Detail`) | `HttpRequestException` or `TaskCanceledException` | `ArgumentException` for conflicting fields | If an error response is not a problem document, for example an HTML page from a proxy, the code is `internal` in TypeScript, Python, Go and .NET. In Java it is `null`. In every SDK, `detail` holds the response body, which may be truncated. ## Pagination `list queues` and `list tasks` return one page at a time with a `next_page_token`. Pass it back as `page_token` to get the next page, and keep the other parameters the same. The last page has no token. Page size defaults to 100 and is capped at 1000. None of the SDKs has an auto-paging iterator, so loop until the token is empty: **TypeScript** ```ts let pageToken: string | undefined; do { const page = await pq.listTasks("emails", { state: "failed", pageSize: 1000, pageToken }); for (const task of page.items) console.log(task.id); pageToken = page.nextPageToken; } while (pageToken); ``` **Python** ```python token = None while True: page = pq.list_tasks("emails", state="failed", page_size=1000, page_token=token) for task in page.items: print(task.id) token = page.next_page_token if token is None: break ``` **Go** ```go token := "" for { tasks, next, err := pq.ListTasks(ctx, "emails", pushq.ListTasksParams{ State: "failed", PageSize: 1000, PageToken: token, }) if err != nil { return err } for _, t := range tasks { fmt.Println(t.ID) } if next == "" { break } token = next } ``` **Java** ```java String token = null; do { ListTasksParams.Builder p = ListTasksParams.builder().state("failed").pageSize(1000); if (token != null) p.pageToken(token); TaskPage page = pq.listTasks("emails", p.build()); for (Task t : page.getTasks()) System.out.println(t.getId()); token = page.getNextPageToken(); } while (token != null && !token.isEmpty()); ``` **.NET** ```csharp string? token = null; do { var page = await pq.ListTasksAsync("emails", new ListTasksOptions { State = TaskState.Failed, PageSize = 1000, PageToken = token, }); foreach (var t in page.Items) Console.WriteLine(t.Id); token = page.NextPageToken; } while (token != null); ``` **curl** ```bash curl "https://api.pushqueue.dev/v1/queues/emails/tasks?state=failed&page_size=1000" \ -H "Authorization: Bearer $PUSHQ_API_KEY" # Next page: pass next_page_token from the previous response curl "https://api.pushqueue.dev/v1/queues/emails/tasks?state=failed&page_size=1000&page_token=MTIzNA" \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` Task lists are returned newest first, and queue lists in name order. Listing queues needs an admin API key. ## Verify signatures When a queue has a `target.signing_secret`, pushq signs every delivery using the [Standard Webhooks](https://www.standardwebhooks.com) scheme, with `webhook-id`, `webhook-timestamp` and `webhook-signature` headers. Each SDK ships a verifier. Use it in the endpoint that receives tasks, and reject the request with `401` if verification fails. [Delivery](https://pushqueue.dev/docs/concepts/delivery/) explains the headers and the signing scheme. Always verify the raw request body, exactly as it arrived. If a framework parses the JSON first and you re-serialize it, the bytes can differ and verification fails. **TypeScript** ```ts const app = express(); // express.raw keeps the body as an unparsed Buffer; don't run express.json() on this route. app.post("/hooks/send-welcome", express.raw({ type: "*/*" }), async (req, res) => { const payload: Buffer = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0); let webhookId: string; try { webhookId = await verifySignature({ secret: process.env.PUSHQ_SIGNING_SECRET!, headers: req.headers, payload, }); } catch (err) { if (err instanceof WebhookVerificationError) return res.sendStatus(401); throw err; } const { userId } = JSON.parse(payload.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 // ... json.Unmarshal(body, &payload), do the work, dedupe on webhookID ... w.WriteHeader(http.StatusNoContent) } // http.HandleFunc("POST /hooks/send-welcome", handleSendWelcome) ``` **Java** ```java import io.pushq.WebhookVerificationException; import io.pushq.Webhooks; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController public class PushqHooks { private final String secret = System.getenv("PUSHQ_SIGNING_SECRET"); @PostMapping("/hooks/send-welcome") public ResponseEntity 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 using Pushq; var signingSecret = builder.Configuration["Pushq:SigningSecret"]!; app.MapPost("/hooks/send-welcome", async (HttpRequest req) => { using var ms = new MemoryStream(); await req.Body.CopyToAsync(ms); var body = ms.ToArray(); try { string webhookId = Webhooks.VerifySignature(signingSecret, 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(); } }); ``` The `webhook-id` has the form `/`, for example `emails/welcome-user-42`, and stays the same on every retry of a task. Use it as an idempotency key to skip work you have already done. Respond with a 2xx status once the work succeeds. Any other status, or no response before the dispatch deadline, counts as a failed attempt and is [retried](https://pushqueue.dev/docs/concepts/retries/). Other frameworks: - **TypeScript (Fetch API runtimes: Hono, Cloudflare Workers, Next.js route handlers, Deno, Bun):** pass `payload: new Uint8Array(await request.arrayBuffer())` and `headers: request.headers`. In Hono, use `c.req.raw.headers`. - **Python:** in Flask, pass `request.headers, request.get_data()`. In Django, pass `request.headers, request.body` in a `@csrf_exempt` view. - **Go:** chi handlers are plain `http.HandlerFunc`s and work unchanged. In gin, read `c.GetRawData()` and `c.Request.Header` before any `ShouldBindJSON`. - **Java (plain Servlet):** read `req.getInputStream().readAllBytes()` and the three headers with `req.getHeader(...)`. - **.NET (MVC controllers):** read `Request.Body` the same way, and don't declare a `[FromBody]` parameter. ### Calling the verifier directly Here is each verifier with all of its arguments, including the timestamp tolerance: **TypeScript** ```ts const webhookId: string = await verifySignature({ secret: "whsec_dGVzdC1zZWNyZXQ=", // "whsec_" or a raw string headers: request.headers, // Headers or a plain object payload: rawBody, // string | Uint8Array, exactly as received toleranceSeconds: 300, // default 300; 0 disables the timestamp check now: new Date(), // optional, for tests }); ``` **Python** ```python import time from pushq import verify_signature webhook_id = verify_signature( "whsec_dGVzdC1zZWNyZXQ=", # "whsec_" or a raw string headers, # any mapping with the webhook-* headers raw_body, # bytes or str tolerance_seconds=300, # default 300; <= 0 disables the timestamp check now=time.time(), # optional, unix seconds, for tests ) ``` **Go** ```go webhookID, err := pushq.VerifySignature( "whsec_dGVzdC1zZWNyZXQ=", // "whsec_" or a raw string r.Header, // http.Header body, // []byte, exactly as received 5*time.Minute, // tolerance; <= 0 disables the timestamp check ) if errors.Is(err, pushq.ErrVerification) { // reject with 401 } ``` **Java** ```java Webhooks.verifySignature( "whsec_dGVzdC1zZWNyZXQ=", // "whsec_" or a raw string msgId, // webhook-id header timestampSecs, // webhook-timestamp header, as a long rawBody, // byte[], exactly as received signatureHeader, // webhook-signature header 300); // tolerance in seconds // Overload with an injectable java.time.Clock, for tests: Webhooks.verifySignature(secret, msgId, timestampSecs, rawBody, signatureHeader, 300, clock); ``` **.NET** ```csharp string webhookId = Webhooks.VerifySignature( secret: "whsec_dGVzdC1zZWNyZXQ=", // "whsec_" or a raw string header: name => headers.TryGetValue(name, out var v) ? v : null, // header lookup function payload: rawBodyBytes, // byte[] (a string overload also exists) tolerance: TimeSpan.FromMinutes(5), // default 5 minutes; TimeSpan.Zero disables now: null); // optional, for tests ``` | SDK | Returns | Default tolerance | Failure | | --- | --- | --- | --- | | TypeScript | `Promise` (the `webhook-id`) | 300 s | rejects with `WebhookVerificationError` | | Python | `str` (the `webhook-id`) | 300 s | raises `WebhookVerificationError` | | Go | `(string, error)` | none, you pass it | error wrapping `pushq.ErrVerification` | | Java | `void` (read the id from the header) | none, you pass it | throws unchecked `WebhookVerificationException` | | .NET | `string` (the `webhook-id`) | 5 minutes (`Webhooks.DefaultTolerance`) | throws `WebhookVerificationException` | In every SDK: - A secret that starts with `whsec_` is base64-decoded after the prefix. Any other string is used as raw UTF-8 key bytes. - The tolerance applies in both directions, to timestamps in the past and in the future. - The signature header may contain several space-separated `v1,` entries. Verification passes if any of them matches, and the comparison is constant-time. Every SDK also exports a `sign` function (`sign`, `pushq.Sign`, `Webhooks.sign`, `Webhooks.Sign`). It produces a `v1,` signature so you can test your endpoint without a pushq server. ## Runtime and version support | SDK | Package | Requires | Notes | | --- | --- | --- | --- | | TypeScript | npm `pushq` | Node.js 18.17+, Bun, Deno, Cloudflare Workers and other runtimes with `fetch` | ESM and CommonJS builds with type declarations; no runtime dependencies. Server-side only: it would expose your API key in a browser, and the API sends no CORS headers. | | Python | PyPI `pushq` | Python 3.9+ | Depends only on `httpx>=0.25`. Ships type hints (`py.typed`). Sync `Pushq` and async `AsyncPushq`. | | Go | `github.com/blissfulrays/pushq/sdks/go` | Go 1.22+ | Every method takes a `context.Context`. | | Java | `io.github.blissfulrays:pushq` (build from source for now) | Java 11+ | Synchronous and thread-safe. Depends on `jackson-databind` and `jackson-datatype-jsr310`. JPMS module name `io.pushq`. | | .NET | NuGet `Pushq` | `netstandard2.0` (.NET Framework 4.6.2+, .NET Core, .NET 5+) and `net10.0` | No dependencies on `net10.0`. On `netstandard2.0` it pulls in `System.Text.Json`. | :::caution - **TypeScript:** `verifySignature` uses the global Web Crypto API (`crypto.subtle`). On Node.js 18 that global is not enabled by default, so use Node.js 20 or later for receivers. On Node 18 you can set `globalThis.crypto = require("node:crypto").webcrypto` at startup. - **Python:** `AsyncPushq` does not have `create_queue`, `patch_queue` or `list_queues`. Use the sync client for those. ::: ## What the SDKs don't cover The SDKs wrap queue and task operations only. To create, list or revoke API keys, manage team members, or read the server version (`GET /v1/version`), use the [console](https://console.pushqueue.dev/) or call the [REST API](https://pushqueue.dev/docs/reference/api/) directly. See [API keys](https://pushqueue.dev/docs/guides/api-keys/) and [Team members](https://pushqueue.dev/docs/guides/team-members/). --- # Local development with pushq dev > Run a local pushq task queue with `pushq dev` for development and testing. Real retries, delays and rate limits, with no account and no API key. Source: https://pushqueue.dev/docs/getting-started/local-development/ `pushq dev` runs the real queue locally: delays, retries and rate limits behave exactly as they do in production, instead of being faked with synchronous calls. ```bash pushq dev ``` That gives you SQLite in a temp file, no authentication, fast timers, and the dashboard at http://localhost:8080/. [Install pushq](https://pushqueue.dev/docs/self-hosting/install/) first if you don't have the binary. ## Point an SDK at your local server SDKs default to the hosted API, so pass your local server's URL. `pushq dev` doesn't check API keys. **TypeScript** ```ts const pq = new Pushq({ baseUrl: "http://localhost:8080" }); ``` **Python** ```python from pushq import Pushq pq = Pushq("http://localhost:8080") ``` **Go** ```go pq := pushq.New("http://localhost:8080", "") // empty key: no Authorization header ``` **Java** ```java Pushq pq = Pushq.builder() .baseUrl("http://localhost:8080") .build(); ``` **.NET** ```csharp using var pq = new PushqClient("http://localhost:8080"); ``` **curl** ```bash export PUSHQ_URL="http://localhost:8080" ``` ## Try it with curl ```bash # Create a queue that delivers to a receiver on port 9000 curl -X PUT localhost:8080/v1/queues/emails -d '{ "rate_limits": {"max_dispatches_per_second": 5}, "retry": {"max_attempts": 5, "min_backoff_seconds": 1, "max_backoff_seconds": 60}, "target": {"base_url": "http://localhost:9000"} }' # Deliver now curl -X POST localhost:8080/v1/queues/emails/tasks -d '{ "path": "/send", "json_body": {"to": "a@example.com"}}' # In 2 hours, deduplicated, with a per-task retry override curl -X POST localhost:8080/v1/queues/emails/tasks -d '{ "path": "/send", "json_body": {"to": "b@example.com"}, "delay_seconds": 7200, "task_id": "welcome-user-42", "retry": {"max_attempts": 1} }' ``` A second create with the same `task_id` returns `409 already_exists`; that's your deduplication. For a receiver, the repository has [an Express example](https://github.com/blissfulrays/pushq/tree/main/examples/express-receiver) and [a FastAPI example](https://github.com/blissfulrays/pushq/tree/main/examples/fastapi-receiver), both of which verify signatures. ## Watch and operate local queues ```bash curl localhost:8080/v1/queues/emails/stats curl "localhost:8080/v1/queues/emails/tasks?state=succeeded" curl localhost:8080/v1/queues/emails/tasks/welcome-user-42/attempts curl -X POST localhost:8080/v1/queues/emails:pause curl -X POST localhost:8080/v1/queues/emails:resume curl -X POST localhost:8080/v1/queues/emails:purge curl -X POST localhost:8080/v1/queues/emails/tasks/welcome-user-42:run # dispatch now ``` Every server also serves its interactive API reference at `/docs` (http://localhost:8080/docs) and the OpenAPI spec at `/openapi.json`. ## Read more - [Quickstart](https://pushqueue.dev/docs/getting-started/quickstart/): the same flow against the hosted API. - [Install pushq](https://pushqueue.dev/docs/self-hosting/install/): binaries, Docker and building from source. - [Configuration](https://pushqueue.dev/docs/self-hosting/configuration/): every setting for `pushq serve`. --- # Queues and queue configuration > Create and configure pushq queues: every setting with defaults and limits, queue states, pause, resume, purge, delete, folders and the stats API. Source: https://pushqueue.dev/docs/concepts/queues/ A pushq queue holds tasks and decides how they are delivered: how fast, how many at once, how failures are retried, and where relative paths point. This page covers creating and configuring queues, every queue setting, pausing, purging and deleting queues, queue folders, and queue stats. Use one queue per kind of work (`emails`, `webhooks`), or one per customer when each needs its own rate limit (see [Rate limits](https://pushqueue.dev/docs/guides/rate-limits/)). The examples on this page assume a client named `pq` (see [Install & configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/)). Parameter tables use the JSON field names; the SDKs use their language's casing (`maxDispatchesPerSecond` in TypeScript and Java, `max_dispatches_per_second` in Python, `MaxDispatchesPerSecond` in Go and .NET). **TypeScript** ```ts const pq = new Pushq({ apiKey: process.env.PUSHQ_API_KEY }); ``` **Python** ```python import os from pushq import Pushq, RateLimits, Retry, Target pq = Pushq(api_key=os.environ["PUSHQ_API_KEY"]) ``` **Go** ```go import pushq "github.com/blissfulrays/pushq/sdks/go" pq := pushq.New("", os.Getenv("PUSHQ_API_KEY")) // "" = hosted API ctx := context.Background() ``` **Java** ```java import io.pushq.*; Pushq pq = Pushq.builder().apiKey(System.getenv("PUSHQ_API_KEY")).build(); ``` **.NET** ```csharp using Pushq; using var pq = new PushqClient(apiKey: Environment.GetEnvironmentVariable("PUSHQ_API_KEY")); ``` **curl** ```bash export PUSHQ_API_KEY=pq_... ``` ## Create a queue There are two ways to create a queue. ### Create or update a queue with PUT (upsert) `PUT /v1/queues/{queue}` is an idempotent upsert. It creates the queue if it doesn't exist and replaces its configuration if it does. It is cheap enough to call before every enqueue, so your code never has to check whether a queue exists. **TypeScript** ```ts await pq.upsertQueue("emails", { rateLimits: { maxDispatchesPerSecond: 10, maxConcurrentDispatches: 5 }, retry: { maxAttempts: 5, minBackoffSeconds: 1, maxBackoffSeconds: 300 }, target: { baseUrl: "https://api.example.com" }, }); ``` **Python** ```python pq.upsert_queue( "emails", rate_limits=RateLimits(max_dispatches_per_second=10, max_concurrent_dispatches=5), retry=Retry(max_attempts=5, min_backoff_seconds=1, max_backoff_seconds=300), target=Target(base_url="https://api.example.com"), ) ``` **Go** ```go _, err := pq.UpsertQueue(ctx, "emails", pushq.QueueConfig{ RateLimits: &pushq.RateLimits{ MaxDispatchesPerSecond: pushq.Float64(10), MaxConcurrentDispatches: pushq.Int(5), }, Retry: &pushq.Retry{ MaxAttempts: pushq.Int(5), MinBackoffSeconds: pushq.Float64(1), MaxBackoffSeconds: pushq.Float64(300), }, Target: &pushq.Target{BaseURL: "https://api.example.com"}, }) ``` **Java** ```java pq.upsertQueue("emails", QueueConfig.builder() .rateLimits(RateLimits.builder().maxDispatchesPerSecond(10).maxConcurrentDispatches(5).build()) .retry(RetryConfig.builder().maxAttempts(5).minBackoffSeconds(1).maxBackoffSeconds(300).build()) .target(Target.builder().baseUrl("https://api.example.com").build()) .build()); ``` **.NET** ```csharp await pq.UpsertQueueAsync("emails", new QueueConfig { RateLimits = new RateLimits { MaxDispatchesPerSecond = 10, MaxConcurrentDispatches = 5 }, Retry = new RetryConfig { MaxAttempts = 5, MinBackoffSeconds = 1, MaxBackoffSeconds = 300 }, Target = new Target { BaseUrl = "https://api.example.com" }, }); ``` **curl** ```bash curl -X PUT https://api.pushqueue.dev/v1/queues/emails \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{ "rate_limits": {"max_dispatches_per_second": 10, "max_concurrent_dispatches": 5}, "retry": {"max_attempts": 5, "min_backoff_seconds": 1, "max_backoff_seconds": 300}, "target": {"base_url": "https://api.example.com"} }' ``` The response is the queue. The status is `201` when the queue was created and `200` otherwise, and the `X-Pushq-Result` header says what happened: `created`, `updated` or `unchanged`. PUT never changes the queue's [state](#queue-states), so calling it on every enqueue can't accidentally resume a paused queue. :::caution PUT sets the **whole** configuration. Any field you leave out goes back to its default: if you PUT only `rate_limits`, the retry settings reset to defaults and `target.base_url`, `target.headers` and `dead_letter_queue` are cleared. The one exception is `target.signing_secret`, which is kept when omitted. To change a single field, use [PATCH](#update-queue-settings-with-patch). ::: ### Create a queue only if it doesn't exist (POST) `POST /v1/queues` creates a queue and fails with `409 already_exists` if the name is taken. The body is the same as PUT plus a `name` field. **TypeScript** ```ts await pq.createQueue("emails", { rateLimits: { maxDispatchesPerSecond: 10 } }); ``` **Python** ```python pq.create_queue("emails", rate_limits=RateLimits(max_dispatches_per_second=10)) ``` **Go** ```go _, err := pq.CreateQueue(ctx, "emails", pushq.QueueConfig{ RateLimits: &pushq.RateLimits{MaxDispatchesPerSecond: pushq.Float64(10)}, }) ``` **Java** ```java pq.createQueue("emails", QueueConfig.builder() .rateLimits(RateLimits.builder().maxDispatchesPerSecond(10).build()) .build()); ``` **.NET** ```csharp await pq.CreateQueueAsync("emails", new QueueConfig { RateLimits = new RateLimits { MaxDispatchesPerSecond = 10 }, }); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{"name": "emails", "rate_limits": {"max_dispatches_per_second": 10}}' ``` Use this when creating a queue that already exists should be an error, for example in a provisioning script. New queues always start in the `running` state. ## Queue configuration reference All fields are optional. Omitted fields take the default shown. ### Rate limit settings | Parameter | Type | Default | Description | |---|---|---|---| | `rate_limits.max_dispatches_per_second` | number | `500` | Token refill rate. Must be greater than 0 and at most 10000. Fractions are allowed: `0.5` is one dispatch every two seconds. | | `rate_limits.max_burst_size` | integer | `0` (auto) | Token bucket size, 0 to 10000. `0` means auto: `max_dispatches_per_second` rounded up, between 1 and 500. Responses always show the resolved value. | | `rate_limits.max_concurrent_dispatches` | integer | `1000` | Maximum requests in flight at once for this queue, 1 to 10000. | How these interact, and how to pick values, is covered in the [Rate limits guide](https://pushqueue.dev/docs/guides/rate-limits/). :::note Because responses show the resolved burst, reading a queue and sending its `rate_limits` back in a PUT turns an auto burst into a fixed one. Send `max_burst_size: 0` (or omit it) to keep it automatic. ::: ### Retry settings | Parameter | Type | Default | Description | |---|---|---|---| | `retry.max_attempts` | integer | `100` | Total attempts, including the first. `-1` means unlimited. `0` is rejected. | | `retry.max_retry_duration_seconds` | number | `0` (unlimited) | How long after the first attempt retries may continue. Must be 0 or more. | | `retry.min_backoff_seconds` | number | `0.1` | Delay before the first retry. Must be 0 or more. | | `retry.max_backoff_seconds` | number | `3600` | Upper bound on any delay. Must be at least `min_backoff_seconds`. | | `retry.max_doublings` | integer | `16` | How many times the delay doubles before growing linearly, 0 to 31. | The exact schedule, and how `max_attempts` and `max_retry_duration_seconds` combine, are explained in [Retries](https://pushqueue.dev/docs/concepts/retries/). Tasks can override any of these individually. ### Target settings: base URL, method, headers and signing secret | Parameter | Type | Default | Description | |---|---|---|---| | `target.base_url` | string | none | Absolute `http` or `https` URL. Tasks created with a relative `path` are sent to `base_url` + `path`. Without it, every task must have an absolute `url`. | | `target.method` | string | none | When set, overrides every task's HTTP method. One of `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`. | | `target.headers` | object | none | Headers added to every delivery. They win over task headers with the same name. At most 16 KiB in total (names plus values). | | `target.signing_secret` | string | none | Standard Webhooks secret (`whsec_...`). When set, every delivery is signed. Never returned; responses show `has_signing_secret` instead. | The target is applied at delivery time, so changing `base_url` or `headers` affects tasks that are already queued. See [Delivery](https://pushqueue.dev/docs/concepts/delivery/) for the full request pushq sends. `target.headers` can't contain `Host`, `Content-Length`, `Transfer-Encoding`, `Connection`, `Keep-Alive`, `Upgrade`, `TE` or `Trailer`, and values can't contain control characters such as CR, LF or NUL. `signing_secret` has special update rules: omit it to keep the stored secret, send `""` to remove it. ### Dead-letter queue | Parameter | Type | Default | Description | |---|---|---|---| | `dead_letter_queue` | string | none | Name of another queue that receives a copy of each task that runs out of retries. Can't be the queue itself. | See [Dead-letter queues](https://pushqueue.dev/docs/concepts/dead-letter-queues/). ### Queue name rules Names are lowercase and made of one or more segments separated by `/`. Each segment matches `[a-z0-9][a-z0-9-]*` (starts with a letter or digit, then letters, digits and hyphens). The whole name is at most 200 characters. See [Folders](#queue-folders). ## Update queue settings with PATCH `PATCH /v1/queues/{queue}` changes only the fields you send and leaves everything else alone. The merged result is validated before it is saved, so a PATCH can never leave a queue with invalid settings. **TypeScript** ```ts await pq.patchQueue("emails", { rateLimits: { maxDispatchesPerSecond: 2 } }); ``` **Python** ```python pq.patch_queue("emails", rate_limits=RateLimits(max_dispatches_per_second=2)) ``` **Go** ```go _, err := pq.PatchQueue(ctx, "emails", pushq.QueueConfig{ RateLimits: &pushq.RateLimits{MaxDispatchesPerSecond: pushq.Float64(2)}, }, "") // last argument: new state, "" = unchanged ``` **Java** ```java pq.patchQueue("emails", QueuePatch.builder() .rateLimits(RateLimits.builder().maxDispatchesPerSecond(2).build()) .build()); ``` **.NET** ```csharp await pq.PatchQueueAsync("emails", new QueuePatch { RateLimits = new RateLimits { MaxDispatchesPerSecond = 2 }, }); ``` **curl** ```bash curl -X PATCH https://api.pushqueue.dev/v1/queues/emails \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{"rate_limits": {"max_dispatches_per_second": 2}}' ``` PATCH differs from PUT in these ways (Go's `PatchQueue` only sends non-empty strings, so it can't clear `base_url`, `method`, `headers` or `dead_letter_queue`; use the HTTP API for that, or `ClearSigningSecret: true` for the secret): - It accepts a `state` field: `running`, `paused` or `disabled`. - `target.headers`, when sent, replaces the whole header map. Send `{}` to remove all queue headers. - `target.signing_secret: ""` removes the secret, `target.base_url: ""` removes the base URL, and `dead_letter_queue: ""` removes the dead-letter queue. Changes take effect for the next dispatch, including tasks already waiting in the queue. Use this when you want to adjust one setting at runtime, such as lowering a rate limit during an incident. ## Queue states | State | Accepts new tasks | Dispatches tasks | `:run` works | |---|---|---|---| | `running` | Yes | Yes | Yes | | `paused` | Yes | No | Yes | | `disabled` | No (`400 failed_precondition`) | No | No (`400 failed_precondition`) | In every state you can still read the queue, list its tasks, read stats, change its configuration and purge it. Pausing or disabling a queue doesn't interrupt requests already in flight; they finish normally. If one of them fails, its retry is scheduled and waits until the queue runs again. ### Pause and resume a queue **TypeScript** ```ts await pq.pauseQueue("emails"); await pq.resumeQueue("emails"); ``` **Python** ```python pq.pause_queue("emails") pq.resume_queue("emails") ``` **Go** ```go _, err := pq.PauseQueue(ctx, "emails") _, err = pq.ResumeQueue(ctx, "emails") ``` **Java** ```java pq.pauseQueue("emails"); pq.resumeQueue("emails"); ``` **.NET** ```csharp await pq.PauseQueueAsync("emails"); await pq.ResumeQueueAsync("emails"); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/emails:pause \ -H "Authorization: Bearer $PUSHQ_API_KEY" curl -X POST https://api.pushqueue.dev/v1/queues/emails:resume \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` Both return the queue. Pausing a `disabled` queue fails with `400 failed_precondition`; `:resume` moves a queue from either `paused` or `disabled` back to `running`. Use pause when the endpoint is down or misbehaving and you want tasks to pile up safely instead of using up their retries. Tasks whose time has passed are delivered as soon as you resume, within the queue's rate limits. ### Disable a queue There is no `:disable` endpoint; set the state with PATCH: **TypeScript** ```ts await pq.patchQueue("emails", { state: "disabled" }); ``` **Python** ```python pq.patch_queue("emails", state="disabled") ``` **Go** ```go _, err := pq.PatchQueue(ctx, "emails", pushq.QueueConfig{}, "disabled") ``` **Java** ```java pq.patchQueue("emails", QueuePatch.builder().state("disabled").build()); ``` **.NET** ```csharp await pq.PatchQueueAsync("emails", new QueuePatch { State = QueueState.Disabled }); ``` **curl** ```bash curl -X PATCH https://api.pushqueue.dev/v1/queues/emails \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{"state": "disabled"}' ``` Use this when producers must stop enqueuing to a queue, for example while you retire it. Re-enable it with `:resume` or a PATCH to `running`. ## Purge all tasks from a queue `POST /v1/queues/{queue}:purge` deletes every task created up to now, in any state (pending, running, succeeded or failed). It answers `202` with the queue; `purged_at` shows the purge time. **TypeScript** ```ts await pq.purgeQueue("emails"); ``` **Python** ```python pq.purge_queue("emails") ``` **Go** ```go _, err := pq.PurgeQueue(ctx, "emails") ``` **Java** ```java pq.purgeQueue("emails"); ``` **.NET** ```csharp await pq.PurgeQueueAsync("emails"); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/emails:purge \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` How it behaves: - The cut-off is exact: every task created before the purge disappears from the API immediately, and the rows are removed in the background. - Tasks created after the purge are not affected, even within the same millisecond. - Requests already in flight can still reach your endpoint, but their results are discarded and they are not retried. - Task IDs of purged tasks can be reused right away, without waiting for the [dedup window](https://pushqueue.dev/docs/concepts/tasks/#task-ids-and-deduplication). - The queue's configuration and state are unchanged. Use this to throw away a backlog you no longer want delivered, such as tasks built from bad data. ## Delete a queue `DELETE /v1/queues/{queue}` deletes the queue together with all of its tasks and their attempt history. It answers `204`. The name can be reused immediately. **TypeScript** ```ts await pq.deleteQueue("emails"); ``` **Python** ```python pq.delete_queue("emails") ``` **Go** ```go err := pq.DeleteQueue(ctx, "emails") ``` **Java** ```java pq.deleteQueue("emails"); ``` **.NET** ```csharp await pq.DeleteQueueAsync("emails"); ``` **curl** ```bash curl -X DELETE https://api.pushqueue.dev/v1/queues/emails \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` Deleting needs more than write access: admin API keys and admin or member dashboard users can delete queues; writer API keys get `403 permission_denied`. Requests already in flight may still reach your endpoint, but their results are discarded. ## Get and list queues `GET /v1/queues/{queue}` returns one queue. Any role can read a queue it knows by name. `GET /v1/queues` lists queues in name order: | Query parameter | Default | Description | |---|---|---| | `name_prefix` | none | Only queues whose name starts with this string, such as `tenants/`. | | `page_size` | `100` | Results per page, up to 1000. | | `page_token` | none | `next_page_token` from the previous page. | **TypeScript** ```ts let pageToken: string | undefined; do { const page = await pq.listQueues({ namePrefix: "tenants/", pageToken }); for (const q of page.items) console.log(q.name, q.state); pageToken = page.nextPageToken; } while (pageToken); ``` **Python** ```python page_token = None while True: page = pq.list_queues(name_prefix="tenants/", page_token=page_token) for q in page.items: print(q.name, q.state) page_token = page.next_page_token if not page_token: break ``` **Go** ```go token := "" for { queues, next, err := pq.ListQueues(ctx, pushq.ListQueuesParams{NamePrefix: "tenants/", PageToken: token}) if err != nil { return err } for _, q := range queues { fmt.Println(q.Name, q.State) } if next == "" { break } token = next } ``` **Java** ```java String token = null; do { QueuePage page = pq.listQueues(ListQueuesParams.builder().namePrefix("tenants/").pageToken(token).build()); for (Queue q : page.getQueues()) System.out.println(q.getName() + " " + q.getState()); token = page.getNextPageToken(); } while (token != null && !token.isEmpty()); ``` **.NET** ```csharp string? token = null; do { var page = await pq.ListQueuesAsync(new ListQueuesOptions { NamePrefix = "tenants/", PageToken = token }); foreach (var q in page.Items) Console.WriteLine($"{q.Name} {q.State}"); token = page.NextPageToken; } while (token != null); ``` **curl** ```bash curl "https://api.pushqueue.dev/v1/queues?name_prefix=tenants/" \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` Listing needs list permission: admin API keys and every dashboard user have it, writer API keys don't. Writer keys are meant for apps that work with queues they already know by name. A queue response looks like this: ```json { "name": "emails", "state": "running", "rate_limits": {"max_dispatches_per_second": 10, "max_burst_size": 10, "max_concurrent_dispatches": 5}, "retry": {"max_attempts": 5, "max_retry_duration_seconds": 0, "min_backoff_seconds": 1, "max_backoff_seconds": 300, "max_doublings": 16}, "target": {"base_url": "https://api.example.com", "has_signing_secret": false}, "created_at": "2026-11-28T10:00:00Z", "updated_at": "2026-11-28T10:00:00Z" } ``` `target.method`, `target.headers`, `dead_letter_queue` and `purged_at` appear when set. ## Queue folders A `/` in a queue name puts the queue in a folder: `user/instagram` is an `instagram` queue in a `user` folder, and folders can nest (`user/tiktok/eu`). Folders are only part of the name. They need no setup, have no settings of their own, and exist as long as some queue name uses them. Each queue in a folder is still independent, with its own limits and retry settings. In API paths, the whole name is a single path segment, so encode `/` as `%2F`. The SDKs do this for you, so pass the name as is: **TypeScript** ```ts await pq.upsertQueue("user/instagram", { target: { baseUrl: "https://api.example.com" } }); await pq.createTask("user/instagram", { path: "/hooks/post" }); ``` **Python** ```python pq.upsert_queue("user/instagram", target=Target(base_url="https://api.example.com")) pq.create_task("user/instagram", path="/hooks/post") ``` **Go** ```go _, err := pq.UpsertQueue(ctx, "user/instagram", pushq.QueueConfig{ Target: &pushq.Target{BaseURL: "https://api.example.com"}, }) _, err = pq.CreateTask(ctx, "user/instagram", pushq.TaskCreate{Path: "/hooks/post"}) ``` **Java** ```java pq.upsertQueue("user/instagram", QueueConfig.builder() .target(Target.builder().baseUrl("https://api.example.com").build()) .build()); pq.createTask("user/instagram", TaskCreate.builder().path("/hooks/post").build()); ``` **.NET** ```csharp await pq.UpsertQueueAsync("user/instagram", new QueueConfig { Target = new Target { BaseUrl = "https://api.example.com" }, }); await pq.CreateTaskAsync("user/instagram", new TaskCreate { Path = "/hooks/post" }); ``` **curl** ```bash curl -X PUT https://api.pushqueue.dev/v1/queues/user%2Finstagram \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{"target": {"base_url": "https://api.example.com"}}' curl -X POST https://api.pushqueue.dev/v1/queues/user%2Finstagram/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{"path": "/hooks/post"}' ``` If you send the `/` unencoded, the API answers `404` with a hint to URL-encode the name. In query strings such as `name_prefix=user/`, no encoding is needed. :::caution If you self-host pushq behind a reverse proxy, the proxy must forward `%2F` unchanged. Caddy does by default. With nginx, use `proxy_pass http://127.0.0.1:8080;` with no URI part; a trailing `/` makes nginx decode `%2F` into `/`, and the request then fails with 404. See [deploying pushq behind a proxy](https://pushqueue.dev/docs/self-hosting/deploy/). ::: Use folders to group many related queues, such as one queue per customer under `tenants/`, and to list or monitor them together with `name_prefix`. ## Queue stats and monitoring `GET /v1/queues/{queue}/stats` returns live counts for a queue without listing its tasks. Add `id_prefix` to count only tasks whose ID starts with a prefix. **TypeScript** ```ts const stats = await pq.queueStats("emails", { idPrefix: "invoice-" }); ``` **Python** ```python stats = pq.queue_stats("emails", id_prefix="invoice-") ``` **Go** ```go stats, err := pq.QueueStats(ctx, "emails", "invoice-") ``` **Java** ```java QueueStats stats = pq.queueStats("emails", "invoice-"); ``` **.NET** ```csharp var stats = await pq.GetQueueStatsAsync("emails", idPrefix: "invoice-"); ``` **curl** ```bash curl "https://api.pushqueue.dev/v1/queues/emails/stats?id_prefix=invoice-" \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` ```json { "state": "running", "pending": 12, "running": 3, "succeeded": 4810, "failed": 2, "scheduled_future": 140, "oldest_due_at": "2026-11-28T10:00:00Z", "oldest_due_age_seconds": 4.2, "dispatched_last_1m": 95, "errors_last_1m": 1, "dispatched_last_1h": 5120, "errors_last_1h": 30 } ``` | Field | Description | |---|---| | `state` | The queue's state: `running`, `paused` or `disabled`. | | `pending` | Tasks that are due now or overdue and waiting to be dispatched, including retries whose time has come. | | `running` | Tasks currently being delivered. | | `succeeded` | Succeeded tasks still retained (24 hours by default on a self-hosted server). | | `failed` | Failed tasks still retained (7 days by default on a self-hosted server). | | `scheduled_future` | Pending tasks scheduled for later, including those waiting for a retry. | | `oldest_due_at` | Schedule time of the oldest due task. Omitted when nothing is due. | | `oldest_due_age_seconds` | How long that task has been waiting past its schedule time. A growing value means the queue is falling behind. | | `dispatched_last_1m` / `dispatched_last_1h` | Delivery attempts started in the last minute / hour. | | `errors_last_1m` / `errors_last_1h` | Of those attempts, how many did not get a 2xx response (non-2xx status, timeout or connection error). | | `last_purge` | Time of the last purge. Omitted if the queue was never purged. | Purged and deleted tasks are not counted. Use stats for dashboards and alerts: alert on `oldest_due_age_seconds` for lag and on `errors_last_1m` for a failing endpoint. ## Read more - [Tasks, scheduling and deduplication](https://pushqueue.dev/docs/concepts/tasks/): what goes into a queue. - [Rate limits and concurrency](https://pushqueue.dev/docs/guides/rate-limits/): choose `rate_limits` values. - [Retry backoff and max attempts](https://pushqueue.dev/docs/concepts/retries/): how the `retry` settings play out. - [Per-tenant queues](https://pushqueue.dev/docs/patterns/per-tenant-queues/): one queue per customer with folders. - [Dead-letter queues](https://pushqueue.dev/docs/concepts/dead-letter-queues/): keep tasks that run out of retries. --- # Tasks, scheduling and deduplication > Enqueue HTTP tasks with pushq: task fields, delayed and scheduled tasks, deduplication with task_id, batch enqueue, run now, cancel and size limits. Source: https://pushqueue.dev/docs/concepts/tasks/ A pushq task is one HTTP request that pushq makes for you: a URL, a method, headers and a body, plus when to send it and how to retry it. This page covers enqueuing tasks, delayed and scheduled tasks, deduplication with `task_id`, batch enqueue, and inspecting, running and cancelling tasks. Tasks live in a [queue](https://pushqueue.dev/docs/concepts/queues/), whose rate limits and retry settings decide when each task is delivered. The examples assume a client named `pq` (and a `ctx` in Go); see [Install & configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/). Tables use the JSON field names; the SDKs use their language's casing (`taskId` in TypeScript and Java, `task_id` in Python, `TaskID`/`TaskId` in Go and .NET). ## Enqueue a task `POST /v1/queues/{queue}/tasks` creates one task and answers `201` with it. **TypeScript** ```ts const task = await pq.createTask("emails", { path: "/hooks/send-welcome", jsonBody: { userId: 42 }, delaySeconds: 3600, taskId: "welcome-user-42", retry: { maxAttempts: 5 }, }); ``` **Python** ```python from pushq import Retry task = pq.create_task( "emails", path="/hooks/send-welcome", json_body={"user_id": 42}, delay_seconds=3600, task_id="welcome-user-42", retry=Retry(max_attempts=5), ) ``` **Go** ```go task, err := pq.CreateTask(ctx, "emails", pushq.TaskCreate{ Path: "/hooks/send-welcome", JSONBody: map[string]any{"user_id": 42}, DelaySeconds: pushq.Float64(3600), TaskID: "welcome-user-42", Retry: &pushq.Retry{MaxAttempts: pushq.Int(5)}, }) ``` **Java** ```java Task task = pq.createTask("emails", TaskCreate.builder() .path("/hooks/send-welcome") .jsonBody(Map.of("user_id", 42)) .delaySeconds(3600) .taskId("welcome-user-42") .retry(RetryConfig.builder().maxAttempts(5).build()) .build()); ``` **.NET** ```csharp var task = await pq.CreateTaskAsync("emails", new TaskCreate { Path = "/hooks/send-welcome", JsonBody = new { user_id = 42 }, Delay = TimeSpan.FromHours(1), TaskId = "welcome-user-42", Retry = new RetryConfig { MaxAttempts = 5 }, }); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/emails/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{ "path": "/hooks/send-welcome", "json_body": {"user_id": 42}, "delay_seconds": 3600, "task_id": "welcome-user-42", "retry": {"max_attempts": 5} }' ``` ### Task fields reference | Parameter | Type | Default | Description | |---|---|---|---| | `url` | string | none | Absolute `http` or `https` URL, at most 2083 characters. Set exactly one of `url` or `path`. | | `path` | string | none | Path starting with `/`, appended to the queue's `target.base_url` at delivery time. The queue must have a `base_url` when you create the task. | | `method` | string | `POST` | `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD` or `OPTIONS` (case-insensitive). A queue `target.method` overrides it. | | `headers` | object | none | Headers sent with the request. Queue `target.headers` with the same name win. | | `json_body` | any JSON value | none | Body sent as JSON. Adds `Content-Type: application/json` unless you set a `Content-Type` header yourself. | | `body_base64` | string | none | Raw body bytes, base64-encoded (standard alphabet). Use for non-JSON payloads. The SDKs take raw bytes and encode them for you. | | `schedule_time` | string (RFC 3339) | now | When to deliver. A time in the past means "now". | | `delay_seconds` | number | `0` | Deliver this many seconds from now. Must be 0 or more. (.NET takes a `TimeSpan` named `Delay`.) | | `dispatch_deadline_seconds` | number | `600` | How long to wait for a response on each attempt, 15 to 1800 seconds. (.NET takes a `TimeSpan` named `DispatchDeadline`.) | | `task_id` | string | generated | Your ID for the task, used for [deduplication](#task-ids-and-deduplication). | | `retry` | object | queue settings | Per-task override of any [retry field](https://pushqueue.dev/docs/concepts/retries/#per-task-retry-overrides). | Rules the API enforces (each violation is `400 invalid_argument`): - Exactly one of `url` or `path`. A `path` on a queue without `target.base_url` is `400 failed_precondition`. - At most one of `json_body` or `body_base64`. - At most one of `schedule_time` or `delay_seconds`. - A body is only allowed with `POST`, `PUT` or `PATCH`. - Header names must be valid HTTP tokens, values can't contain control characters such as CR, LF or NUL, and `Host`, `Content-Length`, `Transfer-Encoding`, `Connection`, `Keep-Alive`, `Upgrade`, `TE` and `Trailer` are reserved. ### Send to an absolute URL with a custom method, headers and body **TypeScript** ```ts await pq.createTask("webhooks", { url: "https://hooks.example.com/orders", method: "PUT", headers: { "Content-Type": "text/csv", "X-Source": "billing" }, body: "id,total\n1,9.99\n", scheduleTime: new Date("2026-12-24T09:00:00Z"), dispatchDeadlineSeconds: 120, }); ``` **Python** ```python from datetime import datetime, timezone pq.create_task( "webhooks", url="https://hooks.example.com/orders", method="PUT", headers={"Content-Type": "text/csv", "X-Source": "billing"}, body=b"id,total\n1,9.99\n", schedule_time=datetime(2026, 12, 24, 9, 0, tzinfo=timezone.utc), dispatch_deadline_seconds=120, ) ``` **Go** ```go at := time.Date(2026, 12, 24, 9, 0, 0, 0, time.UTC) _, err := pq.CreateTask(ctx, "webhooks", pushq.TaskCreate{ URL: "https://hooks.example.com/orders", Method: "PUT", Headers: map[string]string{"Content-Type": "text/csv", "X-Source": "billing"}, Body: []byte("id,total\n1,9.99\n"), ScheduleTime: &at, DispatchDeadlineSeconds: pushq.Float64(120), }) ``` **Java** ```java pq.createTask("webhooks", TaskCreate.builder() .url("https://hooks.example.com/orders") .method("PUT") .header("Content-Type", "text/csv") .header("X-Source", "billing") .body("id,total\n1,9.99\n".getBytes(StandardCharsets.UTF_8)) .scheduleTime(Instant.parse("2026-12-24T09:00:00Z")) .dispatchDeadlineSeconds(120) .build()); ``` **.NET** ```csharp await pq.CreateTaskAsync("webhooks", new TaskCreate { Url = "https://hooks.example.com/orders", Method = "PUT", Headers = new Dictionary { ["Content-Type"] = "text/csv", ["X-Source"] = "billing" }, Body = Encoding.UTF8.GetBytes("id,total\n1,9.99\n"), ScheduleTime = new DateTimeOffset(2026, 12, 24, 9, 0, 0, TimeSpan.Zero), DispatchDeadline = TimeSpan.FromSeconds(120), }); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/webhooks/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{ "url": "https://hooks.example.com/orders", "method": "PUT", "headers": {"Content-Type": "text/csv", "X-Source": "billing"}, "body_base64": "aWQsdG90YWwKMSw5Ljk5Cg==", "schedule_time": "2026-12-24T09:00:00Z", "dispatch_deadline_seconds": 120 }' ``` A raw body without a `Content-Type` header is delivered as `application/octet-stream`. ### Choose between url and path Use `url` when tasks in one queue go to different hosts. Use `path` with a queue `target.base_url` when they all go to one service: producers don't need to know the host, and changing `base_url` re-points every queued task, because the path is resolved when the task is delivered, not when it is created. A queue with `base_url` `https://api.example.com` and a task with `path` `/hooks/send` delivers to `https://api.example.com/hooks/send`. ### Delayed and scheduled tasks Without `schedule_time` or `delay_seconds`, a task is due immediately. With either, it waits until that time and is then delivered as soon as the queue's rate limits allow. Use this for reminders, delayed follow-ups and anything you want to run at a set time without a cron job. See [scheduling and cancelling tasks](https://pushqueue.dev/docs/patterns/scheduling-and-cancelling/) for a full example. ### Dispatch deadline (request timeout) `dispatch_deadline_seconds` is how long pushq waits for your endpoint to respond on each attempt. If no response arrives in time, the attempt counts as a failure (`timeout`) and is retried. Raise it for slow handlers; the maximum is 30 minutes. ## Task IDs and deduplication If you don't set `task_id`, the server generates a UUIDv7. If you do, it must match `[A-Za-z0-9_-]{1,500}` and be unique within the queue: creating a second task with an ID that is still reserved fails with `409 already_exists`. **TypeScript** ```ts try { await pq.createTask("emails", { path: "/hooks/receipt", taskId: "receipt-1001" }); } catch (err) { if (!(err instanceof PushqError && err.code === "already_exists")) throw err; // Already enqueued: safe to ignore. } ``` **Python** ```python from pushq import PushqError try: pq.create_task("emails", path="/hooks/receipt", task_id="receipt-1001") except PushqError as err: if err.code != "already_exists": raise # Already enqueued: safe to ignore. ``` **Go** ```go _, err := pq.CreateTask(ctx, "emails", pushq.TaskCreate{Path: "/hooks/receipt", TaskID: "receipt-1001"}) if err != nil && !pushq.IsCode(err, "already_exists") { return err } // already_exists: already enqueued, safe to ignore. ``` **Java** ```java try { pq.createTask("emails", TaskCreate.builder().path("/hooks/receipt").taskId("receipt-1001").build()); } catch (PushqException e) { if (!"already_exists".equals(e.getCode())) throw e; // Already enqueued: safe to ignore. } ``` **.NET** ```csharp try { await pq.CreateTaskAsync("emails", new TaskCreate { Path = "/hooks/receipt", TaskId = "receipt-1001" }); } catch (PushqException e) when (e.Code == "already_exists") { // Already enqueued: safe to ignore. } ``` **curl** ```bash # A second identical request answers 409 with "code": "already_exists" curl -X POST https://api.pushqueue.dev/v1/queues/emails/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{"path": "/hooks/receipt", "task_id": "receipt-1001"}' ``` An ID stays reserved for as long as the task exists, and a task is kept for a while after it finishes. With a self-hosted server's default settings (the hosted API may use different values): | The task... | ID reserved until | |---|---| | is pending or running | it finishes | | succeeded | 24 hours after it finished | | failed | 7 days after it finished | | was deleted | 1 hour after deletion (the dedup window) | | was purged | free immediately | Retention never drops below the dedup window (1 hour by default), so an ID always stays reserved for at least that long after the task finishes or is deleted. Self-hosters can change these with the `limits.dedup_window` and `retention.*` settings; see [server configuration](https://pushqueue.dev/docs/self-hosting/configuration/). Use a deterministic `task_id` built from your own record ID when the same event might be enqueued twice, for example by a retried request or two workers, and you want it delivered once. The [deduplication pattern](https://pushqueue.dev/docs/patterns/deduplication/) shows how to build good IDs. ## Task states and lifecycle | State | Meaning | |---|---| | `pending` | Waiting for its schedule time, for a retry, or for the queue's rate limits. | | `running` | Being delivered right now. | | `succeeded` | Got a 2xx response. Final. | | `failed` | Ran out of retries. Final. | A task moves from `pending` to `running`, then to `succeeded`, or back to `pending` with a later schedule time when an attempt fails and retries remain. When retries run out it becomes `failed` and is copied to the queue's [dead-letter queue](https://pushqueue.dev/docs/concepts/dead-letter-queues/), if it has one. Deleted and purged tasks disappear from the API. ## Batch enqueue up to 500 tasks `POST /v1/queues/{queue}/tasks:batch` creates up to 500 tasks in one request. **TypeScript** ```ts const results = await pq.createTasks("emails", [ { path: "/hooks/digest", jsonBody: { userId: 1 }, taskId: "digest-1" }, { path: "/hooks/digest", jsonBody: { userId: 2 }, taskId: "digest-2" }, ]); for (const r of results) { if (r.error) console.error(`item ${r.index}: ${r.error.code} ${r.error.detail}`); } ``` **Python** ```python results = pq.create_tasks("emails", [ {"path": "/hooks/digest", "json_body": {"user_id": 1}, "task_id": "digest-1"}, {"path": "/hooks/digest", "json_body": {"user_id": 2}, "task_id": "digest-2"}, ]) for r in results: if r.error: print(f"item {r.index}: {r.error.code} {r.error.detail}") ``` **Go** ```go results, err := pq.CreateTasks(ctx, "emails", []pushq.TaskCreate{ {Path: "/hooks/digest", JSONBody: map[string]any{"user_id": 1}, TaskID: "digest-1"}, {Path: "/hooks/digest", JSONBody: map[string]any{"user_id": 2}, TaskID: "digest-2"}, }) for _, r := range results { if r.Error != nil { log.Printf("item %d: %s %s", r.Index, r.Error.Code, r.Error.Detail) } } ``` **Java** ```java List results = pq.createTasks("emails", List.of( TaskCreate.builder().path("/hooks/digest").jsonBody(Map.of("user_id", 1)).taskId("digest-1").build(), TaskCreate.builder().path("/hooks/digest").jsonBody(Map.of("user_id", 2)).taskId("digest-2").build())); for (BatchResult r : results) { if (!r.isSuccess()) System.err.println("item " + r.getIndex() + ": " + r.getError().getCode()); } ``` **.NET** ```csharp var results = await pq.CreateTasksAsync("emails", new[] { new TaskCreate { Path = "/hooks/digest", JsonBody = new { user_id = 1 }, TaskId = "digest-1" }, new TaskCreate { Path = "/hooks/digest", JsonBody = new { user_id = 2 }, TaskId = "digest-2" }, }); foreach (var r in results) if (r.Error != null) Console.Error.WriteLine($"item {r.Index}: {r.Error.Code} {r.Error.Detail}"); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/emails/tasks:batch \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{"tasks": [ {"path": "/hooks/digest", "json_body": {"user_id": 1}, "task_id": "digest-1"}, {"path": "/hooks/digest", "json_body": {"user_id": 2}, "task_id": "digest-2"} ]}' ``` The batch is **not atomic**. Each item succeeds or fails on its own, and the response has one result per item, in request order: ```json { "results": [ {"index": 0, "task": {"id": "digest-1", "state": "pending"}}, {"index": 1, "error": {"code": "already_exists", "detail": "already exists"}} ] } ``` Item error codes are `invalid_argument`, `already_exists`, `not_found`, `failed_precondition` (for example, the queue is disabled) and `internal`. The request answers `200` even when some items fail. It fails as a whole only if `tasks` is empty or has more than 500 items, the queue doesn't exist, or the request body exceeds 8 MiB. Use batches for fan-out jobs, such as one task per user, where a duplicate or invalid item should not block the rest. For more than 500 tasks, see [bulk enqueue](https://pushqueue.dev/docs/patterns/bulk-enqueue/). ## Get a task `GET /v1/queues/{queue}/tasks/{task_id}` returns one task. By default headers and body are left out; the full view (`?view=full`) includes them. **TypeScript** ```ts const t = await pq.getTask("emails", "welcome-user-42", { view: "full" }); console.log(t.state, t.dispatchCount, t.lastAttempt); ``` **Python** ```python t = pq.get_task("emails", "welcome-user-42", view="full") print(t.state, t.dispatch_count, t.last_attempt) ``` **Go** ```go t, err := pq.GetTaskFull(ctx, "emails", "welcome-user-42") // GetTask for the basic view ``` **Java** ```java Task t = pq.getTaskFull("emails", "welcome-user-42"); // getTask for the basic view ``` **.NET** ```csharp var t = await pq.GetTaskAsync("emails", "welcome-user-42", TaskView.Full); ``` **curl** ```bash curl "https://api.pushqueue.dev/v1/queues/emails/tasks/welcome-user-42?view=full" \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` | Field | Description | |---|---| | `id`, `queue`, `state` | Identity and current state. | | `url`, `method` | As created. `url` holds the path for path-based tasks. | | `headers`, `body_base64` | Only in the full view. | | `schedule_time` | When the task is (or was) due. Each retry moves it forward. | | `created_at` | When the task was created. | | `dispatch_deadline_seconds` | Effective deadline per attempt. | | `retry` | The per-task override, if one was set. | | `dispatch_count` | Attempts started so far. | | `response_count` | Attempts that got an HTTP response (any status). | | `first_attempt_at` | Time of the first attempt. | | `finished_at` | When the task succeeded or failed. | | `last_attempt` | `at`, plus `status` (HTTP status, if any) and `error` (error kind and a snippet). | ## List and filter tasks `GET /v1/queues/{queue}/tasks` lists tasks, newest first. | Query parameter | Default | Description | |---|---|---| | `state` | all | `pending`, `running`, `succeeded` or `failed`. | | `id_prefix` | none | Only tasks whose ID starts with this string. | | `view` | `basic` | `full` includes headers and bodies. | | `page_size` | `100` | Up to 1000. | | `page_token` | none | `next_page_token` from the previous page. | **TypeScript** ```ts const page = await pq.listTasks("emails", { state: "failed", idPrefix: "receipt-", pageSize: 50 }); // page.items, page.nextPageToken ``` **Python** ```python page = pq.list_tasks("emails", state="failed", id_prefix="receipt-", page_size=50) # page.items, page.next_page_token ``` **Go** ```go tasks, next, err := pq.ListTasks(ctx, "emails", pushq.ListTasksParams{ State: "failed", IDPrefix: "receipt-", PageSize: 50, }) ``` **Java** ```java TaskPage page = pq.listTasks("emails", ListTasksParams.builder() .state("failed").idPrefix("receipt-").pageSize(50).build()); // page.getTasks(), page.getNextPageToken() ``` **.NET** ```csharp var page = await pq.ListTasksAsync("emails", new ListTasksOptions { State = TaskState.Failed, IdPrefix = "receipt-", PageSize = 50, }); // page.Items, page.NextPageToken ``` **curl** ```bash curl "https://api.pushqueue.dev/v1/queues/emails/tasks?state=failed&id_prefix=receipt-&page_size=50" \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` Pass the returned page token back to get the next page; it is empty on the last page. Use `id_prefix` with structured IDs (such as `tenant-42-...`) to look at one slice of a queue; the [stats endpoint](https://pushqueue.dev/docs/concepts/queues/#queue-stats-and-monitoring) accepts the same filter. ## Delivery attempts history `GET /v1/queues/{queue}/tasks/{task_id}/attempts` returns the delivery history of a task, newest first (up to the last 1000 attempts). **TypeScript** ```ts const attempts = await pq.listAttempts("emails", "welcome-user-42"); ``` **Python** ```python attempts = pq.list_attempts("emails", "welcome-user-42") ``` **Go** ```go attempts, err := pq.ListAttempts(ctx, "emails", "welcome-user-42") ``` **Java** ```java List attempts = pq.listAttempts("emails", "welcome-user-42"); ``` **.NET** ```csharp var attempts = await pq.ListAttemptsAsync("emails", "welcome-user-42"); ``` **curl** ```bash curl https://api.pushqueue.dev/v1/queues/emails/tasks/welcome-user-42/attempts \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` ```json { "attempts": [ { "number": 2, "dispatch_time": "2026-11-28T10:00:01.2Z", "response_time": "2026-11-28T10:00:01.4Z", "response_status": 200, "duration_ms": 180 }, { "number": 1, "dispatch_time": "2026-11-28T10:00:00Z", "response_time": "2026-11-28T10:00:00.3Z", "response_status": 503, "error_kind": "non_2xx", "error_snippet": "upstream unavailable", "duration_ms": 290 } ] } ``` `error_kind` is one of `non_2xx`, `timeout`, `connect`, `dns`, `tls`, `config` (for example, a path task on a queue whose `base_url` was removed) or `lease_lost` (the outcome was never recorded, for example because the server restarted mid-delivery). `error_snippet` holds the start of the response body or the error message, up to 4 KiB. Use this to see why a task is failing without adding logging to your endpoint. ## Run a task now `POST /v1/queues/{queue}/tasks/{task_id}:run` delivers a pending task immediately, ignoring its schedule time. **TypeScript** ```ts await pq.runTask("emails", "welcome-user-42"); ``` **Python** ```python pq.run_task("emails", "welcome-user-42") ``` **Go** ```go _, err := pq.RunTask(ctx, "emails", "welcome-user-42") ``` **Java** ```java pq.runTask("emails", "welcome-user-42"); ``` **.NET** ```csharp await pq.RunTaskAsync("emails", "welcome-user-42"); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/emails/tasks/welcome-user-42:run \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` - It bypasses the queue's rate limits and concurrency limit, and works on a **paused** queue. - It counts as a normal attempt. If it fails, the usual retry rules apply; on a paused queue the retry then waits until you resume. - It fails with `400 failed_precondition` if the queue is disabled or the task is currently running, and with `404 not_found` if the task already succeeded, failed, or was deleted or purged. Use this to test an endpoint fix on one task before resuming a paused queue, or to skip the wait on a scheduled task. ## Delete or cancel a task `DELETE /v1/queues/{queue}/tasks/{task_id}` deletes a task in any state and answers `204`. **TypeScript** ```ts await pq.deleteTask("emails", "welcome-user-42"); ``` **Python** ```python pq.delete_task("emails", "welcome-user-42") ``` **Go** ```go err := pq.DeleteTask(ctx, "emails", "welcome-user-42") ``` **Java** ```java pq.deleteTask("emails", "welcome-user-42"); ``` **.NET** ```csharp await pq.DeleteTaskAsync("emails", "welcome-user-42"); ``` **curl** ```bash curl -X DELETE https://api.pushqueue.dev/v1/queues/emails/tasks/welcome-user-42 \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` A deleted task is never delivered again. If it was running, that request may still reach your endpoint, but its result is ignored. The ID stays reserved for the dedup window (1 hour by default), so a task with the same ID can't be created right away. Use this to cancel a scheduled task, such as a reminder for an order that was cancelled. ## Retention of finished tasks Finished tasks and their attempt history are kept so you can inspect them: succeeded tasks for 24 hours and failed tasks for 7 days by default on a self-hosted server, never less than the dedup window. After that they are removed automatically. Self-hosters can change this with `retention.succeeded` and `retention.failed`. ## Task size and scheduling limits | Limit | Self-hosted default | Notes | |---|---|---| | Body size | 1 MiB | Decoded bytes. Over the limit is `400 invalid_argument`. Self-hosted: `limits.max_body_bytes`. | | Headers per task | 16 KiB | Sum of names and values. Self-hosted: `limits.max_headers_bytes`. | | Schedule ahead | 1 year | A later `schedule_time` or `delay_seconds` is rejected. Self-hosted: `limits.max_schedule_ahead`. | | `url` length | 2083 characters | | | `task_id` | 500 characters | `[A-Za-z0-9_-]` | | `dispatch_deadline_seconds` | 15 to 1800 | Default 600. | | Batch size | 500 tasks | Request body up to 8 MiB. | A request body larger than the server accepts is rejected with `413 payload_too_large`. The values above are a self-hosted server's defaults; the hosted API may set different ones. Self-hosters can change them, see [server configuration](https://pushqueue.dev/docs/self-hosting/configuration/). ## Read more - [Deduplication with task IDs](https://pushqueue.dev/docs/patterns/deduplication/): enqueue exactly once from retried producers. - [Scheduling and cancelling tasks](https://pushqueue.dev/docs/patterns/scheduling-and-cancelling/): reminders and follow-ups. - [Bulk enqueue](https://pushqueue.dev/docs/patterns/bulk-enqueue/): fan out thousands of tasks with batches. - [Delivery and webhook signatures](https://pushqueue.dev/docs/concepts/delivery/): the request your endpoint receives. - [Retry backoff and max attempts](https://pushqueue.dev/docs/concepts/retries/): what happens when a delivery fails. --- # Retry backoff and max attempts > How pushq retries failed HTTP tasks: the exact backoff schedule with examples, max_attempts, max_retry_duration, Retry-After and per-task overrides. Source: https://pushqueue.dev/docs/concepts/retries/ When a delivery fails, pushq retries the task after a backoff delay, and keeps doing so until it succeeds or its retry limits are reached. This page covers the retry settings, the exact exponential backoff schedule, `max_attempts` and `max_retry_duration`, `Retry-After`, and per-task overrides. The rules follow Google Cloud Tasks exactly, so the same settings give the same schedule. The examples assume a client named `pq` (see [Install & configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/)). Tables use JSON field names; SDKs use their language's casing (`maxAttempts`, `max_attempts`, `MaxAttempts`). ## Configure retries Set these on the queue under `retry`, or on a single task to [override](#per-task-retry-overrides) the queue. | Parameter | Type | Default | Description | |---|---|---|---| | `max_attempts` | integer | `100` | Total attempts, including the first. `-1` means unlimited. `0` is rejected. `1` means no retries. | | `max_retry_duration_seconds` | number | `0` (unlimited) | How long, measured from the first attempt, retries may continue. | | `min_backoff_seconds` | number | `0.1` | Delay before the first retry. | | `max_backoff_seconds` | number | `3600` | No delay is ever longer than this. Must be at least `min_backoff_seconds`. | | `max_doublings` | integer | `16` | How many times the delay doubles before it starts growing linearly, 0 to 31. | **TypeScript** ```ts await pq.patchQueue("emails", { retry: { maxAttempts: 10, minBackoffSeconds: 10, maxBackoffSeconds: 300, maxDoublings: 3 }, }); ``` **Python** ```python from pushq import Retry pq.patch_queue( "emails", retry=Retry(max_attempts=10, min_backoff_seconds=10, max_backoff_seconds=300, max_doublings=3), ) ``` **Go** ```go _, err := pq.PatchQueue(ctx, "emails", pushq.QueueConfig{ Retry: &pushq.Retry{ MaxAttempts: pushq.Int(10), MinBackoffSeconds: pushq.Float64(10), MaxBackoffSeconds: pushq.Float64(300), MaxDoublings: pushq.Int(3), }, }, "") ``` **Java** ```java pq.patchQueue("emails", QueuePatch.builder() .retry(RetryConfig.builder() .maxAttempts(10).minBackoffSeconds(10).maxBackoffSeconds(300).maxDoublings(3).build()) .build()); ``` **.NET** ```csharp await pq.PatchQueueAsync("emails", new QueuePatch { Retry = new RetryConfig { MaxAttempts = 10, MinBackoffSeconds = 10, MaxBackoffSeconds = 300, MaxDoublings = 3 }, }); ``` **curl** ```bash curl -X PATCH https://api.pushqueue.dev/v1/queues/emails \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{"retry": {"max_attempts": 10, "min_backoff_seconds": 10, "max_backoff_seconds": 300, "max_doublings": 3}}' ``` Retry settings are read when an attempt fails, so changing a queue's settings also changes the schedule of tasks that are already retrying. ## How the retry backoff schedule works After the *n*-th failed attempt, the next attempt is scheduled this far in the future: 1. The first delay is `min_backoff`. 2. Each following delay doubles, `max_doublings` times. 3. After that, the delay grows linearly: each retry adds `2^max_doublings × min_backoff`. 4. No delay is ever longer than `max_backoff`. The delay is counted from the moment the failed attempt finished, so the time your endpoint takes to respond adds to the gaps. ### Backoff example: 10-second minimum, 3 doublings With `min_backoff_seconds: 10`, `max_backoff_seconds: 300` and `max_doublings: 3`: | After failed attempt | Delay | Why | Time since first failure | |---|---|---|---| | 1 | 10 s | `min_backoff` | 0 s | | 2 | 20 s | doubled once | 10 s | | 3 | 40 s | doubled twice | 30 s | | 4 | 80 s | doubled 3 times (`max_doublings` reached) | 70 s | | 5 | 160 s | 80 + 80 (linear step = 2³ × 10 = 80) | 150 s | | 6 | 240 s | 160 + 80 | 310 s | | 7 | 300 s | 320 capped at `max_backoff` | 550 s | | 8 and later | 300 s | capped | 850 s, 1150 s, ... | (The last column ignores the time each request itself takes.) ### Default retry schedule With the defaults (`min_backoff_seconds: 0.1`, `max_backoff_seconds: 3600`, `max_doublings: 16`), the delay doubles from 0.1 s until it reaches the one-hour cap: | After failed attempt | Delay | After failed attempt | Delay | |---|---|---|---| | 1 | 0.1 s | 9 | 25.6 s | | 2 | 0.2 s | 10 | 51.2 s | | 3 | 0.4 s | 11 | 102.4 s (about 1.7 min) | | 4 | 0.8 s | 12 | 204.8 s (about 3.4 min) | | 5 | 1.6 s | 13 | 409.6 s (about 6.8 min) | | 6 | 3.2 s | 14 | 819.2 s (about 13.7 min) | | 7 | 6.4 s | 15 | 1638.4 s (about 27 min) | | 8 | 12.8 s | 16 | 3276.8 s (about 55 min) | | | | 17 and later | 3600 s (1 hour, capped) | The first 16 retries together take about 1.8 hours. With the default `max_attempts` of 100, the remaining 83 retries are an hour apart, so a task that never succeeds keeps retrying for about 3.5 days before it is marked `failed`. Use a larger `min_backoff_seconds` (a few seconds) when your endpoint fails because of something that takes time to recover, such as a deploy or a downstream outage; the default retries very quickly at first. ## max_attempts and max_retry_duration Two settings limit retries: `max_attempts` (counts attempts, including the first) and `max_retry_duration_seconds` (time since the first attempt). How they combine depends on which ones are set: | `max_attempts` | `max_retry_duration_seconds` | Retries stop when | |---|---|---| | `-1` (unlimited) | `0` (unlimited) | Never. The task retries until it succeeds or you delete it. | | set | `0` (unlimited) | The attempt count is reached. | | `-1` (unlimited) | set | The duration has passed. | | set | set | **Both** limits are reached. | The last row surprises people: with both limits set, a task keeps retrying until it has made `max_attempts` attempts **and** `max_retry_duration_seconds` has passed since its first attempt, whichever comes later. This matches Cloud Tasks. Because `max_attempts` defaults to 100, setting only `max_retry_duration_seconds: 3600` does not stop retries after an hour; it stops them after 100 attempts or one hour, whichever is later. To make the duration the only limit, also set `max_attempts: -1`. The limits are checked after each failed attempt. A retry that was already scheduled still runs, even if it starts after `max_retry_duration_seconds` has passed. ## What counts as a failed delivery An attempt **succeeds** only when your endpoint returns a 2xx status. Everything else is a failure and is retried: | Outcome | `error_kind` in the attempt log | |---|---| | Any non-2xx status, including 3xx that isn't followed and every 4xx | `non_2xx` | | No response within the task's `dispatch_deadline_seconds` (default 600) | `timeout` | | Connection refused or reset | `connect` | | DNS lookup failed | `dns` | | TLS handshake or certificate error | `tls` | | The request couldn't be built, for example a path task on a queue whose `base_url` was removed | `config` | | The outcome was never recorded, for example the server restarted mid-delivery | `lease_lost` | pushq does not treat 4xx as permanent: a `400` or `404` is retried like a `500`. If your endpoint knows a task can never succeed, return a 2xx (and log or record the problem) to stop the retries; see [stop retrying a task](https://pushqueue.dev/docs/patterns/stop-retrying/). **Redirects** are followed automatically (up to 10 hops) and the whole chain counts as a single attempt; only the final response's status matters. Redirects follow standard HTTP client rules: `307` and `308` repeat the same method and body, while `301`, `302` and `303` switch to a `GET` without a body. Point tasks at the final URL so the body isn't dropped. You can see the outcome of each attempt with the [attempts endpoint](https://pushqueue.dev/docs/concepts/tasks/#delivery-attempts-history). ## Retry-After and the queue cool-down When your endpoint answers `429 Too Many Requests` or `503 Service Unavailable` with a `Retry-After` header (in seconds or as an HTTP date), pushq treats it as back-pressure: - **The task** is retried after the `Retry-After` delay instead of the computed backoff. The delay is capped at the task's `max_backoff_seconds`. - **The whole queue** cools down: it starts no new deliveries for the `Retry-After` delay, up to 30 seconds. Requests already in flight are not affected. `Retry-After` on any other status is ignored, and a 429 or 503 without the header is an ordinary failure with the normal backoff. A `Retry-After` response is still a failed attempt and counts toward `max_attempts`. Use this from your endpoint when it is overloaded: answering `429` with `Retry-After: 10` slows the whole queue down without you changing any settings. The [Rate limits guide](https://pushqueue.dev/docs/guides/rate-limits/#back-pressure-with-retry-after) shows an example handler. ## Per-task retry overrides Any retry field can be set on a single task. Fields you leave out come from the queue's settings at the time of each failure. **TypeScript** ```ts await pq.createTask("emails", { path: "/hooks/send-receipt", jsonBody: { orderId: 1001 }, retry: { maxAttempts: 3, minBackoffSeconds: 30 }, }); ``` **Python** ```python from pushq import Retry pq.create_task( "emails", path="/hooks/send-receipt", json_body={"order_id": 1001}, retry=Retry(max_attempts=3, min_backoff_seconds=30), ) ``` **Go** ```go _, err := pq.CreateTask(ctx, "emails", pushq.TaskCreate{ Path: "/hooks/send-receipt", JSONBody: map[string]any{"order_id": 1001}, Retry: &pushq.Retry{MaxAttempts: pushq.Int(3), MinBackoffSeconds: pushq.Float64(30)}, }) ``` **Java** ```java pq.createTask("emails", TaskCreate.builder() .path("/hooks/send-receipt") .jsonBody(Map.of("order_id", 1001)) .retry(RetryConfig.builder().maxAttempts(3).minBackoffSeconds(30).build()) .build()); ``` **.NET** ```csharp await pq.CreateTaskAsync("emails", new TaskCreate { Path = "/hooks/send-receipt", JsonBody = new { order_id = 1001 }, Retry = new RetryConfig { MaxAttempts = 3, MinBackoffSeconds = 30 }, }); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/emails/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{"path": "/hooks/send-receipt", "json_body": {"order_id": 1001}, "retry": {"max_attempts": 3, "min_backoff_seconds": 30}}' ``` The override is validated together with the defaults when the task is created, so an invalid combination (such as a `max_backoff_seconds` below `min_backoff_seconds`) is rejected with `400 invalid_argument`. A task's `retry` field in API responses shows only its override, not the effective settings. Use this when one kind of task in a shared queue needs different handling, for example a time-sensitive notification that isn't worth delivering after three tries. ## What happens when retries run out When the limits are reached after a failed attempt, the task becomes `failed`: - It is never attempted again, and `finished_at` is set. - It stays visible, with its full attempt history, for the failed-task retention period (7 days by default), and its ID stays reserved for that long. - If the queue has a `dead_letter_queue`, a copy of the task is created there. See [Dead-letter queues](https://pushqueue.dev/docs/concepts/dead-letter-queues/). To find failed tasks, list them with `state=failed` (see [List tasks](https://pushqueue.dev/docs/concepts/tasks/#list-and-filter-tasks)) or watch the `failed` count in [queue stats](https://pushqueue.dev/docs/concepts/queues/#queue-stats-and-monitoring). There is no endpoint to retry a failed task in place; create a new task with the same content (with a new `task_id`, if you set one), or use a dead-letter queue to replay it. ## Read more - [Stop retrying a task](https://pushqueue.dev/docs/patterns/stop-retrying/): end retries from your handler on purpose. - [Dead-letter queues](https://pushqueue.dev/docs/concepts/dead-letter-queues/): keep and replay tasks that run out of retries. - [Rate limits and concurrency](https://pushqueue.dev/docs/guides/rate-limits/): how retries share a queue's rate budget. - [Troubleshooting](https://pushqueue.dev/docs/guides/troubleshooting/): find out why tasks keep failing. --- # 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 `/`) 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` | `/`, 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 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 { ["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. --- # Dead-letter queues > Use pushq dead-letter queues to keep tasks that ran out of retries: setup, what is copied, the X-Pushq-Deadletter headers, and how to replay them. Source: https://pushqueue.dev/docs/concepts/dead-letter-queues/ A pushq dead-letter queue (DLQ) catches tasks that ran out of [retries](https://pushqueue.dev/docs/concepts/retries/), so failed work isn't lost. When a task in a queue with `dead_letter_queue` set fails for good, pushq creates a copy of it in the dead-letter queue. The original stays `failed` in its own queue. A DLQ is an ordinary queue. It has its own state, rate limits, retry settings and target, and its tasks are dispatched like any others. That is what makes replay possible, and it is also the main thing to plan for: a running DLQ delivers its copies right away. The examples assume a client named `pq` (see [Install & configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/)). ## Set up a dead-letter queue 1. Create the DLQ and pause it, so dead letters are kept instead of being delivered again immediately. 2. Point the source queue at it with `dead_letter_queue`. **TypeScript** ```ts await pq.upsertQueue("emails-dead", { target: { baseUrl: "https://api.example.com" } }); await pq.pauseQueue("emails-dead"); await pq.patchQueue("emails", { deadLetterQueue: "emails-dead" }); ``` **Python** ```python from pushq import Target pq.upsert_queue("emails-dead", target=Target(base_url="https://api.example.com")) pq.pause_queue("emails-dead") pq.patch_queue("emails", dead_letter_queue="emails-dead") ``` **Go** ```go _, err := pq.UpsertQueue(ctx, "emails-dead", pushq.QueueConfig{ Target: &pushq.Target{BaseURL: "https://api.example.com"}, }) _, err = pq.PauseQueue(ctx, "emails-dead") _, err = pq.PatchQueue(ctx, "emails", pushq.QueueConfig{DeadLetterQueue: "emails-dead"}, "") ``` **Java** ```java pq.upsertQueue("emails-dead", QueueConfig.builder() .target(Target.builder().baseUrl("https://api.example.com").build()) .build()); pq.pauseQueue("emails-dead"); pq.patchQueue("emails", QueuePatch.builder().deadLetterQueue("emails-dead").build()); ``` **.NET** ```csharp await pq.UpsertQueueAsync("emails-dead", new QueueConfig { Target = new Target { BaseUrl = "https://api.example.com" }, }); await pq.PauseQueueAsync("emails-dead"); await pq.PatchQueueAsync("emails", new QueuePatch { DeadLetterQueue = "emails-dead" }); ``` **curl** ```bash curl -X PUT https://api.pushqueue.dev/v1/queues/emails-dead \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{"target": {"base_url": "https://api.example.com"}}' curl -X POST https://api.pushqueue.dev/v1/queues/emails-dead:pause \ -H "Authorization: Bearer $PUSHQ_API_KEY" curl -X PATCH https://api.pushqueue.dev/v1/queues/emails \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{"dead_letter_queue": "emails-dead"}' ``` You can also set `dead_letter_queue` in the PUT that creates the source queue. Remember that a PUT without `dead_letter_queue` removes it; to remove it with PATCH, send `"dead_letter_queue": ""`. | Parameter | Type | Default | Description | |---|---|---|---| | `dead_letter_queue` | string | none | Name of the queue that receives copies of permanently failed tasks. Must be a valid queue name and can't be the queue itself. Several queues can share one DLQ. | ### The dead-letter queue must exist pushq checks only that `dead_letter_queue` is a valid name; it doesn't check that the queue exists when you set it. The copy is made when a task fails, and if the DLQ doesn't exist at that moment, or is `disabled`, the copy is dropped (the server logs the error) and the task is only marked `failed` in its own queue. Create the DLQ first and don't disable it. A `paused` DLQ accepts copies normally. ## What is copied to the dead-letter queue When a task fails for the last time, the DLQ gets a new task with: | Copied from the original | Not copied | |---|---| | `url` or `path` | `task_id`: the copy gets a new server-generated ID | | `method` (the task's own) | Per-task `retry` override: the DLQ's retry settings apply | | Task `headers`, plus the headers below | Attempt history and counters | | Body | The source queue's `target` (`base_url`, `method`, `headers`, `signing_secret`): the DLQ's own target applies | | `dispatch_deadline_seconds` | | The copy is scheduled for immediate delivery. On a running DLQ it is sent right away; on a paused DLQ it waits. Because the source queue's `target` doesn't come along, set up the DLQ to match it when you want replays to reach the same endpoint: the same `base_url` (path-based tasks are resolved against the **DLQ's** `base_url`, and fail with a `config` error if it has none), and the same `target.headers` and `signing_secret` if your endpoint expects them. ### X-Pushq-Deadletter headers Three headers are added to the copy's headers, so they are visible in the task (with `view=full`) and sent with every delivery of the copy: | Header | Example | Meaning | |---|---|---| | `X-Pushq-Deadletter-Source-Queue` | `emails` | The queue the task failed in. | | `X-Pushq-Deadletter-Task-Id` | `welcome-user-42` | The original task's ID. | | `X-Pushq-Deadletter-Final-Status` | `500` or `timeout` | The last attempt's HTTP status, or its error kind (`timeout`, `connect`, `dns`, `tls`, `config`, `lease_lost`) when there was no response. | The copy's own `X-Pushq-Task-Id` and `webhook-id` use the new ID and the DLQ's name. If your endpoint deduplicates on those, use `X-Pushq-Deadletter-Task-Id` to recognize a replay of a task it already saw. ## Inspect failed tasks in a dead-letter queue List the DLQ with the full view to see bodies and headers: **TypeScript** ```ts const page = await pq.listTasks("emails-dead", { view: "full", pageSize: 50 }); for (const t of page.items) { console.log(t.id, t.headers?.["X-Pushq-Deadletter-Task-Id"], t.headers?.["X-Pushq-Deadletter-Final-Status"]); } ``` **Python** ```python page = pq.list_tasks("emails-dead", view="full", page_size=50) for t in page.items: print(t.id, t.headers.get("X-Pushq-Deadletter-Task-Id"), t.headers.get("X-Pushq-Deadletter-Final-Status")) ``` **Go** ```go tasks, _, err := pq.ListTasks(ctx, "emails-dead", pushq.ListTasksParams{View: "full", PageSize: 50}) for _, t := range tasks { fmt.Println(t.ID, t.Headers["X-Pushq-Deadletter-Task-Id"], t.Headers["X-Pushq-Deadletter-Final-Status"]) } ``` **Java** ```java TaskPage page = pq.listTasks("emails-dead", ListTasksParams.builder().view("full").pageSize(50).build()); for (Task t : page.getTasks()) { System.out.println(t.getId() + " " + t.getHeaders().get("X-Pushq-Deadletter-Task-Id") + " " + t.getHeaders().get("X-Pushq-Deadletter-Final-Status")); } ``` **.NET** ```csharp var page = await pq.ListTasksAsync("emails-dead", new ListTasksOptions { View = TaskView.Full, PageSize = 50 }); foreach (var t in page.Items) Console.WriteLine($"{t.Id} {t.Headers?["X-Pushq-Deadletter-Task-Id"]} {t.Headers?["X-Pushq-Deadletter-Final-Status"]}"); ``` **curl** ```bash curl "https://api.pushqueue.dev/v1/queues/emails-dead/tasks?view=full&page_size=50" \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` Watch the DLQ's `pending` and `scheduled_future` counts in [queue stats](https://pushqueue.dev/docs/concepts/queues/#queue-stats-and-monitoring) to alert when tasks start dead-lettering. ## Replay tasks from a dead-letter queue Once you've fixed the cause, there are three ways to deal with what's in a paused DLQ (the [replay dead letters pattern](https://pushqueue.dev/docs/patterns/replay-dead-letters/) walks through a full replay): - **Replay one task:** `:run` delivers a single task right away, even though the DLQ is paused. Use it to check that the fix works. - **Replay everything:** resume the DLQ. Its tasks are delivered at the DLQ's rate limits and retried with the DLQ's retry settings. Pause it again afterwards if you want it to keep collecting. - **Discard everything:** purge the DLQ, or delete individual tasks. **TypeScript** ```ts await pq.runTask("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b"); // one task await pq.resumeQueue("emails-dead"); // all of them ``` **Python** ```python pq.run_task("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b") # one task pq.resume_queue("emails-dead") # all of them ``` **Go** ```go _, err := pq.RunTask(ctx, "emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b") // one task _, err = pq.ResumeQueue(ctx, "emails-dead") // all of them ``` **Java** ```java pq.runTask("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b"); // one task pq.resumeQueue("emails-dead"); // all of them ``` **.NET** ```csharp await pq.RunTaskAsync("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b"); // one task await pq.ResumeQueueAsync("emails-dead"); // all of them ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/emails-dead/tasks/0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b:run \ -H "Authorization: Bearer $PUSHQ_API_KEY" curl -X POST https://api.pushqueue.dev/v1/queues/emails-dead:resume \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` To replay into the original queue instead (for example, to get its rate limits), read the tasks with `view=full` and create new tasks in the source queue with the same `path` or `url`, method, headers and body. If a replayed task fails again in the DLQ, it follows the DLQ's retry settings. When those run out it becomes `failed` in the DLQ, or moves on to the DLQ's own `dead_letter_queue` if it has one. ## Dead-letter queue use cases - **Parking lot (paused DLQ):** keep failed work safe during an outage, then replay it after the fix. This is the setup shown above. - **Failure handler (running DLQ with a different target):** give the DLQ a `base_url` that points at a handler which alerts, refunds or marks the record as failed. Path-based tasks then reach that handler with the original body and the dead-letter headers. Tasks created with an absolute `url` still go to that URL, so this pattern needs path-based tasks. - **Shared DLQ:** point many queues (such as every queue under `tenants/`) at one DLQ and use `X-Pushq-Deadletter-Source-Queue` to tell them apart. ## Read more - [Replay dead letters](https://pushqueue.dev/docs/patterns/replay-dead-letters/): a step-by-step replay after an outage. - [Retry backoff and max attempts](https://pushqueue.dev/docs/concepts/retries/): when a task counts as permanently failed. - [Queues and queue configuration](https://pushqueue.dev/docs/concepts/queues/): pause, resume and purge a dead-letter queue. - [Stop retrying a task](https://pushqueue.dev/docs/patterns/stop-retrying/): send a task to the dead-letter queue sooner. --- # Rate limits and concurrency > Rate limit HTTP tasks with pushq: dispatch rate, burst size and concurrency per queue, Retry-After back-pressure, and recipes for APIs and tenants. Source: https://pushqueue.dev/docs/guides/rate-limits/ Every pushq queue has three rate limits that decide how fast its tasks are delivered: a dispatch rate, a burst size and a concurrency cap. They protect the endpoint receiving the tasks, whether that's your own service or a third-party API with a quota. This guide explains how the limits work together and gives recipes for rate limiting an API, per-tenant limits and incidents. The examples assume a client named `pq` (see [Install & configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/)). Tables use JSON field names; SDKs use their language's casing (`maxDispatchesPerSecond`, `max_dispatches_per_second`, `MaxDispatchesPerSecond`). ## Queue rate limit settings | Parameter | Type | Default | Description | |---|---|---|---| | `rate_limits.max_dispatches_per_second` | number | `500` | How many deliveries may start per second, on average. Greater than 0, at most 10000; fractions allowed. | | `rate_limits.max_burst_size` | integer | `0` (auto) | How many deliveries may start at once after the queue has been idle. 0 to 10000; `0` means `max_dispatches_per_second` rounded up, between 1 and 500. | | `rate_limits.max_concurrent_dispatches` | integer | `1000` | How many deliveries may be in flight at the same time. 1 to 10000. | A task is delivered only when all of these hold: 1. The queue is `running` and the task's schedule time has passed. 2. A rate token is available (`max_dispatches_per_second` and `max_burst_size`). 3. Fewer than `max_concurrent_dispatches` of the queue's requests are in flight. 4. The queue isn't cooling down after a [`Retry-After`](#back-pressure-with-retry-after) response. 5. The server has a free delivery slot (see [Server-wide concurrency](#server-wide-concurrency)). Retries go through the same limits as first attempts. Only [`:run`](https://pushqueue.dev/docs/concepts/tasks/#run-a-task-now) bypasses them. ### Dispatch rate and burst size (token bucket) Each queue has a bucket that holds up to `max_burst_size` tokens and refills at `max_dispatches_per_second` tokens per second. Starting a delivery takes one token. - After the queue has been idle, the bucket is full, so up to `max_burst_size` tasks start at once. After that, deliveries are spaced out at the refill rate. - With the auto burst, a queue limited to 10 per second can start 10 tasks at once, then continues at 10 per second. - With `max_burst_size: 1`, deliveries are evenly spaced: at 10 per second, one every 100 ms. - Fractional rates work for slow trickles: `0.2` is one delivery every 5 seconds. Use an explicit small burst when the receiver counts requests in short windows and a sudden spike would trip its limit even though your average is fine. ### Max concurrent dispatches `max_concurrent_dispatches` caps the requests in flight for the queue. When the cap is reached, the next delivery waits until one finishes, however many tokens are available. It protects endpoints whose capacity is limited by workers, connections or database load rather than by requests per second. ### How rate and concurrency limits interact The effective throughput is the lower of the rate limit and what concurrency allows: ```text throughput ≈ min(max_dispatches_per_second, max_concurrent_dispatches / average response time) ``` For example, with `max_dispatches_per_second: 100` and `max_concurrent_dispatches: 5`, an endpoint that takes 500 ms per request gets at most 5 / 0.5 s = 10 deliveries per second. The concurrency cap is the binding limit, and the rate limit only matters if the endpoint speeds up. Slow responses therefore lower throughput automatically, which is usually what you want. ### Server-wide concurrency On top of the per-queue limits, the server caps the total number of deliveries in flight across all queues. On a self-hosted server this is `dispatcher.global_concurrency` (environment variable `PUSHQ_GLOBAL_CONCURRENCY`), default 512. When every slot is busy, queues wait for a free slot, so a per-queue `max_concurrent_dispatches` above this value has no extra effect. See [server configuration](https://pushqueue.dev/docs/self-hosting/configuration/). ## Back-pressure with Retry-After Your endpoint can slow pushq down without any configuration change. Answer `429 Too Many Requests` or `503 Service Unavailable` with a `Retry-After` header (seconds, or an HTTP date): - the task is retried after that delay (capped at its `max_backoff_seconds`) instead of the normal backoff; - the whole queue starts no new deliveries for that delay, up to 30 seconds. Without the header, a 429 or 503 is an ordinary failure with normal backoff and no cool-down. A `Retry-After` response still counts as a failed attempt toward `max_attempts`. Details are in [Retries](https://pushqueue.dev/docs/concepts/retries/#retry-after-and-the-queue-cool-down). This handler sheds load when it is too busy: **TypeScript** ```ts app.post("/hooks/sync", async (req, res) => { if (inFlight >= MAX_IN_FLIGHT) { res.set("Retry-After", "10").sendStatus(429); return; } // ... do the work ... res.sendStatus(204); }); ``` **Python** ```python from fastapi import Response @app.post("/hooks/sync") async def sync(request: Request): if in_flight >= MAX_IN_FLIGHT: return Response(status_code=429, headers={"Retry-After": "10"}) # ... do the work ... return Response(status_code=204) ``` **Go** ```go func handleSync(w http.ResponseWriter, r *http.Request) { if inFlight.Load() >= maxInFlight { w.Header().Set("Retry-After", "10") w.WriteHeader(http.StatusTooManyRequests) return } // ... do the work ... w.WriteHeader(http.StatusNoContent) } ``` **Java** ```java @PostMapping("/hooks/sync") public ResponseEntity sync(@RequestBody byte[] payload) { if (inFlight.get() >= MAX_IN_FLIGHT) { return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).header("Retry-After", "10").build(); } // ... do the work ... return ResponseEntity.noContent().build(); } ``` **.NET** ```csharp app.MapPost("/hooks/sync", (HttpResponse res) => { if (inFlight >= MaxInFlight) { res.Headers.RetryAfter = "10"; return Results.StatusCode(StatusCodes.Status429TooManyRequests); } // ... do the work ... return Results.NoContent(); }); ``` These are your endpoint's handlers, so there is no curl version. ## Rate limiting recipes ### Rate limit a third-party API Say a provider allows 10 requests per second and 5 concurrent connections, and you call it from your own handler for each task. Stay a little under the limits, and spread requests evenly so a burst after an idle period doesn't trip a per-second window: **TypeScript** ```ts await pq.upsertQueue("crm-sync", { rateLimits: { maxDispatchesPerSecond: 8, maxBurstSize: 1, maxConcurrentDispatches: 5 }, target: { baseUrl: "https://worker.example.com" }, }); ``` **Python** ```python from pushq import RateLimits, Target pq.upsert_queue( "crm-sync", rate_limits=RateLimits(max_dispatches_per_second=8, max_burst_size=1, max_concurrent_dispatches=5), target=Target(base_url="https://worker.example.com"), ) ``` **Go** ```go _, err := pq.UpsertQueue(ctx, "crm-sync", pushq.QueueConfig{ RateLimits: &pushq.RateLimits{ MaxDispatchesPerSecond: pushq.Float64(8), MaxBurstSize: pushq.Int(1), MaxConcurrentDispatches: pushq.Int(5), }, Target: &pushq.Target{BaseURL: "https://worker.example.com"}, }) ``` **Java** ```java pq.upsertQueue("crm-sync", QueueConfig.builder() .rateLimits(RateLimits.builder().maxDispatchesPerSecond(8).maxBurstSize(1).maxConcurrentDispatches(5).build()) .target(Target.builder().baseUrl("https://worker.example.com").build()) .build()); ``` **.NET** ```csharp await pq.UpsertQueueAsync("crm-sync", new QueueConfig { RateLimits = new RateLimits { MaxDispatchesPerSecond = 8, MaxBurstSize = 1, MaxConcurrentDispatches = 5 }, Target = new Target { BaseUrl = "https://worker.example.com" }, }); ``` **curl** ```bash curl -X PUT https://api.pushqueue.dev/v1/queues/crm-sync \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{ "rate_limits": {"max_dispatches_per_second": 8, "max_burst_size": 1, "max_concurrent_dispatches": 5}, "target": {"base_url": "https://worker.example.com"} }' ``` If the provider returns `429`, pass it through from your handler with the provider's `Retry-After` so pushq [backs off](#back-pressure-with-retry-after). Use one queue per provider limit: if two kinds of work share the same API key, put them in the same queue so they share the budget. The [throttle a third-party API pattern](https://pushqueue.dev/docs/patterns/throttle-a-third-party-api/) has a complete example. ### Per-tenant rate limits with one queue per tenant When each customer has their own quota (or you want one noisy customer not to delay the others), give each tenant its own queue in a `tenants/` [folder](https://pushqueue.dev/docs/concepts/queues/#queue-folders). Queues are independent, so each gets its own rate limit and backlog. Because PUT is an idempotent upsert, you can call it right before every enqueue; the queue is created the first time and left unchanged after that. **TypeScript** ```ts const LIMITS = { free: 1, pro: 20 } as const; async function enqueueForTenant(tenantId: string, plan: keyof typeof LIMITS, payload: unknown) { const queue = `tenants/${tenantId}`; // tenantId must be lowercase [a-z0-9-] await pq.upsertQueue(queue, { rateLimits: { maxDispatchesPerSecond: LIMITS[plan], maxConcurrentDispatches: 5 }, target: { baseUrl: "https://api.example.com" }, }); await pq.createTask(queue, { path: "/hooks/tenant-sync", jsonBody: payload }); } ``` **Python** ```python LIMITS = {"free": 1, "pro": 20} def enqueue_for_tenant(tenant_id: str, plan: str, payload: dict) -> None: queue = f"tenants/{tenant_id}" # tenant_id must be lowercase [a-z0-9-] pq.upsert_queue( queue, rate_limits=RateLimits(max_dispatches_per_second=LIMITS[plan], max_concurrent_dispatches=5), target=Target(base_url="https://api.example.com"), ) pq.create_task(queue, path="/hooks/tenant-sync", json_body=payload) ``` **Go** ```go var limits = map[string]float64{"free": 1, "pro": 20} func enqueueForTenant(ctx context.Context, tenantID, plan string, payload any) error { queue := "tenants/" + tenantID // tenantID must be lowercase [a-z0-9-] _, err := pq.UpsertQueue(ctx, queue, pushq.QueueConfig{ RateLimits: &pushq.RateLimits{ MaxDispatchesPerSecond: pushq.Float64(limits[plan]), MaxConcurrentDispatches: pushq.Int(5), }, Target: &pushq.Target{BaseURL: "https://api.example.com"}, }) if err != nil { return err } _, err = pq.CreateTask(ctx, queue, pushq.TaskCreate{Path: "/hooks/tenant-sync", JSONBody: payload}) return err } ``` **Java** ```java static final Map LIMITS = Map.of("free", 1.0, "pro", 20.0); void enqueueForTenant(String tenantId, String plan, Object payload) { String queue = "tenants/" + tenantId; // tenantId must be lowercase [a-z0-9-] pq.upsertQueue(queue, QueueConfig.builder() .rateLimits(RateLimits.builder().maxDispatchesPerSecond(LIMITS.get(plan)).maxConcurrentDispatches(5).build()) .target(Target.builder().baseUrl("https://api.example.com").build()) .build()); pq.createTask(queue, TaskCreate.builder().path("/hooks/tenant-sync").jsonBody(payload).build()); } ``` **.NET** ```csharp static readonly Dictionary Limits = new() { ["free"] = 1, ["pro"] = 20 }; async Task EnqueueForTenantAsync(string tenantId, string plan, object payload) { var queue = $"tenants/{tenantId}"; // tenantId must be lowercase [a-z0-9-] await pq.UpsertQueueAsync(queue, new QueueConfig { RateLimits = new RateLimits { MaxDispatchesPerSecond = Limits[plan], MaxConcurrentDispatches = 5 }, Target = new Target { BaseUrl = "https://api.example.com" }, }); await pq.CreateTaskAsync(queue, new TaskCreate { Path = "/hooks/tenant-sync", JsonBody = payload }); } ``` **curl** ```bash curl -X PUT https://api.pushqueue.dev/v1/queues/tenants%2Facme \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{"rate_limits": {"max_dispatches_per_second": 20, "max_concurrent_dispatches": 5}, "target": {"base_url": "https://api.example.com"}}' curl -X POST https://api.pushqueue.dev/v1/queues/tenants%2Facme/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{"path": "/hooks/tenant-sync", "json_body": {"account": "acme"}}' ``` Things to know (the [per-tenant queues pattern](https://pushqueue.dev/docs/patterns/per-tenant-queues/) covers this in more depth): - Queue names allow only lowercase letters, digits and hyphens in each segment, so map tenant IDs to that form (for example, lowercase a UUID). - The PUT sets the whole configuration each time, so a plan change takes effect on the tenant's next enqueue. A paused tenant queue stays paused, because PUT never changes the state. - List or monitor all tenant queues with `name_prefix=tenants/` (this needs an admin API key) and check each one's [stats](https://pushqueue.dev/docs/concepts/queues/#queue-stats-and-monitoring). - On the hosted service, the Free plan allows up to 1,000 queues and Pay as you go is unlimited; see [pricing](https://pushqueue.dev/pricing). When you only need per-tenant visibility, not separate limits, one shared queue with task IDs like `acme-...` also works: `id_prefix=acme-` filters both the task list and the stats. ### Change rate limits at runtime PATCH changes one limit and leaves the rest of the configuration alone. The new limit applies to the next delivery, including tasks already waiting in the queue. **TypeScript** ```ts await pq.patchQueue("crm-sync", { rateLimits: { maxDispatchesPerSecond: 20 } }); ``` **Python** ```python pq.patch_queue("crm-sync", rate_limits=RateLimits(max_dispatches_per_second=20)) ``` **Go** ```go _, err := pq.PatchQueue(ctx, "crm-sync", pushq.QueueConfig{ RateLimits: &pushq.RateLimits{MaxDispatchesPerSecond: pushq.Float64(20)}, }, "") ``` **Java** ```java pq.patchQueue("crm-sync", QueuePatch.builder() .rateLimits(RateLimits.builder().maxDispatchesPerSecond(20).build()) .build()); ``` **.NET** ```csharp await pq.PatchQueueAsync("crm-sync", new QueuePatch { RateLimits = new RateLimits { MaxDispatchesPerSecond = 20 }, }); ``` **curl** ```bash curl -X PATCH https://api.pushqueue.dev/v1/queues/crm-sync \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{"rate_limits": {"max_dispatches_per_second": 20}}' ``` Use this when a provider raises your quota, or to drain a large backlog faster overnight. Prefer PATCH over PUT here: a PUT with only `rate_limits` would reset the queue's retry settings and clear its target. ### Slow down or pause during an incident When the receiving service is struggling, first slow the queue down. Lowering concurrency is usually the most direct relief, because it caps the load regardless of how slow responses get: **TypeScript** ```ts await pq.patchQueue("crm-sync", { rateLimits: { maxDispatchesPerSecond: 1, maxConcurrentDispatches: 1 } }); ``` **Python** ```python pq.patch_queue("crm-sync", rate_limits=RateLimits(max_dispatches_per_second=1, max_concurrent_dispatches=1)) ``` **Go** ```go _, err := pq.PatchQueue(ctx, "crm-sync", pushq.QueueConfig{ RateLimits: &pushq.RateLimits{MaxDispatchesPerSecond: pushq.Float64(1), MaxConcurrentDispatches: pushq.Int(1)}, }, "") ``` **Java** ```java pq.patchQueue("crm-sync", QueuePatch.builder() .rateLimits(RateLimits.builder().maxDispatchesPerSecond(1).maxConcurrentDispatches(1).build()) .build()); ``` **.NET** ```csharp await pq.PatchQueueAsync("crm-sync", new QueuePatch { RateLimits = new RateLimits { MaxDispatchesPerSecond = 1, MaxConcurrentDispatches = 1 }, }); ``` **curl** ```bash curl -X PATCH https://api.pushqueue.dev/v1/queues/crm-sync \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{"rate_limits": {"max_dispatches_per_second": 1, "max_concurrent_dispatches": 1}}' ``` If the service is down, pause the queue instead. New tasks are still accepted and wait, and no retries are used up while paused. Requests already in flight finish normally. **TypeScript** ```ts await pq.pauseQueue("crm-sync"); // ... after the fix ... await pq.runTask("crm-sync", "welcome-user-42"); // optional: test one task while still paused await pq.resumeQueue("crm-sync"); ``` **Python** ```python pq.pause_queue("crm-sync") # ... after the fix ... pq.run_task("crm-sync", "welcome-user-42") # optional: test one task while still paused pq.resume_queue("crm-sync") ``` **Go** ```go _, err := pq.PauseQueue(ctx, "crm-sync") // ... after the fix ... _, err = pq.RunTask(ctx, "crm-sync", "welcome-user-42") // optional: test one task while still paused _, err = pq.ResumeQueue(ctx, "crm-sync") ``` **Java** ```java pq.pauseQueue("crm-sync"); // ... after the fix ... pq.runTask("crm-sync", "welcome-user-42"); // optional: test one task while still paused pq.resumeQueue("crm-sync"); ``` **.NET** ```csharp await pq.PauseQueueAsync("crm-sync"); // ... after the fix ... await pq.RunTaskAsync("crm-sync", "welcome-user-42"); // optional: test one task while still paused await pq.ResumeQueueAsync("crm-sync"); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/crm-sync:pause -H "Authorization: Bearer $PUSHQ_API_KEY" curl -X POST https://api.pushqueue.dev/v1/queues/crm-sync/tasks/welcome-user-42:run -H "Authorization: Bearer $PUSHQ_API_KEY" curl -X POST https://api.pushqueue.dev/v1/queues/crm-sync:resume -H "Authorization: Bearer $PUSHQ_API_KEY" ``` On resume, the backlog drains at the queue's limits, starting with a burst of up to `max_burst_size`. If the service is fragile right after recovery, keep the lowered limits for a while and raise them with PATCH once it is stable. Watch `oldest_due_age_seconds` in the queue's [stats](https://pushqueue.dev/docs/concepts/queues/#queue-stats-and-monitoring) to see the backlog shrink. ### Limit concurrency for a fragile endpoint For an endpoint that can only handle one request at a time, such as a legacy system or a job that locks a shared resource, set `max_concurrent_dispatches: 1`. Each delivery starts only after the previous one has finished. **TypeScript** ```ts await pq.upsertQueue("legacy-erp", { rateLimits: { maxConcurrentDispatches: 1 }, retry: { minBackoffSeconds: 5, maxBackoffSeconds: 600 }, target: { baseUrl: "https://erp.example.com" }, }); ``` **Python** ```python pq.upsert_queue( "legacy-erp", rate_limits=RateLimits(max_concurrent_dispatches=1), retry=Retry(min_backoff_seconds=5, max_backoff_seconds=600), target=Target(base_url="https://erp.example.com"), ) ``` **Go** ```go _, err := pq.UpsertQueue(ctx, "legacy-erp", pushq.QueueConfig{ RateLimits: &pushq.RateLimits{MaxConcurrentDispatches: pushq.Int(1)}, Retry: &pushq.Retry{MinBackoffSeconds: pushq.Float64(5), MaxBackoffSeconds: pushq.Float64(600)}, Target: &pushq.Target{BaseURL: "https://erp.example.com"}, }) ``` **Java** ```java pq.upsertQueue("legacy-erp", QueueConfig.builder() .rateLimits(RateLimits.builder().maxConcurrentDispatches(1).build()) .retry(RetryConfig.builder().minBackoffSeconds(5).maxBackoffSeconds(600).build()) .target(Target.builder().baseUrl("https://erp.example.com").build()) .build()); ``` **.NET** ```csharp await pq.UpsertQueueAsync("legacy-erp", new QueueConfig { RateLimits = new RateLimits { MaxConcurrentDispatches = 1 }, Retry = new RetryConfig { MinBackoffSeconds = 5, MaxBackoffSeconds = 600 }, Target = new Target { BaseUrl = "https://erp.example.com" }, }); ``` **curl** ```bash curl -X PUT https://api.pushqueue.dev/v1/queues/legacy-erp \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -d '{ "rate_limits": {"max_concurrent_dispatches": 1}, "retry": {"min_backoff_seconds": 5, "max_backoff_seconds": 600}, "target": {"base_url": "https://erp.example.com"} }' ``` The longer `min_backoff_seconds` keeps a failing endpoint from being hit again within a fraction of a second. Keep the handler's response time well under `dispatch_deadline_seconds`: with one slot, a hanging request blocks the whole queue until it times out. :::note A concurrency of 1 means one request at a time, not strict ordering. Due tasks are generally picked in schedule-time order, but a failed task is rescheduled for later and the tasks behind it go ahead. Don't rely on pushq for ordering; have the handler cope with tasks arriving out of order. ::: ## How to choose rate limit values - **Start from the receiver's real limit.** For a third-party API, use its documented rate and concurrency, about 80 percent of each, to leave room for other callers and clock drift between its window and yours. - **Size concurrency from latency.** To sustain *R* deliveries per second against an endpoint that takes *L* seconds per request, you need about *R* × *L* concurrent slots. 50 per second at 200 ms needs about 10; give it some headroom. - **Use the burst to absorb or avoid spikes.** Leave it on auto when the receiver handles short spikes well. Set it to 1 when the receiver enforces per-second windows strictly. - **Remember retries share the budget.** When the endpoint fails, retries consume tokens and slots too. Keep `min_backoff_seconds` reasonable so a broken endpoint doesn't spend the whole rate on retries. - **Watch the stats.** A rising `oldest_due_age_seconds` means the limits are lower than the incoming rate; a rising `errors_last_1m` means the receiver is struggling and the limits may be too high. ## Read more - [Throttle a third-party API](https://pushqueue.dev/docs/patterns/throttle-a-third-party-api/): a complete worked example. - [Per-tenant queues](https://pushqueue.dev/docs/patterns/per-tenant-queues/): isolate customers with one queue each. - [Retry backoff and max attempts](https://pushqueue.dev/docs/concepts/retries/): Retry-After and the queue cool-down in detail. - [Queues and queue configuration](https://pushqueue.dev/docs/concepts/queues/): every queue setting and the stats API. - [Going to production](https://pushqueue.dev/docs/guides/going-to-production/): limits and monitoring checklist. --- # Create and manage API keys > Create, use, rotate and revoke pushq API keys, and choose between writer and admin roles, in the console, through the API, or in a self-hosted server's config. Source: https://pushqueue.dev/docs/guides/api-keys/ Your apps authenticate to pushq with an API key sent as a bearer token. This page covers creating keys, what each role may do, keeping keys safe, rotating them without downtime and revoking one that leaked. Self-hosters can also define keys in the server config; see [Config-file keys](#config-file-keys-self-hosted). ## How keys work - A key looks like `pq_` followed by 32 random characters (24 random bytes, base64url-encoded). - The full key is returned **once**, when you create it. pushq stores only its SHA-256 hash, so nobody (including you) can read it back later. Lists show only the first 11 characters (the `prefix`, e.g. `pq_AbC12dEf`) so you can tell keys apart. - Every key has a role, `writer` or `admin`. Pick the smallest one that does the job. - On the hosted service, a key belongs to the team that created it and only sees that team's queues. - Revoking a key takes effect on the next request that uses it. ## Key roles | Action | Endpoints | Writer | Admin | |---|---|---|---| | Read a queue you name, its stats, its tasks and their attempts | `GET /v1/queues/{queue}`, `.../stats`, `.../tasks`, `.../tasks/{id}`, `.../attempts`, `GET /v1/version` | Yes | Yes | | Create and change queues; pause, resume, purge | `POST /v1/queues`, `PUT`/`PATCH /v1/queues/{queue}`, `:pause`, `:resume`, `:purge` | Yes | Yes | | Enqueue, force-run and delete tasks | `POST .../tasks`, `.../tasks:batch`, `.../tasks/{id}:run`, `DELETE .../tasks/{id}` | Yes | Yes | | List queues | `GET /v1/queues` | No | Yes | | Delete queues | `DELETE /v1/queues/{queue}` | No | Yes | | Manage team members, invites, API keys and the team name | `/v1/users`, `/v1/invites`, `/v1/api-keys`, `PATCH /v1/teams/current` | No | Yes | A **writer** key works only with queues it already knows by name: it can't list queues or delete them. That makes it the right choice for application code that enqueues tasks. Use an **admin** key for tooling that needs to see everything or manage the team, such as a provisioning script. A few endpoints don't accept any API key, because they act on a person rather than a team: `PATCH /v1/me`, `POST /v1/me/password`, `GET /v1/teams`, `POST /v1/teams` and `POST /v1/teams/{id}:switch` need a signed-in dashboard session. See [Team members](https://pushqueue.dev/docs/guides/team-members/). When a key isn't allowed to do something, the API answers `403` with code `permission_denied`: ```json { "type": "about:blank", "title": "Forbidden", "status": 403, "code": "permission_denied", "detail": "the writer role is not allowed to do this", "instance": "/v1/queues" } ``` A missing, unknown or revoked key gets `401` with code `unauthenticated` (`"sign in or send a valid API key"`). ## Create a key in the console Only team admins can create keys. 1. Sign in to the [console](https://console.pushqueue.dev/) (on a self-hosted server, open the dashboard at `/`). 2. Open the account menu in the top-right corner and choose **Settings**, then the **API keys** tab. 3. Under **Create an API key**, enter what will use the key, for example `billing-service` (1–100 characters). 4. Pick **Writer** or **Admin** and click **Create key**. 5. Copy the key from the dialog and store it in your secret manager. Click **I've saved it** to close the dialog. It will not be shown again. The table below the form lists every key with its name, prefix, role, when and by whom it was created, and when it was last used. Use this when you set up a new app or environment and need a key for it. ## Manage keys through the API The `/v1/api-keys` endpoints need an **admin** key or a signed-in admin user. On the hosted service they act on the team the key (or session) belongs to. The SDKs don't wrap these endpoints, so the examples use plain HTTP; call them with any HTTP client. ### Create a key `POST /v1/api-keys` | Parameter | Type | Default | Description | |---|---|---|---| | `name` | string | required | What uses the key, e.g. `billing-service`. 1–100 characters after trimming spaces. | | `role` | string | required | `writer` or `admin`. | ```bash curl -X POST https://api.pushqueue.dev/v1/api-keys \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name": "billing-service", "role": "writer"}' ``` Response, `201 Created`: ```json { "key": { "id": 42, "name": "billing-service", "prefix": "pq_AbC12dEf", "role": "writer", "created_at": "2026-11-28T10:15:00Z" }, "secret": "pq_AbC12dEfGh3456789ijklMNOPqrstuvw" } ``` | Field | Type | Description | |---|---|---| | `secret` | string | The API key itself. Shown only once; store it now. | | `key` | object | The key's metadata (see [Key object](#key-object)). | An empty or too-long name, or a role other than `writer`/`admin`, returns `400 invalid_argument`. Use this when you provision environments with a script and want each service to get its own key. ### List keys `GET /v1/api-keys` ```bash curl https://api.pushqueue.dev/v1/api-keys \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` ```json { "keys": [ { "id": 42, "name": "billing-service", "prefix": "pq_AbC12dEf", "role": "writer", "created_by": "ada@example.com", "created_at": "2026-11-28T10:15:00Z", "last_used_at": "2026-11-28T11:02:00Z" } ], "config_keys": 0 } ``` | Field | Type | Description | |---|---|---| | `keys` | array | Keys created in the dashboard or through the API, newest first. On the hosted service, only the current team's keys. | | `config_keys` | integer | How many more keys are defined in the server config file. Always `0` on the hosted service. | #### Key object | Field | Type | Description | |---|---|---| | `id` | integer | Use it to revoke the key. | | `name` | string | The name given at creation. | | `prefix` | string | The first 11 characters of the key, for recognizing it. | | `role` | string | `writer` or `admin`. | | `created_by` | string | Email of the user who created it. Omitted when it was created with an API key. | | `created_at` | string (date-time) | When it was created. | | `last_used_at` | string (date-time) | When it last authenticated a request. Omitted if never used. Updated at most once a minute per key, so treat it as approximate. | ### Revoke a key `DELETE /v1/api-keys/{id}` ```bash curl -X DELETE https://api.pushqueue.dev/v1/api-keys/42 \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` Returns `204 No Content`. Requests using that key fail with `401` from then on. An `id` that doesn't exist, or belongs to another team, returns `404 not_found`. There is no undo; create a new key instead. In the console, click **Revoke** next to the key and confirm. ## Use a key Send the key in the `Authorization` header of every request: ```http Authorization: Bearer pq_... ``` Every SDK takes the key when you create the client and sends the header for you. None of them read an environment variable on their own, so pass it in explicitly: **TypeScript** ```ts const pq = new Pushq({ apiKey: process.env.PUSHQ_API_KEY }); ``` **Python** ```python import os from pushq import Pushq pq = Pushq(api_key=os.environ["PUSHQ_API_KEY"]) ``` **Go** ```go // "" means the hosted API. pq := pushq.New("", os.Getenv("PUSHQ_API_KEY")) ``` **Java** ```java Pushq pq = Pushq.builder() .apiKey(System.getenv("PUSHQ_API_KEY")) .build(); ``` **.NET** ```csharp using var pq = new PushqClient( apiKey: Environment.GetEnvironmentVariable("PUSHQ_API_KEY")); ``` **curl** ```bash curl https://api.pushqueue.dev/v1/queues/emails \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` For a self-hosted server, also pass its URL. See [Install & configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/) for every constructor option. The `pushq` command-line client reads `PUSHQ_API_KEY` (or `--api-key`) and talks to `PUSHQ_SERVER` (or `--server`, default `http://localhost:8080`). ## Store keys safely - Keep keys out of source control. Load them from an environment variable such as `PUSHQ_API_KEY`, set by your secret manager, deployment platform or a git-ignored `.env` file. - Give each service or environment its own key, named after it. Then you can revoke one without touching the others, and `last_used_at` tells you which one is in use. - Prefer writer keys in application code. Keep admin keys for people and tooling. - Never ship a key to a browser or mobile app. Anyone who can read the page can read the key. Enqueue tasks from your backend instead. ## Rotate a key with zero downtime pushq accepts any number of keys at once, so you can overlap old and new: 1. Create a new key with the same role and a name that marks it as the replacement, for example `billing-service-2026-11`. 2. Deploy the new key to the service (update the secret, then restart or redeploy). 3. Check that the old key's `last_used_at` stops moving. It updates at most once a minute, so wait a few minutes after the rollout finishes. 4. Revoke the old key. Use this when a key is old, someone who knew it left, or your policy requires periodic rotation. ## Revoke a leaked key If a key may have been exposed (committed to a repository, pasted in a ticket, printed in logs): 1. Revoke it immediately in **Settings → API keys** or with `DELETE /v1/api-keys/{id}`. It stops working on the next request. 2. Create a replacement and deploy it. Services using the old key get `401` until they have the new one, so do this quickly, or create and deploy the replacement first if you can afford a few minutes. 3. Review what the key could do. A writer key could enqueue, run and delete tasks and change or purge queues it knew by name; an admin key could also list and delete queues and manage members and keys. Check your queues and team in the console. ## Config-file keys (self-hosted) A self-hosted server can also take keys from its configuration. These exist alongside keys created in the dashboard. ```yaml # pushq.yaml api_keys: - { key: "pq_admin_", role: admin } - { key: "pq_writer_", role: writer } ``` Or as an environment variable, a comma-separated list of `role:key` pairs. When set, it replaces the file's `api_keys` list: ```bash PUSHQ_API_KEYS="admin:pq_admin_,writer:pq_writer_" ``` The key can be any non-empty string, and the role must be `admin` or `writer` or the server refuses to start. Generate a long random value, for example: ```bash echo "pq_$(openssl rand -hex 24)" ``` How they differ from dashboard keys: | | Config-file keys | Dashboard keys | |---|---|---| | Where they live | Config file or `PUSHQ_API_KEYS` | The database (stored as SHA-256 hashes) | | Create and revoke | Edit the config and restart the server | Console or `/v1/api-keys`, effective immediately | | Shown in the dashboard | Only as a count ("N more keys are defined in the server config file") | Listed with name, prefix, role and last use | | `last_used_at` | Not tracked | Tracked | | First-time setup | If any exist, creating the first dashboard account requires one of the **admin** config keys | Not involved | To rotate a config-file key, add the new key next to the old one, restart, deploy the new key to your apps, then remove the old one and restart again. :::caution A self-hosted server with no config keys and no dashboard account yet accepts anonymous requests as admin. Create the first account (or set `api_keys`) before exposing it. See [Team members](https://pushqueue.dev/docs/guides/team-members/#first-time-setup). ::: In [SaaS mode](https://pushqueue.dev/docs/self-hosting/saas-mode/) (a self-hosted server running multi-tenant with WorkOS), config-file keys become **operator keys**: they don't belong to any team, they see every team's queues, and teams never see them. Teams create their own keys in the console as described above. On a self-hosted server's dashboard you can also sign in with an API key instead of an account: on the sign-in page choose **Use an API key instead**. The key is kept for that browser tab only. --- # Team members and roles > Invite people to your pushq team, assign admin, member or viewer roles, and manage invites and password resets on hosted and self-hosted servers. Source: https://pushqueue.dev/docs/guides/team-members/ People use the pushq dashboard as members of a team, and each member has a role that decides what they can do. This page covers roles, inviting and removing people, and the matching API endpoints. How sign-in and invites work depends on where pushq runs: | | Hosted service (console.pushqueue.dev) | Self-hosted server | |---|---|---| | Sign-in | A 6-digit code emailed to you, or GitHub. Signing in the first time creates your account. | Email and password. The first person creates the admin account. | | Teams | Create as many as you like; one person can be in several and switch between them. | One team: everyone with an account on the server. | | Data | Isolated per team: queues, tasks, stats and API keys. | Shared by everyone on the server. | | Invites | Emailed for you. | You get a one-time link to send yourself. | | Forgotten password | Not applicable (no passwords). | Reset link from an admin, or the `pushq users reset-password` command. | A self-hosted server can also run like the hosted service; see [SaaS mode](https://pushqueue.dev/docs/self-hosting/saas-mode/). Everything this page says about the hosted service applies to SaaS mode too. ## Roles | Role | Can | |---|---| | Admin | Everything, including team members, invites, API keys and the team name. | | Member | Create, change, pause, resume, purge and delete queues; enqueue, run and delete tasks. | | Viewer | Read-only: browse queues, stats, tasks and attempt history. | The full permission table, from the server's permission checks: | Capability | Endpoints | Admin | Member | Viewer | |---|---|---|---|---| | View a queue, its stats, tasks and attempts | `GET /v1/queues/{queue}`, `.../stats`, `.../tasks`, `.../tasks/{id}`, `.../attempts` | Yes | Yes | Yes | | List and browse queues | `GET /v1/queues` | Yes | Yes | Yes | | Create and change queues; pause, resume, purge | `POST /v1/queues`, `PUT`/`PATCH /v1/queues/{queue}`, `:pause`, `:resume`, `:purge` | Yes | Yes | No | | Enqueue, force-run and delete tasks | `POST .../tasks`, `.../tasks:batch`, `.../tasks/{id}:run`, `DELETE .../tasks/{id}` | Yes | Yes | No | | Delete queues | `DELETE /v1/queues/{queue}` | Yes | Yes | No | | Manage members and invites | `/v1/users`, `/v1/invites` | Yes | No | No | | Create and revoke API keys | `/v1/api-keys` | Yes | No | No | | Rename the team (hosted) | `PATCH /v1/teams/current` | Yes | No | No | | Change your own name and password | `/v1/me`, `/v1/me/password` | Yes | Yes | Yes | A team always keeps at least one admin: the last admin can't be demoted or removed. Trying returns `400 failed_precondition` with `"the team must keep at least one admin"`. API keys have their own two roles, `writer` and `admin`; see [API keys](https://pushqueue.dev/docs/guides/api-keys/#key-roles). ## On the hosted service ### Sign up and sign in 1. Open the [console](https://console.pushqueue.dev/). 2. Click **Continue with GitHub**, or enter your email and click **Email me a sign-in code**, then type the 6-digit code from the email. The code expires in 10 minutes; **Send a new code** sends another. 3. If this is the first time you've signed in, your account is created now. There's no separate sign-up and no password. Sometimes a GitHub sign-in asks you to verify your email first: the console asks for a verification code that was just emailed to you. Enter it to finish signing in. Your sign-in lasts 30 days and is extended automatically while you keep using it. ### Create a team Queues, tasks and API keys belong to a team, so a new account starts on the **Welcome** screen: 1. Enter a team name (1–100 characters, usually your company or project). 2. Click **Create team**. You become the team's admin and land on its (empty) queue list. To create another team later, open the account menu and choose **+ Create team**. Use this when you want a separate workspace, for example one per company or per client, with its own queues and keys. ### Invite people Admins invite from **Settings → Team**: 1. Under **Invite a team member**, enter their email address. 2. Pick a role: **Admin**, **Member** or **Viewer**. 3. Click **Send invite**. We email them an invitation. The invite appears under **Pending invites** with its expiry date until they accept, and **Revoke** cancels it. To join, they accept the invitation from the email and then sign in to the console with that email address; they join with the role you picked. ### Switch teams If you belong to several teams, open the account menu (top right). Under **Teams**, click the team you want; the console reloads its queues. The console remembers the team you used last and opens it the next time you sign in. ### Rename the team Admins can change the name under **Settings → Team → Team name**. Everyone in the team sees it in the team switcher. ```bash curl -X PATCH https://api.pushqueue.dev/v1/teams/current \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name": "Acme Production"}' ``` ### Change a role In **Settings → Team**, pick a new role from the dropdown next to the member. It applies to their next request. ### Remove a member Click **Remove** next to the member and confirm. They lose access to this team immediately, but keep their pushq account and any other teams they belong to. You can invite them again later. ## On a self-hosted server ### First-time setup When you first open the dashboard of a new server (at `/`, for example `http://localhost:8080/`), it asks you to create the admin account: 1. Enter your name, email and a password (at least 8 characters). 2. If the server has `api_keys` in its config, also enter one of its **admin** keys. This stops whoever reaches the dashboard first from claiming a protected server. 3. Click **Create admin account**. :::caution Until the first account exists, a server without config-file API keys accepts anonymous requests with full access. Create the admin account before exposing the server, and serve the dashboard over HTTPS. ::: From then on, the API needs either a dashboard session or an API key. Create keys for your apps under **Settings → API keys** (see [API keys](https://pushqueue.dev/docs/guides/api-keys/)). `pushq dev` turns authentication off entirely, so none of this applies to it. ### Invite people with a link pushq doesn't send email on a self-hosted server. Instead: 1. In **Settings → Team**, enter the person's email, pick a role and click **Create invite link**. 2. Copy the link from the dialog (it looks like `https://pushq.example.com/invite#token=pqi_...`) and send it to them however you like. 3. They open it, enter their name and choose a password, and click **Create account**. They're signed in straight away. Each link works once and expires after 7 days. Creating a new invite for the same email replaces the previous link. You can't invite an email that already has an account (`409 already_exists`). Pending invites are listed on the Team page, where **Revoke** cancels them. ### Change roles and remove people Use the role dropdown and **Remove** button on **Settings → Team**. Removing someone deletes their account and signs them out everywhere. ### Reset a password Admins can make a reset link from **Settings → Team**: click **Reset password** next to the person and send them the link. It works once, expires after 24 hours, and signs them out on every device once they set the new password. Making a new link replaces the previous one. People can change their own password under **Settings → Your account**; that signs them out on their other devices. If nobody can sign in (for example, the only admin forgot their password), run this on the server. It works directly on the database, so the server doesn't have to be reachable: ```bash pushq users reset-password you@example.com -c /etc/pushq/pushq.yaml --url https://pushq.example.com ``` | Flag | Default | Description | |---|---|---| | `-c`, `--config` | none | The server's config file, used to find the database. | | `--db` | from config | Database URL (`sqlite:PATH` or `postgres://...`), overriding the config. | | `--url` | `http://localhost:8080` | Public URL of the server, used to build the printed link. | It prints a one-time link valid for 24 hours. `pushq users list` lists every account with its role and last sign-in. ## API reference ### Which credentials each endpoint accepts | Endpoints | Admin API key | Signed-in dashboard user | |---|---|---| | `/v1/users`, `/v1/invites`, `PATCH /v1/teams/current` | Yes | Admins only | | `PATCH /v1/me`, `POST /v1/me/password` | No | Any role | | `GET /v1/teams`, `POST /v1/teams`, `POST /v1/teams/{id}:switch` | No | Any role (hosted / SaaS mode only) | | `/v1/auth/*` | No credentials needed | | Session-only endpoints use the `pushq_session` cookie that sign-in sets; the console calls them for you. If you call them yourself with the cookie, `POST`, `PATCH` and `DELETE` requests must also send an `X-Requested-With` header (any value), or they're rejected with `403`. On the hosted service, an admin API key acts on the team it belongs to. Invites it sends have no inviting user. ### User object | Field | Type | Description | |---|---|---| | `id` | integer | Use it in `/v1/users/{id}`. | | `email` | string | | | `name` | string | May be empty. | | `role` | string | `admin`, `member` or `viewer`. On the hosted service, the role in the current team. | | `created_at` | string (date-time) | | | `last_login_at` | string (date-time) | Omitted if they never signed in. | ### Invite object | Field | Type | Description | |---|---|---| | `id` | integer | Use it in `DELETE /v1/invites/{id}`. | | `kind` | string | `invite` (new member) or `reset` (password reset link). | | `email` | string | | | `role` | string | The role they'll get. Omitted for reset links. | | `created_at` | string (date-time) | | | `expires_at` | string (date-time) | | ### List members `GET /v1/users` returns `{"users": [User, ...]}`. Self-hosted: every account, sorted by email. Hosted: the current team's members. ```bash curl https://api.pushqueue.dev/v1/users \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` ```json { "users": [ { "id": 7, "email": "ada@example.com", "name": "Ada", "role": "admin", "created_at": "2026-10-01T09:00:00Z", "last_login_at": "2026-11-28T08:30:00Z" } ] } ``` ### Change a member `PATCH /v1/users/{id}` returns the updated User. | Parameter | Type | Default | Description | |---|---|---|---| | `role` | string | unchanged | `admin`, `member` or `viewer`. The last admin can't be demoted. | | `name` | string | unchanged | Self-hosted only, at most 100 characters. On the hosted service names come from the person's sign-in, and only `role` can be changed. | ```bash curl -X PATCH https://api.pushqueue.dev/v1/users/12 \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{"role": "viewer"}' ``` ### Remove a member `DELETE /v1/users/{id}` returns `204`. They lose access immediately. The last admin can't be removed. ### Create a password-reset link (self-hosted) `POST /v1/users/{id}/reset-link` returns `201`: | Field | Type | Description | |---|---|---| | `link` | Invite | The reset link's details (`kind` is `reset`). | | `path` | string | The single-use link relative to the server, e.g. `/invite#token=pqi_...`. Prefix it with your server's URL. | Returns `404` on the hosted service. ### List pending invites `GET /v1/invites` returns `{"invites": [Invite, ...]}`: unexpired, unaccepted invites, newest first. ### Invite someone `POST /v1/invites` | Parameter | Type | Default | Description | |---|---|---|---| | `email` | string | required | Who to invite. | | `role` | string | required | `admin`, `member` or `viewer`. | ```bash curl -X POST https://api.pushqueue.dev/v1/invites \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{"email": "grace@example.com", "role": "member"}' ``` Response, `201 Created`: | Field | Type | Description | |---|---|---| | `invite` | Invite | The new invite. | | `emailed` | boolean | Hosted: `true`, the invitation was emailed. | | `path` | string | Self-hosted: the invite link to send, relative to the server (`/invite#token=pqi_...`). | ### Revoke an invite `DELETE /v1/invites/{id}` returns `204`, or `404` if there's no such pending invite. ### Your own account `PATCH /v1/me` with `{"name": "..."}` (at most 100 characters) changes your name and returns your User. `POST /v1/me/password` (self-hosted only) changes your password and returns `204`. Your other sessions are signed out. | Parameter | Type | Default | Description | |---|---|---|---| | `current_password` | string | required | Your current password. | | `new_password` | string | required | At least 8 characters, at most 256 bytes. | ### Teams (hosted / SaaS mode) A Team object has `id` (integer), `name` (string) and `role` (your role in it). | Endpoint | Body | Response | |---|---|---| | `GET /v1/teams` | none | `{"teams": [Team, ...]}`, the teams you belong to. | | `POST /v1/teams` | `{"name": "..."}`, 1–100 characters | `201` Team. You become its admin and your session switches to it. | | `POST /v1/teams/{id}:switch` | none | `204`. Your session now works in that team. `404` if you're not a member. | | `PATCH /v1/teams/current` | `{"name": "..."}`, 1–100 characters | `200` Team. Admins only. | On a self-hosted server without SaaS mode these return `404`. ### Sign-in endpoints The dashboard uses these; you rarely need them directly. None need credentials. | Endpoint | Where | What it does | |---|---|---| | `GET /v1/auth/session` | Both | Who you are and how this server signs people in (see below). | | `POST /v1/auth/setup` | Self-hosted | Create the first admin. Body: `email`, `name`, `password`, and `api_key` (an admin config key, required when the server has config keys). Only works while no account exists. | | `POST /v1/auth/login` | Self-hosted | Body: `email`, `password`. Sets the session cookie. | | `POST /v1/auth/logout` | Both | Ends the session. `204`. | | `GET /v1/auth/invites/{token}` | Self-hosted | Look up an invite or reset link without using it. Returns an Invite. | | `POST /v1/auth/invites/{token}:accept` | Self-hosted | Body: `name`, `password`. Creates the account (invite) or sets the password (reset) and signs in. | | `POST /v1/auth/email-code` | Hosted | Body: `email`. Emails a 6-digit code. Returns `{"sent": true}`. | | `POST /v1/auth/email-code:verify` | Hosted | Body: `email`, `code`. Signs in. | | `GET /v1/auth/workos/login?provider=github` | Hosted | Starts GitHub sign-in (browser redirect). | Password, setup, invite-accept and email-code endpoints are rate limited per client IP (10 attempts, then one more every 6 seconds); over the limit they return `429 rate_limited`. `GET /v1/auth/session` returns: | Field | Type | Description | |---|---|---| | `mode` | string | `saas` (hosted / SaaS mode), `locked` (sign-in required), `open` (self-hosted with no accounts or config keys yet) or `dev` (authentication off). | | `authenticated` | boolean | Whether the request carried valid credentials. | | `kind` | string | `user`, `api_key` or `open`. | | `role` | string | Your role (or the key's role). | | `user` | User | When signed in as a person. | | `key_name` | string | When authenticated with an API key. | | `permissions` | object | `read`, `list`, `write`, `delete_queue`, `manage` booleans. | | `setup_required` | boolean | Self-hosted: no account exists yet. | | `setup_requires_key` | boolean | Self-hosted: setup needs an admin config key. | | `sso_providers` | array | `["workos"]` in hosted / SaaS mode. | | `team` | Team | Hosted: the team this session works in. | | `teams` | array | Hosted: all your teams. | | `needs_team` | boolean | Hosted: you must create or pick a team first. | --- # Dashboard and console > A tour of the pushq dashboard: queues by folder, live queue stats, task attempt history, pause, resume, purge and run actions, and settings. Source: https://pushqueue.dev/docs/guides/dashboard/ The dashboard is a web UI for watching and operating your queues. It shows every queue and its live numbers, lets you inspect any task and its delivery attempts, and gives admins the team and API key settings. ## Where it lives - **Hosted service:** [console.pushqueue.dev](https://console.pushqueue.dev/). Sign in with GitHub or a code emailed to you; see [Team members](https://pushqueue.dev/docs/guides/team-members/#sign-up-and-sign-in). - **Self-hosted server:** the site root of your server, for example `http://localhost:8080/` or `https://pushq.example.com/`. The dashboard is built into the `pushq` binary; there's nothing extra to install or run. Requests under `/v1/` go to the API, and any other page a browser loads gets the dashboard. On a self-hosted server you sign in with email and password, or click **Use an API key instead** on the sign-in page to use a key for that browser tab only. Under `pushq dev` authentication is off and the dashboard opens straight away. Every screen refreshes itself every 5 seconds, so you can leave it open while tasks flow. What you see depends on your role. Viewers get every screen but none of the action buttons; members and writer keys get the queue and task actions; only admins see the Team and API keys settings. See [Roles](https://pushqueue.dev/docs/guides/team-members/#roles). ## Queues The home page lists your queues. | Column | Shows | |---|---| | Name | The queue name. Click a row to open the queue. | | State | `running`, `paused` or `disabled`. | | Created | How long ago the queue was created (hover for the exact time). | ### Folders Queue names can contain `/`, and the dashboard turns those into folders: queues named `user/instagram` and `user/tiktok` appear inside a `user/` folder. A folder row summarizes what's inside it, for example `2 queues, 1 paused`. Click it to open the folder; the breadcrumbs at the top take you back up. Folders are only part of queue names and need no setup. See [Queues](https://pushqueue.dev/docs/concepts/queues/). ### Filter and paging Type in **Filter by name prefix…** to narrow the list. Inside a folder the filter applies within that folder, and matches are shown as a flat list. Choose 10, 25, 50 or 100 rows per page; the dashboard remembers your choice. A single view loads at most 5,000 queues; if there are more, open a folder or filter to narrow it down. ### First run When there are no queues at all yet, the list is replaced by a **No queues yet** panel. Admins get a **Create API key** button that opens the API keys settings, and everyone gets an **API docs** link. Queues and tasks are created from your app or the API, not from the dashboard; see the [Quickstart](https://pushqueue.dev/docs/getting-started/quickstart/). ### Signed in with a writer key Writer API keys can't list queues, so instead of the list you see **Listing queues isn't allowed for this key** and a box to open a queue by its name. ## Queue detail Opening a queue shows its state, live statistics, configuration and tasks. ### Actions Members and admins (and writer or admin keys) get two buttons in the header: - **Pause / Resume:** pausing stops dispatching new tasks while still accepting new ones; resuming starts dispatching again. Use this when a downstream service is down or being deployed and you want tasks to wait instead of failing. - **Purge:** after you confirm, deletes every task created up to now, including in-flight ones. Their results are discarded and their IDs become reusable. Tasks created after the purge are unaffected. Use this to throw away a backlog you no longer want delivered. The dashboard doesn't delete queues. Use `DELETE /v1/queues/{queue}` with an admin key (or as a member or admin), see the [API reference](https://pushqueue.dev/docs/reference/api/). ### Statistics | Card | Shows | |---|---| | Pending | Tasks waiting to be dispatched. | | Running | Tasks being delivered right now. | | Succeeded | Tasks that finished successfully and are still retained. | | Failed | Tasks that ran out of retries and are still retained. | | Scheduled | Tasks due in the future. | | Oldest due | How long the oldest due task has been waiting, with its due time. A growing value means the queue is falling behind. | | Dispatched | Dispatches in the last minute and the last hour. | | Errors | Failed dispatches in the last minute and the last hour. | These come from `GET /v1/queues/{queue}/stats`. ### Configuration A summary of the queue's settings: state, target (method and base URL), whether a signing secret is configured, the dead-letter queue (a link, if set), rate limit (dispatches per second and burst), maximum concurrent dispatches, retry limits (attempts and maximum retry duration), backoff (minimum to maximum, and doublings), when it was created and updated, and the last purge if there was one. The dashboard shows configuration but doesn't edit it; change it through the API or an SDK. See [Rate limits](https://pushqueue.dev/docs/guides/rate-limits/), [Retries](https://pushqueue.dev/docs/concepts/retries/) and [Dead-letter queues](https://pushqueue.dev/docs/concepts/dead-letter-queues/). ### Tasks The task table lists the queue's tasks, newest first, with tabs to filter by state: **All**, **Pending**, **Running**, **Succeeded**, **Failed**. | Column | Shows | |---|---| | ID | The task ID. Click a row to open the task. | | State | `pending`, `running`, `succeeded` or `failed`. | | Scheduled | When it's due (or was due). | | Dispatches | How many times it has been sent. | | Last attempt | The HTTP status of the last attempt (green below 400, red otherwise) and its error, if any. | Use **Previous** and **Next** to page through tasks. ## Task detail The task page shows everything about one task. ### Actions Members and admins (and writer or admin keys) get: - **Run now:** dispatches a pending task immediately instead of waiting for its scheduled time or next retry, even if the queue is paused or at its rate limit. Use this when a task is waiting out a long backoff and you've fixed the receiver, or to test a scheduled task without waiting. Tasks that already succeeded or failed can't be run again. - **Delete:** after you confirm, removes the task. Its ID stays reserved for the dedup window before it can be reused. Use this to cancel a task that should no longer be sent. ### Request What pushq sends to your endpoint: the method and full URL, the task's headers, and the body. JSON and text bodies are shown with their size; binary bodies show only their size. ### Execution | Field | Shows | |---|---| | State | The task's state. | | Scheduled | When it's due. | | Created | When it was enqueued. | | Dispatch deadline | How long pushq waits for your endpoint to respond. | | Dispatches | How many times it was sent. | | Responses | How many times your endpoint answered. | | First attempt | When it was first sent, if it has been. | | Finished | When it succeeded or failed for good, if it has. | | Last attempt | Time, HTTP status and error of the most recent attempt. | | Retry override | Shown when the task has its own retry settings that override the queue's. | ### Attempts The delivery history, newest first: | Column | Shows | |---|---| | # | Attempt number. | | Dispatched | When it was sent. | | Status | The HTTP status your endpoint returned (green below 400, red otherwise). | | Error kind | The kind of failure, for example a timeout or connection error, if any. | | Duration | How long the attempt took. | | Error snippet | Click **show** to see the start of the error response. | Use this to see why a task is being retried: the status codes and error snippets usually point straight at the problem in your receiver. See [Delivery](https://pushqueue.dev/docs/concepts/delivery/). ## Settings Open the account menu in the top-right corner and choose **Settings**. The tabs you see depend on your role. ### Your account Everyone signed in with an account sees this tab. - **Profile:** your email and role, and a field to change your name. - **Password** (self-hosted): change your password. This signs you out on your other devices. - **Sign-in** (hosted): a reminder that you sign in with an emailed code or GitHub; there's no password to manage. ### Team Admins only. Invite people, change roles, remove members, and see pending invites. On the hosted service this tab also renames the team; on a self-hosted server it creates invite links and password-reset links. See [Team members](https://pushqueue.dev/docs/guides/team-members/). ### API keys Admins only. Create keys (name and role), copy a new key from the one-time dialog, and revoke keys. The table shows each key's name, prefix, role, creator, creation time and last use. On a self-hosted server, keys defined in the config file are counted below the table. See [API keys](https://pushqueue.dev/docs/guides/api-keys/). ## Account menu The menu in the top-right corner shows who you are (name, email and role, or the API key's name and role). On the hosted service it also lists your **Teams**: click one to switch, or choose **+ Create team**. It links to **Settings** and has **Sign out**. Next to it, the theme button switches between light and dark mode; your choice is remembered in the browser. --- # Migrate from Google Cloud Tasks > Migrate from Google Cloud Tasks to pushq: a concept map, before-and-after client code in five languages, and signed deliveries instead of OIDC. Source: https://pushqueue.dev/docs/guides/migrate-from-cloud-tasks/ pushq keeps Cloud Tasks' delivery semantics: rate limits with token-bucket bursts, the same retry backoff math, pause/resume/purge, named-task deduplication and at-least-once HTTP push delivery. Most migrations are a mechanical rename of fields and calls. Use this guide when you have code that uses a `google-cloud-tasks` client library or the Cloud Tasks REST API with HTTP targets, and you want to run the same workload on pushq, hosted or self-hosted. ## Cloud Tasks to pushq concept map | Cloud Tasks | pushq | |---|---| | Project / location / queue path | A queue name: `[a-z0-9-]` segments joined by `/` for folders (e.g. `billing/invoices`), up to 200 characters | | `CreateQueue` / `UpdateQueue` | `PUT /v1/queues/{queue}`: one idempotent upsert, cheap enough to call before every enqueue | | `rateLimits.maxDispatchesPerSecond` | `rate_limits.max_dispatches_per_second` | | `rateLimits.maxBurstSize` | `rate_limits.max_burst_size` (`0` = automatic, like Cloud Tasks) | | `rateLimits.maxConcurrentDispatches` | `rate_limits.max_concurrent_dispatches` | | `retryConfig.maxAttempts` | `retry.max_attempts` (`-1` = unlimited) | | `retryConfig.maxRetryDuration` | `retry.max_retry_duration_seconds` (`0` = unlimited) | | `retryConfig.minBackoff` / `maxBackoff` | `retry.min_backoff_seconds` / `retry.max_backoff_seconds` | | `retryConfig.maxDoublings` | `retry.max_doublings` (same doubling-then-linear schedule) | | `PauseQueue` / `ResumeQueue` / `PurgeQueue` | `POST /v1/queues/{queue}:pause`, `:resume`, `:purge` | | `DeleteQueue` | `DELETE /v1/queues/{queue}`. The name can be reused immediately (Cloud Tasks blocks reuse for days). | | `CreateTask` with `task.name` | `POST /v1/queues/{queue}/tasks` with `task_id` (`[A-Za-z0-9_-]`, up to 500 characters). Reusing an ID within the dedup window (default 1h) returns `409 already_exists`. | | `httpRequest.url` | `url`, or `path` resolved against the queue's `target.base_url` | | `httpRequest.httpMethod` | `method` (default `POST`), or `target.method` to override it for the whole queue | | `httpRequest.headers` / `body` | `headers` / `body_base64`, or `json_body` for JSON payloads (no manual encoding; sets `Content-Type: application/json`) | | `scheduleTime` | `schedule_time`, or `delay_seconds` | | `dispatchDeadline` | `dispatch_deadline_seconds` (same 15s to 30m range, default 10m) | | `RunTask` | `POST /v1/queues/{queue}/tasks/{id}:run` (also bypasses rate limits and the paused state) | | `ListTasks` / `GetTask` / `DeleteTask` | The same, plus `state` and `id_prefix` filters and cursor pagination | | OIDC / OAuth tokens on delivery | Static headers (`target.headers`) or Standard Webhooks HMAC signing (`target.signing_secret`). See [authenticate deliveries without OIDC tokens](#authenticate-deliveries-without-oidc-tokens). | | `X-CloudTasks-QueueName`, `X-CloudTasks-TaskName`, … | `X-Pushq-Queue`, `X-Pushq-Task-Id`, `X-Pushq-Attempt`, `X-Pushq-Execution-Count`, `X-Pushq-Scheduled-Time` | | App Engine targets, pull queues, `BufferTask` | Not supported. pushq delivers HTTP push only. | Parameter names in this guide are the JSON field names. The SDKs use their language's casing: camelCase in TypeScript and Java, snake_case in Python, PascalCase in Go and .NET. ## What pushq adds over Cloud Tasks - **Per-task retry overrides.** Set `retry` on a task to override any part of the queue's retry config for that task. In the Cloud Tasks Python client, `client.create_task(..., retry=Retry(...))` is a retry policy for the *enqueue RPC itself*, not for delivery, which is a common source of silent misconfiguration. In pushq, `retry` on a task controls delivery retries. - **Many queues.** Cloud Tasks limits queues per region. A self-hosted pushq server has no queue cap and is designed for 10,000+ dynamic queues, for example one per tenant. On the hosted service, the number of queues depends on your [plan](https://pushqueue.dev/pricing). - **Dead-letter queues.** Set `dead_letter_queue` on a queue and tasks that exhaust their retries are copied there. See [dead-letter queues](https://pushqueue.dev/docs/concepts/dead-letter-queues/). - **Stats API.** `GET /v1/queues/{queue}/stats?id_prefix=` returns depth by state, the age of the oldest due task and recent error counts, without listing tasks. - **Batch enqueue.** `POST /v1/queues/{queue}/tasks:batch` takes up to 500 tasks; each succeeds or fails on its own. - **Retained history.** Finished tasks and their full attempt history are kept for a configurable time (default 24h for succeeded, 7 days for failed). - **Longer schedules.** Tasks can be scheduled up to a year ahead by default (Cloud Tasks: 30 days); self-hosters can change the limit. ## Cloud Tasks semantics pushq keeps - **Backoff schedule.** The retry interval starts at `min_backoff_seconds`, doubles `max_doublings` times, then grows linearly by `2^max_doublings × min_backoff_seconds` per retry, capped at `max_backoff_seconds`. For example, min 10s, max 300s, 3 doublings gives 10, 20, 40, 80, 160, 240, 300, 300, … - **The both-limits rule.** When `max_attempts` and `max_retry_duration_seconds` are both set, a task keeps retrying until **both** are reached, exactly like Cloud Tasks. If either is unlimited, the other one alone decides. - **What counts as success.** Any 2xx response. Anything else, or no response before `dispatch_deadline_seconds`, is a failed attempt. A `429` or `503` with a `Retry-After` header also briefly cools the whole queue down. - **At-least-once delivery.** Make handlers idempotent. With signing on, the `webhook-id` header (`queue/task_id`) is stable across retries; use it as an idempotency key. - **Run and pause.** `:run` works on paused queues and bypasses rate limits. A `disabled` queue refuses new tasks and `:run`. See [retries and backoff](https://pushqueue.dev/docs/concepts/retries/) and [how delivery works](https://pushqueue.dev/docs/concepts/delivery/) for the details. ## Migrate your client code The example creates or updates a queue named `account-42` limited to 10 deliveries per second, then enqueues a JSON task for `/hooks/send` in one hour, deduplicated by ID, with at most 3 attempts. ### Before: Google Cloud Tasks client **TypeScript** ```ts const client = new CloudTasksClient(); const parent = client.queuePath(project, location, "account-42"); await client.createTask({ parent, task: { name: `${parent}/tasks/follow-up-${uid}`, scheduleTime: { seconds: Math.floor(Date.now() / 1000) + 3600 }, httpRequest: { httpMethod: "POST", url: `${baseUrl}/hooks/send`, headers: { "Content-Type": "application/json", "x-internal-key": KEY }, body: Buffer.from(JSON.stringify(payload)).toString("base64"), }, }, }); ``` **Python** ```python import json, time from google.cloud import tasks_v2 from google.protobuf import timestamp_pb2 client = tasks_v2.CloudTasksClient() parent = client.queue_path(project, location, "account-42") client.create_task(parent=parent, task={ "name": f"{parent}/tasks/follow-up-{uid}", "schedule_time": timestamp_pb2.Timestamp(seconds=int(time.time() + 3600)), "http_request": { "http_method": tasks_v2.HttpMethod.POST, "url": f"{base_url}/hooks/send", "headers": {"Content-Type": "application/json", "x-internal-key": KEY}, "body": json.dumps(payload).encode(), }, }) ``` **Go** ```go import ( cloudtasks "cloud.google.com/go/cloudtasks/apiv2" "cloud.google.com/go/cloudtasks/apiv2/cloudtaskspb" "google.golang.org/protobuf/types/known/timestamppb" ) client, err := cloudtasks.NewClient(ctx) if err != nil { return err } defer client.Close() parent := fmt.Sprintf("projects/%s/locations/%s/queues/account-42", project, location) body, _ := json.Marshal(payload) _, err = client.CreateTask(ctx, &cloudtaskspb.CreateTaskRequest{ Parent: parent, Task: &cloudtaskspb.Task{ Name: parent + "/tasks/follow-up-" + uid, ScheduleTime: timestamppb.New(time.Now().Add(time.Hour)), MessageType: &cloudtaskspb.Task_HttpRequest{ HttpRequest: &cloudtaskspb.HttpRequest{ HttpMethod: cloudtaskspb.HttpMethod_POST, Url: baseURL + "/hooks/send", Headers: map[string]string{"Content-Type": "application/json", "x-internal-key": key}, Body: body, }, }, }, }) ``` **Java** ```java import com.google.cloud.tasks.v2.*; import com.google.protobuf.ByteString; import com.google.protobuf.Timestamp; try (CloudTasksClient client = CloudTasksClient.create()) { String parent = QueueName.of(project, location, "account-42").toString(); Task task = Task.newBuilder() .setName(TaskName.of(project, location, "account-42", "follow-up-" + uid).toString()) .setScheduleTime(Timestamp.newBuilder() .setSeconds(Instant.now().plusSeconds(3600).getEpochSecond())) .setHttpRequest(HttpRequest.newBuilder() .setHttpMethod(HttpMethod.POST) .setUrl(baseUrl + "/hooks/send") .putHeaders("Content-Type", "application/json") .putHeaders("x-internal-key", key) .setBody(ByteString.copyFromUtf8(payloadJson))) .build(); client.createTask(parent, task); } ``` **.NET** ```csharp using Google.Cloud.Tasks.V2; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; var client = await CloudTasksClient.CreateAsync(); await client.CreateTaskAsync(new CreateTaskRequest { ParentAsQueueName = new QueueName(project, location, "account-42"), Task = new Google.Cloud.Tasks.V2.Task { TaskName = new TaskName(project, location, "account-42", $"follow-up-{uid}"), ScheduleTime = Timestamp.FromDateTime(DateTime.UtcNow.AddHours(1)), HttpRequest = new HttpRequest { HttpMethod = HttpMethod.Post, Url = $"{baseUrl}/hooks/send", Headers = { ["Content-Type"] = "application/json", ["x-internal-key"] = key }, Body = ByteString.CopyFromUtf8(payloadJson), }, }, }); ``` **curl** ```bash curl -X POST "https://cloudtasks.googleapis.com/v2/projects/$PROJECT/locations/$LOCATION/queues/account-42/tasks" \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ -d '{ "task": { "name": "projects/'"$PROJECT"'/locations/'"$LOCATION"'/queues/account-42/tasks/follow-up-123", "scheduleTime": "2026-12-01T17:00:00Z", "httpRequest": { "httpMethod": "POST", "url": "https://app.example.com/hooks/send", "headers": {"Content-Type": "application/json", "x-internal-key": "change-me"}, "body": "eyJ0byI6ImFAZXhhbXBsZS5jb20ifQ==" } } }' ``` ### After: pushq SDK The queue upsert replaces the separate create/update-queue step. It's idempotent, so you can call it at startup or before enqueueing. The SDK clients default to the hosted API; when self-hosting, pass your server's URL (see [Install & configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/)). **TypeScript** ```ts const pq = new Pushq({ apiKey: process.env.PUSHQ_API_KEY }); await pq.upsertQueue("account-42", { rateLimits: { maxDispatchesPerSecond: 10 }, target: { baseUrl, headers: { "x-internal-key": KEY } }, // or signingSecret: "whsec_..." }); await pq.createTask("account-42", { path: "/hooks/send", jsonBody: payload, delaySeconds: 3600, taskId: `follow-up-${uid}`, retry: { maxAttempts: 3 }, }); ``` **Python** ```python import os from pushq import Pushq, RateLimits, Retry, Target pq = Pushq(api_key=os.environ["PUSHQ_API_KEY"]) pq.upsert_queue( "account-42", rate_limits=RateLimits(max_dispatches_per_second=10), target=Target(base_url=base_url, headers={"x-internal-key": KEY}), # or signing_secret="whsec_..." ) pq.create_task( "account-42", path="/hooks/send", json_body=payload, delay_seconds=3600, task_id=f"follow-up-{uid}", retry=Retry(max_attempts=3), ) ``` **Go** ```go import pushq "github.com/blissfulrays/pushq/sdks/go" pq := pushq.New("", os.Getenv("PUSHQ_API_KEY")) // "" = hosted API _, err := pq.UpsertQueue(ctx, "account-42", pushq.QueueConfig{ RateLimits: &pushq.RateLimits{MaxDispatchesPerSecond: pushq.Float64(10)}, Target: &pushq.Target{ BaseURL: baseURL, Headers: map[string]string{"x-internal-key": key}, // or SigningSecret: "whsec_..." }, }) if err != nil { return err } _, err = pq.CreateTask(ctx, "account-42", pushq.TaskCreate{ Path: "/hooks/send", JSONBody: payload, DelaySeconds: pushq.Float64(3600), TaskID: "follow-up-" + uid, Retry: &pushq.Retry{MaxAttempts: pushq.Int(3)}, }) ``` **Java** ```java import io.pushq.*; Pushq pq = Pushq.builder().apiKey(System.getenv("PUSHQ_API_KEY")).build(); pq.upsertQueue("account-42", QueueConfig.builder() .rateLimits(RateLimits.builder().maxDispatchesPerSecond(10).build()) .target(Target.builder() .baseUrl(baseUrl) .header("x-internal-key", key) // or .signingSecret("whsec_...") .build()) .build()); pq.createTask("account-42", TaskCreate.builder() .path("/hooks/send") .jsonBody(payload) .delaySeconds(3600) .taskId("follow-up-" + uid) .retry(RetryConfig.builder().maxAttempts(3).build()) .build()); ``` **.NET** ```csharp using Pushq; var pq = new PushqClient(apiKey: Environment.GetEnvironmentVariable("PUSHQ_API_KEY")); await pq.UpsertQueueAsync("account-42", new QueueConfig { RateLimits = new RateLimits { MaxDispatchesPerSecond = 10 }, Target = new Target { BaseUrl = baseUrl, Headers = new Dictionary { ["x-internal-key"] = key }, // or SigningSecret = "whsec_..." }, }); await pq.CreateTaskAsync("account-42", new TaskCreate { Path = "/hooks/send", JsonBody = payload, Delay = TimeSpan.FromHours(1), TaskId = $"follow-up-{uid}", Retry = new RetryConfig { MaxAttempts = 3 }, }); ``` **curl** ```bash curl -X PUT https://api.pushqueue.dev/v1/queues/account-42 \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "rate_limits": {"max_dispatches_per_second": 10}, "target": {"base_url": "https://app.example.com", "headers": {"x-internal-key": "change-me"}} }' curl -X POST https://api.pushqueue.dev/v1/queues/account-42/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "path": "/hooks/send", "json_body": {"to": "a@example.com"}, "delay_seconds": 3600, "task_id": "follow-up-123", "retry": {"max_attempts": 3} }' ``` What changed: - The queue path becomes a plain name. If you encoded the project or region in the path to separate tenants, use folders instead: `tenant-42/emails`. - The receiver's base URL and shared headers move to the queue (`target`), so each task only carries a `path`. - `json_body` replaces hand-encoded bytes or base64. - The task name becomes `task_id`. Duplicate IDs fail with `409 already_exists`; treat that as "already enqueued". See [the already_exists error](https://pushqueue.dev/docs/reference/errors/#already_exists). - `retry` on the task controls delivery retries for that task. ### Update your task handlers Your HTTP handlers keep working. Update anything that reads Cloud Tasks headers: | Cloud Tasks header | pushq header | |---|---| | `X-CloudTasks-QueueName` | `X-Pushq-Queue` | | `X-CloudTasks-TaskName` | `X-Pushq-Task-Id` | | `X-CloudTasks-TaskRetryCount` | `X-Pushq-Attempt` (1-based: the first delivery is `1`) | | `X-CloudTasks-TaskExecutionCount` | `X-Pushq-Execution-Count` (attempts that got a response) | | `X-CloudTasks-TaskETA` | `X-Pushq-Scheduled-Time` (RFC 3339) | Cloud Tasks' retry count starts at 0; pushq's attempt number starts at 1. ## Authenticate deliveries without OIDC tokens Cloud Tasks can attach a Google-signed OIDC or OAuth token to each request. pushq doesn't issue Google tokens. Use one or both of these instead: 1. **Static headers.** Set `target.headers` on the queue, for example `{"x-internal-key": "..."}`. pushq adds them to every delivery and they override task headers with the same name. Use this as a drop-in for an internal shared-secret header. 2. **Signing (recommended).** Set `target.signing_secret` (e.g. `whsec_...`) on the queue. Each delivery then carries Standard Webhooks headers (`webhook-id`, `webhook-timestamp`, `webhook-signature`). Verify them with any Standard Webhooks library or with the verify-signature helper in every pushq SDK, which checks the HMAC in constant time and rejects stale timestamps to stop replays. Upserting a queue without `target.signing_secret` keeps the stored secret; send an empty string to clear it. See [webhook signature verification](https://pushqueue.dev/docs/concepts/delivery/) for examples in every language. If your receiver sits behind something that only accepts Google identity tokens (for example a Cloud Run service with IAM authentication), allow unauthenticated invocations and verify the pushq signature in your handler instead. ## Migration checklist 1. Create the queues in pushq with the same rate limits and retry config. Call the upsert from your deploy or startup code so the config lives in your repository. 2. Point your receivers' header parsing at the `X-Pushq-*` headers, and add signature verification if you use signing. 3. Switch producers to the pushq SDK. New tasks now go to pushq. 4. Let the Cloud Tasks queues drain, then pause and delete them. Tasks already in Cloud Tasks stay there; there's no import. If a task must not run twice during the switch, keep its ID the same in both systems and make the handler idempotent on it. ## Test the migration locally `pushq dev` runs a full queue on your machine (SQLite, no auth, fast timers), so delays, retries and rate limits behave as in production instead of being faked with synchronous calls. See [local development](https://pushqueue.dev/docs/getting-started/local-development/). ## Read more - [Queues](https://pushqueue.dev/docs/concepts/queues/): rate limits, targets and folders. - [Tasks](https://pushqueue.dev/docs/concepts/tasks/): scheduling, deduplication and per-task retries. - [Rate limits](https://pushqueue.dev/docs/guides/rate-limits/): token buckets and concurrency caps. - [Install & configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/): TypeScript, Python, Go, Java and .NET. - [REST API overview](https://pushqueue.dev/docs/reference/api/): every endpoint. --- # 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 (`/`, 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. --- # Troubleshooting common errors > Fix common pushq problems, from tasks not being delivered, 401, 403, 404 and 409 errors and failed webhook signature checks to endless retries and timeouts. Source: https://pushqueue.dev/docs/guides/troubleshooting/ This troubleshooting guide lists pushq failures people actually hit, each as symptom, cause and fix: tasks that aren't delivered, API errors such as `401`, `403`, `404`, `409` and `413`, webhook signature verification failures, retries that never stop, and self-hosted server issues. Find your symptom in the headings below. ## Diagnose a task that isn't delivered Start with the queue's stats and the task's attempt log. The queue `state`, the `scheduled_future` count and each attempt's `response_status` or `error_kind` (with `error_snippet`) point at the cause in most cases. **TypeScript** ```ts const stats = await pq.queueStats("emails"); console.log(stats.state, stats.pending, stats.scheduledFuture, stats.oldestDueAgeSeconds); const task = await pq.getTask("emails", "welcome-user-42"); console.log(task.state, task.scheduleTime, task.dispatchCount); for (const a of await pq.listAttempts("emails", "welcome-user-42")) { console.log(a.number, a.responseStatus ?? a.errorKind, a.errorSnippet, a.durationMs); } ``` **Python** ```python stats = pq.queue_stats("emails") print(stats.state, stats.pending, stats.scheduled_future, stats.oldest_due_age_seconds) task = pq.get_task("emails", "welcome-user-42") print(task.state, task.schedule_time, task.dispatch_count) for a in pq.list_attempts("emails", "welcome-user-42"): print(a.number, a.response_status or a.error_kind, a.error_snippet, a.duration_ms) ``` **Go** ```go st, err := pq.QueueStats(ctx, "emails", "") if err != nil { return err } fmt.Println(st.State, st.Pending, st.ScheduledFuture, st.ErrorsLast1m) t, err := pq.GetTask(ctx, "emails", "welcome-user-42") if err != nil { return err } fmt.Println(t.State, t.ScheduleTime, t.DispatchCount) attempts, err := pq.ListAttempts(ctx, "emails", "welcome-user-42") if err != nil { return err } for _, a := range attempts { fmt.Println(a.Number, a.ResponseStatus, a.ErrorKind, a.ErrorSnippet, a.DurationMS) } ``` **Java** ```java QueueStats s = pq.queueStats("emails"); System.out.println(s.getState() + " pending=" + s.getPending() + " future=" + s.getScheduledFuture() + " lag=" + s.getOldestDueAgeSeconds()); Task t = pq.getTask("emails", "welcome-user-42"); System.out.println(t.getState() + " " + t.getScheduleTime() + " " + t.getDispatchCount()); for (Attempt a : pq.listAttempts("emails", "welcome-user-42")) { System.out.printf("#%d status=%s kind=%s %s%n", a.getNumber(), a.getResponseStatus(), a.getErrorKind(), a.getErrorSnippet()); } ``` **.NET** ```csharp QueueStats stats = await pq.GetQueueStatsAsync("emails"); Console.WriteLine($"{stats.State} pending={stats.Pending} future={stats.ScheduledFuture} lag={stats.OldestDueAgeSeconds}"); PushqTask task = await pq.GetTaskAsync("emails", "welcome-user-42"); Console.WriteLine($"{task.State} {task.ScheduleTime} {task.DispatchCount}"); foreach (var a in await pq.ListAttemptsAsync("emails", "welcome-user-42")) Console.WriteLine($"#{a.Number} {a.ResponseStatus?.ToString() ?? a.ErrorKind} {a.ErrorSnippet}"); ``` **curl** ```bash curl -s https://api.pushqueue.dev/v1/queues/emails/stats -H "Authorization: Bearer $PUSHQ_API_KEY" curl -s https://api.pushqueue.dev/v1/queues/emails/tasks/welcome-user-42 -H "Authorization: Bearer $PUSHQ_API_KEY" curl -s https://api.pushqueue.dev/v1/queues/emails/tasks/welcome-user-42/attempts -H "Authorization: Bearer $PUSHQ_API_KEY" ``` The [dashboard](https://pushqueue.dev/docs/guides/dashboard/) shows the same numbers and the attempt history on each task's page. Error codes below are the `code` field of the problem+json body, which every SDK exposes on its error type; see the [errors reference](https://pushqueue.dev/docs/reference/errors/). ## Tasks not being delivered ### Tasks stay pending because the queue is paused **Symptom:** tasks are created but never delivered; stats show `state: "paused"` and a growing `pending` count. **Cause:** a paused queue accepts new tasks but starts no deliveries. **Fix:** resume the queue (`POST /v1/queues/{queue}:resume`). Queued tasks then go out at the queue's rate limits. See [pause and resume a queue](https://pushqueue.dev/docs/concepts/queues/#pause-and-resume-a-queue). ### Enqueue fails with failed_precondition: queue is disabled **Symptom:** creating a task fails with `400 failed_precondition` and a detail like `queue "emails" is disabled`. **Cause:** a disabled queue rejects new tasks and dispatches nothing. Running a task with `:run` is refused too. **Fix:** resume the queue; resume also re-enables a disabled queue. See [queue states](https://pushqueue.dev/docs/concepts/queues/#queue-states). ### Tasks stay pending because they are scheduled in the future **Symptom:** the queue is `running` but a task isn't delivered; stats count it in `scheduled_future`, and the task's `schedule_time` is later than now. **Cause:** the task was created with `delay_seconds` or `schedule_time`. A common slip is passing milliseconds where seconds are expected, or a local time without a time zone. **Fix:** check `schedule_time` on the task. To deliver it now, call `POST /v1/queues/{queue}/tasks/{task_id}:run`. See [scheduling and cancelling tasks](https://pushqueue.dev/docs/patterns/scheduling-and-cancelling/). ### Tasks are delivered slowly: rate limit or concurrency cap **Symptom:** tasks go out, but more slowly than expected; `oldest_due_age_seconds` keeps growing. **Cause:** one of the queue's limits is in effect: - `rate_limits.max_dispatches_per_second` caps how fast deliveries start. - `rate_limits.max_concurrent_dispatches` caps requests in flight. A slow handler fills every slot, and the queue then waits for responses. - Your endpoint answered `429` or `503` with `Retry-After`, which pauses new deliveries on the whole queue for up to 30 seconds. - On a self-hosted server, `dispatcher.global_concurrency` (default 512) caps in-flight deliveries across all queues. **Fix:** raise the limit that binds, or make the handler respond faster. See the [rate limits guide](https://pushqueue.dev/docs/guides/rate-limits/) and [Retry-After and the queue cool-down](https://pushqueue.dev/docs/concepts/retries/#retry-after-and-the-queue-cool-down). ### Every attempt fails with connect, dns, tls or timeout: wrong base_url **Symptom:** attempts have no `response_status` and an `error_kind` of `connect`, `dns`, `tls` or `timeout`. **Cause:** pushq can't reach the target. Usually `target.base_url` (or the task's `url`) has a typo, the wrong port, or a host that is only reachable on your machine or private network. The hosted service can't reach `localhost`; use a public URL or a tunnel, or run [`pushq dev` locally](https://pushqueue.dev/docs/getting-started/local-development/). **Fix:** read the queue and check `target.base_url`, then correct it with PATCH. The target is applied at delivery time, so tasks already queued use the new URL on their next attempt. See [the target settings](https://pushqueue.dev/docs/concepts/queues/#target-settings-base-url-method-headers-and-signing-secret). ### Relative path rejected: queue has no target.base_url **Symptom:** creating a task with `path` fails with `400 failed_precondition`: `task uses a relative path but queue "emails" has no target.base_url`. Or tasks that were already queued fail with `error_kind: config`. **Cause:** relative paths are resolved against the queue's `target.base_url`, and the queue has none, often because a PUT upsert left out `target` (see [Upsert wiped my target](#upsert-wiped-my-target-base_url-headers-or-dead-letter-queue)). **Fix:** set `target.base_url` on the queue, or create tasks with an absolute `url`. Queued tasks pick up the fixed base URL on their next retry. ## Authentication errors: 401 and 403 ### 401 unauthenticated on every API call **Symptom:** every call fails with `401 unauthenticated` and `sign in or send a valid API key`. **Cause:** the request carried no valid key. Check, in order: - The header is `Authorization: Bearer ` with the complete key: no quotes, no other scheme such as `Token`, nothing cut off. - The environment variable is set in the process that makes the call. The SDKs don't read `PUSHQ_API_KEY` for you. - The key belongs to the server you're calling. A hosted key doesn't work on your own server, and the reverse. Check the SDK's base URL. - The key hasn't been revoked. **Fix:** create a new key if needed and pass it explicitly. See [use an API key](https://pushqueue.dev/docs/guides/api-keys/#use-a-key). ### 403 permission_denied: writer key can't list or delete queues **Symptom:** listing queues (`GET /v1/queues`) or deleting one fails with `403 permission_denied`: `the writer role is not allowed to do this`. Other calls with the same key work. **Cause:** writer keys work only with queues they know by name. They can't list or delete queues, read `/metrics` when it isn't public, or manage keys and members. **Fix:** keep the writer key for app code and use an admin key for tooling that lists or deletes queues. See [API key roles](https://pushqueue.dev/docs/guides/api-keys/#key-roles). ### 401 on /v1/me or /v1/teams: session-only endpoints **Symptom:** `401 unauthenticated` with `sign in to the dashboard to manage your account`, even with a valid admin key. **Cause:** `/v1/me`, `/v1/me/password` and `/v1/teams` act on a signed-in person, so they need a dashboard session; API keys can't call them. **Fix:** use the dashboard or console for these. Admin API keys can still manage API keys, members and invites. See the [API reference](https://pushqueue.dev/docs/reference/api/). ### 403 browser requests must send the X-Requested-With header **Symptom:** `403 permission_denied` with `browser requests must send the X-Requested-With header` on a POST, PUT, PATCH or DELETE. **Cause:** the request relied on the dashboard session cookie without an `Authorization` header. pushq requires `X-Requested-With` on such requests to block cross-site request forgery. **Fix:** call the API from your backend with an API key. pushq serves no CORS headers, so calling it from browser code on another site doesn't work anyway. ## 404, 409 and 400 errors ### 404 not_found for a queue name with a slash **Symptom:** a queue in a folder, such as `user/instagram`, returns `404 not_found` with `no such endpoint; if the queue name contains '/', URL-encode it in the path`. **Cause:** the name must travel as one URL segment, `user%2Finstagram`. Either the request didn't encode it, or a reverse proxy decoded `%2F` back into `/` before it reached pushq. **Fix:** with curl or your own HTTP client, encode the name (`/v1/queues/user%2Finstagram/tasks`). The SDKs encode it for you, so if an SDK call still gets this 404 on a self-hosted server, fix the proxy: with nginx, write `proxy_pass http://127.0.0.1:8080;` with no URI part. See [queue names in URLs](https://pushqueue.dev/docs/reference/api/#url-encode-queue-names) and [forward the path unmodified](https://pushqueue.dev/docs/self-hosting/deploy/#forward-encoded-queue-names-unmodified). ### 404 not_found: queue not found **Symptom:** `404 not_found` with `queue "emails": not found` when you enqueue or read. **Cause:** the queue doesn't exist on this server or, on the hosted service, in the team the key belongs to. Enqueuing never creates a queue. **Fix:** create the queue first (an idempotent PUT at deploy time works well), and check the base URL and key. See [create a queue](https://pushqueue.dev/docs/concepts/queues/#create-a-queue). ### 400 invalid_argument: queue name must be... **Symptom:** creating a queue fails with `400 invalid_argument` and `queue name must be 1-200 chars of '/'-separated segments...`. **Cause:** queue names are lowercase letters, digits and hyphens, in segments separated by `/`. Uppercase letters, underscores and dots are rejected. **Fix:** use a name like `emails` or `user/instagram`. See [queue names](https://pushqueue.dev/docs/concepts/queues/#queue-name-rules). ### 409 already_exists when creating a task **Symptom:** creating a task fails with `409 already_exists`. **Cause:** a task with that `task_id` already exists in the queue, or finished recently and its ID is still reserved (by default 24 hours after success, 7 days after failure, 1 hour after deletion). **Fix:** if you set the ID to deduplicate, this is success: the task is already enqueued, so catch the code and carry on. If you meant to run the work again, use a new ID (for example with a version or date suffix). For queues, `POST /v1/queues` returns the same code when the queue exists; use PUT to create or update. 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/). ### :run returns 404 for a finished task **Symptom:** `POST .../tasks/{task_id}:run` returns `404 not_found` for a task you can still see, or `400 failed_precondition`. **Cause:** `:run` works only on pending tasks. Succeeded and failed tasks return `404` (Cloud Tasks parity). A task currently being delivered returns `400 failed_precondition`, and so does any task on a disabled queue. **Fix:** to redo a finished task, create a new task with the same request and a new `task_id`; read the original with `view=full` to get its body and headers. See [run a task now](https://pushqueue.dev/docs/concepts/tasks/#run-a-task-now) and [replay dead letters](https://pushqueue.dev/docs/patterns/replay-dead-letters/). ## Webhook signature verification fails ### Signature verification fails because the body was parsed **Symptom:** the verifier reports `no matching signature` for every delivery, though the secret is right. **Cause:** the signature covers the exact bytes pushq sent. If your framework parsed the JSON and you re-serialized it, key order, spacing or number formatting changed. **Fix:** verify the raw body before parsing: `express.raw()` instead of `express.json()` on that route, `await request.body()` in FastAPI, `io.ReadAll(r.Body)` in Go, `@RequestBody byte[]` in Spring, and no `[FromBody]` model in ASP.NET Core. See [verify signatures](https://pushqueue.dev/docs/getting-started/sdks/#verify-signatures). ### Signature verification fails with the wrong signing secret **Symptom:** `no matching signature`, with the raw body. **Cause:** the secret in your handler isn't the one on the queue that delivered the request. Common cases: a different environment's secret; the queue's secret was changed (deliveries are signed when sent, so retries of old tasks use the new secret); or a task delivered from a dead-letter queue, which is signed with the dead-letter queue's own secret. **Fix:** use the exact string you set as `target.signing_secret` on that queue, including the `whsec_` prefix. Accept both secrets during a rotation, or give related queues the same secret. ### "timestamp outside tolerance": clock skew **Symptom:** the verifier reports `timestamp outside tolerance`. **Cause:** `webhook-timestamp` is set when the delivery starts, and the verifier rejects timestamps further from your server's clock than the tolerance, in either direction. The usual tolerance is 300 seconds (5 minutes): the default in TypeScript, Python and .NET, and the value the Go and Java examples pass. Your server's clock is off, or you're verifying a stored request long after it arrived. **Fix:** sync the clock with NTP. Verify when the request arrives, not later. Raise the tolerance only if you have to. In TypeScript, Python, Go and .NET a tolerance of `0` turns the timestamp check off, which also turns off replay protection. ### Missing webhook-id, webhook-timestamp or webhook-signature headers **Symptom:** the verifier reports missing `webhook-*` headers. **Cause:** the queue has no signing secret (`has_signing_secret: false`), so pushq sends unsigned requests. A PUT that sent `signing_secret: ""` clears it. **Fix:** set `target.signing_secret` on the queue. Omitting `signing_secret` in a later PUT keeps it. ### Every delivery fails with error_kind config: invalid whsec_ secret **Symptom:** deliveries never reach your endpoint; every attempt has `error_kind: config` and `sign request: invalid whsec_ secret`. Or your verifier throws a base64 error instead of a verification error. **Cause:** a secret that starts with `whsec_` must be valid base64 after the prefix. The server accepts an invalid one when you save it, then can't sign with it. On the receiving side the SDKs reject it too: Python raises `binascii.Error`, .NET throws `ArgumentException`, Java throws `WebhookVerificationException`, and Go returns an error wrapping `ErrVerification`. **Fix:** generate a valid secret, for example `echo "whsec_$(openssl rand -base64 32)"`, and set it on the queue and in your handler. The failing tasks keep retrying, so they go through once the secret is fixed. ## Retries and timeouts ### Tasks retried for days: max_attempts defaults to 100 **Symptom:** a failing task keeps being retried, about once an hour, long after you expected it to give up. **Cause:** the default retry config allows 100 attempts with a backoff capped at one hour, so a task that never succeeds retries for about 3.5 days. With `max_attempts: -1` and no `max_retry_duration_seconds`, it retries forever. **Fix:** set `retry.max_attempts` (and a [dead-letter queue](https://pushqueue.dev/docs/concepts/dead-letter-queues/)) on the queue, or per task. To stop one task now, delete it. See [retries and backoff](https://pushqueue.dev/docs/concepts/retries/) and [stop retrying](https://pushqueue.dev/docs/patterns/stop-retrying/). ### Task keeps retrying after max_retry_duration_seconds **Symptom:** you set `max_retry_duration_seconds: 3600`, but the task still retries hours later. **Cause:** when both `max_attempts` and `max_retry_duration_seconds` are set, retries stop only when **both** limits are reached (Cloud Tasks parity). `max_attempts` defaults to 100, so it is always set unless you change it. **Fix:** to make the duration the only limit, also set `max_attempts: -1`. See [when retries stop](https://pushqueue.dev/docs/concepts/retries/#what-happens-when-retries-run-out). ### A 400 or 404 from my endpoint is retried **Symptom:** your handler returns `400` or `404` for a bad task and pushq keeps retrying it. **Cause:** pushq treats every non-2xx status as a failure and retries it, 4xx included. **Fix:** when a task can never succeed, log it and return a 2xx. See [what counts as a failure](https://pushqueue.dev/docs/concepts/retries/#what-counts-as-a-failed-delivery). ### Deliveries time out: dispatch_deadline_seconds **Symptom:** attempts fail with `error_kind: timeout` and a `duration_ms` close to the task's `dispatch_deadline_seconds`. Your handler may still have finished the work, and then runs it again on the retry. **Cause:** pushq waits up to `dispatch_deadline_seconds` (default 600, range 15 to 1800) for a response. A slower handler times out. A load balancer or proxy in front of your handler may also cut the request off sooner and answer `502` or `504`, which shows up as `non_2xx`. **Fix:** set `dispatch_deadline_seconds` above your handler's worst case, raise the proxy timeout to match, or acknowledge quickly and do the slow work elsewhere. Make the handler idempotent either way. See [dispatch deadline](https://pushqueue.dev/docs/concepts/tasks/#dispatch-deadline-request-timeout), [long-running work](https://pushqueue.dev/docs/patterns/long-running-work/) and [idempotent handlers](https://pushqueue.dev/docs/patterns/idempotent-handlers/). ## Queue configuration problems ### Upsert wiped my target base_url, headers or dead-letter queue **Symptom:** after a `PUT /v1/queues/{queue}` (`upsertQueue`), the queue lost its `target.base_url`, `target.headers` or `dead_letter_queue`, or its rate limits went back to defaults. **Cause:** PUT is a full replace. Every field you leave out is reset to its default. Only `signing_secret` is kept when omitted, and the run state never changes. **Fix:** send the queue's complete config with every PUT, or change single fields with PATCH. In the Go SDK, `PatchQueue` can't clear string fields (empty strings aren't sent), so use a full `UpsertQueue` to remove a base URL or dead-letter queue. 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). ### Failed tasks don't show up in the dead-letter queue **Symptom:** tasks end as `failed` but nothing appears in the queue named in `dead_letter_queue`. **Cause:** the dead-letter queue doesn't exist. pushq checks the name's format, not that the queue exists; when the copy fails it only logs `dead-letter failed`. Tasks are also copied only after their retries run out, which with the defaults takes days. **Fix:** create the dead-letter queue. The copy keeps the original task's `path`, so if tasks use relative paths, give the dead-letter queue its own `target.base_url` too; otherwise its deliveries fail with `error_kind: config`. See [dead-letter queues](https://pushqueue.dev/docs/concepts/dead-letter-queues/). ## Request size and batch errors ### 413 payload_too_large **Symptom:** a request fails with `413 payload_too_large` (`request body too large`). **Cause:** the request body is bigger than the server reads. With default settings that is about 2 MiB for a single task create (twice `max_body_bytes`, to allow for base64, plus 64 KiB), 8 MiB for a batch, and 256 KiB for a queue config. A task body that fits the request but is over 1 MiB once decoded is rejected separately, with `400 invalid_argument` and `body exceeds 1048576 bytes`. **Fix:** keep task bodies under 1 MiB. Store large payloads elsewhere and send a reference, and split big batches. On a self-hosted server, also check the reverse proxy's body limit (nginx defaults to 1 MB; set `client_max_body_size`). See [task limits](https://pushqueue.dev/docs/concepts/tasks/#task-size-and-scheduling-limits). ### Batch enqueue returns 200 but some tasks failed **Symptom:** `POST .../tasks:batch` succeeds, but some tasks don't exist. **Cause:** a batch reports per-item results. The request returns `200` as long as the batch itself is valid; each item has either a `task` or an `error` with its own `code` (`already_exists`, `invalid_argument`, `failed_precondition`, ...). Only a malformed request (invalid JSON, an empty batch, more than 500 tasks), a missing queue or an oversized body fails the whole request. **Fix:** check every result's `error`. Treat `already_exists` as success, fix and resend the `invalid_argument` items. See [batch enqueue](https://pushqueue.dev/docs/concepts/tasks/#batch-enqueue-up-to-500-tasks) and [bulk enqueue](https://pushqueue.dev/docs/patterns/bulk-enqueue/). ### SDK error with code internal and an HTML detail **Symptom:** an SDK error has code `internal` and a detail that looks like an HTML page. **Cause:** the response didn't come from pushq. A proxy, load balancer or wrong base URL returned its own error page, and the SDK wraps it as `internal`. **Fix:** check the base URL and the status code, then the proxy's logs. ## Self-hosted server problems ### Dashboard says setup required **Symptom:** the dashboard asks you to create an admin account, and the server logs `the API is UNAUTHENTICATED`. **Cause:** no dashboard account exists yet. Until one does, a server without `api_keys` in its config accepts every request without credentials. If the config has `api_keys`, the API is already protected and setup asks for one of its admin keys. **Fix:** create the admin account right away, before exposing the server. If you're locked out of an existing install, use `pushq users reset-password`. See [create the first admin account](https://pushqueue.dev/docs/self-hosting/install/#create-the-first-admin-account) and [locked out](https://pushqueue.dev/docs/self-hosting/install/#recover-a-locked-out-admin-account). ### Session cookie isn't Secure behind a reverse proxy **Symptom:** the `pushq_session` cookie lacks the `Secure` flag even though the dashboard is served over HTTPS. **Cause:** TLS ends at your proxy, so pushq sees plain HTTP. It marks the cookie `Secure` only when the request arrived over TLS or carries `X-Forwarded-Proto: https`. **Fix:** have the proxy send `X-Forwarded-Proto` (nginx: `proxy_set_header X-Forwarded-Proto $scheme;`; Caddy sets it by default). See [tell pushq the request was HTTPS](https://pushqueue.dev/docs/self-hosting/deploy/#set-x-forwarded-proto-for-tls). ## Read more - [Going to production](https://pushqueue.dev/docs/guides/going-to-production/): the checklist that prevents most of these problems. - [Errors reference](https://pushqueue.dev/docs/reference/errors/): every error code and HTTP status. - [Retries and backoff](https://pushqueue.dev/docs/concepts/retries/): what counts as a failure and when retries stop. - [Delivery](https://pushqueue.dev/docs/concepts/delivery/): the request pushq sends and its headers. - [Self-hosting operations](https://pushqueue.dev/docs/self-hosting/operations/): health checks, metrics and logs. --- # Idempotent webhook handlers > Make pushq task handlers idempotent so retries and duplicate deliveries run your side effects once, using the webhook-id as an idempotency key. Source: https://pushqueue.dev/docs/patterns/idempotent-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 Enqueue the task as usual. Give it a [task ID](https://pushqueue.dev/docs/patterns/deduplication/) when you have a natural one; the handler works with server-generated IDs too. **TypeScript** ```ts await pq.createTask("orders", { taskId: "fulfil-order-1234", path: "/hooks/fulfil-order", jsonBody: { order_id: 1234 }, }); ``` **Python** ```python pq.create_task( "orders", task_id="fulfil-order-1234", path="/hooks/fulfil-order", json_body={"order_id": 1234}, ) ``` **Go** ```go _, err := pq.CreateTask(ctx, "orders", pushq.TaskCreate{ TaskID: "fulfil-order-1234", Path: "/hooks/fulfil-order", JSONBody: map[string]any{"order_id": 1234}, }) ``` **Java** ```java pq.createTask("orders", TaskCreate.builder() .taskId("fulfil-order-1234") .path("/hooks/fulfil-order") .jsonBody(Map.of("order_id", 1234)) .build()); ``` **.NET** ```csharp await pq.CreateTaskAsync("orders", new TaskCreate { TaskId = "fulfil-order-1234", Path = "/hooks/fulfil-order", JsonBody = new { order_id = 1234 }, }); ``` **curl** ```bash 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](https://pushqueue.dev/docs/concepts/delivery/#webhook-signing), 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. ```sql CREATE TABLE processed_tasks ( id text PRIMARY KEY, -- webhook-id: "/" processed_at timestamptz NOT NULL DEFAULT now() ); ``` **TypeScript** ```ts 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 }); ``` **Python** ```python import json import os import psycopg from fastapi import FastAPI, HTTPException, Request, Response from 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 done ``` **Go** ```go func 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 } ``` **Java** ```java @RestController public 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 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 } } ``` **.NET** ```csharp 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 - **It is stable across retries.** When the queue has a signing secret, pushq sends `webhook-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](https://pushqueue.dev/docs/concepts/delivery/#static-header-authentication)), 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. ## 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](https://pushqueue.dev/docs/patterns/long-running-work/). - **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](https://pushqueue.dev/docs/patterns/deduplication/). ## 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](https://pushqueue.dev/docs/patterns/chaining-steps/). :::caution[Check and claim in one atomic step] `SELECT` to check whether the key exists and then `INSERT` it is a race: two concurrent deliveries can both see "not processed". Use a unique constraint (`INSERT ... ON CONFLICT DO NOTHING`, or catch the duplicate-key error) inside the same transaction as the work. ::: ## 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](https://pushqueue.dev/docs/concepts/dead-letter-queues/), 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. ## Read more - [At-least-once delivery and the X-Pushq headers](https://pushqueue.dev/docs/concepts/delivery/) - [Task deduplication with task IDs](https://pushqueue.dev/docs/patterns/deduplication/) - [Retry backoff and what counts as a failure](https://pushqueue.dev/docs/concepts/retries/) - [Stop retrying a task that can't succeed](https://pushqueue.dev/docs/patterns/stop-retrying/) - [Chain tasks into multi-step workflows](https://pushqueue.dev/docs/patterns/chaining-steps/) --- # Task deduplication with task IDs > Deduplicate pushq tasks with a deterministic task_id, handle 409 already_exists as success in every SDK, and learn how long task IDs stay reserved. Source: https://pushqueue.dev/docs/patterns/deduplication/ Task deduplication stops the same piece of work from being enqueued twice, for example when your code retries a create call after a timeout, or two requests race to schedule the same job. In pushq you deduplicate by setting your own `task_id`: a second create with an ID that is still reserved in that queue is rejected with `409 already_exists`, and you treat that as success. ## Enqueue once with a deterministic task ID **TypeScript** ```ts try { await pq.createTask("emails", { taskId: "welcome-user-42", path: "/hooks/send-welcome", jsonBody: { user_id: 42 }, }); } catch (err) { if (!(err instanceof PushqError && err.code === "already_exists")) throw err; // already enqueued: nothing to do } ``` **Python** ```python from pushq import PushqError try: pq.create_task( "emails", task_id="welcome-user-42", path="/hooks/send-welcome", json_body={"user_id": 42}, ) except PushqError as e: if e.code != "already_exists": raise # already enqueued: nothing to do ``` **Go** ```go _, err := pq.CreateTask(ctx, "emails", pushq.TaskCreate{ TaskID: "welcome-user-42", Path: "/hooks/send-welcome", JSONBody: map[string]any{"user_id": 42}, }) if err != nil && !pushq.IsCode(err, "already_exists") { return err } // err == nil or already_exists: the task is enqueued ``` **Java** ```java try { pq.createTask("emails", TaskCreate.builder() .taskId("welcome-user-42") .path("/hooks/send-welcome") .jsonBody(Map.of("user_id", 42)) .build()); } catch (PushqException e) { if (!"already_exists".equals(e.getCode())) throw e; // already enqueued: nothing to do } ``` **.NET** ```csharp try { await pq.CreateTaskAsync("emails", new TaskCreate { TaskId = "welcome-user-42", Path = "/hooks/send-welcome", JsonBody = new { user_id = 42 }, }); } catch (PushqException e) when (e.Code == "already_exists") { // already enqueued: nothing to do } ``` **curl** ```bash status=$(curl -s -o /dev/null -w '%{http_code}' \ -X POST https://api.pushqueue.dev/v1/queues/emails/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{"task_id":"welcome-user-42","path":"/hooks/send-welcome","json_body":{"user_id":42}}') # 201 = created, 409 = already_exists (already enqueued) if [ "$status" != "201" ] && [ "$status" != "409" ]; then echo "enqueue failed: HTTP $status" >&2 exit 1 fi ``` Use this when an event can reach your enqueue code more than once (a user double-clicks, an upstream webhook is redelivered, your job runner retries) and the task should still run once. The duplicate create returns this problem response; the task that already exists is not changed: ```json { "type": "about:blank", "title": "Conflict", "status": 409, "code": "already_exists", "detail": "already exists", "instance": "/v1/queues/emails/tasks" } ``` ## How task ID deduplication works A task ID is unique within its queue. pushq keeps the ID reserved for as long as the task's record exists, whatever its state, so a create with the same ID fails while the task is pending, running, finished, or recently deleted. | Task state | ID stays reserved | Self-hosted default | |---|---|---| | Pending or running | Until the task finishes | No limit | | Succeeded | The longer of `retention.succeeded` and `limits.dedup_window`, from when it finished | 24 hours | | Failed | The longer of `retention.failed` and `limits.dedup_window`, from when it failed | 7 days | | Deleted | `limits.dedup_window`, from when it was deleted | 1 hour | | Purged, or its queue deleted | Not reserved: the ID is free immediately | n/a | Old records are removed by a background cleanup pass (every minute by default), so an ID can stay reserved slightly longer than the table says, never shorter. Self-hosters set these values with `limits.dedup_window`, `retention.succeeded` and `retention.failed` (or `PUSHQ_DEDUP_WINDOW`, `PUSHQ_RETENTION_SUCCEEDED`, `PUSHQ_RETENTION_FAILED`); see [server configuration](https://pushqueue.dev/docs/self-hosting/configuration/). The values on the hosted service may differ. Deduplication only compares IDs. pushq doesn't look at the URL, body or schedule of the existing task, and the `409` response doesn't return it. If you need the existing task, fetch it with a get-task call. ## Choosing deterministic task IDs A deterministic ID is built from the work itself, so every attempt to enqueue the same work produces the same ID. - **Use the business key.** `welcome-user-42`, `invoice-inv-881-reminder-1`, `refund-ord-1234`. - **Add a time bucket for "at most once per period".** `digest-user-42-2026-11-28` sends one digest per user per day, however many times your scheduler fires. - **Hash long or unsafe keys.** Task IDs must match `[A-Za-z0-9_-]{1,500}`: letters, digits, `_` and `-`, up to 500 characters. Characters such as `:`, `.`, `/` or `@` are rejected with `invalid_argument`. Build the ID from a hex digest (for example SHA-256 of the email address plus the template name), prefixed with something readable. - **Never include values that change between attempts**: the current time, a random value, or a request ID generated per call. They make every create unique and turn deduplication off. Leave `task_id` out when duplicates don't matter; pushq then generates a UUIDv7 ID. ## Deduplicate in a batch enqueue The batch endpoint reports `already_exists` per item instead of failing the whole request. Treat those items as enqueued. **TypeScript** ```ts const results = await pq.createTasks("emails", [ { taskId: "welcome-user-42", path: "/hooks/send-welcome", jsonBody: { user_id: 42 } }, { taskId: "welcome-user-43", path: "/hooks/send-welcome", jsonBody: { user_id: 43 } }, ]); const failed = results.filter((r) => r.error && r.error.code !== "already_exists"); if (failed.length > 0) throw new Error(`enqueue failed: ${JSON.stringify(failed)}`); ``` **Python** ```python results = pq.create_tasks("emails", [ {"task_id": "welcome-user-42", "path": "/hooks/send-welcome", "json_body": {"user_id": 42}}, {"task_id": "welcome-user-43", "path": "/hooks/send-welcome", "json_body": {"user_id": 43}}, ]) failed = [r for r in results if r.error and r.error.code != "already_exists"] if failed: raise RuntimeError(f"enqueue failed: {failed}") ``` **Go** ```go results, err := pq.CreateTasks(ctx, "emails", []pushq.TaskCreate{ {TaskID: "welcome-user-42", Path: "/hooks/send-welcome", JSONBody: map[string]any{"user_id": 42}}, {TaskID: "welcome-user-43", Path: "/hooks/send-welcome", JSONBody: map[string]any{"user_id": 43}}, }) if err != nil { return err } for _, r := range results { if r.Error != nil && r.Error.Code != "already_exists" { return fmt.Errorf("item %d: %s: %s", r.Index, r.Error.Code, r.Error.Detail) } } ``` **Java** ```java List results = pq.createTasks("emails", List.of( TaskCreate.builder().taskId("welcome-user-42").path("/hooks/send-welcome") .jsonBody(Map.of("user_id", 42)).build(), TaskCreate.builder().taskId("welcome-user-43").path("/hooks/send-welcome") .jsonBody(Map.of("user_id", 43)).build())); for (BatchResult r : results) { if (!r.isSuccess() && !"already_exists".equals(r.getError().getCode())) { throw new IllegalStateException(r.getIndex() + ": " + r.getError().getDetail()); } } ``` **.NET** ```csharp var results = await pq.CreateTasksAsync("emails", new[] { new TaskCreate { TaskId = "welcome-user-42", Path = "/hooks/send-welcome", JsonBody = new { user_id = 42 } }, new TaskCreate { TaskId = "welcome-user-43", Path = "/hooks/send-welcome", JsonBody = new { user_id = 43 } }, }); var failed = results.Where(r => r.Error != null && r.Error.Code != "already_exists").ToList(); if (failed.Count > 0) throw new InvalidOperationException($"{failed.Count} tasks failed to enqueue"); ``` **curl** ```bash curl -X POST "https://api.pushqueue.dev/v1/queues/emails/tasks:batch" \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{"tasks":[ {"task_id":"welcome-user-42","path":"/hooks/send-welcome","json_body":{"user_id":42}}, {"task_id":"welcome-user-43","path":"/hooks/send-welcome","json_body":{"user_id":43}} ]}' # 200 with one result per item; a duplicate item has # "error": {"code": "already_exists", ...} ``` A batch holds up to 500 tasks and is not atomic: other items are created even when some fail. Two items with the same ID in one batch also dedupe; the second gets `already_exists`. See [bulk enqueue](https://pushqueue.dev/docs/patterns/bulk-enqueue/) for larger loads. ## Safe retries of the enqueue call The SDKs don't retry API calls themselves. If a create call times out, you can't tell whether pushq stored the task. With a `task_id` set, retry the call: if the first one was stored, the retry gets `already_exists`, which you already treat as success. Without a `task_id`, a retry can create a second task. ## Pitfalls :::caution[Deduplication is time-limited] An ID is only reserved while the task's record exists. Once a succeeded task is cleaned up (24 hours on self-hosted defaults), the same ID is accepted again and the work runs again. If something must happen at most once ever, also record it in your own database. ::: - **Deleting a task doesn't free its ID right away.** A deleted task's ID stays reserved for `dedup_window` (1 hour on self-hosted defaults). To re-enqueue sooner, use a new ID such as `welcome-user-42-v2`. - **IDs are per queue.** The same `task_id` in two queues creates two tasks. Pick one queue per kind of work, or put the queue's purpose in the ID. - **Purging frees IDs.** After a [purge](https://pushqueue.dev/docs/concepts/queues/), every purged ID can be used again immediately, so a replay of old events right after a purge enqueues them again. - **Deduplication doesn't stop duplicate deliveries.** A single task can still reach your endpoint more than once because delivery is at-least-once. Make the handler [idempotent](https://pushqueue.dev/docs/patterns/idempotent-handlers/) as well. ## Read more - [Idempotent webhook handlers](https://pushqueue.dev/docs/patterns/idempotent-handlers/) - [Tasks: IDs, states and the task lifecycle](https://pushqueue.dev/docs/concepts/tasks/) - [Bulk enqueue with the batch API](https://pushqueue.dev/docs/patterns/bulk-enqueue/) - [Error codes such as already_exists](https://pushqueue.dev/docs/reference/errors/) - [Retention and dedup window settings](https://pushqueue.dev/docs/self-hosting/configuration/) --- # Per-tenant queues and rate limits > Give every customer its own pushq queue and rate limit with folders like tenants/, create queues on first use, list, pause and delete them. Source: https://pushqueue.dev/docs/patterns/per-tenant-queues/ This pattern gives each customer (tenant, user, workspace) its own pushq queue with its own rate limit, so one busy customer can't slow everyone else down. You name the queues `tenants/`, create each one the first time that tenant enqueues work, and pause, re-limit or delete one tenant's queue without touching the others. ## Create a queue per tenant on first use Enqueue into the tenant's queue. If the queue doesn't exist yet the API answers `404 not_found`; create the queue with its full configuration and enqueue again. In the normal case this costs one API call per task. **TypeScript** ```ts const pq = new Pushq({ apiKey: process.env.PUSHQ_API_KEY }); // The full config for one tenant: always send all of it (see the caution below). function tenantConfig(perSecond: number, concurrent: number) { return { rateLimits: { maxDispatchesPerSecond: perSecond, maxConcurrentDispatches: concurrent }, retry: { maxAttempts: 10, maxBackoffSeconds: 600 }, target: { baseUrl: "https://api.example.com" }, }; } async function enqueueForTenant(tenantId: string, perSecond: number, concurrent: number, jsonBody: unknown) { const queue = `tenants/${tenantId}`; const task = { path: "/hooks/sync", jsonBody }; try { return await pq.createTask(queue, task); } catch (err) { if (!(err instanceof PushqError && err.code === "not_found")) throw err; await pq.upsertQueue(queue, tenantConfig(perSecond, concurrent)); // first task for this tenant return await pq.createTask(queue, task); } } ``` **Python** ```python import os from pushq import Pushq, PushqError, RateLimits, Retry, Target pq = Pushq(api_key=os.environ["PUSHQ_API_KEY"]) def tenant_config(per_second: float, concurrent: int) -> dict: # The full config for one tenant: always send all of it (see the caution below). return dict( rate_limits=RateLimits(max_dispatches_per_second=per_second, max_concurrent_dispatches=concurrent), retry=Retry(max_attempts=10, max_backoff_seconds=600), target=Target(base_url="https://api.example.com"), ) def enqueue_for_tenant(tenant_id: str, per_second: float, concurrent: int, payload: dict): queue = f"tenants/{tenant_id}" try: return pq.create_task(queue, path="/hooks/sync", json_body=payload) except PushqError as e: if e.code != "not_found": raise pq.upsert_queue(queue, **tenant_config(per_second, concurrent)) # first task for this tenant return pq.create_task(queue, path="/hooks/sync", json_body=payload) ``` **Go** ```go // The full config for one tenant: always send all of it (see the caution below). func tenantConfig(perSecond float64, concurrent int) pushq.QueueConfig { return pushq.QueueConfig{ RateLimits: &pushq.RateLimits{ MaxDispatchesPerSecond: pushq.Float64(perSecond), MaxConcurrentDispatches: pushq.Int(concurrent), }, Retry: &pushq.Retry{MaxAttempts: pushq.Int(10), MaxBackoffSeconds: pushq.Float64(600)}, Target: &pushq.Target{BaseURL: "https://api.example.com"}, } } func enqueueForTenant(ctx context.Context, pq *pushq.Client, tenantID string, perSecond float64, concurrent int, payload any) (*pushq.Task, error) { queue := "tenants/" + tenantID task := pushq.TaskCreate{Path: "/hooks/sync", JSONBody: payload} t, err := pq.CreateTask(ctx, queue, task) if !pushq.IsCode(err, "not_found") { return t, err } // First task for this tenant: create the queue, then enqueue again. if _, err := pq.UpsertQueue(ctx, queue, tenantConfig(perSecond, concurrent)); err != nil { return nil, err } return pq.CreateTask(ctx, queue, task) } ``` **Java** ```java import io.pushq.*; import java.util.Map; // The full config for one tenant: always send all of it (see the caution below). static QueueConfig tenantConfig(double perSecond, int concurrent) { return QueueConfig.builder() .rateLimits(RateLimits.builder() .maxDispatchesPerSecond(perSecond) .maxConcurrentDispatches(concurrent) .build()) .retry(RetryConfig.builder().maxAttempts(10).maxBackoffSeconds(600).build()) .target(Target.builder().baseUrl("https://api.example.com").build()) .build(); } static Task enqueueForTenant(Pushq pq, String tenantId, double perSecond, int concurrent, Map payload) { String queue = "tenants/" + tenantId; TaskCreate task = TaskCreate.builder().path("/hooks/sync").jsonBody(payload).build(); try { return pq.createTask(queue, task); } catch (PushqException e) { if (!"not_found".equals(e.getCode())) throw e; } pq.upsertQueue(queue, tenantConfig(perSecond, concurrent)); // first task for this tenant return pq.createTask(queue, task); } ``` **.NET** ```csharp using Pushq; // The full config for one tenant: always send all of it (see the caution below). static QueueConfig TenantConfig(double perSecond, int concurrent) => new QueueConfig { RateLimits = new RateLimits { MaxDispatchesPerSecond = perSecond, MaxConcurrentDispatches = concurrent }, Retry = new RetryConfig { MaxAttempts = 10, MaxBackoffSeconds = 600 }, Target = new Target { BaseUrl = "https://api.example.com" }, }; static async Task EnqueueForTenantAsync(PushqClient pq, string tenantId, double perSecond, int concurrent, object payload) { var queue = $"tenants/{tenantId}"; var task = new TaskCreate { Path = "/hooks/sync", JsonBody = payload }; try { return await pq.CreateTaskAsync(queue, task); } catch (PushqException e) when (e.Code == "not_found") { await pq.UpsertQueueAsync(queue, TenantConfig(perSecond, concurrent)); // first task for this tenant return await pq.CreateTaskAsync(queue, task); } } ``` **curl** ```bash # Enqueue. A 404 with "code": "not_found" means the tenant's queue doesn't exist yet. # The "/" in the queue name is URL-encoded as %2F. curl -X POST "https://api.pushqueue.dev/v1/queues/tenants%2Facme/tasks" \ -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \ -d '{"path":"/hooks/sync","json_body":{"account":"acme"}}' # Create the queue with its full config, then send the task again. curl -X PUT "https://api.pushqueue.dev/v1/queues/tenants%2Facme" \ -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \ -d '{"rate_limits":{"max_dispatches_per_second":5,"max_concurrent_dispatches":2}, "retry":{"max_attempts":10,"max_backoff_seconds":600}, "target":{"base_url":"https://api.example.com"}}' ``` The examples assume a client named `pq` (see [install and configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/)). JSON field names are used in the text; the SDKs use their language's casing (`maxDispatchesPerSecond` in TypeScript and Java, `max_dispatches_per_second` in Python, `MaxDispatchesPerSecond` in Go and .NET). Use this when each customer must get a fair share of delivery, when a customer's own downstream system (their webhook endpoint, their API key with a third party) has its own limit, or when you need to stop one customer's work without stopping anyone else's. If two of your processes hit `not_found` for the same new tenant at the same moment, both upsert the queue. That is safe: `PUT` is idempotent, and with the same config the second call changes nothing. ## Why one queue per tenant isolates customers - **Each queue has its own token bucket and concurrency cap.** The dispatcher claims tasks from a queue only while that queue has rate-limit tokens and fewer than `max_concurrent_dispatches` requests in flight. A tenant with a million queued tasks is drained at its own rate while other tenants' queues keep dispatching at theirs. See [rate limits](https://pushqueue.dev/docs/guides/rate-limits/). - **Retries, pause and purge are per queue.** A tenant whose endpoint is failing backs off on its own schedule, and you can pause or empty that tenant's queue alone. - **Folders are only names.** `tenants/acme` is a queue called `acme` in the folder `tenants`. A folder has no config of its own and exists as long as some queue name uses it, so there is nothing to create up front. Folders can nest: `tenants/acme/emails` and `tenants/acme/webhooks` give one tenant several queues. On a self-hosted server all queues still share the server's total in-flight capacity (`dispatcher.global_concurrency`, 512 by default; see [self-hosting configuration](https://pushqueue.dev/docs/self-hosting/configuration/)). On the hosted service, the Free plan allows up to 1,000 queues and Pay as you go has no queue limit (see [pricing](https://pushqueue.dev/pricing)). :::caution[Tenant IDs must be valid queue-name segments] Each segment of a queue name must match `[a-z0-9][a-z0-9-]*`, and the whole name is at most 200 characters. Uppercase letters, underscores and dots are rejected with `invalid_argument`. Lowercase your tenant IDs (lowercase UUIDs work) or map them to a slug before building the queue name. ::: ## Upsert replaces the whole queue config :::danger[Omitted fields reset to defaults] `PUT /v1/queues/{queue}` (`upsertQueue`) replaces the queue's entire configuration. Any field you leave out goes back to its default: the rate limit returns to 500 per second, `target.base_url` and `target.headers` are cleared, and `dead_letter_queue` is removed. Only `target.signing_secret` is kept when omitted. Upsert never changes the queue's state, so it won't resume a paused tenant. ::: Pick one of two safe approaches and stick to it: 1. **Send the full config every time.** Build it from the tenant's record in your database (plan, limits, endpoint), as `tenantConfig()` does above. Any upsert, from any process, then produces the right config. 2. **Create once, then patch.** Create the queue with `POST /v1/queues` (`createQueue`) and treat `already_exists` as success. Change single settings later with `PATCH`, and never call `PUT` for tenant queues. What breaks is mixing the two: patching a tenant's limit after a plan upgrade, then letting an enqueue path upsert a default config that silently undoes it. ## Change one tenant's rate limit When a tenant upgrades or a tenant's endpoint asks you to slow down, patch only the rate limit. `PATCH` leaves every other field as it is. **TypeScript** ```ts await pq.patchQueue("tenants/acme", { rateLimits: { maxDispatchesPerSecond: 20, maxConcurrentDispatches: 10 }, }); ``` **Python** ```python from pushq import RateLimits pq.patch_queue("tenants/acme", rate_limits=RateLimits(max_dispatches_per_second=20, max_concurrent_dispatches=10)) ``` **Go** ```go _, err := pq.PatchQueue(ctx, "tenants/acme", pushq.QueueConfig{ RateLimits: &pushq.RateLimits{ MaxDispatchesPerSecond: pushq.Float64(20), MaxConcurrentDispatches: pushq.Int(10), }, }, "") // "" = leave the queue state unchanged ``` **Java** ```java pq.patchQueue("tenants/acme", QueuePatch.builder() .rateLimits(RateLimits.builder().maxDispatchesPerSecond(20).maxConcurrentDispatches(10).build()) .build()); ``` **.NET** ```csharp await pq.PatchQueueAsync("tenants/acme", new QueuePatch { RateLimits = new RateLimits { MaxDispatchesPerSecond = 20, MaxConcurrentDispatches = 10 }, }); ``` **curl** ```bash curl -X PATCH "https://api.pushqueue.dev/v1/queues/tenants%2Facme" \ -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \ -d '{"rate_limits":{"max_dispatches_per_second":20,"max_concurrent_dispatches":10}}' ``` If you follow approach 1 (full config every time), update the tenant's record in your database too, or the next upsert sets the old limit back. In Python, `patch_queue` is on the sync `Pushq` client only; `AsyncPushq` doesn't have it. ## List all tenant queues in a folder List queues with `name_prefix` set to the folder, including the trailing slash. Results are ordered by name and paged (100 per page by default, up to 1,000). **TypeScript** ```ts let pageToken: string | undefined; do { const page = await pq.listQueues({ namePrefix: "tenants/", pageSize: 1000, pageToken }); for (const q of page.items) console.log(q.name, q.state, q.rateLimits.maxDispatchesPerSecond); pageToken = page.nextPageToken; } while (pageToken); ``` **Python** ```python token = None while True: page = pq.list_queues(name_prefix="tenants/", page_size=1000, page_token=token) for q in page.items: print(q.name, q.state, q.rate_limits.max_dispatches_per_second) token = page.next_page_token if token is None: break ``` **Go** ```go token := "" for { queues, next, err := pq.ListQueues(ctx, pushq.ListQueuesParams{ NamePrefix: "tenants/", PageSize: 1000, PageToken: token, }) if err != nil { return err } for _, q := range queues { fmt.Println(q.Name, q.State, q.RateLimitsSet.MaxDispatchesPerSecond) } if next == "" { break } token = next } ``` **Java** ```java String token = null; do { ListQueuesParams.Builder p = ListQueuesParams.builder().namePrefix("tenants/").pageSize(1000); if (token != null) p.pageToken(token); QueuePage page = pq.listQueues(p.build()); for (Queue q : page.getQueues()) { System.out.println(q.getName() + " " + q.getState()); } token = page.getNextPageToken(); } while (token != null && !token.isEmpty()); ``` **.NET** ```csharp string? token = null; do { var page = await pq.ListQueuesAsync(new ListQueuesOptions { NamePrefix = "tenants/", PageSize = 1000, PageToken = token }); foreach (var q in page.Items) Console.WriteLine($"{q.Name} {q.State} {q.RateLimits.MaxDispatchesPerSecond}"); token = page.NextPageToken; } while (token != null); ``` **curl** ```bash curl "https://api.pushqueue.dev/v1/queues?name_prefix=tenants/&page_size=1000" \ -H "Authorization: Bearer $PUSHQ_API_KEY" # Repeat with &page_token= until the response has none. ``` :::caution[Listing queues needs an admin key] Writer API keys get `403 permission_denied` on `GET /v1/queues`. Use an admin key for tooling that lists or deletes tenant queues, and a writer key for the services that only enqueue. See [API keys](https://pushqueue.dev/docs/guides/api-keys/). ::: `name_prefix` is a plain string prefix: `tenants/acme` also matches `tenants/acme-labs`. Use `tenants/acme/` (with the trailing slash) to list only the queues inside one tenant's folder. ## Pause a noisy tenant's queue When one tenant floods its queue or its endpoint is down, pause that queue. A paused queue keeps accepting tasks; they wait until you resume it. Every other tenant keeps running. **TypeScript** ```ts await pq.pauseQueue("tenants/acme"); const stats = await pq.queueStats("tenants/acme"); console.log(stats.pending, stats.oldestDueAgeSeconds); // later await pq.resumeQueue("tenants/acme"); ``` **Python** ```python pq.pause_queue("tenants/acme") stats = pq.queue_stats("tenants/acme") print(stats.pending, stats.oldest_due_age_seconds) # later pq.resume_queue("tenants/acme") ``` **Go** ```go if _, err := pq.PauseQueue(ctx, "tenants/acme"); err != nil { return err } st, err := pq.QueueStats(ctx, "tenants/acme", "") if err == nil { fmt.Println(st.Pending, st.OldestDueAgeSeconds) } // later _, err = pq.ResumeQueue(ctx, "tenants/acme") ``` **Java** ```java pq.pauseQueue("tenants/acme"); QueueStats s = pq.queueStats("tenants/acme"); System.out.println(s.getPending() + " " + s.getOldestDueAgeSeconds()); // later pq.resumeQueue("tenants/acme"); ``` **.NET** ```csharp await pq.PauseQueueAsync("tenants/acme"); var stats = await pq.GetQueueStatsAsync("tenants/acme"); Console.WriteLine($"{stats.Pending} {stats.OldestDueAgeSeconds}"); // later await pq.ResumeQueueAsync("tenants/acme"); ``` **curl** ```bash curl -X POST "https://api.pushqueue.dev/v1/queues/tenants%2Facme:pause" -H "Authorization: Bearer $PUSHQ_API_KEY" curl "https://api.pushqueue.dev/v1/queues/tenants%2Facme/stats" -H "Authorization: Bearer $PUSHQ_API_KEY" curl -X POST "https://api.pushqueue.dev/v1/queues/tenants%2Facme:resume" -H "Authorization: Bearer $PUSHQ_API_KEY" ``` Pausing is the right tool when you want to keep the tenant's backlog. To slow a tenant down instead of stopping it, [change its rate limit](#change-one-tenants-rate-limit). Resume also re-enables a queue that was set to `disabled`. ## Delete or purge a tenant's queue When a customer leaves, delete the queue. Deleting removes the queue and all of its tasks; pending tasks are never delivered. To drop a tenant's backlog but keep the queue and its config, purge it instead. **TypeScript** ```ts await pq.purgeQueue("tenants/acme"); // drop every task, keep the queue await pq.deleteQueue("tenants/acme"); // remove the queue and its tasks (admin key) ``` **Python** ```python pq.purge_queue("tenants/acme") # drop every task, keep the queue pq.delete_queue("tenants/acme") # remove the queue and its tasks (admin key) ``` **Go** ```go _, err := pq.PurgeQueue(ctx, "tenants/acme") // drop every task, keep the queue err = pq.DeleteQueue(ctx, "tenants/acme") // remove the queue and its tasks (admin key) ``` **Java** ```java pq.purgeQueue("tenants/acme"); // drop every task, keep the queue pq.deleteQueue("tenants/acme"); // remove the queue and its tasks (admin key) ``` **.NET** ```csharp await pq.PurgeQueueAsync("tenants/acme"); // drop every task, keep the queue await pq.DeleteQueueAsync("tenants/acme"); // remove the queue and its tasks (admin key) ``` **curl** ```bash curl -X POST "https://api.pushqueue.dev/v1/queues/tenants%2Facme:purge" -H "Authorization: Bearer $PUSHQ_API_KEY" curl -X DELETE "https://api.pushqueue.dev/v1/queues/tenants%2Facme" -H "Authorization: Bearer $PUSHQ_API_KEY" ``` To remove a tenant with several queues (`tenants/acme/emails`, `tenants/acme/webhooks`), list `tenants/acme/` and delete each queue. Like listing, deleting a queue needs an admin key. ## Pitfalls - **Mixing `PUT` and `PATCH` on the same queue.** A later upsert with a default config undoes earlier patches. See [upsert replaces the whole queue config](#upsert-replaces-the-whole-queue-config). - **Upserting before every enqueue.** It works, but doubles your API calls and makes the full-config rule apply to every code path that enqueues. The `not_found` fallback above only upserts once per tenant. - **Deleting a queue a producer still uses.** The next enqueue gets `not_found` and the fallback recreates the queue. Stop producers for that tenant first, or pause the queue instead of deleting it. - **One queue shared by all tenants with a high limit.** A single tenant's burst then fills the queue ahead of everyone else, and you can't pause just that tenant. ## Read more - [Queues: settings, states and folders](https://pushqueue.dev/docs/concepts/queues/) - [Rate limits for dispatch rate, burst and concurrency](https://pushqueue.dev/docs/guides/rate-limits/) - [Throttle requests to a third-party API](https://pushqueue.dev/docs/patterns/throttle-a-third-party-api/) - [API keys and roles](https://pushqueue.dev/docs/guides/api-keys/) --- # Throttle requests to a third-party API > Stay under a third-party API rate limit with pushq. Map the provider's limit to queue settings, relay 429 Retry-After, and share one limit across producers. Source: https://pushqueue.dev/docs/patterns/throttle-a-third-party-api/ This pattern keeps your calls to a third-party API (a CRM, an email provider, a payment or AI API) under the provider's documented rate limit. You send every call through one pushq queue whose rate limit matches the provider's, and your handler passes the provider's `429` and `Retry-After` back to pushq so the queue slows down when the provider asks it to. ## Match the queue's rate limit to the provider's limit Say the provider documents "25 requests per second, at most 10 concurrent requests". Create one queue for that provider with a little headroom, then enqueue every call to it: **TypeScript** ```ts await pq.upsertQueue("crm-api", { rateLimits: { maxDispatchesPerSecond: 20, // provider allows 25/s; keep headroom maxBurstSize: 20, maxConcurrentDispatches: 10, // provider allows 10 in flight }, retry: { maxAttempts: 20, minBackoffSeconds: 1, maxBackoffSeconds: 600 }, target: { baseUrl: "https://api.example.com" }, }); await pq.createTask("crm-api", { path: "/hooks/crm-sync", jsonBody: { contactId: 42 } }); ``` **Python** ```python from pushq import RateLimits, Retry, Target pq.upsert_queue( "crm-api", rate_limits=RateLimits( max_dispatches_per_second=20, # provider allows 25/s; keep headroom max_burst_size=20, max_concurrent_dispatches=10, # provider allows 10 in flight ), retry=Retry(max_attempts=20, min_backoff_seconds=1, max_backoff_seconds=600), target=Target(base_url="https://api.example.com"), ) pq.create_task("crm-api", path="/hooks/crm-sync", json_body={"contact_id": 42}) ``` **Go** ```go _, err := pq.UpsertQueue(ctx, "crm-api", pushq.QueueConfig{ RateLimits: &pushq.RateLimits{ MaxDispatchesPerSecond: pushq.Float64(20), // provider allows 25/s; keep headroom MaxBurstSize: pushq.Int(20), MaxConcurrentDispatches: pushq.Int(10), // provider allows 10 in flight }, Retry: &pushq.Retry{ MaxAttempts: pushq.Int(20), MinBackoffSeconds: pushq.Float64(1), MaxBackoffSeconds: pushq.Float64(600), }, Target: &pushq.Target{BaseURL: "https://api.example.com"}, }) if err != nil { return err } _, err = pq.CreateTask(ctx, "crm-api", pushq.TaskCreate{ Path: "/hooks/crm-sync", JSONBody: map[string]any{"contact_id": 42}, }) ``` **Java** ```java pq.upsertQueue("crm-api", QueueConfig.builder() .rateLimits(RateLimits.builder() .maxDispatchesPerSecond(20) // provider allows 25/s; keep headroom .maxBurstSize(20) .maxConcurrentDispatches(10) // provider allows 10 in flight .build()) .retry(RetryConfig.builder().maxAttempts(20).minBackoffSeconds(1).maxBackoffSeconds(600).build()) .target(Target.builder().baseUrl("https://api.example.com").build()) .build()); pq.createTask("crm-api", TaskCreate.builder() .path("/hooks/crm-sync") .jsonBody(Map.of("contact_id", 42)) .build()); ``` **.NET** ```csharp await pq.UpsertQueueAsync("crm-api", new QueueConfig { RateLimits = new RateLimits { MaxDispatchesPerSecond = 20, // provider allows 25/s; keep headroom MaxBurstSize = 20, MaxConcurrentDispatches = 10, // provider allows 10 in flight }, Retry = new RetryConfig { MaxAttempts = 20, MinBackoffSeconds = 1, MaxBackoffSeconds = 600 }, Target = new Target { BaseUrl = "https://api.example.com" }, }); await pq.CreateTaskAsync("crm-api", new TaskCreate { Path = "/hooks/crm-sync", JsonBody = new { contact_id = 42 } }); ``` **curl** ```bash curl -X PUT https://api.pushqueue.dev/v1/queues/crm-api \ -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \ -d '{"rate_limits":{"max_dispatches_per_second":20,"max_burst_size":20,"max_concurrent_dispatches":10}, "retry":{"max_attempts":20,"min_backoff_seconds":1,"max_backoff_seconds":600}, "target":{"base_url":"https://api.example.com"}}' curl -X POST https://api.pushqueue.dev/v1/queues/crm-api/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \ -d '{"path":"/hooks/crm-sync","json_body":{"contact_id":42}}' ``` pushq delivers each task to your endpoint (`https://api.example.com/hooks/crm-sync`), and your handler makes the provider call. The examples assume a client named `pq` (see [install and configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/)). The text uses JSON field names; the SDKs use their language's casing (`maxDispatchesPerSecond` in TypeScript and Java, `max_dispatches_per_second` in Python, `MaxDispatchesPerSecond` in Go and .NET). Use this when a provider rejects or bans clients that exceed a documented requests-per-second, requests-per-minute or concurrency limit, and the calls can happen in the background. ## Translate a provider rate limit into queue settings | Provider documents | Queue setting | Example | | --- | --- | --- | | N requests per second | `rate_limits.max_dispatches_per_second` = N, or a bit less | 25/s → `20` | | N requests per minute | `max_dispatches_per_second` = N / 60, and a small `max_burst_size` | 120/min → `2`, burst `0` (auto = 2) | | One request every N seconds | `max_dispatches_per_second` = 1 / N, `max_burst_size` = 1 | every 5 s → `0.2`, burst `1` | | At most N requests in flight | `rate_limits.max_concurrent_dispatches` = N | 10 concurrent → `10` | | A short burst above the steady rate | `rate_limits.max_burst_size` = the burst | burst of 50 → `50` | Valid ranges: `max_dispatches_per_second` is greater than 0 and at most 10,000 (fractions are fine), `max_burst_size` is 0 to 10,000, and `max_concurrent_dispatches` is 1 to 10,000. A `max_burst_size` of `0` means auto: the rate rounded up, between 1 and 500. :::caution[A full burst plus a minute of refill can exceed a per-minute cap] The rate limit is a token bucket: up to `max_burst_size` tasks can go out at once, then tokens refill at `max_dispatches_per_second`. With 120/min configured as 2 per second and a burst of 120, an idle queue could send 120 tasks immediately and another 120 over the next minute. For per-minute limits keep the burst small (auto, or 1). ::: Concurrency matters as much as rate when the provider is slow. At 20 dispatches per second and 3-second responses, 60 requests would be in flight; `max_concurrent_dispatches: 10` caps that at 10, which in turn caps the real rate at about 3 per second. Set both. ## Relay 429 and Retry-After from the provider When the provider says "slow down", answer pushq with `429 Too Many Requests` (or `503`) and a `Retry-After` header. pushq then delays that task and briefly stops dispatching the whole queue. **TypeScript** ```ts app.post("/hooks/crm-sync", express.json(), async (req, res) => { const r = await fetch("https://api.crm.example.com/v1/contacts", { method: "POST", headers: { Authorization: `Bearer ${process.env.CRM_TOKEN}`, "Content-Type": "application/json" }, body: JSON.stringify(req.body), }); if (r.status === 429 || r.status === 503) { // Pass the provider's back-off on to pushq. res.set("Retry-After", r.headers.get("Retry-After") ?? "10"); return res.sendStatus(429); } res.sendStatus(r.ok ? 204 : 502); }); ``` **Python** ```python import os import httpx from fastapi import FastAPI, Request, Response app = FastAPI() crm = httpx.AsyncClient(base_url="https://api.crm.example.com", headers={"Authorization": f"Bearer {os.environ['CRM_TOKEN']}"}) @app.post("/hooks/crm-sync") async def crm_sync(request: Request) -> Response: r = await crm.post("/v1/contacts", content=await request.body(), headers={"Content-Type": "application/json"}) if r.status_code in (429, 503): # Pass the provider's back-off on to pushq. return Response(status_code=429, headers={"Retry-After": r.headers.get("Retry-After", "10")}) return Response(status_code=204 if r.is_success else 502) ``` **Go** ```go func handleCRMSync(w http.ResponseWriter, r *http.Request) { req, _ := http.NewRequestWithContext(r.Context(), "POST", "https://api.crm.example.com/v1/contacts", r.Body) req.Header.Set("Authorization", "Bearer "+os.Getenv("CRM_TOKEN")) req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } defer resp.Body.Close() if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode == http.StatusServiceUnavailable { retryAfter := resp.Header.Get("Retry-After") if retryAfter == "" { retryAfter = "10" } // Pass the provider's back-off on to pushq. w.Header().Set("Retry-After", retryAfter) w.WriteHeader(http.StatusTooManyRequests) return } if resp.StatusCode >= 300 { w.WriteHeader(http.StatusBadGateway) return } w.WriteHeader(http.StatusNoContent) } ``` **Java** ```java @RestController public class CrmSync { private final HttpClient http = HttpClient.newHttpClient(); @PostMapping("/hooks/crm-sync") public ResponseEntity sync(@RequestBody byte[] payload) throws Exception { HttpRequest req = HttpRequest.newBuilder(URI.create("https://api.crm.example.com/v1/contacts")) .header("Authorization", "Bearer " + System.getenv("CRM_TOKEN")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofByteArray(payload)) .build(); HttpResponse resp = http.send(req, HttpResponse.BodyHandlers.discarding()); int status = resp.statusCode(); if (status == 429 || status == 503) { // Pass the provider's back-off on to pushq. String retryAfter = resp.headers().firstValue("Retry-After").orElse("10"); return ResponseEntity.status(429).header("Retry-After", retryAfter).build(); } return ResponseEntity.status(status < 300 ? 204 : 502).build(); } } ``` **.NET** ```csharp // "crm" HttpClient registered at startup with BaseAddress and the Authorization header. app.MapPost("/hooks/crm-sync", async (HttpRequest req, IHttpClientFactory factory) => { var crm = factory.CreateClient("crm"); using var body = new StreamContent(req.Body); body.Headers.ContentType = new MediaTypeHeaderValue("application/json"); using var resp = await crm.PostAsync("/v1/contacts", body); if ((int)resp.StatusCode is 429 or 503) { // Pass the provider's back-off on to pushq. req.HttpContext.Response.Headers["Retry-After"] = resp.Headers.RetryAfter?.ToString() ?? "10"; return Results.StatusCode(429); } return resp.IsSuccessStatusCode ? Results.NoContent() : Results.StatusCode(502); }); ``` These handlers are plain web code, so there is no curl tab. In production, also [verify the webhook signature](https://pushqueue.dev/docs/concepts/delivery/#verify-webhook-signatures-in-your-handler) before calling the provider, and make the handler [idempotent](https://pushqueue.dev/docs/patterns/idempotent-handlers/): a task can be delivered more than once. The fallback of `"10"` seconds applies when the provider sends a 429 without `Retry-After`. Without the header, pushq treats a 429 as an ordinary failure: normal backoff and no queue cool-down. ## How the queue slows down after a 429 pushq's dispatcher enforces the limit on the server, at delivery time: 1. **Token bucket.** Each queue has a bucket that holds up to `max_burst_size` tokens and refills at `max_dispatches_per_second`. A task is claimed for delivery only when a token is available. 2. **Concurrency cap.** No new task is claimed while the queue has `max_concurrent_dispatches` requests in flight. 3. **Retries go through the same limits.** A retry is a pending task like any other, so it uses a token and a concurrency slot. Retries can't push you over the provider's limit. 4. **429 or 503 with `Retry-After`.** When your endpoint answers `429` or `503` with a `Retry-After` header (seconds or an HTTP date): - that task's next attempt is scheduled `Retry-After` from now instead of after its normal backoff, capped at the queue's `retry.max_backoff_seconds`; - the whole queue stops claiming new tasks for `Retry-After`, capped at **30 seconds**. Requests already in flight finish normally. So a single 429 pauses the queue briefly and pushes the throttled task back by as much as the provider asked. See [Retry-After and the queue cool-down](https://pushqueue.dev/docs/concepts/retries/#retry-after-and-the-queue-cool-down) for the retry details. :::caution[Every 429 counts as an attempt] A `429` is a failed attempt and counts toward `retry.max_attempts` (and `max_retry_duration_seconds`). If a provider throttles you for a long time, tasks can run out of attempts and fail. Give provider queues a generous `max_attempts` (or `-1` for unlimited with a `max_retry_duration_seconds`), and a [dead-letter queue](https://pushqueue.dev/docs/concepts/dead-letter-queues/) to catch the rest. ::: :::caution[max_backoff_seconds caps Retry-After] If the provider sends `Retry-After: 3600` and the queue's `max_backoff_seconds` is 300, the task retries after 300 seconds and probably gets throttled again. Set `max_backoff_seconds` at least as high as the longest `Retry-After` you expect. ::: ## Share one rate limit across many producers The limit belongs to the queue, not to the code that enqueues. Ten services, a cron job and a backfill script can all enqueue into `crm-api` at once; pushq still dispatches at most 20 per second with 10 in flight. You don't need a distributed lock or a shared Redis counter. To make that hold: - **Route every call to the provider through the queue.** Any code path that calls the provider directly uses up the same provider quota without pushq seeing it. - **Use one queue per provider credential.** Provider limits are usually per API key or per account. If each of your customers connects their own provider account, give each one a queue (see [per-tenant queues](https://pushqueue.dev/docs/patterns/per-tenant-queues/)). - **Split by limit, not by caller.** If the provider limits endpoints separately (for example, search versus writes), use one queue per limit: `crm-api/search` and `crm-api/writes`. :::danger[Run now bypasses the rate limit] `POST /v1/queues/{queue}/tasks/{task_id}:run` dispatches a pending task immediately, ignoring the queue's rate limit, `max_concurrent_dispatches` and paused state. Don't use it in bulk on a provider queue. ::: ## Call the provider directly from pushq If the provider call needs no logic of your own, a task can target the provider's URL directly: set `url` to the absolute URL and pass the provider's auth header in the task's `headers` (or once in the queue's `target.headers`). pushq then sees the provider's own `429` and `Retry-After`. The trade-off is that the credential is stored with the task or queue and is returned by the API (task `headers` in the full view, queue `target.headers` on every read), and any non-2xx answer, including permanent errors like `400`, is retried. A handler of your own keeps the secret in your service and lets you [stop retrying](https://pushqueue.dev/docs/patterns/stop-retrying/) errors that will never succeed. ## Pitfalls - **Rate set at exactly the provider's limit.** Clock skew and the provider's own window boundaries can still trip it. Leave 10 to 20 percent headroom. - **Ignoring concurrency.** A rate limit alone doesn't stop slow responses from piling up in flight. - **Calls outside the queue.** Synchronous calls from your web app share the provider quota with the queue. - **Short `max_backoff_seconds`.** It caps how long a throttled task waits, regardless of `Retry-After`. - **Watching the backlog.** If the provider limit is lower than your enqueue rate, the queue grows. Check `oldest_due_age_seconds` and `errors_last_1m` from the [queue stats](https://pushqueue.dev/docs/concepts/queues/) to see whether you are falling behind. ## Read more - [Rate limits: dispatch rate, burst size and concurrency](https://pushqueue.dev/docs/guides/rate-limits/) - [Retries, backoff and Retry-After](https://pushqueue.dev/docs/concepts/retries/) - [Per-tenant queues and rate limits](https://pushqueue.dev/docs/patterns/per-tenant-queues/) - [Idempotent task handlers](https://pushqueue.dev/docs/patterns/idempotent-handlers/) - [Stop retrying permanent errors](https://pushqueue.dev/docs/patterns/stop-retrying/) --- # Schedule, cancel and reschedule tasks > Schedule delayed tasks with pushq using delay_seconds or schedule_time, then cancel or reschedule them by task ID. Includes a follow-up reminder example. Source: https://pushqueue.dev/docs/patterns/scheduling-and-cancelling/ This pattern covers delayed and scheduled tasks in pushq: sending a request later (a reminder, a follow-up email, a trial-expiry check), cancelling it when it is no longer needed, and moving it to a different time. You give each scheduled task a predictable task ID, so you can cancel it later without storing anything. ## Schedule a follow-up and cancel it A user signs up. If they haven't activated in three days, send a follow-up email. If they activate before then, cancel it. **TypeScript** ```ts // At signup: follow up in 3 days. await pq.createTask("emails", { taskId: "followup-user-42", path: "/hooks/follow-up", jsonBody: { userId: 42 }, delaySeconds: 3 * 24 * 3600, }); // When the user activates: cancel it. try { await pq.deleteTask("emails", "followup-user-42"); } catch (err) { if (!(err instanceof PushqError && err.code === "not_found")) throw err; // already cancelled } ``` **Python** ```python from pushq import PushqError # At signup: follow up in 3 days. pq.create_task( "emails", task_id="followup-user-42", path="/hooks/follow-up", json_body={"user_id": 42}, delay_seconds=3 * 24 * 3600, ) # When the user activates: cancel it. try: pq.delete_task("emails", "followup-user-42") except PushqError as e: if e.code != "not_found": # not_found: already cancelled raise ``` **Go** ```go // At signup: follow up in 3 days. _, err := pq.CreateTask(ctx, "emails", pushq.TaskCreate{ TaskID: "followup-user-42", Path: "/hooks/follow-up", JSONBody: map[string]any{"user_id": 42}, DelaySeconds: pushq.Float64(3 * 24 * 3600), }) if err != nil { return err } // When the user activates: cancel it. not_found means it was already cancelled. if err := pq.DeleteTask(ctx, "emails", "followup-user-42"); err != nil && !pushq.IsCode(err, "not_found") { return err } ``` **Java** ```java // At signup: follow up in 3 days. pq.createTask("emails", TaskCreate.builder() .taskId("followup-user-42") .path("/hooks/follow-up") .jsonBody(Map.of("user_id", 42)) .delaySeconds(3 * 24 * 3600) .build()); // When the user activates: cancel it. try { pq.deleteTask("emails", "followup-user-42"); } catch (PushqException e) { if (!"not_found".equals(e.getCode())) throw e; // not_found: already cancelled } ``` **.NET** ```csharp // At signup: follow up in 3 days. await pq.CreateTaskAsync("emails", new TaskCreate { TaskId = "followup-user-42", Path = "/hooks/follow-up", JsonBody = new { user_id = 42 }, Delay = TimeSpan.FromDays(3), }); // When the user activates: cancel it. try { await pq.DeleteTaskAsync("emails", "followup-user-42"); } catch (PushqException e) when (e.Code == "not_found") { // already cancelled } ``` **curl** ```bash # At signup: follow up in 3 days (259200 seconds). curl -X POST https://api.pushqueue.dev/v1/queues/emails/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \ -d '{"task_id":"followup-user-42","path":"/hooks/follow-up","json_body":{"user_id":42},"delay_seconds":259200}' # When the user activates: cancel it (204 No Content; 404 not_found if already cancelled). curl -X DELETE https://api.pushqueue.dev/v1/queues/emails/tasks/followup-user-42 \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` The examples assume a client named `pq` (see [install and configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/)). The text uses JSON field names; the SDKs use their language's casing (`delaySeconds` in TypeScript and Java, `delay_seconds` in Python, `DelaySeconds` in Go, and a `TimeSpan` named `Delay` in .NET). Use this when something should happen later unless something else happens first: reminders, follow-ups, abandoned-cart nudges, trial-expiry checks, "close this ticket if no reply in 7 days". A deterministic task ID (`followup-user-42`) does double duty: it makes enqueueing [idempotent](https://pushqueue.dev/docs/concepts/tasks/#task-ids-and-deduplication) (a second create for the same user returns `already_exists` instead of a second follow-up), and it lets you cancel the task from anywhere that knows the user ID. ## Delay a task or schedule it at an exact time Set one of these on the task, not both (sending both is `invalid_argument`): | Parameter | Type | Default | Description | | --- | --- | --- | --- | | `delay_seconds` | number | `0` | Deliver this many seconds after the task is created. Must be `>= 0`; fractions are allowed. | | `schedule_time` | string (RFC 3339) | now | Deliver at this instant, for example `2026-12-01T09:00:00Z`. A time in the past makes the task due immediately. | Use `delay_seconds` for relative times ("in 3 days") and `schedule_time` for wall-clock times ("Monday 09:00 in the user's time zone"). `schedule_time` is an absolute instant: convert the user's local time to UTC (or include the offset) in your code. **TypeScript** ```ts await pq.createTask("emails", { taskId: "digest-user-42-2026-12-07", path: "/hooks/weekly-digest", jsonBody: { userId: 42 }, scheduleTime: new Date("2026-12-07T09:00:00-05:00"), // 09:00 New York time }); ``` **Python** ```python from datetime import datetime, timedelta, timezone pq.create_task( "emails", task_id="digest-user-42-2026-12-07", path="/hooks/weekly-digest", json_body={"user_id": 42}, schedule_time=datetime(2026, 12, 7, 9, 0, tzinfo=timezone(timedelta(hours=-5))), # 09:00 New York ) ``` **Go** ```go ny, _ := time.LoadLocation("America/New_York") at := time.Date(2026, 12, 7, 9, 0, 0, 0, ny) _, err := pq.CreateTask(ctx, "emails", pushq.TaskCreate{ TaskID: "digest-user-42-2026-12-07", Path: "/hooks/weekly-digest", JSONBody: map[string]any{"user_id": 42}, ScheduleTime: &at, // sent as UTC }) ``` **Java** ```java Instant at = ZonedDateTime.of(2026, 12, 7, 9, 0, 0, 0, ZoneId.of("America/New_York")).toInstant(); pq.createTask("emails", TaskCreate.builder() .taskId("digest-user-42-2026-12-07") .path("/hooks/weekly-digest") .jsonBody(Map.of("user_id", 42)) .scheduleTime(at) .build()); ``` **.NET** ```csharp await pq.CreateTaskAsync("emails", new TaskCreate { TaskId = "digest-user-42-2026-12-07", Path = "/hooks/weekly-digest", JsonBody = new { user_id = 42 }, ScheduleTime = new DateTimeOffset(2026, 12, 7, 9, 0, 0, TimeSpan.FromHours(-5)), // 09:00 New York }); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/emails/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \ -d '{"task_id":"digest-user-42-2026-12-07","path":"/hooks/weekly-digest", "json_body":{"user_id":42},"schedule_time":"2026-12-07T09:00:00-05:00"}' ``` ## How far ahead you can schedule a task A task can be scheduled at most **one year** ahead on a default self-hosted server (`limits.max_schedule_ahead`, or `PUSHQ_MAX_SCHEDULE_AHEAD`; see [self-hosting configuration](https://pushqueue.dev/docs/self-hosting/configuration/)). The limit applies to both `delay_seconds` and `schedule_time`; going past it returns `invalid_argument` with "schedule_time is more than ... ahead". Independently of that setting, `delay_seconds` can never exceed 100 years. For anything further out (a renewal reminder in two years), store the date in your own database and have a periodic job enqueue the task once it is within range. ## Cancel a scheduled task by ID Delete the task with `DELETE /v1/queues/{queue}/tasks/{task_id}`. What that does depends on where the task is: | Task state | Effect of delete | | --- | --- | | `pending` (waiting for its time, or due) | Removed. It is never delivered. | | `running` (a request is in flight) | Marked deleted and its result is discarded, so it won't be retried. The request already sent can't be recalled. | | `succeeded` or `failed` | The record is removed. Delivery already happened (or gave up). | | Already deleted, or never existed | `404 not_found`. | To cancel every scheduled task for a user, give their tasks a shared prefix (`followup-user-42`, `digest-user-42-2026-12-07`, ...) and delete the pending ones you find with `id_prefix`: **TypeScript** ```ts const page = await pq.listTasks("emails", { state: "pending", idPrefix: "digest-user-42-", pageSize: 1000 }); for (const t of page.items) await pq.deleteTask("emails", t.id); ``` **Python** ```python page = pq.list_tasks("emails", state="pending", id_prefix="digest-user-42-", page_size=1000) for t in page.items: pq.delete_task("emails", t.id) ``` **Go** ```go tasks, _, err := pq.ListTasks(ctx, "emails", pushq.ListTasksParams{ State: "pending", IDPrefix: "digest-user-42-", PageSize: 1000, }) if err != nil { return err } for _, t := range tasks { if err := pq.DeleteTask(ctx, "emails", t.ID); err != nil && !pushq.IsCode(err, "not_found") { return err } } ``` **Java** ```java TaskPage page = pq.listTasks("emails", ListTasksParams.builder() .state("pending").idPrefix("digest-user-42-").pageSize(1000).build()); for (Task t : page.getTasks()) { pq.deleteTask("emails", t.getId()); } ``` **.NET** ```csharp var page = await pq.ListTasksAsync("emails", new ListTasksOptions { State = TaskState.Pending, IdPrefix = "digest-user-42-", PageSize = 1000, }); foreach (var t in page.Items) await pq.DeleteTaskAsync("emails", t.Id); ``` **curl** ```bash curl "https://api.pushqueue.dev/v1/queues/emails/tasks?state=pending&id_prefix=digest-user-42-&page_size=1000" \ -H "Authorization: Bearer $PUSHQ_API_KEY" # then DELETE /v1/queues/emails/tasks/ for each task in the response ``` If a user can have more than 1,000 pending tasks, follow `next_page_token` as shown in [list and filter tasks](https://pushqueue.dev/docs/concepts/tasks/#list-and-filter-tasks). :::caution[Cancel and delivery can race] If the task becomes due while you are deleting it, it may already be in flight. Make the handler check whether the work is still wanted (has the user activated?) and answer `2xx` without acting if not. That check is what makes cancellation reliable; the delete is an optimization. See [idempotent handlers](https://pushqueue.dev/docs/patterns/idempotent-handlers/). ::: ## Reschedule a task pushq has no "update task" call. To move a task to a new time, delete it and create it again. :::caution[A deleted task ID stays reserved] After a delete, the task ID is kept as a tombstone for the dedup window (1 hour on a default self-hosted server, `limits.dedup_window`). Creating a task with the same ID in that window fails with `already_exists`. IDs of finished tasks are reserved even longer: for their retention period (24 hours after success, 7 days after failure, by default). See [task IDs and deduplication](https://pushqueue.dev/docs/concepts/tasks/#task-ids-and-deduplication). ::: So give the new task a new ID. A version or the target time in the ID works well, and an `id_prefix` lookup still finds it: **TypeScript** ```ts // Move the follow-up from 3 days to 7 days after signup. await pq.deleteTask("emails", "followup-user-42"); await pq.createTask("emails", { taskId: "followup-user-42-v2", path: "/hooks/follow-up", jsonBody: { userId: 42 }, delaySeconds: 7 * 24 * 3600, }); ``` **Python** ```python # Move the follow-up from 3 days to 7 days after signup. pq.delete_task("emails", "followup-user-42") pq.create_task( "emails", task_id="followup-user-42-v2", path="/hooks/follow-up", json_body={"user_id": 42}, delay_seconds=7 * 24 * 3600, ) ``` **Go** ```go // Move the follow-up from 3 days to 7 days after signup. if err := pq.DeleteTask(ctx, "emails", "followup-user-42"); err != nil && !pushq.IsCode(err, "not_found") { return err } _, err := pq.CreateTask(ctx, "emails", pushq.TaskCreate{ TaskID: "followup-user-42-v2", Path: "/hooks/follow-up", JSONBody: map[string]any{"user_id": 42}, DelaySeconds: pushq.Float64(7 * 24 * 3600), }) ``` **Java** ```java // Move the follow-up from 3 days to 7 days after signup. pq.deleteTask("emails", "followup-user-42"); pq.createTask("emails", TaskCreate.builder() .taskId("followup-user-42-v2") .path("/hooks/follow-up") .jsonBody(Map.of("user_id", 42)) .delaySeconds(7 * 24 * 3600) .build()); ``` **.NET** ```csharp // Move the follow-up from 3 days to 7 days after signup. await pq.DeleteTaskAsync("emails", "followup-user-42"); await pq.CreateTaskAsync("emails", new TaskCreate { TaskId = "followup-user-42-v2", Path = "/hooks/follow-up", JsonBody = new { user_id = 42 }, Delay = TimeSpan.FromDays(7), }); ``` **curl** ```bash curl -X DELETE https://api.pushqueue.dev/v1/queues/emails/tasks/followup-user-42 \ -H "Authorization: Bearer $PUSHQ_API_KEY" curl -X POST https://api.pushqueue.dev/v1/queues/emails/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \ -d '{"task_id":"followup-user-42-v2","path":"/hooks/follow-up","json_body":{"user_id":42},"delay_seconds":604800}' ``` To cancel a rescheduled task later, look it up with `id_prefix: "followup-user-42"` rather than a fixed ID. Delete first, then create: if you create first and the delete fails, both versions are scheduled. To move a pending task to **now**, use [run a task now](https://pushqueue.dev/docs/concepts/tasks/#run-a-task-now) (`POST .../tasks/{task_id}:run`) instead. It keeps the same ID, works only on pending tasks, and bypasses the queue's rate limit and paused state. ## How scheduled tasks are stored and delivered A scheduled task is an ordinary `pending` task whose `schedule_time` is in the future. Nothing runs on your side while it waits. pushq's dispatcher tracks the earliest `schedule_time` of each queue and claims the task once that time has passed, subject to the queue's [rate limits](https://pushqueue.dev/docs/guides/rate-limits/). Queue stats count waiting tasks in `scheduled_future`, and each delivery carries the original time in the `X-Pushq-Scheduled-Time` header. Some consequences: - **Delivery is at or after `schedule_time`, not exactly at it.** A busy queue, a low rate limit, or a paused queue makes tasks late. Tasks that become due while a queue is paused go out when it is resumed. - **Retries move the time.** If the first attempt fails, the task is retried with backoff (see [retries](https://pushqueue.dev/docs/concepts/retries/)), so the follow-up can arrive later than scheduled. - **Scheduled tasks live in their queue.** Deleting or purging the queue removes every scheduled task in it. ## Pitfalls - **Random task IDs.** Without a predictable ID you must store the returned ID to cancel the task later. - **Reusing an ID right after delete.** It fails with `already_exists` for the dedup window; use a new ID. - **Local times without an offset.** `schedule_time` must be an RFC 3339 instant. In Python a naive `datetime` is treated as UTC. - **Relying on delete alone.** Re-check in the handler that the action is still wanted. - **Scheduling years ahead.** Past the schedule-ahead limit the create fails; keep long-range dates in your own database. ## Read more - [Tasks: delayed and scheduled tasks, IDs and states](https://pushqueue.dev/docs/concepts/tasks/) - [Deduplicate tasks with task IDs](https://pushqueue.dev/docs/patterns/deduplication/) - [Idempotent task handlers](https://pushqueue.dev/docs/patterns/idempotent-handlers/) - [Bulk enqueue tasks in batches](https://pushqueue.dev/docs/patterns/bulk-enqueue/) --- # Stop retrying failed tasks > Stop pushq retrying a task that can never succeed: return 2xx and record the failure, cap max_attempts, delete the task, or dead-letter it. Source: https://pushqueue.dev/docs/patterns/stop-retrying/ pushq retries every failed delivery with backoff, and a failure is any response that isn't `2xx`, including `400`, `404` and `422`. When a task can never succeed (the record it points to was deleted, the payload is invalid, a downstream API rejects it for good), you have to stop the retries yourself: acknowledge it with a `2xx` and record the failure, cap its attempts, delete it, or let it land in a dead-letter queue. ## Acknowledge permanent failures with a 2xx Your handler knows which errors are permanent. Return a `2xx` for those so pushq marks the task succeeded and stops, and keep your own record of what went wrong. Return a non-2xx (or let the request fail) only for errors a retry can fix. **TypeScript** ```ts app.post("/hooks/send-welcome", express.raw({ type: "*/*" }), async (req, res) => { // Authenticate the request first: see /docs/concepts/delivery/ const taskId = req.get("X-Pushq-Task-Id"); const { user_id } = JSON.parse(req.body.toString("utf8")); try { const user = await findUser(user_id); if (!user) { // Permanent: retrying won't make the user exist. Record it and acknowledge. await recordFailure(taskId, "user not found"); return res.status(200).json({ skipped: "user not found" }); } await sendWelcomeEmail(user); res.sendStatus(204); } catch (err) { // Temporary (timeout, 5xx from the email API): let pushq retry. console.error(err); res.sendStatus(500); } }); ``` **Python** ```python @app.post("/hooks/send-welcome") async def send_welcome(request: Request): # Authenticate the request first: see /docs/concepts/delivery/ task_id = request.headers.get("x-pushq-task-id") payload = await request.json() user = await find_user(payload["user_id"]) if user is None: # Permanent: retrying won't make the user exist. Record it and acknowledge. await record_failure(task_id, "user not found") return {"skipped": "user not found"} # 200 # A temporary error raised here becomes a 500, so pushq retries. await send_welcome_email(user) return Response(status_code=204) ``` **Go** ```go func sendWelcome(w http.ResponseWriter, r *http.Request) { // Authenticate the request first: see /docs/concepts/delivery/ taskID := r.Header.Get("X-Pushq-Task-Id") var p struct { UserID int64 `json:"user_id"` } if err := json.NewDecoder(r.Body).Decode(&p); err != nil { // Permanent: this payload will never parse. recordFailure(r.Context(), taskID, "invalid payload: "+err.Error()) w.WriteHeader(http.StatusOK) return } user, err := findUser(r.Context(), p.UserID) if errors.Is(err, errUserNotFound) { // Permanent: retrying won't make the user exist. recordFailure(r.Context(), taskID, "user not found") w.WriteHeader(http.StatusOK) return } if err == nil { err = sendWelcomeEmail(r.Context(), user) } if err != nil { // Temporary: let pushq retry. http.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatusNoContent) } ``` **Java** ```java @PostMapping("/hooks/send-welcome") public ResponseEntity> sendWelcome( @RequestBody Map payload, @RequestHeader("X-Pushq-Task-Id") String taskId) { // Authenticate the request first: see /docs/concepts/delivery/ long userId = ((Number) payload.get("user_id")).longValue(); Optional user = users.findById(userId); if (user.isEmpty()) { // Permanent: retrying won't make the user exist. Record it and acknowledge. failures.record(taskId, "user not found"); return ResponseEntity.ok(Map.of("skipped", "user not found")); } // A temporary error thrown here becomes a 500, so pushq retries. mailer.sendWelcome(user.get()); return ResponseEntity.noContent().build(); } ``` **.NET** ```csharp app.MapPost("/hooks/send-welcome", async (HttpRequest req, UserStore users, FailureLog failures, Mailer mailer) => { // Authenticate the request first: see /docs/concepts/delivery/ var taskId = req.Headers["X-Pushq-Task-Id"].FirstOrDefault(); var payload = await JsonDocument.ParseAsync(req.Body); var userId = payload.RootElement.GetProperty("user_id").GetInt64(); var user = await users.FindAsync(userId); if (user is null) { // Permanent: retrying won't make the user exist. Record it and acknowledge. await failures.RecordAsync(taskId, "user not found"); return Results.Ok(new { skipped = "user not found" }); } // A temporary error thrown here becomes a 500, so pushq retries. await mailer.SendWelcomeAsync(user); return Results.NoContent(); }); ``` `findUser`, `recordFailure` and `sendWelcomeEmail` stand for your own code. Use this when your handler can tell a permanent error from a temporary one, which is most of the time. :::note pushq keeps the response body only for non-2xx attempts (as the attempt's `error_snippet`). A `2xx` body is not stored, so the task just shows as succeeded. The failure record is yours to keep: a table, a log line, an alert, or a task on another queue. ::: ## What pushq treats as success and failure | Outcome of an attempt | What pushq does | |---|---| | Any `2xx` status | Marks the task `succeeded`. No more attempts. | | Any other status, including `400`, `401`, `404`, `410`, `422`, `500` | Schedules a retry with backoff. | | `429` or `503` with a `Retry-After` header | Retries after the `Retry-After` delay (capped at the queue's `max_backoff_seconds`) and briefly holds back the whole queue. | | Timeout, connection refused, DNS or TLS error | Schedules a retry with backoff. | There is no status code that means "don't retry". Retries end only when the task succeeds, when its retry limits run out, or when you delete it. When the limits run out, the task becomes `failed` and, if the queue has a [dead-letter queue](https://pushqueue.dev/docs/concepts/dead-letter-queues/), a copy goes there. The details are on the [retries page](https://pushqueue.dev/docs/concepts/retries/). ## Cap retries with max_attempts and a dead-letter queue When you can't tell permanent errors apart (for example, a third-party endpoint you don't control), limit how long pushq keeps trying. Set `retry.max_attempts` on the task (it counts the first attempt, so `5` means one try and four retries) and give the queue a dead-letter queue to collect what runs out. The dead-letter queue must already exist. **TypeScript** ```ts await pq.patchQueue("webhooks", { deadLetterQueue: "webhooks-dead" }); await pq.createTask("webhooks", { taskId: "order-created-1234", url: "https://partner.example.com/events", jsonBody: { event: "order.created", order_id: 1234 }, retry: { maxAttempts: 5 }, }); ``` **Python** ```python from pushq import Retry pq.patch_queue("webhooks", dead_letter_queue="webhooks-dead") pq.create_task( "webhooks", task_id="order-created-1234", url="https://partner.example.com/events", json_body={"event": "order.created", "order_id": 1234}, retry=Retry(max_attempts=5), ) ``` **Go** ```go _, err := pq.PatchQueue(ctx, "webhooks", pushq.QueueConfig{DeadLetterQueue: "webhooks-dead"}, "") if err != nil { return err } _, err = pq.CreateTask(ctx, "webhooks", pushq.TaskCreate{ TaskID: "order-created-1234", URL: "https://partner.example.com/events", JSONBody: map[string]any{"event": "order.created", "order_id": 1234}, Retry: &pushq.Retry{MaxAttempts: pushq.Int(5)}, }) ``` **Java** ```java pq.patchQueue("webhooks", QueuePatch.builder() .deadLetterQueue("webhooks-dead") .build()); pq.createTask("webhooks", TaskCreate.builder() .taskId("order-created-1234") .url("https://partner.example.com/events") .jsonBody(Map.of("event", "order.created", "order_id", 1234)) .retry(RetryConfig.builder().maxAttempts(5).build()) .build()); ``` **.NET** ```csharp await pq.PatchQueueAsync("webhooks", new QueuePatch { DeadLetterQueue = "webhooks-dead" }); await pq.CreateTaskAsync("webhooks", new TaskCreate { TaskId = "order-created-1234", Url = "https://partner.example.com/events", JsonBody = new { @event = "order.created", order_id = 1234 }, Retry = new RetryConfig { MaxAttempts = 5 }, }); ``` **curl** ```bash curl -X PATCH https://api.pushqueue.dev/v1/queues/webhooks \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{"dead_letter_queue":"webhooks-dead"}' curl -X POST https://api.pushqueue.dev/v1/queues/webhooks/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{"task_id":"order-created-1234","url":"https://partner.example.com/events","json_body":{"event":"order.created","order_id":1234},"retry":{"max_attempts":5}}' ``` Use this when a task is worth a few tries but not the queue default of 100 attempts. To change the limit for every task in the queue, set `retry.max_attempts` on the queue instead; see [queues](https://pushqueue.dev/docs/concepts/queues/). SDKs use their own casing for these fields (`maxAttempts` in TypeScript and Java, `max_attempts` in Python, `MaxAttempts` in Go and .NET). :::caution[Both retry limits must be reached] If `max_attempts` and `max_retry_duration_seconds` are both set (on the task, or one inherited from the queue), pushq keeps retrying until **both** are reached, the same as Cloud Tasks. A per-task `max_attempts: 3` on a queue with `max_retry_duration_seconds: 86400` still retries for a day. Set the duration to `0` (unlimited) to let `max_attempts` decide alone. ::: ## Delete a task to stop its retries Deleting a task stops it immediately, whatever state it is in. Use it for a task that is already retrying and that you know is hopeless. **TypeScript** ```ts await pq.deleteTask("webhooks", "order-created-1234"); ``` **Python** ```python pq.delete_task("webhooks", "order-created-1234") ``` **Go** ```go err := pq.DeleteTask(ctx, "webhooks", "order-created-1234") ``` **Java** ```java pq.deleteTask("webhooks", "order-created-1234"); ``` **.NET** ```csharp await pq.DeleteTaskAsync("webhooks", "order-created-1234"); ``` **curl** ```bash curl -X DELETE https://api.pushqueue.dev/v1/queues/webhooks/tasks/order-created-1234 \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` - A pending task is never dispatched again. - A running task's in-flight request is not cancelled, but its result is discarded and it won't be retried. - A deleted task is not copied to the dead-letter queue, and its ID stays reserved for the dedup window (1 hour on self-hosted defaults). See [task deduplication](https://pushqueue.dev/docs/patterns/deduplication/). To stop every task in a queue at once, pause the queue (dispatch stops, tasks are kept) or purge it (tasks are deleted). ## Pitfalls - **Returning 4xx for bad input retries it up to 100 times.** Validation errors are permanent; answer them with a `2xx` and record the problem. - **Returning 2xx too eagerly loses work.** Only acknowledge errors you are sure a retry can't fix. Timeouts and `5xx` from your dependencies usually clear up. - **A failure in the dead-letter queue retries too.** Dead-lettered copies get the dead-letter queue's own retry settings and a new task ID. Give that queue a sensible `max_attempts`, and see [replaying dead letters](https://pushqueue.dev/docs/patterns/replay-dead-letters/). - **The dead-letter queue must exist.** If the queue named in `dead_letter_queue` doesn't exist when a task runs out of retries, the copy is not made (the server logs the error) and only the `failed` task remains. - **Use `Retry-After` for "not yet", not "never".** A `429` or `503` with `Retry-After` delays the retry; it doesn't stop it. ## Read more - [Retry backoff and when retries stop](https://pushqueue.dev/docs/concepts/retries/) - [Dead-letter queues for failed tasks](https://pushqueue.dev/docs/concepts/dead-letter-queues/) - [Replay tasks from a dead-letter queue](https://pushqueue.dev/docs/patterns/replay-dead-letters/) - [Idempotent webhook handlers](https://pushqueue.dev/docs/patterns/idempotent-handlers/) - [Troubleshooting failing tasks](https://pushqueue.dev/docs/guides/troubleshooting/) --- # Long-running tasks and timeouts > Run long jobs with pushq by raising dispatch_deadline_seconds, accepting work fast and finishing it in the background, or splitting it into chunked tasks. Source: https://pushqueue.dev/docs/patterns/long-running-work/ Every pushq delivery is one HTTP request with a time limit, `dispatch_deadline_seconds`: 10 minutes by default, 30 minutes at most. This page covers how to run long tasks within that limit: raise the deadline for jobs that fit, accept the request fast and finish the work elsewhere, or split the job into a chain of shorter tasks. ## Set the dispatch deadline for a long task **TypeScript** ```ts await pq.createTask("reports", { taskId: "monthly-report-2026-11", path: "/hooks/build-report", jsonBody: { month: "2026-11" }, dispatchDeadlineSeconds: 1800, // 30 minutes, the maximum }); ``` **Python** ```python pq.create_task( "reports", task_id="monthly-report-2026-11", path="/hooks/build-report", json_body={"month": "2026-11"}, dispatch_deadline_seconds=1800, # 30 minutes, the maximum ) ``` **Go** ```go _, err := pq.CreateTask(ctx, "reports", pushq.TaskCreate{ TaskID: "monthly-report-2026-11", Path: "/hooks/build-report", JSONBody: map[string]any{"month": "2026-11"}, DispatchDeadlineSeconds: pushq.Float64(1800), // 30 minutes, the maximum }) ``` **Java** ```java pq.createTask("reports", TaskCreate.builder() .taskId("monthly-report-2026-11") .path("/hooks/build-report") .jsonBody(Map.of("month", "2026-11")) .dispatchDeadlineSeconds(1800) // 30 minutes, the maximum .build()); ``` **.NET** ```csharp await pq.CreateTaskAsync("reports", new TaskCreate { TaskId = "monthly-report-2026-11", Path = "/hooks/build-report", JsonBody = new { month = "2026-11" }, DispatchDeadline = TimeSpan.FromMinutes(30), // the maximum }); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/reports/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{"task_id":"monthly-report-2026-11","path":"/hooks/build-report","json_body":{"month":"2026-11"},"dispatch_deadline_seconds":1800}' ``` Use this when the job reliably finishes in well under 30 minutes and your endpoint's own request timeout allows it. | Parameter | Type | Default | Description | |---|---|---|---| | `dispatch_deadline_seconds` | number | `600` | How long pushq waits for a response to one attempt, from sending the request to receiving the response status. Must be between `15` and `1800`; other values are rejected with `invalid_argument`. Set per task. | SDKs use their language's casing: `dispatchDeadlineSeconds` in TypeScript and Java, `dispatch_deadline_seconds` in Python, `DispatchDeadlineSeconds` in Go. The .NET SDK takes a `TimeSpan` named `DispatchDeadline`. ## What happens when a task times out When the deadline passes before your endpoint responds, pushq: 1. Abandons the request and closes the connection. 2. Records the attempt with error kind `timeout`. 3. Schedules a retry with the queue's backoff, like any other failure. If retries have run out, the task becomes `failed` and goes to the [dead-letter queue](https://pushqueue.dev/docs/concepts/dead-letter-queues/) if there is one. Closing the connection doesn't stop your code. Whether your handler notices depends on your framework, and many keep running. The retry can then start while the first attempt is still working, so a timed-out task can run twice at the same time. Make the handler [idempotent](https://pushqueue.dev/docs/patterns/idempotent-handlers/), and prefer the patterns below to a deadline your job only just fits in. :::caution[Other timeouts may be shorter] `dispatch_deadline_seconds` is only pushq's limit. A load balancer, reverse proxy, serverless platform or your web server can cut the request off sooner and answer with a `502`/`504`, which pushq retries as a failure. Check every hop between pushq and your handler before raising the deadline. ::: :::note[Self-hosted restarts] When a self-hosted pushq server shuts down, it waits up to `dispatcher.drain_timeout` (default 30 seconds, `PUSHQ_DRAIN_TIMEOUT`) for in-flight deliveries, then aborts the rest. Aborted attempts are retried. Long requests are the ones most likely to be cut off by a deploy. See [operations](https://pushqueue.dev/docs/self-hosting/operations/). ::: ## Accept fast, then do the work For jobs that take longer than the deadline, or that you don't want tied to one HTTP request, have the handler save the job durably and return `202` straight away. A worker of your own (a background thread, a job runner, a process reading a jobs table) does the actual work. **TypeScript** ```ts app.post("/hooks/build-report", express.raw({ type: "*/*" }), async (req, res) => { // Authenticate the request first: see /docs/concepts/delivery/ const taskId = req.get("X-Pushq-Task-Id")!; try { // Insert into your jobs table, ignoring a duplicate taskId. await saveJob(taskId, JSON.parse(req.body.toString("utf8"))); } catch (err) { console.error(err); return res.sendStatus(500); // not saved: pushq retries } res.sendStatus(202); // saved: pushq marks the task succeeded }); ``` **Python** ```python @app.post("/hooks/build-report", status_code=202) async def build_report(request: Request): # Authenticate the request first: see /docs/concepts/delivery/ task_id = request.headers["x-pushq-task-id"] # Insert into your jobs table, ignoring a duplicate task_id. # If this raises, the response is a 500 and pushq retries. await save_job(task_id, await request.json()) return {"accepted": task_id} ``` **Go** ```go func buildReport(w http.ResponseWriter, r *http.Request) { // Authenticate the request first: see /docs/concepts/delivery/ taskID := r.Header.Get("X-Pushq-Task-Id") body, err := io.ReadAll(r.Body) if err == nil { // Insert into your jobs table, ignoring a duplicate taskID. err = saveJob(r.Context(), taskID, body) } if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) // not saved: pushq retries return } w.WriteHeader(http.StatusAccepted) // saved: pushq marks the task succeeded } ``` **Java** ```java @PostMapping("/hooks/build-report") public ResponseEntity buildReport(@RequestBody byte[] payload, @RequestHeader("X-Pushq-Task-Id") String taskId) { // Authenticate the request first: see /docs/concepts/delivery/ // Insert into your jobs table, ignoring a duplicate taskId. // If this throws, the response is a 500 and pushq retries. jobs.save(taskId, payload); return ResponseEntity.accepted().build(); } ``` **.NET** ```csharp app.MapPost("/hooks/build-report", async (HttpRequest req, JobStore jobs) => { // Authenticate the request first: see /docs/concepts/delivery/ var taskId = req.Headers["X-Pushq-Task-Id"].FirstOrDefault()!; using var ms = new MemoryStream(); await req.Body.CopyToAsync(ms); // Insert into your jobs table, ignoring a duplicate taskId. // If this throws, the response is a 500 and pushq retries. await jobs.SaveAsync(taskId, ms.ToArray()); return Results.Accepted(); }); ``` `saveJob` stands for your own code. Use this when a job runs for a long or unpredictable time and you already have somewhere to run background work. :::danger[Save before you acknowledge] Once your handler returns `2xx`, pushq considers the task done and never sends it again. Starting the work in memory (a goroutine, a thread, an un-awaited promise) and returning `202` loses the job if your process restarts. Write the job somewhere durable first, and have your worker handle its own retries. ::: ## Split long work into chunked tasks If the work can be cut into pieces (rows of a table, pages of an API, files in a bucket), process one piece per task and enqueue the next one before responding. Each delivery stays short, a failure retries only the current piece, and pushq's retries, rate limits and visibility apply to every step. The cursor travels in `json_body`, and the next task's ID is derived from the cursor so a retried chunk can't enqueue its successor twice. **TypeScript** ```ts const pq = new Pushq({ apiKey: process.env.PUSHQ_API_KEY }); app.post("/hooks/export-chunk", express.raw({ type: "*/*" }), async (req, res) => { // Authenticate the request first: see /docs/concepts/delivery/ const { export_id, cursor } = JSON.parse(req.body.toString("utf8")); try { // Your code: process up to 1,000 rows after `cursor`; returns null when done. const next = await exportRows(export_id, cursor, 1000); if (next !== null) { await pq.createTask("exports", { taskId: `export-${export_id}-after-${next}`, path: "/hooks/export-chunk", jsonBody: { export_id, cursor: next }, }).catch((err) => { if (!(err instanceof PushqError && err.code === "already_exists")) throw err; }); } res.sendStatus(204); } catch (err) { console.error(err); res.sendStatus(500); // pushq retries this chunk } }); ``` **Python** ```python from pushq import AsyncPushq, PushqError pq = AsyncPushq(api_key=os.environ["PUSHQ_API_KEY"]) @app.post("/hooks/export-chunk", status_code=204) async def export_chunk(request: Request): # Authenticate the request first: see /docs/concepts/delivery/ payload = await request.json() export_id, cursor = payload["export_id"], payload["cursor"] # Your code: process up to 1,000 rows after `cursor`; returns None when done. nxt = await export_rows(export_id, cursor, 1000) if nxt is not None: try: await pq.create_task( "exports", task_id=f"export-{export_id}-after-{nxt}", path="/hooks/export-chunk", json_body={"export_id": export_id, "cursor": nxt}, ) except PushqError as e: if e.code != "already_exists": raise # 500: pushq retries this chunk ``` **Go** ```go func exportChunk(w http.ResponseWriter, r *http.Request) { // Authenticate the request first: see /docs/concepts/delivery/ var p struct { ExportID string `json:"export_id"` Cursor int64 `json:"cursor"` } if err := json.NewDecoder(r.Body).Decode(&p); err != nil { http.Error(w, "bad payload", http.StatusBadRequest) return } // Your code: process up to 1,000 rows after Cursor; done is true at the end. next, done, err := exportRows(r.Context(), p.ExportID, p.Cursor, 1000) if err == nil && !done { _, err = pq.CreateTask(r.Context(), "exports", pushq.TaskCreate{ TaskID: fmt.Sprintf("export-%s-after-%d", p.ExportID, next), Path: "/hooks/export-chunk", JSONBody: map[string]any{"export_id": p.ExportID, "cursor": next}, }) if pushq.IsCode(err, "already_exists") { err = nil } } if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) // pushq retries this chunk return } w.WriteHeader(http.StatusNoContent) } ``` **Java** ```java @PostMapping("/hooks/export-chunk") public ResponseEntity exportChunk(@RequestBody Map payload) { // Authenticate the request first: see /docs/concepts/delivery/ String exportId = (String) payload.get("export_id"); long cursor = ((Number) payload.get("cursor")).longValue(); // Your code: process up to 1,000 rows after cursor; empty when done. OptionalLong next = exporter.exportRows(exportId, cursor, 1000); if (next.isPresent()) { try { pq.createTask("exports", TaskCreate.builder() .taskId("export-" + exportId + "-after-" + next.getAsLong()) .path("/hooks/export-chunk") .jsonBody(Map.of("export_id", exportId, "cursor", next.getAsLong())) .build()); } catch (PushqException e) { if (!"already_exists".equals(e.getCode())) throw e; // 500: pushq retries } } return ResponseEntity.noContent().build(); } ``` **.NET** ```csharp app.MapPost("/hooks/export-chunk", async (ExportChunk chunk, Exporter exporter, PushqClient pq) => { // Authenticate the request first: see /docs/concepts/delivery/ // Your code: process up to 1,000 rows after the cursor; null when done. long? next = await exporter.ExportRowsAsync(chunk.export_id, chunk.cursor, 1000); if (next is long cursor) { try { await pq.CreateTaskAsync("exports", new TaskCreate { TaskId = $"export-{chunk.export_id}-after-{cursor}", Path = "/hooks/export-chunk", JsonBody = new { chunk.export_id, cursor }, }); } catch (PushqException e) when (e.Code == "already_exists") { // A retry of this chunk already enqueued the next one. } } return Results.NoContent(); }); record ExportChunk(string export_id, long cursor); ``` Start the chain by enqueuing the first chunk (for example `{"export_id": "exp-7", "cursor": 0}`). Use this when the job is a loop over many items: it needs no extra infrastructure and each chunk finishes well inside the deadline. More multi-step shapes, including fan-out, are in [chaining steps](https://pushqueue.dev/docs/patterns/chaining-steps/). ## Pitfalls - **Respond only after the next chunk is enqueued.** If you respond first and the enqueue fails, the chain stops silently. If the enqueue fails, return a non-2xx so pushq retries the current chunk. - **Chunks run more than once.** A chunk retried after a lost response processes its rows again. Make each chunk's writes idempotent (upserts keyed by row ID, for example). - **The deadline covers the whole request.** It runs from sending the request until the response status arrives, including time your handler spends waiting on a slow dependency. - **Leave headroom.** Size chunks so a slow run takes a fraction of the deadline, not most of it. A chunk that sometimes times out turns into a chunk that sometimes runs twice in parallel. - **The deadline is set per task.** There is no queue-level setting; pass it on every create call that needs it. A dead-lettered copy keeps the original task's deadline. ## Read more - [Chain tasks into multi-step workflows](https://pushqueue.dev/docs/patterns/chaining-steps/) - [Idempotent webhook handlers](https://pushqueue.dev/docs/patterns/idempotent-handlers/) - [Task options such as dispatch_deadline_seconds](https://pushqueue.dev/docs/concepts/tasks/) - [Retry backoff after a timeout](https://pushqueue.dev/docs/concepts/retries/) - [Troubleshooting timeouts and failing tasks](https://pushqueue.dev/docs/guides/troubleshooting/) --- # Chain tasks into workflows > Build multi-step workflows with pushq by enqueuing the next step from a handler, using deterministic task IDs, batch fan-out and state in json_body. Source: https://pushqueue.dev/docs/patterns/chaining-steps/ A multi-step workflow (charge an order, then ship it, then email the customer) is easier to run as a chain of tasks than as one long request: each step retries on its own, and a failure in step 3 doesn't repeat steps 1 and 2. In pushq, each step's handler does its work and then enqueues the next step, with a task ID derived from the workflow so a retried step never enqueues its successor twice. ## Start the workflow Enqueue the first step. The workflow's identity (here the order ID) goes into both the task ID and the `json_body`. **TypeScript** ```ts await pq.createTask("orders", { taskId: "order-1234-charge", path: "/hooks/orders/charge", jsonBody: { order_id: 1234 }, }); ``` **Python** ```python pq.create_task( "orders", task_id="order-1234-charge", path="/hooks/orders/charge", json_body={"order_id": 1234}, ) ``` **Go** ```go _, err := pq.CreateTask(ctx, "orders", pushq.TaskCreate{ TaskID: "order-1234-charge", Path: "/hooks/orders/charge", JSONBody: map[string]any{"order_id": 1234}, }) ``` **Java** ```java pq.createTask("orders", TaskCreate.builder() .taskId("order-1234-charge") .path("/hooks/orders/charge") .jsonBody(Map.of("order_id", 1234)) .build()); ``` **.NET** ```csharp await pq.CreateTaskAsync("orders", new TaskCreate { TaskId = "order-1234-charge", Path = "/hooks/orders/charge", JsonBody = new { order_id = 1234 }, }); ``` **curl** ```bash 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":"order-1234-charge","path":"/hooks/orders/charge","json_body":{"order_id":1234}}' ``` ## Enqueue the next step from the handler Each step does its work, enqueues the next step with a deterministic ID, and only then returns `2xx`. An `already_exists` error means a previous attempt of this step already enqueued the successor, so it counts as success. **TypeScript** ```ts const pq = new Pushq({ apiKey: process.env.PUSHQ_API_KEY }); app.post("/hooks/orders/charge", express.raw({ type: "*/*" }), async (req, res) => { // Authenticate the request first: see /docs/concepts/delivery/ const { order_id } = JSON.parse(req.body.toString("utf8")); try { await chargeOrder(order_id); // your code, idempotent await pq.createTask("orders", { taskId: `order-${order_id}-ship`, path: "/hooks/orders/ship", jsonBody: { order_id }, }).catch((err) => { if (!(err instanceof PushqError && err.code === "already_exists")) throw err; }); res.sendStatus(204); } catch (err) { console.error(err); res.sendStatus(500); // pushq retries this step } }); ``` **Python** ```python import os from pushq import AsyncPushq, PushqError pq = AsyncPushq(api_key=os.environ["PUSHQ_API_KEY"]) @app.post("/hooks/orders/charge", status_code=204) async def charge(request: Request): # Authenticate the request first: see /docs/concepts/delivery/ order_id = (await request.json())["order_id"] await charge_order(order_id) # your code, idempotent try: await pq.create_task( "orders", task_id=f"order-{order_id}-ship", path="/hooks/orders/ship", json_body={"order_id": order_id}, ) except PushqError as e: if e.code != "already_exists": raise # 500: pushq retries this step ``` **Go** ```go func charge(w http.ResponseWriter, r *http.Request) { // Authenticate the request first: see /docs/concepts/delivery/ var p struct { OrderID int64 `json:"order_id"` } if err := json.NewDecoder(r.Body).Decode(&p); err != nil { http.Error(w, "bad payload", http.StatusBadRequest) return } err := chargeOrder(r.Context(), p.OrderID) // your code, idempotent if err == nil { _, err = pq.CreateTask(r.Context(), "orders", pushq.TaskCreate{ TaskID: fmt.Sprintf("order-%d-ship", p.OrderID), Path: "/hooks/orders/ship", JSONBody: map[string]any{"order_id": p.OrderID}, }) if pushq.IsCode(err, "already_exists") { err = nil } } if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) // pushq retries this step return } w.WriteHeader(http.StatusNoContent) } ``` **Java** ```java @PostMapping("/hooks/orders/charge") public ResponseEntity charge(@RequestBody Map payload) { // Authenticate the request first: see /docs/concepts/delivery/ long orderId = ((Number) payload.get("order_id")).longValue(); billing.chargeOrder(orderId); // your code, idempotent try { pq.createTask("orders", TaskCreate.builder() .taskId("order-" + orderId + "-ship") .path("/hooks/orders/ship") .jsonBody(Map.of("order_id", orderId)) .build()); } catch (PushqException e) { if (!"already_exists".equals(e.getCode())) throw e; // 500: pushq retries this step } return ResponseEntity.noContent().build(); } ``` **.NET** ```csharp app.MapPost("/hooks/orders/charge", async (OrderStep step, Billing billing, PushqClient pq) => { // Authenticate the request first: see /docs/concepts/delivery/ await billing.ChargeOrderAsync(step.order_id); // your code, idempotent try { await pq.CreateTaskAsync("orders", new TaskCreate { TaskId = $"order-{step.order_id}-ship", Path = "/hooks/orders/ship", JsonBody = new { step.order_id }, }); } catch (PushqException e) when (e.Code == "already_exists") { // A previous attempt of this step already enqueued it. } return Results.NoContent(); // any other exception: 500, pushq retries this step }); record OrderStep(long order_id); ``` The ship handler has the same shape and enqueues `order-1234-email`; the last step enqueues nothing. Use this when a workflow has steps with different failure modes or different external dependencies, and you want each one retried, rate limited and visible on its own. ## Why deterministic task IDs prevent double steps The risky moment is a step that enqueued its successor and then failed to respond (it crashed, timed out, or the response was lost). pushq retries the step, and the retry tries to enqueue the successor again. - The successor's ID (`order-1234-ship`) is the same on every attempt, because it's built only from the workflow ID and the step name. - pushq keeps that ID reserved while the successor is pending or running, and after it finishes (24 hours after success, 7 days after failure on self-hosted defaults). The second create gets `409 already_exists`; see [task deduplication](https://pushqueue.dev/docs/patterns/deduplication/). - The step treats `already_exists` as success and returns `2xx`, so the chain carries on with exactly one successor. The work inside a step can still run twice (that's [at-least-once delivery](https://pushqueue.dev/docs/concepts/delivery/#at-least-once-delivery-and-idempotency-keys)), so each step's own side effects need to be [idempotent](https://pushqueue.dev/docs/patterns/idempotent-handlers/). ## Fan out with batch enqueue A step can start many tasks at once, for example one email per subscriber. Use the batch endpoint (up to 500 tasks per call) with one deterministic ID per child. If any item fails with something other than `already_exists`, fail the step: its retry re-sends the whole fan-out, and the children that were already created are skipped as duplicates. **TypeScript** ```ts const day = "2026-11-28"; for (let i = 0; i < userIds.length; i += 500) { const results = await pq.createTasks( "newsletter", userIds.slice(i, i + 500).map((userId) => ({ taskId: `newsletter-${day}-user-${userId}`, path: "/hooks/newsletter/send", jsonBody: { user_id: userId, day }, })), ); const failed = results.filter((r) => r.error && r.error.code !== "already_exists"); if (failed.length > 0) throw new Error(`${failed.length} tasks failed to enqueue`); } ``` **Python** ```python day = "2026-11-28" for i in range(0, len(user_ids), 500): results = pq.create_tasks("newsletter", [ { "task_id": f"newsletter-{day}-user-{user_id}", "path": "/hooks/newsletter/send", "json_body": {"user_id": user_id, "day": day}, } for user_id in user_ids[i:i + 500] ]) failed = [r for r in results if r.error and r.error.code != "already_exists"] if failed: raise RuntimeError(f"{len(failed)} tasks failed to enqueue") ``` **Go** ```go day := "2026-11-28" for start := 0; start < len(userIDs); start += 500 { end := min(start+500, len(userIDs)) batch := make([]pushq.TaskCreate, 0, end-start) for _, userID := range userIDs[start:end] { batch = append(batch, pushq.TaskCreate{ TaskID: fmt.Sprintf("newsletter-%s-user-%d", day, userID), Path: "/hooks/newsletter/send", JSONBody: map[string]any{"user_id": userID, "day": day}, }) } results, err := pq.CreateTasks(ctx, "newsletter", batch) if err != nil { return err } for _, r := range results { if r.Error != nil && r.Error.Code != "already_exists" { return fmt.Errorf("item %d: %s: %s", start+r.Index, r.Error.Code, r.Error.Detail) } } } ``` **Java** ```java String day = "2026-11-28"; for (int start = 0; start < userIds.size(); start += 500) { List batch = new ArrayList<>(); for (long userId : userIds.subList(start, Math.min(start + 500, userIds.size()))) { batch.add(TaskCreate.builder() .taskId("newsletter-" + day + "-user-" + userId) .path("/hooks/newsletter/send") .jsonBody(Map.of("user_id", userId, "day", day)) .build()); } for (BatchResult r : pq.createTasks("newsletter", batch)) { if (!r.isSuccess() && !"already_exists".equals(r.getError().getCode())) { throw new IllegalStateException("item " + (start + r.getIndex()) + ": " + r.getError().getDetail()); } } } ``` **.NET** ```csharp var day = "2026-11-28"; foreach (var chunk in userIds.Chunk(500)) { var results = await pq.CreateTasksAsync("newsletter", chunk.Select(userId => new TaskCreate { TaskId = $"newsletter-{day}-user-{userId}", Path = "/hooks/newsletter/send", JsonBody = new { user_id = userId, day }, })); var failed = results.Count(r => r.Error != null && r.Error.Code != "already_exists"); if (failed > 0) throw new InvalidOperationException($"{failed} tasks failed to enqueue"); } ``` **curl** ```bash curl -X POST "https://api.pushqueue.dev/v1/queues/newsletter/tasks:batch" \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{"tasks":[ {"task_id":"newsletter-2026-11-28-user-42","path":"/hooks/newsletter/send","json_body":{"user_id":42,"day":"2026-11-28"}}, {"task_id":"newsletter-2026-11-28-user-43","path":"/hooks/newsletter/send","json_body":{"user_id":43,"day":"2026-11-28"}} ]}' ``` A batch is not atomic: valid items are created even when others fail, and the request body is capped at 8 MiB. The queue's [rate limits](https://pushqueue.dev/docs/guides/rate-limits/) pace the children, so a fan-out of 100,000 tasks doesn't hit your endpoint all at once. For very large loads see [bulk enqueue](https://pushqueue.dev/docs/patterns/bulk-enqueue/). ### Join the results (fan-in) pushq has no built-in "wait for all children" step. Track completion yourself: store a counter per fan-out (for example `remaining = 100000`), have each child decrement it in the same transaction as its own work, and let the child that brings it to zero enqueue the final step. Give that final step a deterministic ID (`newsletter-2026-11-28-summary`), so if two children both believe they finished last, or one is retried, the final step is still created once. ## Pass workflow state in json_body Each step gets its input from the task's `json_body`, so the body is how state flows through the chain. - **Pass identifiers, not snapshots.** Send `{"order_id": 1234}` and load the order in the step. The body is fixed when the task is created and can be stale by the time a retry runs hours later. - **Carry what the next step can't look up**: the workflow ID, the step's input from the previous step (a charge ID, a cursor), and anything you need for logging. - **Keep it small.** A task body is limited to 1 MiB on self-hosted defaults. Put large data in your database or object storage and pass the key. - **Add delays between steps** with `delay_seconds` or `schedule_time` on the next step, for example a follow-up email three days after signup. See [scheduling and cancelling tasks](https://pushqueue.dev/docs/patterns/scheduling-and-cancelling/). - **Use different queues for different steps** when they call different services, so each step gets its own rate limit, retry policy and target. See [queues](https://pushqueue.dev/docs/concepts/queues/). ## Pitfalls :::caution[Enqueue the next step after your work commits] If you enqueue the successor inside a database transaction that later rolls back, the next step runs against state that doesn't exist. Commit first, then enqueue, then respond. If the enqueue fails, return a non-2xx so pushq retries the step; your idempotent work is skipped and the enqueue is tried again. ::: - **Return 2xx only after the enqueue succeeded.** Responding first and enqueuing afterwards (or in the background) can drop the rest of the workflow without any error in pushq. - **Deduplication is time-limited.** A step that keeps failing for longer than its successor's ID stays reserved (24 hours after the successor succeeded, on self-hosted defaults) enqueues the successor again on its next attempt. If that matters, record step completion in your database too, or cap the step's retries; see [stopping retries](https://pushqueue.dev/docs/patterns/stop-retrying/). - **Task IDs allow only `[A-Za-z0-9_-]`.** Build IDs like `order-1234-ship`, not `order:1234:ship`. - **One step, one side effect.** Steps that do several external things repeat all of them on a retry. Split them, or make each one idempotent on its own. ## Read more - [Task deduplication with task IDs](https://pushqueue.dev/docs/patterns/deduplication/) - [Idempotent webhook handlers](https://pushqueue.dev/docs/patterns/idempotent-handlers/) - [Split long jobs into chunked tasks](https://pushqueue.dev/docs/patterns/long-running-work/) - [Bulk enqueue with the batch API](https://pushqueue.dev/docs/patterns/bulk-enqueue/) - [Tasks: json_body, delays and task IDs](https://pushqueue.dev/docs/concepts/tasks/) --- # Bulk enqueue tasks in batches > Bulk enqueue thousands of tasks with the pushq batch API. Send up to 500 per request, handle partial failures, chunk large lists and target several queues. Source: https://pushqueue.dev/docs/patterns/bulk-enqueue/ This pattern enqueues a large number of tasks at once (a nightly digest for every user, a backfill, a fan-out) with the batch endpoint, `POST /v1/queues/{queue}/tasks:batch`. Each request takes up to 500 tasks, creates every valid one, and reports a result per task, so you chunk big lists and handle the few that fail. ## Enqueue a large list in chunks of 500 **TypeScript** ```ts const users = await loadUsers(); // e.g. 12,000 rows const failed: string[] = []; for (let start = 0; start < users.length; start += 500) { const chunk = users.slice(start, start + 500); const results = await pq.createTasks("emails", chunk.map((u) => ({ taskId: `digest-2026-11-30-user-${u.id}`, path: "/hooks/send-digest", jsonBody: { userId: u.id }, }))); for (const r of results) { // already_exists: created by an earlier run, so it counts as done if (r.error && r.error.code !== "already_exists") { failed.push(`user ${chunk[r.index].id}: ${r.error.code} ${r.error.detail}`); } } } ``` **Python** ```python users = load_users() # e.g. 12,000 rows failed = [] for start in range(0, len(users), 500): chunk = users[start:start + 500] results = pq.create_tasks("emails", [ {"task_id": f"digest-2026-11-30-user-{u.id}", "path": "/hooks/send-digest", "json_body": {"user_id": u.id}} for u in chunk ]) for r in results: # already_exists: created by an earlier run, so it counts as done if r.error and r.error.code != "already_exists": failed.append((chunk[r.index].id, r.error.code, r.error.detail)) ``` **Go** ```go var failed []string for start := 0; start < len(users); start += 500 { chunk := users[start:min(start+500, len(users))] tasks := make([]pushq.TaskCreate, len(chunk)) for i, u := range chunk { tasks[i] = pushq.TaskCreate{ TaskID: fmt.Sprintf("digest-2026-11-30-user-%d", u.ID), Path: "/hooks/send-digest", JSONBody: map[string]any{"user_id": u.ID}, } } results, err := pq.CreateTasks(ctx, "emails", tasks) if err != nil { return err // the whole request failed; resending this chunk is safe } for _, r := range results { // already_exists: created by an earlier run, so it counts as done if r.Error != nil && r.Error.Code != "already_exists" { failed = append(failed, fmt.Sprintf("user %d: %s %s", chunk[r.Index].ID, r.Error.Code, r.Error.Detail)) } } } ``` **Java** ```java List failed = new ArrayList<>(); for (int start = 0; start < users.size(); start += 500) { List chunk = users.subList(start, Math.min(start + 500, users.size())); List tasks = new ArrayList<>(); for (User u : chunk) { tasks.add(TaskCreate.builder() .taskId("digest-2026-11-30-user-" + u.id()) .path("/hooks/send-digest") .jsonBody(Map.of("user_id", u.id())) .build()); } for (BatchResult r : pq.createTasks("emails", tasks)) { // already_exists: created by an earlier run, so it counts as done if (!r.isSuccess() && !"already_exists".equals(r.getError().getCode())) { failed.add("user " + chunk.get(r.getIndex()).id() + ": " + r.getError().getCode() + " " + r.getError().getDetail()); } } } ``` **.NET** ```csharp var failed = new List(); foreach (var chunk in users.Chunk(500)) { var results = await pq.CreateTasksAsync("emails", chunk.Select(u => new TaskCreate { TaskId = $"digest-2026-11-30-user-{u.Id}", Path = "/hooks/send-digest", JsonBody = new { user_id = u.Id }, })); foreach (var r in results) { // already_exists: created by an earlier run, so it counts as done if (r.Error != null && r.Error.Code != "already_exists") failed.Add($"user {chunk[r.Index].Id}: {r.Error.Code} {r.Error.Detail}"); } } ``` **curl** ```bash curl -X POST "https://api.pushqueue.dev/v1/queues/emails/tasks:batch" \ -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \ -d '{"tasks":[ {"task_id":"digest-2026-11-30-user-42","path":"/hooks/send-digest","json_body":{"user_id":42}}, {"task_id":"digest-2026-11-30-user-43","path":"/hooks/send-digest","json_body":{"user_id":43}} ]}' ``` The response lists one result per input task, in input order. Each result has the task's `index` and either the created `task` or an `error`: ```json { "results": [ { "index": 0, "task": { "id": "digest-2026-11-30-user-42", "state": "pending", "...": "..." } }, { "index": 1, "error": { "code": "already_exists", "detail": "already exists" } } ] } ``` The examples assume a client named `pq` (see [install and configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/)). The SDK method is `createTasks` (`create_tasks` in Python, `CreateTasks` in Go, `CreateTasksAsync` in .NET). Each item takes the same fields as a single [task create](https://pushqueue.dev/docs/concepts/tasks/#enqueue-a-task), with your language's casing. Use this when you enqueue more than a handful of tasks at a time: one request per 500 tasks is far faster than 500 separate requests. ## Batch API limits and behaviour | Rule | Value | | --- | --- | | Tasks per request | 1 to 500. An empty list or more than 500 rejects the whole request with `400 invalid_argument`. | | Request body size | 8 MiB for the whole JSON request. Larger requests get `413 payload_too_large`. | | Per-task limits | The same as a single create: 1 MiB body, 16 KiB headers, one-year schedule-ahead (self-hosted defaults). | | Atomicity | None. Valid tasks are created even when others in the same request fail. | | HTTP status | `200` whenever the request itself was accepted, even if every item failed. Check each result. | | Queue | One queue per request. An unknown queue fails the whole request with `404 not_found`. | Task bodies count toward the 8 MiB request limit, and a raw `body_base64` grows by a third when base64-encoded. With large bodies, send fewer than 500 tasks per request. ## Handle partial failures in a batch Every item that fails has an error `code`. Decide per code: | Code | Cause | What to do | | --- | --- | --- | | `already_exists` | A task with this `task_id` exists (or was finished or deleted recently), including a duplicate ID earlier in the same batch. | Usually treat as success: it was enqueued before. | | `invalid_argument` | The item failed validation: bad `task_id`, missing `url`/`path`, `body_base64` with `json_body`, `delay_seconds` with `schedule_time`, body or headers too large. | Fix the data. Resending won't help. | | `failed_precondition` | The item uses `path` but the queue has no `target.base_url`, or the queue is disabled. | Fix the queue, then resend those items. | | `internal` | A server-side error for that item. | Resend the item. | Set a deterministic `task_id` on every item. Then retrying is always safe: if a request times out and you don't know what happened, send the same chunk again, and the tasks that were already created come back as `already_exists` instead of being enqueued twice. Without IDs, a resend after a timeout can create duplicates. See [deduplicate tasks with task IDs](https://pushqueue.dev/docs/patterns/deduplication/). :::caution[Whole-request errors are exceptions, item errors are not] In every SDK, a failed request (network error, `404` unknown queue, `400` empty or oversized batch, `413`) raises an error from `createTasks`. Failed items don't: they come back as results with `error` set. Code that only catches exceptions misses them. ::: :::caution[Python ignores unknown keys] `create_tasks` in Python takes plain dicts and silently drops keys it doesn't know, so a typo like `"delay_second"` creates a task without the delay. Use the same names as `create_task`'s keyword arguments. ::: ## Enqueue to several queues A batch targets one queue. To enqueue to several, group the tasks by queue and send one batch (or several chunks) per queue: **TypeScript** ```ts const byQueue = new Map(); for (const job of jobs) { const queue = `tenants/${job.tenantId}`; if (!byQueue.has(queue)) byQueue.set(queue, []); byQueue.get(queue)!.push({ taskId: job.id, path: "/hooks/sync", jsonBody: job.payload }); } for (const [queue, tasks] of byQueue) { for (let start = 0; start < tasks.length; start += 500) { const results = await pq.createTasks(queue, tasks.slice(start, start + 500)); // handle per-item errors as above } } ``` **Python** ```python from collections import defaultdict by_queue = defaultdict(list) for job in jobs: by_queue[f"tenants/{job.tenant_id}"].append( {"task_id": job.id, "path": "/hooks/sync", "json_body": job.payload}) for queue, tasks in by_queue.items(): for start in range(0, len(tasks), 500): results = pq.create_tasks(queue, tasks[start:start + 500]) # handle per-item errors as above ``` **Go** ```go byQueue := map[string][]pushq.TaskCreate{} for _, job := range jobs { queue := "tenants/" + job.TenantID byQueue[queue] = append(byQueue[queue], pushq.TaskCreate{ TaskID: job.ID, Path: "/hooks/sync", JSONBody: job.Payload, }) } for queue, tasks := range byQueue { for start := 0; start < len(tasks); start += 500 { results, err := pq.CreateTasks(ctx, queue, tasks[start:min(start+500, len(tasks))]) if err != nil { return err } _ = results // handle per-item errors as above } } ``` **Java** ```java Map> byQueue = new HashMap<>(); for (Job job : jobs) { byQueue.computeIfAbsent("tenants/" + job.tenantId(), k -> new ArrayList<>()) .add(TaskCreate.builder().taskId(job.id()).path("/hooks/sync").jsonBody(job.payload()).build()); } for (Map.Entry> e : byQueue.entrySet()) { List tasks = e.getValue(); for (int start = 0; start < tasks.size(); start += 500) { List results = pq.createTasks(e.getKey(), tasks.subList(start, Math.min(start + 500, tasks.size()))); // handle per-item errors as above } } ``` **.NET** ```csharp foreach (var group in jobs.GroupBy(j => $"tenants/{j.TenantId}")) { foreach (var chunk in group.Chunk(500)) { var results = await pq.CreateTasksAsync(group.Key, chunk.Select(j => new TaskCreate { TaskId = j.Id, Path = "/hooks/sync", JsonBody = j.Payload, })); // handle per-item errors as above } } ``` **curl** ```bash curl -X POST "https://api.pushqueue.dev/v1/queues/tenants%2Facme/tasks:batch" \ -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \ -d '{"tasks":[{"task_id":"job-1","path":"/hooks/sync"},{"task_id":"job-2","path":"/hooks/sync"}]}' curl -X POST "https://api.pushqueue.dev/v1/queues/tenants%2Fglobex/tasks:batch" \ -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \ -d '{"tasks":[{"task_id":"job-3","path":"/hooks/sync"}]}' ``` In TypeScript, `TaskCreate` is the task input type exported by the `pushq` package. Queue names containing `/` are URL-encoded (`tenants%2Facme`) in curl; the SDKs do it for you. If some of the queues may not exist yet, create them first (see [per-tenant queues](https://pushqueue.dev/docs/patterns/per-tenant-queues/)): a batch to an unknown queue fails as a whole with `404 not_found`. ## Why bulk enqueue doesn't flood your endpoint The batch endpoint validates each item, then inserts all valid items in a single database transaction, isolating conflicts per item so one duplicate doesn't undo the rest. It wakes the dispatcher once per batch. Enqueueing and delivery are separate: 100,000 new tasks don't mean 100,000 requests at once. The queue's [rate limits](https://pushqueue.dev/docs/guides/rate-limits/) (`max_dispatches_per_second`, `max_burst_size`, `max_concurrent_dispatches`) pace delivery, so you don't need to spread enqueues out with `delay_seconds` to protect your endpoint. Use `delay_seconds` or `schedule_time` only when the work should really happen later. Sending chunks one after another is usually fast enough. If you send chunks in parallel, keep it to a few at a time. ## Pitfalls - **Treating `200` as "all created".** Always walk the results. - **No task IDs.** Without them, resending a chunk after a timeout creates duplicates. - **Retrying `invalid_argument` items.** They fail the same way every time; log and fix them. - **Large bodies in a 500-item batch.** The 8 MiB request cap is hit long before 500 items with 1 MiB bodies. - **Mixing queues in one batch.** Not possible; group by queue first. ## Read more - [Batch enqueue up to 500 tasks](https://pushqueue.dev/docs/concepts/tasks/#batch-enqueue-up-to-500-tasks) - [Deduplicate tasks with task IDs](https://pushqueue.dev/docs/patterns/deduplication/) - [Rate limits: dispatch rate, burst size and concurrency](https://pushqueue.dev/docs/guides/rate-limits/) - [Per-tenant queues and rate limits](https://pushqueue.dev/docs/patterns/per-tenant-queues/) - [API errors and codes](https://pushqueue.dev/docs/reference/errors/) --- # Replay dead-lettered tasks > Park failed tasks in a paused pushq dead-letter queue, inspect why they failed, then replay them after a fix by resuming the DLQ or re-creating them, and purge. Source: https://pushqueue.dev/docs/patterns/replay-dead-letters/ This pattern turns a [dead-letter queue](https://pushqueue.dev/docs/concepts/dead-letter-queues/) (DLQ) into a parking lot: tasks that run out of retries are kept in a paused DLQ, where nothing is delivered, until you have fixed the cause and decide to replay them or throw them away. It covers setting up the DLQ, inspecting dead-lettered tasks, the three ways to replay, and cleaning up. ## Set up a paused dead-letter queue Create the DLQ first, with the same target as the source queue, and pause it. Then point the source queue at it. **TypeScript** ```ts const target = { baseUrl: "https://api.example.com", signingSecret: process.env.PUSHQ_SIGNING_SECRET }; // 1. The DLQ: same target as the source, paused so nothing is delivered until you decide. await pq.upsertQueue("emails-dead", { target, retry: { maxAttempts: 3 } }); await pq.pauseQueue("emails-dead"); // 2. The source queue: tasks that exhaust their retries are copied to the DLQ. await pq.upsertQueue("emails", { target, retry: { maxAttempts: 5 }, deadLetterQueue: "emails-dead", }); ``` **Python** ```python import os from pushq import Retry, Target target = Target(base_url="https://api.example.com", signing_secret=os.environ["PUSHQ_SIGNING_SECRET"]) # 1. The DLQ: same target as the source, paused so nothing is delivered until you decide. pq.upsert_queue("emails-dead", target=target, retry=Retry(max_attempts=3)) pq.pause_queue("emails-dead") # 2. The source queue: tasks that exhaust their retries are copied to the DLQ. pq.upsert_queue("emails", target=target, retry=Retry(max_attempts=5), dead_letter_queue="emails-dead") ``` **Go** ```go target := &pushq.Target{BaseURL: "https://api.example.com", SigningSecret: os.Getenv("PUSHQ_SIGNING_SECRET")} // 1. The DLQ: same target as the source, paused so nothing is delivered until you decide. if _, err := pq.UpsertQueue(ctx, "emails-dead", pushq.QueueConfig{ Target: target, Retry: &pushq.Retry{MaxAttempts: pushq.Int(3)}, }); err != nil { return err } if _, err := pq.PauseQueue(ctx, "emails-dead"); err != nil { return err } // 2. The source queue: tasks that exhaust their retries are copied to the DLQ. _, err := pq.UpsertQueue(ctx, "emails", pushq.QueueConfig{ Target: target, Retry: &pushq.Retry{MaxAttempts: pushq.Int(5)}, DeadLetterQueue: "emails-dead", }) ``` **Java** ```java Target target = Target.builder() .baseUrl("https://api.example.com") .signingSecret(System.getenv("PUSHQ_SIGNING_SECRET")) .build(); // 1. The DLQ: same target as the source, paused so nothing is delivered until you decide. pq.upsertQueue("emails-dead", QueueConfig.builder() .target(target) .retry(RetryConfig.builder().maxAttempts(3).build()) .build()); pq.pauseQueue("emails-dead"); // 2. The source queue: tasks that exhaust their retries are copied to the DLQ. pq.upsertQueue("emails", QueueConfig.builder() .target(target) .retry(RetryConfig.builder().maxAttempts(5).build()) .deadLetterQueue("emails-dead") .build()); ``` **.NET** ```csharp var target = new Target { BaseUrl = "https://api.example.com", SigningSecret = Environment.GetEnvironmentVariable("PUSHQ_SIGNING_SECRET"), }; // 1. The DLQ: same target as the source, paused so nothing is delivered until you decide. await pq.UpsertQueueAsync("emails-dead", new QueueConfig { Target = target, Retry = new RetryConfig { MaxAttempts = 3 } }); await pq.PauseQueueAsync("emails-dead"); // 2. The source queue: tasks that exhaust their retries are copied to the DLQ. await pq.UpsertQueueAsync("emails", new QueueConfig { Target = target, Retry = new RetryConfig { MaxAttempts = 5 }, DeadLetterQueue = "emails-dead", }); ``` **curl** ```bash # 1. The DLQ, then pause it. curl -X PUT https://api.pushqueue.dev/v1/queues/emails-dead \ -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \ -d '{"target":{"base_url":"https://api.example.com","signing_secret":"'"$PUSHQ_SIGNING_SECRET"'"}, "retry":{"max_attempts":3}}' curl -X POST https://api.pushqueue.dev/v1/queues/emails-dead:pause -H "Authorization: Bearer $PUSHQ_API_KEY" # 2. The source queue. curl -X PUT https://api.pushqueue.dev/v1/queues/emails \ -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \ -d '{"target":{"base_url":"https://api.example.com","signing_secret":"'"$PUSHQ_SIGNING_SECRET"'"}, "retry":{"max_attempts":5},"dead_letter_queue":"emails-dead"}' ``` The examples assume a client named `pq` (see [install and configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/)). The text uses JSON field names; the SDKs use their language's casing (`deadLetterQueue` in TypeScript and Java, `dead_letter_queue` in Python, `DeadLetterQueue` in Go and .NET). Use this when failed work must not be lost and must not be retried blindly: payments, order fulfilment, outbound webhooks to customers, anything where you want a human to look before it runs again. Running this setup again is safe: upsert never changes a queue's state, so the DLQ stays paused. ## Why the dead-letter queue must match the source target When a task fails for the last time, pushq copies it into the DLQ as a new task: same `url` or `path`, method, headers and body, plus three `X-Pushq-Deadletter-*` headers. The copy does **not** take the source queue's target or the task's own retry override: - A path-based task (`/hooks/send-welcome`) is resolved against the **DLQ's** `target.base_url`. Without one, every delivery fails with a `config` error. - The DLQ's `target.headers` and `signing_secret` are used, not the source's. If your endpoint checks a static header or a [webhook signature](https://pushqueue.dev/docs/concepts/delivery/#webhook-signing), give the DLQ the same ones. - The DLQ's `retry` settings apply to the copy. That's why the setup reuses one `target` for both queues. See [what is copied to the dead-letter queue](https://pushqueue.dev/docs/concepts/dead-letter-queues/#what-is-copied-to-the-dead-letter-queue) for the full list. :::danger[A missing or disabled DLQ silently drops the copy] pushq doesn't check that the dead-letter queue exists when you set `dead_letter_queue`. If it doesn't exist, or is `disabled`, when a task fails, the copy is dropped (only the server log shows it) and the task is just `failed` in its source queue. Create the DLQ before pointing a queue at it, and pause it rather than disabling it. ::: :::caution[A running DLQ delivers immediately] A dead-lettered copy is scheduled for right now. On a running DLQ it is delivered (and retried) at once, before you've looked at it. Keep the DLQ paused if you want to decide first. A paused queue still accepts the copies. ::: ## Inspect dead-lettered tasks List the DLQ with the full view to see bodies and headers. The original task is still in the source queue in the `failed` state (for 7 days on a default self-hosted server), with its attempt history, which tells you why it failed. **TypeScript** ```ts const page = await pq.listTasks("emails-dead", { view: "full", pageSize: 100 }); for (const t of page.items) { const source = t.headers?.["X-Pushq-Deadletter-Source-Queue"]!; const originalId = t.headers?.["X-Pushq-Deadletter-Task-Id"]!; console.log(t.id, source, originalId, t.headers?.["X-Pushq-Deadletter-Final-Status"]); const attempts = await pq.listAttempts(source, originalId); for (const a of attempts) console.log(" ", a.number, a.responseStatus ?? a.errorKind, a.errorSnippet); } ``` **Python** ```python page = pq.list_tasks("emails-dead", view="full", page_size=100) for t in page.items: source = t.headers["X-Pushq-Deadletter-Source-Queue"] original_id = t.headers["X-Pushq-Deadletter-Task-Id"] print(t.id, source, original_id, t.headers.get("X-Pushq-Deadletter-Final-Status")) for a in pq.list_attempts(source, original_id): print(" ", a.number, a.response_status or a.error_kind, a.error_snippet) ``` **Go** ```go tasks, _, err := pq.ListTasks(ctx, "emails-dead", pushq.ListTasksParams{View: "full", PageSize: 100}) if err != nil { return err } for _, t := range tasks { source := t.Headers["X-Pushq-Deadletter-Source-Queue"] originalID := t.Headers["X-Pushq-Deadletter-Task-Id"] fmt.Println(t.ID, source, originalID, t.Headers["X-Pushq-Deadletter-Final-Status"]) attempts, err := pq.ListAttempts(ctx, source, originalID) if err != nil { continue // the original may already have been cleaned up } for _, a := range attempts { fmt.Println(" ", a.Number, a.ResponseStatus, a.ErrorKind, a.ErrorSnippet) } } ``` **Java** ```java TaskPage page = pq.listTasks("emails-dead", ListTasksParams.builder().view("full").pageSize(100).build()); for (Task t : page.getTasks()) { String source = t.getHeaders().get("X-Pushq-Deadletter-Source-Queue"); String originalId = t.getHeaders().get("X-Pushq-Deadletter-Task-Id"); System.out.println(t.getId() + " " + source + " " + originalId + " " + t.getHeaders().get("X-Pushq-Deadletter-Final-Status")); for (Attempt a : pq.listAttempts(source, originalId)) { System.out.println(" " + a.getNumber() + " " + a.getResponseStatus() + " " + a.getErrorKind() + " " + a.getErrorSnippet()); } } ``` **.NET** ```csharp var page = await pq.ListTasksAsync("emails-dead", new ListTasksOptions { View = TaskView.Full, PageSize = 100 }); foreach (var t in page.Items) { var source = t.Headers!["X-Pushq-Deadletter-Source-Queue"]; var originalId = t.Headers["X-Pushq-Deadletter-Task-Id"]; Console.WriteLine($"{t.Id} {source} {originalId} {t.Headers["X-Pushq-Deadletter-Final-Status"]}"); foreach (var a in await pq.ListAttemptsAsync(source, originalId)) Console.WriteLine($" {a.Number} {a.ResponseStatus?.ToString() ?? a.ErrorKind} {a.ErrorSnippet}"); } ``` **curl** ```bash curl "https://api.pushqueue.dev/v1/queues/emails-dead/tasks?view=full&page_size=100" \ -H "Authorization: Bearer $PUSHQ_API_KEY" # Attempt history of the original task, from X-Pushq-Deadletter-Task-Id: curl "https://api.pushqueue.dev/v1/queues/emails/tasks/welcome-user-42/attempts" \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` The three dead-letter headers: | Header | Meaning | | --- | --- | | `X-Pushq-Deadletter-Source-Queue` | The queue the task failed in. | | `X-Pushq-Deadletter-Task-Id` | The original task's ID in that queue. | | `X-Pushq-Deadletter-Final-Status` | The last attempt's HTTP status (`500`), or its error kind when there was no response (`timeout`, `connect`, `dns`, `tls`, `config`, `lease_lost`). | To alert when tasks start dead-lettering, watch the DLQ's `pending` count in [queue stats](https://pushqueue.dev/docs/concepts/queues/). On a paused DLQ, every task is pending until you act. ## Replay dead-lettered tasks Fix the cause first: deploy the handler fix, restore the downstream service, or correct the queue config. Then pick one of three ways to replay. ### Replay one task with run `POST /v1/queues/emails-dead/tasks/{id}:run` delivers one DLQ task now, even though the DLQ is paused. Use it to check that the fix works before replaying the rest. ### Replay all tasks by resuming the DLQ Resume the DLQ. Its pending tasks are delivered to the DLQ's target (the same endpoint, given the setup above) at the DLQ's rate limits, with the DLQ's retry settings. When the DLQ's `pending` count reaches zero, pause it again so it goes back to collecting. **TypeScript** ```ts await pq.runTask("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b"); // try one await pq.resumeQueue("emails-dead"); // then all of them // ...when queueStats("emails-dead").pending is 0: await pq.pauseQueue("emails-dead"); ``` **Python** ```python pq.run_task("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b") # try one pq.resume_queue("emails-dead") # then all of them # ...when queue_stats("emails-dead").pending is 0: pq.pause_queue("emails-dead") ``` **Go** ```go _, err := pq.RunTask(ctx, "emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b") // try one _, err = pq.ResumeQueue(ctx, "emails-dead") // then all of them // ...when QueueStats(ctx, "emails-dead", "").Pending is 0: _, err = pq.PauseQueue(ctx, "emails-dead") ``` **Java** ```java pq.runTask("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b"); // try one pq.resumeQueue("emails-dead"); // then all of them // ...when queueStats("emails-dead").getPending() is 0: pq.pauseQueue("emails-dead"); ``` **.NET** ```csharp await pq.RunTaskAsync("emails-dead", "0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b"); // try one await pq.ResumeQueueAsync("emails-dead"); // then all of them // ...when (await pq.GetQueueStatsAsync("emails-dead")).Pending is 0: await pq.PauseQueueAsync("emails-dead"); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/emails-dead/tasks/0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b:run \ -H "Authorization: Bearer $PUSHQ_API_KEY" curl -X POST https://api.pushqueue.dev/v1/queues/emails-dead:resume -H "Authorization: Bearer $PUSHQ_API_KEY" # ...when GET /v1/queues/emails-dead/stats shows "pending": 0 curl -X POST https://api.pushqueue.dev/v1/queues/emails-dead:pause -H "Authorization: Bearer $PUSHQ_API_KEY" ``` While the DLQ is running, tasks that newly fail in the source queue are delivered from the DLQ right away too. Replayed copies that fail again follow the DLQ's retry settings and end up `failed` in the DLQ (or in the DLQ's own `dead_letter_queue`, if you set one). ### Replay into the source queue To replay with the source queue's rate limits and retry settings, read each DLQ task and create a new task in the source queue with the same `url` or `path`, method, headers and body, then delete the DLQ copy. Deriving the new ID from the DLQ copy's ID (`replay-`) makes the script safe to run again after a crash: a task that was already re-created comes back as `already_exists`. **TypeScript** ```ts const page = await pq.listTasks("emails-dead", { view: "full", pageSize: 100 }); for (const t of page.items) { const source = t.headers!["X-Pushq-Deadletter-Source-Queue"]; try { await pq.createTask(source, { taskId: `replay-${t.id}`, ...(t.url.startsWith("/") ? { path: t.url } : { url: t.url }), method: t.method, headers: t.headers, body: t.body, }); } catch (err) { if (!(err instanceof PushqError && err.code === "already_exists")) throw err; } await pq.deleteTask("emails-dead", t.id); } ``` **Python** ```python from pushq import PushqError page = pq.list_tasks("emails-dead", view="full", page_size=100) for t in page.items: source = t.headers["X-Pushq-Deadletter-Source-Queue"] where = {"path": t.url} if t.url.startswith("/") else {"url": t.url} try: pq.create_task(source, task_id=f"replay-{t.id}", method=t.method, headers=t.headers, body=t.body, **where) except PushqError as e: if e.code != "already_exists": raise pq.delete_task("emails-dead", t.id) ``` **Go** ```go tasks, _, err := pq.ListTasks(ctx, "emails-dead", pushq.ListTasksParams{View: "full", PageSize: 100}) if err != nil { return err } for _, t := range tasks { body, err := base64.StdEncoding.DecodeString(t.BodyBase64) if err != nil { return err } replay := pushq.TaskCreate{ TaskID: "replay-" + t.ID, Method: t.Method, Headers: t.Headers, Body: body, } if strings.HasPrefix(t.URL, "/") { replay.Path = t.URL } else { replay.URL = t.URL } source := t.Headers["X-Pushq-Deadletter-Source-Queue"] if _, err := pq.CreateTask(ctx, source, replay); err != nil && !pushq.IsCode(err, "already_exists") { return err } if err := pq.DeleteTask(ctx, "emails-dead", t.ID); err != nil { return err } } ``` **Java** ```java TaskPage page = pq.listTasks("emails-dead", ListTasksParams.builder().view("full").pageSize(100).build()); for (Task t : page.getTasks()) { String source = t.getHeaders().get("X-Pushq-Deadletter-Source-Queue"); TaskCreate.Builder replay = TaskCreate.builder() .taskId("replay-" + t.getId()) .method(t.getMethod()) .headers(t.getHeaders()) .body(t.getBodyBase64() == null ? null : Base64.getDecoder().decode(t.getBodyBase64())); if (t.getUrl().startsWith("/")) replay.path(t.getUrl()); else replay.url(t.getUrl()); try { pq.createTask(source, replay.build()); } catch (PushqException e) { if (!"already_exists".equals(e.getCode())) throw e; } pq.deleteTask("emails-dead", t.getId()); } ``` **.NET** ```csharp var page = await pq.ListTasksAsync("emails-dead", new ListTasksOptions { View = TaskView.Full, PageSize = 100 }); foreach (var t in page.Items) { var source = t.Headers!["X-Pushq-Deadletter-Source-Queue"]; var replay = new TaskCreate { TaskId = $"replay-{t.Id}", Method = t.Method, Headers = t.Headers, Body = t.Body }; if (t.Url.StartsWith("/")) replay.Path = t.Url; else replay.Url = t.Url; try { await pq.CreateTaskAsync(source, replay); } catch (PushqException e) when (e.Code == "already_exists") { // re-created by an earlier run } await pq.DeleteTaskAsync("emails-dead", t.Id); } ``` **curl** ```bash # 1. Read the DLQ task (url, method, headers, body_base64): curl "https://api.pushqueue.dev/v1/queues/emails-dead/tasks/0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b?view=full" \ -H "Authorization: Bearer $PUSHQ_API_KEY" # 2. Re-create it in the source queue ("path" when url starts with "/", else "url"): curl -X POST https://api.pushqueue.dev/v1/queues/emails/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \ -d '{"task_id":"replay-0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b","path":"/hooks/send-welcome", "method":"POST","headers":{"Content-Type":"application/json"},"body_base64":"eyJ1c2VyX2lkIjo0Mn0="}' # 3. Delete the DLQ copy: curl -X DELETE https://api.pushqueue.dev/v1/queues/emails-dead/tasks/0193a1b2-7c4d-7e8f-9a0b-1c2d3e4f5a6b \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` This replays the first 100 tasks; loop over `next_page_token` for more, or run it again until the DLQ is empty. The `X-Pushq-Deadletter-*` headers come along with the other headers, so your handler can tell a replay apart (they are replaced, not duplicated, if the task dead-letters again). :::caution[The original task ID is still taken] You can't re-create the task under its original ID: the failed original keeps that ID reserved in the source queue for its retention period (7 days on a default self-hosted server). Use a new ID such as `replay-`, and if your handler deduplicates on `X-Pushq-Task-Id` or `webhook-id`, have it use `X-Pushq-Deadletter-Task-Id` when present. See [idempotent handlers](https://pushqueue.dev/docs/patterns/idempotent-handlers/). ::: ## Purge the dead-letter queue when done To throw away everything left in the DLQ (tasks you decided not to replay), purge it. Purge deletes every task created up to that moment and keeps the queue and its paused state, so it keeps collecting new failures. **TypeScript** ```ts await pq.purgeQueue("emails-dead"); ``` **Python** ```python pq.purge_queue("emails-dead") ``` **Go** ```go _, err := pq.PurgeQueue(ctx, "emails-dead") ``` **Java** ```java pq.purgeQueue("emails-dead"); ``` **.NET** ```csharp await pq.PurgeQueueAsync("emails-dead"); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/emails-dead:purge -H "Authorization: Bearer $PUSHQ_API_KEY" ``` To drop only some tasks, delete them one by one with `DELETE /v1/queues/emails-dead/tasks/{id}`. ## Pitfalls - **DLQ created after the source queue starts failing.** Copies made before the DLQ existed are lost. Create the DLQ first. - **DLQ without the source's `base_url`, headers or signing secret.** Replays by resume fail with `config` errors or are rejected by your endpoint. - **Resuming and forgetting.** A running DLQ delivers new failures immediately. Pause it again after the replay. - **Replaying before fixing.** The tasks fail again and use up the DLQ's retries. Try one with run first. - **Using `upsertQueue` with a partial config on the source queue.** Upsert replaces the whole config, and an omitted `dead_letter_queue` is removed. Always include it (see [per-tenant queues](https://pushqueue.dev/docs/patterns/per-tenant-queues/#upsert-replaces-the-whole-queue-config)). ## Read more - [Dead-letter queues: setup, copied fields and headers](https://pushqueue.dev/docs/concepts/dead-letter-queues/) - [Retries, backoff and max attempts](https://pushqueue.dev/docs/concepts/retries/) - [Stop retrying permanent errors](https://pushqueue.dev/docs/patterns/stop-retrying/) - [Idempotent task handlers](https://pushqueue.dev/docs/patterns/idempotent-handlers/) - [Troubleshooting failed tasks](https://pushqueue.dev/docs/guides/troubleshooting/) --- # Install a self-hosted server > Install the pushq server from a GitHub release binary, the Docker image, go install or source, then create the first admin account. Source: https://pushqueue.dev/docs/self-hosting/install/ pushq is a single static binary that contains the API, the dispatcher and the dashboard. Install it one of four ways, then run `pushq serve` (production) or `pushq dev` (local development). Use this page when you want to run pushq on your own machine or servers. If you'd rather not run anything, use the hosted API at `https://api.pushqueue.dev` and sign up in the [console](https://console.pushqueue.dev/). ## Install options at a glance **Binary** ```bash VERSION=1.0.0 # or any release from GitHub Releases curl -fsSLO https://github.com/blissfulrays/pushq/releases/download/v${VERSION}/pushq_${VERSION}_linux_amd64.tar.gz tar -xzf pushq_${VERSION}_linux_amd64.tar.gz sudo install pushq /usr/local/bin/pushq ``` **Docker** ```bash docker run -p 8080:8080 -v pushq-data:/data ghcr.io/blissfulrays/pushq:latest ``` **go install** ```bash # API and dispatcher only; no dashboard go install github.com/blissfulrays/pushq/cmd/pushq@latest ``` **Source** ```bash git clone https://github.com/blissfulrays/pushq.git cd pushq make build # needs Go and Node.js 20+; embeds the dashboard ``` The sections below explain each option. ## Download a release binary Every release on [GitHub Releases](https://github.com/blissfulrays/pushq/releases) ships prebuilt binaries with the dashboard embedded: | OS | Architectures | Archive | |---|---|---| | Linux | `amd64`, `arm64` | `.tar.gz` | | macOS | `amd64`, `arm64` | `.tar.gz` | | Windows | `amd64` | `.zip` | Archives are named `pushq___`, for example `pushq_1.0.0_linux_amd64.tar.gz`, and contain the `pushq` binary, `LICENSE` and `README.md`. Each release also has a `checksums.txt`. ```bash VERSION=1.0.0 # pick the release you want curl -fsSLO https://github.com/blissfulrays/pushq/releases/download/v${VERSION}/pushq_${VERSION}_linux_amd64.tar.gz curl -fsSLO https://github.com/blissfulrays/pushq/releases/download/v${VERSION}/checksums.txt sha256sum --check --ignore-missing checksums.txt tar -xzf pushq_${VERSION}_linux_amd64.tar.gz sudo install pushq /usr/local/bin/pushq pushq version ``` :::tip `https://github.com/blissfulrays/pushq/releases/latest` always points at the newest stable release. ::: ## Run the Docker image The image is `ghcr.io/blissfulrays/pushq`, built for `linux/amd64` and `linux/arm64` with the dashboard included. | Tag | Points at | |---|---| | `:` (e.g. `:1.0.0`) | That exact release. Use this in production. | | `:latest` | The newest stable release. | | `:edge` | The newest release of any kind, prereleases included. Moves on every release. | The image runs `pushq serve` by default, as a non-root user, listens on port `8080`, declares a volume at `/data`, and sets `PUSHQ_DB=sqlite:/data/pushq.db`. Configure it with `PUSHQ_*` environment variables (see the [server configuration reference](https://pushqueue.dev/docs/self-hosting/configuration/)): **SQLite** ```bash docker run -p 8080:8080 -v pushq-data:/data ghcr.io/blissfulrays/pushq:latest ``` **Postgres** ```bash docker run -p 8080:8080 \ -e PUSHQ_DB='postgres://pushq:secret@db.internal/pushq?sslmode=disable' \ ghcr.io/blissfulrays/pushq:1.0.0 ``` The image is distroless: it has no shell, `curl` or `wget`. Health checks that run a command inside the container won't work; probe `GET /healthz` or `GET /readyz` from outside instead (see [health and readiness checks](https://pushqueue.dev/docs/self-hosting/operations/#health-and-readiness-checks)). ## Install with go install ```bash go install github.com/blissfulrays/pushq/cmd/pushq@latest ``` This needs the Go version in the module's `go.mod` (currently Go 1.26). The result is a fully working server, but **without the dashboard**: the compiled dashboard is a build artifact, not a committed file, and the Go module proxy never runs npm. A binary built this way serves a short placeholder page at `/`; the API, dispatcher and metrics are unaffected. Use this when you only need the API, for example in CI or for SDK tests. ## Build from source with the dashboard To build the binary with the dashboard embedded you need Go and Node.js 20 or newer: ```bash git clone https://github.com/blissfulrays/pushq.git cd pushq make build # builds the dashboard (web/) first, then ./pushq ./pushq version ``` `make build-go` skips the dashboard build, like `go install`. ## Run the server for the first time Start the server with SQLite (the default database is `sqlite:pushq.db` in the working directory) or with Postgres, which lets you run several replicas: **SQLite** ```bash pushq serve --db sqlite:/var/lib/pushq/pushq.db --listen :8080 ``` **Postgres** ```bash pushq serve --db postgres://user:pass@host/pushq --listen :8080 ``` Database migrations run automatically on startup. You can also run them on their own with `pushq migrate`. ### Create the first admin account A new server with no `api_keys` in its config and no dashboard accounts is **unauthenticated**: anyone who can reach it can use the API. The server logs a warning saying so until you close it. 1. Open the dashboard at `http://:8080/`. 2. It asks you to create the admin account (email, name, password). 3. From then on every API request needs a login session or an API key. Do this before you expose the server publicly. If the config already has `api_keys`, setup also asks for one of its **admin** keys, so a protected server can't be claimed by whoever reaches the dashboard first. Then create API keys for your apps under **Settings → API keys** (see [API keys](https://pushqueue.dev/docs/guides/api-keys/)), or define them in the config file. :::caution Serve the dashboard over HTTPS. Behind a TLS-terminating proxy, forward `X-Forwarded-Proto: https` so pushq marks the session cookie `Secure`. See [reverse proxy setup](https://pushqueue.dev/docs/self-hosting/deploy/#put-pushq-behind-a-reverse-proxy). ::: ### Recover a locked-out admin account `pushq users` works directly on the database, so it works even when nobody can sign in: ```bash pushq users list -c /etc/pushq/pushq.yaml pushq users reset-password you@example.com -c /etc/pushq/pushq.yaml --url https://pushq.example.com ``` `reset-password` prints a one-time link. Opening it lets the person choose a new password and signs them out everywhere. ## Run a local dev server with pushq dev ```bash pushq dev ``` `pushq dev` runs a full server with authentication disabled, SQLite in a temp file (`pushq-dev.db` in your OS temp directory), debug logs and faster internal timers. Add `--memory` for an in-memory database that is discarded on exit, and `--listen :9090` to change the port. Never expose a `pushq dev` server: it accepts every request. See [local development](https://pushqueue.dev/docs/getting-started/local-development/) for a walkthrough. ## Read more - [Server configuration reference](https://pushqueue.dev/docs/self-hosting/configuration/): every config key, environment variable and CLI flag. - [Deploy to production](https://pushqueue.dev/docs/self-hosting/deploy/): systemd, docker-compose with Postgres, reverse proxies. - [Monitoring, backups and upgrades](https://pushqueue.dev/docs/self-hosting/operations/): health checks, metrics and day-2 operations. - [SaaS mode with WorkOS](https://pushqueue.dev/docs/self-hosting/saas-mode/): multi-team sign-in. - [Install & configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/): point a client at your server. --- # Server configuration reference > Every pushq server setting: YAML keys, PUSHQ_* environment variables, defaults, .env loading order, and all CLI commands and flags. Source: https://pushqueue.dev/docs/self-hosting/configuration/ A pushq server reads its settings from four places. Later sources override earlier ones: 1. Built-in defaults. 2. A YAML config file, passed with `pushq serve -c pushq.yaml`. 3. Environment variables (`PUSHQ_*` and `WORKOS_*`), including ones loaded from a `.env` file. 4. Command-line flags (`--db`, `--listen`, `--log-level`). Every setting has a default, so `pushq serve` with no config at all starts a working server on `:8080` with SQLite in `./pushq.db`. ## Load settings from a .env file Before reading the config file, pushq loads environment variables from a `.env` file in the working directory. Set `PUSHQ_ENV_FILE` to load a different file instead. - Variables that are already set in the real environment are left alone, so the real environment always wins over `.env`. - A missing file is not an error. - The format is `KEY=VALUE`, one per line. Blank lines, `#` comments, an `export ` prefix and matching single or double quotes around the value are allowed. Anything else is a startup error that names the line. ```bash # .env PUSHQ_DB=postgres://pushq:secret@localhost/pushq PUSHQ_API_KEYS=admin:pq_admin_change-me export PUSHQ_LOG_FORMAT="json" ``` `pushq serve`, `pushq migrate` and `pushq users` load `.env`. `pushq dev` ignores both `.env` and the config file and uses its own fixed settings. Use this when you want to keep secrets such as `WORKOS_API_KEY` or a database password out of the YAML file. ## Configuration settings reference Durations use Go syntax: `500ms`, `30s`, `15m`, `1h`, `168h`. There is no `d` unit, so write 7 days as `168h`. The YAML parser rejects unknown keys, so a typo fails at startup instead of being ignored. ### Database, listen address and API keys | YAML key | Environment variable | Type | Default | Description | |---|---|---|---|---| | `db` | `PUSHQ_DB` | string | `sqlite:pushq.db` | Database URL: `sqlite:` or `postgres://…` / `postgresql://…`. Anything else is rejected. Flag: `--db`. | | `listen` | `PUSHQ_LISTEN` | string | `:8080` | Address the HTTP server listens on, e.g. `127.0.0.1:8080`. Flag: `--listen`. | | `api_keys` | `PUSHQ_API_KEYS` | list | none | Config-file API keys. Each entry has a `key` and a `role` of `admin` or `writer`. In the environment variable, write comma-separated `role:key` pairs: `admin:pq_aaa,writer:pq_bbb`. Setting the variable replaces the YAML list. | Config-file keys are optional; you can also create keys in the dashboard. An `admin` key can do everything, including listing and deleting queues and managing members and keys. A `writer` key can create and change queues, enqueue tasks, and read queues and tasks it knows by name, but can't list all queues or delete queues. See [API keys](https://pushqueue.dev/docs/guides/api-keys/) for creating keys in the dashboard. :::caution With no `api_keys` and no dashboard accounts, the server accepts unauthenticated requests until someone completes first-time setup. See [create the first admin account](https://pushqueue.dev/docs/self-hosting/install/#create-the-first-admin-account). ::: ### WorkOS settings (SaaS mode) Setting both `client_id` and `api_key` turns on SaaS mode: WorkOS becomes the only sign-in, teams are WorkOS Organizations, and each team's data is isolated. Setting only one of the two is a startup error. See [SaaS mode](https://pushqueue.dev/docs/self-hosting/saas-mode/) for the full setup. | YAML key | Environment variable | Type | Default | Description | |---|---|---|---|---| | `workos.client_id` | `WORKOS_CLIENT_ID` | string | empty | WorkOS client ID. | | `workos.api_key` | `WORKOS_API_KEY` | string | empty | WorkOS API key. Prefer the environment variable over the YAML file. | | `workos.redirect_uri` | `WORKOS_REDIRECT_URI` | string | `/v1/auth/workos/callback` | Where WorkOS sends people back after GitHub sign-in. Must be listed under Redirects in the WorkOS dashboard. Set it when a proxy changes the host or scheme. | | `workos.api_base` | `WORKOS_API_BASE` | string | `https://api.workos.com` | Overrides the WorkOS API URL. Only useful for tests. | ### Dispatcher and concurrency | YAML key | Environment variable | Type | Default | Description | |---|---|---|---|---| | `dispatcher.global_concurrency` | `PUSHQ_GLOBAL_CONCURRENCY` | int | `512` | Maximum HTTP deliveries in flight across all queues on this server. Must be at least 1. | | `dispatcher.per_queue_claim_cap` | `PUSHQ_PER_QUEUE_CLAIM_CAP` | int | `100` | Maximum tasks claimed from one queue in a single scheduling pass. Must be at least 1. | | `dispatcher.reconcile_interval` | `PUSHQ_RECONCILE_INTERVAL` | duration | `30s` | How often the dispatcher re-reads which queues have due work and their settings from the database. | | `dispatcher.drain_timeout` | `PUSHQ_DRAIN_TIMEOUT` | duration | `30s` | On shutdown, how long in-flight deliveries get to finish before they are cancelled. | | `dispatcher.sweep_interval` | none | duration | `15s` | How often expired task leases are found and the tasks retried. | | `dispatcher.cleanup_interval` | none | duration | `60s` | How often finished tasks past their retention are deleted. | | `dispatcher.lease_grace` | none | duration | `60s` | Extra time added to a task's `dispatch_deadline_seconds` to form its lease. A task whose lease expires without a recorded result counts as a failed attempt (`lease_lost`) and is retried. | ### Request limits and dedup window | YAML key | Environment variable | Type | Default | Description | |---|---|---|---|---| | `limits.max_body_bytes` | `PUSHQ_MAX_BODY_BYTES` | int | `1048576` (1 MiB) | Largest task body, after base64 decoding. Must be at least 1. | | `limits.max_headers_bytes` | `PUSHQ_MAX_HEADERS_BYTES` | int | `16384` (16 KiB) | Largest total size of a task's custom headers (names plus values). | | `limits.max_schedule_ahead` | `PUSHQ_MAX_SCHEDULE_AHEAD` | duration | `8760h` (1 year) | How far in the future a task may be scheduled. `0` turns the check off (`delay_seconds` is still capped at 100 years). | | `limits.dedup_window` | `PUSHQ_DEDUP_WINDOW` | duration | `1h` | How long a `task_id` stays reserved after the task finishes or is deleted. Reusing it within the window returns `409 already_exists`. | ### Task retention | YAML key | Environment variable | Type | Default | Description | |---|---|---|---|---| | `retention.succeeded` | `PUSHQ_RETENTION_SUCCEEDED` | duration | `24h` | How long succeeded tasks and their attempt history are kept. | | `retention.failed` | `PUSHQ_RETENTION_FAILED` | duration | `168h` (7 days) | How long failed tasks and their attempt history are kept. | A finished task is never deleted before `limits.dedup_window` has passed, even if its retention is shorter. ### Metrics | YAML key | Environment variable | Type | Default | Description | |---|---|---|---|---| | `metrics.public` | `PUSHQ_METRICS_PUBLIC` | bool | `true` | Serve `GET /metrics` without authentication. When `false`, it needs an admin API key or a dashboard session (in SaaS mode, only a config-file key). In the variable, `1` or `true` (any case) means true; any other value means false. | ### Logging | YAML key | Environment variable | Type | Default | Description | |---|---|---|---|---| | `log.level` | `PUSHQ_LOG_LEVEL` | string | `info` | `debug`, `info`, `warn` or `error`. Unknown values fall back to `info`. Flag: `--log-level`. | | `log.format` | `PUSHQ_LOG_FORMAT` | string | `text` | `text` or `json`. Logs go to stderr. | ## Example pushq.yaml config file The same configuration as a YAML file and as environment variables: **YAML** ```yaml # /etc/pushq/pushq.yaml # sqlite: for one node, postgres://… for several replicas. db: sqlite:/var/lib/pushq/pushq.db # db: postgres://pushq:secret@db.internal:5432/pushq?sslmode=require # Bind to localhost and put a TLS-terminating proxy in front. listen: 127.0.0.1:8080 # Optional config-file keys. You can also create keys in the dashboard. api_keys: - { key: "pq_admin_change-me", role: admin } # everything - { key: "pq_writer_change-me", role: writer } # queues and tasks by name # SaaS mode. Leave out for a self-hosted server with local accounts. # Prefer WORKOS_API_KEY in the environment over putting it here. # workos: # client_id: client_01... # redirect_uri: https://pushq.example.com/v1/auth/workos/callback dispatcher: global_concurrency: 512 # deliveries in flight, all queues together per_queue_claim_cap: 100 # tasks claimed per queue per scheduling pass reconcile_interval: 30s drain_timeout: 30s # keep below your process manager's stop timeout sweep_interval: 15s cleanup_interval: 60s lease_grace: 60s limits: max_body_bytes: 1048576 # 1 MiB max_headers_bytes: 16384 # 16 KiB max_schedule_ahead: 8760h # 1 year; 0 = no limit dedup_window: 1h retention: succeeded: 24h failed: 168h # 7 days metrics: public: true # false = /metrics needs an admin key or a session log: level: info # debug | info | warn | error format: json # text | json ``` **Environment** ```bash PUSHQ_DB=sqlite:/var/lib/pushq/pushq.db PUSHQ_LISTEN=127.0.0.1:8080 PUSHQ_API_KEYS=admin:pq_admin_change-me,writer:pq_writer_change-me PUSHQ_GLOBAL_CONCURRENCY=512 PUSHQ_PER_QUEUE_CLAIM_CAP=100 PUSHQ_RECONCILE_INTERVAL=30s PUSHQ_DRAIN_TIMEOUT=30s PUSHQ_MAX_BODY_BYTES=1048576 PUSHQ_MAX_HEADERS_BYTES=16384 PUSHQ_MAX_SCHEDULE_AHEAD=8760h PUSHQ_DEDUP_WINDOW=1h PUSHQ_RETENTION_SUCCEEDED=24h PUSHQ_RETENTION_FAILED=168h PUSHQ_METRICS_PUBLIC=true PUSHQ_LOG_LEVEL=info PUSHQ_LOG_FORMAT=json ``` `dispatcher.sweep_interval`, `dispatcher.cleanup_interval` and `dispatcher.lease_grace` have no environment variables; set them in the YAML file. ## CLI commands and flags Run `pushq --help` for the built-in help. ### pushq serve Runs the server: the API, the dashboard and the dispatcher. Applies database migrations on startup. Stops gracefully on `SIGINT` or `SIGTERM`. | Flag | Description | |---|---| | `-c, --config ` | YAML config file. | | `--db ` | Database URL. Overrides `db` and `PUSHQ_DB`. | | `--listen ` | Listen address. Overrides `listen` and `PUSHQ_LISTEN`. | | `--log-level ` | `debug`, `info`, `warn` or `error`. Overrides `log.level` and `PUSHQ_LOG_LEVEL`. | ```bash pushq serve -c /etc/pushq/pushq.yaml --log-level debug ``` ### pushq dev Runs a local development server: authentication disabled, SQLite in `/pushq-dev.db`, debug logs, and faster reconcile (1s), sweep (2s) and cleanup (5s) timers. It does not read a config file or `.env`. | Flag | Default | Description | |---|---|---| | `--listen ` | `:8080` | Listen address. | | `--memory` | off | Use an in-memory database; all state is lost on exit. | ### pushq migrate Applies database migrations and exits. `pushq serve` does this on its own, so you only need it to migrate ahead of a deploy. | Flag | Description | |---|---| | `-c, --config ` | YAML config file. | | `--db ` | Database URL. | ### pushq users Manages dashboard accounts directly in the database, so it works when nobody can sign in. Takes `-c, --config` and `--db` like `migrate`. | Command | Description | |---|---| | `pushq users list` | Lists accounts with email, name, role and last login. | | `pushq users reset-password [--url ]` | Prints a one-time password-reset link. `--url` is the server's public URL used to build the link (default `http://localhost:8080`). | ### pushq openapi Prints the OpenAPI document generated from the server's routes, the same one a running server serves at `/openapi.json`. Needs no database. ```bash pushq openapi > openapi.json ``` ### pushq version Prints the version and commit, e.g. `pushq 1.0.0 (abc1234)`. ### pushq queues and pushq tasks Client commands that call a running server's API. Both take: | Flag | Default | Description | |---|---|---| | `--server ` | `$PUSHQ_SERVER`, else `http://localhost:8080` | Server URL. | | `--api-key ` | `$PUSHQ_API_KEY` | API key sent as a bearer token. | | Command | Description | |---|---| | `pushq queues ls [--prefix

]` | List queues (admin key). | | `pushq queues upsert [flags]` | Create or update a queue. Flags: `--rate`, `--burst`, `--concurrency`, `--max-attempts`, `--min-backoff`, `--max-backoff` (durations, e.g. `1s`, `5m`), `--base-url`, `--method`, `--signing-secret` (`""` clears it; omit to keep), `--dlq`. | | `pushq queues get ` | Show a queue. | | `pushq queues pause ` / `resume ` | Pause or resume dispatching. | | `pushq queues purge ` | Delete all tasks created up to now. | | `pushq queues rm ` | Delete a queue (admin key). | | `pushq queues stats [--id-prefix

]` | Queue depth and error rates. | | `pushq tasks ls [--state ] [--prefix

] [--view basic\|full]` | List tasks. `--state` is `pending`, `running`, `succeeded` or `failed`. | | `pushq tasks create [flags]` | Enqueue a task. Flags: `--id`, `--url`, `--path`, `--method`, `--json`, `--delay` (e.g. `30s`, `2h`), `--max-attempts`. | | `pushq tasks get ` | Show a task, including headers and body. | | `pushq tasks rm ` | Delete a task. | | `pushq tasks run ` | Dispatch a task now. | | `pushq tasks attempts ` | Show a task's attempt history. | ```bash export PUSHQ_SERVER=https://pushq.example.com PUSHQ_API_KEY=pq_admin_change-me pushq queues upsert emails --rate 10 --max-attempts 5 --base-url https://app.example.com pushq tasks create emails --path /hooks/send --json '{"to":"a@example.com"}' --delay 1h pushq queues stats emails ``` --- # Deploy a self-hosted server > Deploy pushq in production: one SQLite node with systemd, or Postgres replicas with docker-compose, behind nginx or Caddy, with blue/green deploys. Source: https://pushqueue.dev/docs/self-hosting/deploy/ pushq is one static binary with the dashboard included. It runs in one of two shapes: | Shape | Use it when | |---|---| | **Single node + SQLite** | You want zero dependencies: one box, one file. Plan for up to about 500 sustained dispatches per second. | | **Several replicas + Postgres** | You need high availability or more throughput. Every replica serves the API; a Postgres advisory lock elects one replica to run the dispatcher. | Both shapes run the same binary; only the `db` setting changes. See the [server configuration reference](https://pushqueue.dev/docs/self-hosting/configuration/) for every setting. **systemd** ```bash # Single node, SQLite: install the unit and config below, then sudo systemctl enable --now pushq ``` **docker-compose** ```bash # Two replicas on Postgres: save the compose file below, then docker compose up -d ``` ## Deploy a single node with systemd and SQLite Use this when one machine is enough and you don't want to run a database server. ```ini # /etc/systemd/system/pushq.service [Unit] Description=pushq task queue After=network-online.target Wants=network-online.target [Service] ExecStart=/usr/local/bin/pushq serve -c /etc/pushq/pushq.yaml Restart=always RestartSec=2 User=pushq StateDirectory=pushq # SIGTERM starts a graceful drain: in-flight deliveries get up to # dispatcher.drain_timeout (default 30s) to finish. TimeoutStopSec=45 [Install] WantedBy=multi-user.target ``` ```yaml # /etc/pushq/pushq.yaml db: sqlite:/var/lib/pushq/pushq.db listen: 127.0.0.1:8080 # a reverse proxy in front terminates TLS log: { format: json } ``` ```bash sudo useradd --system --no-create-home pushq sudo systemctl daemon-reload sudo systemctl enable --now pushq journalctl -u pushq -f ``` `StateDirectory=pushq` creates `/var/lib/pushq` owned by the `pushq` user. SQLite runs in WAL mode, so you'll see `pushq.db-wal` and `pushq.db-shm` next to the database file. Keep `TimeoutStopSec` above `drain_timeout` plus a few seconds, or systemd will kill the process before in-flight deliveries finish. :::caution Create the admin account in the dashboard **before** exposing the server. Until then, a server without `api_keys` accepts anonymous requests. See [create the first admin account](https://pushqueue.dev/docs/self-hosting/install/#create-the-first-admin-account). ::: ## Run multiple replicas with docker-compose and Postgres Use this when you need the API to stay up through a crash or a deploy. All replicas serve the API; one at a time runs the dispatcher. ```yaml # docker-compose.yml services: db: image: postgres:16 environment: { POSTGRES_USER: pushq, POSTGRES_PASSWORD: pushq, POSTGRES_DB: pushq } volumes: [pgdata:/var/lib/postgresql/data] healthcheck: { test: ["CMD-SHELL", "pg_isready -U pushq"], interval: 2s, retries: 30 } pushq-a: &pushq image: ghcr.io/blissfulrays/pushq:1.0.0 # pin a version command: serve environment: PUSHQ_DB: postgres://pushq:pushq@db/pushq?sslmode=disable PUSHQ_LISTEN: ":8080" PUSHQ_LOG_FORMAT: json PUSHQ_API_KEYS: "admin:pq_admin_,writer:pq_writer_" depends_on: { db: { condition: service_healthy } } ports: ["8081:8080"] pushq-b: <<: *pushq ports: ["8082:8080"] volumes: pgdata: ``` Generate real keys (for example `echo "pq_$(openssl rand -hex 24)"`) instead of the placeholders. Load-balance across the replicas however you like. `GET /readyz` reports which replica currently runs the dispatcher (`"role": "leader"`); the others report `"follower"` and still serve every API request. See [high availability and leader election](https://pushqueue.dev/docs/self-hosting/operations/#high-availability-and-leader-election). ## Put pushq behind a reverse proxy Run pushq on a private address and put a TLS-terminating proxy in front. Two things matter. ### Forward encoded queue names unmodified Queue names can contain `/` (folders, e.g. `user/instagram`). In URLs the whole name travels as one encoded segment: `/v1/queues/user%2Finstagram`. Your proxy must pass `%2F` through as-is. If it decodes `%2F` into `/`, pushq sees a different path and answers `404 not_found`. - **Caddy** forwards the path unmodified by default. - **nginx**: write `proxy_pass http://127.0.0.1:8080;` with **no** URI part. A trailing slash (`proxy_pass http://127.0.0.1:8080/;`) makes nginx normalize the path and decode `%2F`. ### Set X-Forwarded-Proto for TLS pushq marks the dashboard session cookie `Secure` only when the request arrived over TLS or carries `X-Forwarded-Proto: https`. In SaaS mode the same check picks the scheme of the default WorkOS redirect URI. Behind a TLS-terminating proxy, forward that header. Caddy sets `X-Forwarded-Proto` and gets certificates on its own; with nginx, set it yourself. **nginx** ```nginx server { listen 443 ssl; server_name pushq.example.com; # ssl_certificate / ssl_certificate_key ... client_max_body_size 10m; # batch enqueue bodies can be up to 8 MiB location / { proxy_pass http://127.0.0.1:8080; # no trailing slash proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; proxy_read_timeout 60s; } } ``` **Caddy** ```text pushq.example.com { reverse_proxy 127.0.0.1:8080 } ``` pushq rate-limits password sign-in attempts per client IP. Behind a proxy every client shares the proxy's address, which still caps brute-force attempts but means one noisy client can briefly lock out others. ## Zero-downtime blue/green deploys You can run the old and new versions side by side against the same Postgres database: 1. Start the new instance. It serves the API immediately; its dispatcher role is `follower`. 2. Send `SIGTERM` to the old instance. It releases dispatcher leadership at once, stops accepting new connections, then drains in-flight deliveries for up to `dispatcher.drain_timeout` (default 30s). 3. The new instance takes leadership within about 5 seconds (followers retry the lock every 5s) and continues from where the old one left off. Correctness never depends on the lock: each delivery's result is recorded only if the task's lease token still matches, so overlapping instances can't both complete the same attempt. As with any at-least-once queue, a task whose lease expires mid-delivery is retried, so keep handlers idempotent. See [at-least-once delivery](https://pushqueue.dev/docs/concepts/delivery/). New versions apply their database migrations on startup. To apply them before switching traffic, run `pushq migrate` with the new binary first. ## Deploy on Coolify or another Docker PaaS The image works on any platform that runs a container image. A typical setup on Coolify or a similar Docker PaaS: 1. Create a Postgres database on a private network. 2. Create an app from the Docker image `ghcr.io/blissfulrays/pushq:`, or `:latest` to follow stable releases. 3. Expose port `8080` and attach your domain. The platform's proxy terminates TLS and should send `X-Forwarded-Proto`. 4. Set environment variables: `PUSHQ_DB=postgres://USER:PASS@:5432/?sslmode=disable`, plus `PUSHQ_API_KEYS` or the [SaaS mode](https://pushqueue.dev/docs/self-hosting/saas-mode/) variables if you need them. Use the platform's secret storage for passwords and keys. 5. Turn off the platform's in-container health check, or point it at the HTTP endpoint from outside: the image is distroless, so a check that runs `curl` or `wget` inside the container fails. To redeploy automatically on every release, run the app on `:latest` and trigger the platform's deploy webhook when a new image is published. With SQLite instead of Postgres, mount a persistent volume at `/data` (the image defaults to `PUSHQ_DB=sqlite:/data/pushq.db`). ## Sizing and performance - **Memory**: the ceiling is roughly `dispatcher.global_concurrency × limits.max_body_bytes` (defaults: 512 × 1 MiB = 512 MiB worst case), plus a few MB per 10,000 active queues. - **SQLite** (pure-Go driver, one writer): plan for about 500 sustained dispatches per second with headroom. Beyond that, or for high availability, use Postgres. - **Postgres**: each replica opens up to 16 pooled connections, plus a dedicated connection for the leader lock and one for `LISTEN`/`NOTIFY`. If you put PgBouncer in front, use **session** mode: `LISTEN`/`NOTIFY` and advisory locks need real sessions. ### Throughput benchmark Smoke benchmark from the repository (`PUSHQ_LOAD=1 go test ./test/load`): one laptop, a local receiver that answers instantly, 1,000 dynamic queues and 50,000 tasks. | Backend | Queue creation | Enqueue | End-to-end dispatch | |---|---|---|---| | SQLite | 1,000 in 0.2s | ~11,000/s | ~2,300 tasks/s | | Postgres 15 | 1,000 in 0.6s | ~2,600/s (batched) | ~3,600 tasks/s | Treat these as upper-bound smoke numbers, not guarantees. In production, throughput is usually bounded by your receivers and by each queue's rate limits. ## Read more - [Install a self-hosted server](https://pushqueue.dev/docs/self-hosting/install/): binaries, Docker image and first-time setup. - [Server configuration reference](https://pushqueue.dev/docs/self-hosting/configuration/): every setting and environment variable. - [Monitoring, backups and upgrades](https://pushqueue.dev/docs/self-hosting/operations/): health checks, metrics and leader election. - [SaaS mode with WorkOS](https://pushqueue.dev/docs/self-hosting/saas-mode/): multi-team sign-in. - [How delivery works](https://pushqueue.dev/docs/concepts/delivery/): at-least-once delivery and signatures. --- # Monitoring, backups and upgrades > Operate a self-hosted pushq server: health checks, Prometheus metrics, logging, leader election, task retention, backups and upgrades. Source: https://pushqueue.dev/docs/self-hosting/operations/ This page covers what you need once pushq is running: probing it, monitoring it, keeping it highly available, backing it up and upgrading it. ## Health and readiness checks | Endpoint | Auth | Answers | Use it for | |---|---|---|---| | `GET /healthz` | none | `200` with body `ok` while the process is up. Doesn't touch the database. | Liveness probes: restart the process if this fails. | | `GET /readyz` | none | `200` with `{"role": "...", "dialect": "..."}` when the database answers a ping; `503` with a problem+json body (`"detail": "database unreachable"`) when it doesn't. | Readiness probes and load balancer health checks. | ```bash curl -s http://localhost:8080/readyz ``` ```json {"role":"leader","dialect":"postgres"} ``` `dialect` is `sqlite` or `postgres`. `role` says what this replica's dispatcher is doing: | `role` | Meaning | |---|---| | `leader` | This replica runs the dispatcher. A SQLite server is always `leader` once started. | | `follower` | Another replica holds the dispatcher lock. This one still serves the full API. | | `stopped` | The dispatcher has shut down (the process is exiting). | A `follower` is healthy. Don't take followers out of the load balancer: every replica serves the API. Use `/readyz` for Kubernetes readiness probes and `/healthz` for liveness probes: ```yaml livenessProbe: httpGet: { path: /healthz, port: 8080 } readinessProbe: httpGet: { path: /readyz, port: 8080 } ``` `GET /v1/version` (any API key) returns `{"version", "commit", "dialect"}`, and `pushq version` prints the same for a binary. ## Prometheus metrics `GET /metrics` serves Prometheus metrics. It is public by default; set `metrics.public: false` (or `PUSHQ_METRICS_PUBLIC=false`) to require an admin API key or a dashboard session. In [SaaS mode](https://pushqueue.dev/docs/self-hosting/saas-mode/) with metrics not public, only the operator's config-file keys can read it. ```yaml # prometheus.yml scrape_configs: - job_name: pushq static_configs: - targets: ["pushq-a:8080", "pushq-b:8080"] # with metrics.public: false # authorization: { credentials: pq_admin_... } ``` The metrics are aggregate on purpose: there are no per-queue labels, because a server with 10,000+ dynamic queues would explode label cardinality. For per-queue numbers use `GET /v1/queues/{queue}/stats`. | Metric | Type | Labels | Meaning | |---|---|---|---| | `pushq_dispatches_total` | counter | `code_class`: `2xx`, `3xx`, `4xx`, `5xx`, `error` | Delivery attempts by response class. `error` means no HTTP response (timeout, connection, DNS, TLS, or a request that couldn't be built). | | `pushq_dispatch_errors_total` | counter | `error_kind`: `non_2xx`, `timeout`, `connect`, `dns`, `tls`, `config` | Failed delivery attempts by cause. | | `pushq_dispatch_duration_seconds` | histogram | none | Delivery round-trip latency, default Prometheus buckets. | | `pushq_dispatch_inflight` | gauge | none | Deliveries currently in flight. Compare with `dispatcher.global_concurrency`. | | `pushq_tasks_claimed_total` | counter | none | Tasks leased by the dispatcher for delivery. | | `pushq_task_retries_total` | counter | none | Failed attempts that were rescheduled for retry. | | `pushq_tasks_dead_lettered_total` | counter | none | Tasks copied to a dead-letter queue after exhausting retries. | | `pushq_leases_expired_total` | counter | none | Leases reclaimed by the sweeper because no result was recorded in time (for example after a crash). | | `pushq_active_queues` | gauge | none | Queues the dispatcher is currently tracking. | The endpoint also exposes the standard Go runtime (`go_*`) and process (`process_*`) collectors. Only the replica that is `leader` dispatches, so dispatch metrics come from that replica. Sum across replicas in your queries so a leader change doesn't look like a drop. Useful queries: ```text # Delivery error ratio over 5 minutes sum(rate(pushq_dispatches_total{code_class!="2xx"}[5m])) / sum(rate(pushq_dispatches_total[5m])) # p95 delivery latency histogram_quantile(0.95, sum(rate(pushq_dispatch_duration_seconds_bucket[5m])) by (le)) # Dispatcher saturation (alert when close to global_concurrency) max(pushq_dispatch_inflight) ``` ## Structured logging Logs go to stderr. Choose the format and level in the config (see [logging settings](https://pushqueue.dev/docs/self-hosting/configuration/#logging)): ```yaml log: level: info # debug | info | warn | error format: json # text | json ``` At `info` you get startup and shutdown messages, warnings (such as an unauthenticated server, or a lost leader lock) and errors. At `debug` you also get one line per HTTP request (`method`, `path`, `status`, `dur_ms`) and dispatcher detail. `pushq dev` always logs at `debug`. ## High availability and leader election Run two or more replicas against one Postgres database for high availability. SQLite servers are single-node. - **Every replica serves the API.** Enqueues, queue changes and reads work on any replica. - **One replica dispatches.** Replicas compete for a session-level Postgres advisory lock. The holder becomes `leader` and runs the dispatcher; the rest are `follower` and retry the lock every 5 seconds. - **Failover.** The leader pings its lock connection every 5 seconds. If that connection dies, the lock is gone and another replica takes over at its next attempt. On a graceful shutdown (`SIGTERM`), the leader releases the lock immediately. - **Wakeups.** With Postgres, new tasks and queue changes reach the leader through `LISTEN`/`NOTIFY`, so a task enqueued on a follower is dispatched without waiting for a poll. ### Lease fencing The lock is an optimization that avoids duplicate work, not what keeps delivery correct. Correctness comes from per-task leases: 1. When the dispatcher claims a task, it writes a fresh lease token and a lease expiry of `dispatch_deadline_seconds + dispatcher.lease_grace` (default grace 60s). 2. A delivery's result is recorded only if the task still carries that lease token. A stale worker, for example from a replica that lost leadership mid-delivery, can't overwrite a newer attempt. 3. Every `dispatcher.sweep_interval` (default 15s), the leader finds leases that expired without a result, records a `lease_lost` attempt, and retries or fails the task by its retry policy. The attempt counts toward `max_attempts`, because the request may well have reached your endpoint. This is why blue/green deploys and crash failover are safe. It is also why delivery is at-least-once: make your handlers idempotent. See [at-least-once delivery](https://pushqueue.dev/docs/concepts/delivery/). ## Task retention and cleanup The leader deletes finished tasks in the background, every `dispatcher.cleanup_interval` (default 60s), in batches. If a backlog remains, it runs again a second later instead of waiting a full interval. | What | Kept for | Setting | |---|---|---| | Succeeded tasks and their attempts | 24h | `retention.succeeded` | | Failed tasks and their attempts | 7 days | `retention.failed` | | Deleted tasks (tombstones) | 1h | `limits.dedup_window` | | Tasks removed by a purge | Deleted in the background right after the purge | none | A finished or deleted task's ID stays reserved for at least `limits.dedup_window`, so retention shorter than the dedup window is extended to it. Longer retention means more rows to scan; size your database accordingly. ## Back up the database All state lives in the database: queues, tasks, attempt history, dashboard accounts, sessions, invites, API keys and teams. The binary itself is stateless. ### Back up SQLite The database runs in WAL mode, so copying only the `.db` file while the server runs can miss recent writes. Use SQLite's online backup, which is safe while pushq runs: ```bash sqlite3 /var/lib/pushq/pushq.db ".backup '/backups/pushq-$(date +%F).db'" ``` Or stop the service and copy `pushq.db` together with any `pushq.db-wal` and `pushq.db-shm` files. To restore, stop pushq, put the backup in place as `pushq.db` (removing stale `-wal` and `-shm` files), and start it. ### Back up Postgres Use your normal Postgres tooling: ```bash pg_dump --format=custom --file=pushq-$(date +%F).dump "postgres://pushq:secret@db/pushq" pg_restore --clean --dbname="postgres://pushq:secret@db/pushq" pushq-2026-11-28.dump ``` Managed Postgres snapshots and point-in-time recovery work too. :::note Restoring a backup brings back tasks as they were at backup time. Tasks that were delivered after the backup may be delivered again, consistent with at-least-once delivery. ::: ## Upgrade to a new version 1. Read the [release notes](https://github.com/blissfulrays/pushq/releases) for the version you're moving to. 2. Back up the database. 3. Replace the binary or change the image tag, then restart. `pushq serve` applies any new database migrations on startup; each migration runs in its own transaction and is recorded in a `schema_migrations` table, so restarting is safe. 4. Check `GET /readyz` and `GET /v1/version` on each replica. With several Postgres replicas, upgrade one replica at a time, or follow the [blue/green procedure](https://pushqueue.dev/docs/self-hosting/deploy/#zero-downtime-bluegreen-deploys). To apply migrations before you switch traffic, run the new binary's `pushq migrate -c pushq.yaml` first. Pin an exact image tag (`:1.0.0`) in production so upgrades happen when you choose. `:latest` moves on every stable release and `:edge` on every release, prereleases included. There is no `down` migration. To roll back to an older binary after a release that changed the schema, restore the backup you took in step 2. ## Read more - [Deploy to production](https://pushqueue.dev/docs/self-hosting/deploy/): systemd, docker-compose and blue/green deploys. - [Server configuration reference](https://pushqueue.dev/docs/self-hosting/configuration/): retention, dispatcher and metrics settings. - [Retries and backoff](https://pushqueue.dev/docs/concepts/retries/): how failed deliveries are retried. - [Dead-letter queues](https://pushqueue.dev/docs/concepts/dead-letter-queues/): where tasks go after their last attempt. --- # Multi-tenant SaaS mode with WorkOS > Run your own multi-tenant pushq with WorkOS sign-in, where anyone can sign up, create teams and get isolated queues, tasks and API keys. Source: https://pushqueue.dev/docs/self-hosting/saas-mode/ By default a self-hosted pushq server has one team: you and the people you invite, all sharing the same queues. **SaaS mode** turns it into a multi-tenant service like the hosted one at pushqueue.dev: anyone can sign up, create teams, and get their own isolated queues, tasks, stats and API keys. Sign-in and team membership are handled by [WorkOS](https://workos.com/). Use this when you want to offer pushq to several customers or internal groups from one deployment, with each one unable to see the others' data. For a single team, the default mode is simpler. ## What changes | | Self-hosted (default) | SaaS mode | |---|---|---| | Turned on by | Nothing; no WorkOS settings | `WORKOS_CLIENT_ID` and `WORKOS_API_KEY` | | Sign-in | Local accounts with passwords; the first person creates the admin | A 6-digit code emailed by WorkOS, or GitHub, on pushq's own sign-in page. Signing in the first time creates the account. No passwords. | | Teams | One: everyone on the server | Anyone can create teams; a person can belong to several and switch between them | | Data | Shared by everyone | Isolated per team: queues, tasks, attempts, stats and API keys | | Invites | A one-time link you send yourself | Emailed by WorkOS | | Config-file `api_keys` | Ordinary admin/writer keys | Operator keys that see every team | Everything in [Team members](https://pushqueue.dev/docs/guides/team-members/) that's described for the hosted service applies to SaaS mode. ## Turn it on Set both WorkOS credentials and start the server with `pushq serve`: ```bash export WORKOS_CLIENT_ID=client_... export WORKOS_API_KEY=sk_... export PUSHQ_DB=postgres://pushq:secret@db.internal/pushq export PUSHQ_API_KEYS="admin:pq_operator_" export PUSHQ_METRICS_PUBLIC=false pushq serve ``` The log confirms it at startup: ```text level=INFO msg="SaaS mode: WorkOS sign-in, one isolated workspace per team" client_id=client_... redirect_uri=/v1/auth/workos/callback ``` | Variable | YAML key | Default | Description | |---|---|---|---| | `WORKOS_CLIENT_ID` | `workos.client_id` | none | Your WorkOS client ID. Required for SaaS mode. | | `WORKOS_API_KEY` | `workos.api_key` | none | Your WorkOS API key. Required for SaaS mode. Prefer the environment variable over writing it in the config file. | | `WORKOS_REDIRECT_URI` | `workos.redirect_uri` | `/v1/auth/workos/callback` | Where WorkOS sends people back after GitHub sign-in. Set it when pushq is behind a proxy that changes the host or scheme. It must be listed under Redirects in WorkOS. | Set both `WORKOS_CLIENT_ID` and `WORKOS_API_KEY`, or neither: with only one, the server refuses to start. With neither, it runs in the default self-hosted mode. pushq also reads a `.env` file from the directory where `pushq serve` runs (or the file named by `PUSHQ_ENV_FILE`). Variables already set in the real environment win over the file. ```bash # .env (keep it out of version control) WORKOS_CLIENT_ID=client_... WORKOS_API_KEY=sk_... # WORKOS_REDIRECT_URI=https://pushq.example.com/v1/auth/workos/callback PUSHQ_API_KEYS=admin:pq_operator_ ``` The equivalent in the YAML config file: ```yaml workos: client_id: client_... redirect_uri: https://pushq.example.com/v1/auth/workos/callback # api_key: better passed as WORKOS_API_KEY ``` SaaS mode works with SQLite and Postgres. `pushq dev` ignores WorkOS settings and always runs with authentication off. Serve pushq over HTTPS. Behind a TLS-terminating proxy, forward `X-Forwarded-Proto: https` so session cookies are marked `Secure` and the default redirect URI uses `https`. See [Deploy](https://pushqueue.dev/docs/self-hosting/deploy/). ## WorkOS dashboard checklist 1. **Authentication:** enable **Magic Auth** (email codes) and **GitHub OAuth**, and allow sign-ups so new people can create accounts. - **Email verification:** with it on, WorkOS pauses a GitHub sign-in until the person enters a code it emails them; pushq's sign-in page asks for it. Turn it off to let GitHub sign-ins straight in, in which case pushq trusts the email address GitHub provides. Email-code sign-ins prove the address either way. 2. **Redirects → Sign-in callback** (used by GitHub sign-in only): add `https:///v1/auth/workos/callback`. For local testing against a staging environment, `http://localhost:8080/v1/auth/workos/callback`. If you set `WORKOS_REDIRECT_URI`, add exactly that URL. 3. **Roles:** keep the default `admin` and `member` roles. pushq uses those slugs; if `admin` is missing, it falls back to the environment's default role. 4. Use the WorkOS **staging** environment while testing. ## How people sign in The sign-in page is pushq's own (served by the dashboard at `/login`); WorkOS works behind it and no WorkOS-hosted screens are shown, apart from GitHub's consent screen. - **Email code:** the person enters their email and pushq asks WorkOS to send a 6-digit code. An email WorkOS hasn't seen before gets a new WorkOS user first, so this is also sign-up. The response never reveals whether the email already had an account. - **GitHub:** the browser goes to GitHub through WorkOS and comes back to `/v1/auth/workos/callback`. After sign-in, pushq finds or creates the local account (matching by WorkOS user, then by verified email), mirrors the person's WorkOS organizations as teams, and starts the session in the team they used last. Someone with no team yet lands on the **Welcome** screen to create one. Password sign-in, first-time setup, invite and reset links, and password changes are switched off: those endpoints return `404` (`/v1/auth/setup`, `/v1/auth/login`, `/v1/auth/invites/{token}`, `/v1/auth/invites/{token}:accept`, `/v1/me/password`, `/v1/users/{id}/reset-link`). ## Teams and roles **Each team is a WorkOS Organization.** Creating a team in the dashboard creates an organization with the creator as its `admin` member. Renaming the team renames the organization. Inviting someone sends a WorkOS invitation email; removing someone deletes their organization membership. **Roles live in pushq.** pushq has three roles per team (admin, member, viewer; see [Roles](https://pushqueue.dev/docs/guides/team-members/#roles)), and WorkOS has two. pushq maps them like this: | pushq role | WorkOS organization role | |---|---| | admin | `admin` | | member | `member` | | viewer | `member` (pushq enforces read-only) | pushq's role is authoritative. When it learns of a member from WorkOS (someone added in the WorkOS dashboard, for example), it gives them `admin` if their WorkOS role is `admin` and `member` otherwise, unless a pending pushq invite for their email says which role to grant. After that, changing their role in WorkOS doesn't change it in pushq; change it on pushq's Team page. **pushq re-syncs from WorkOS** every time a person signs in (their teams) and whenever a team's Team settings page is opened (its members). Memberships added or removed directly in the WorkOS dashboard are picked up then. ## How team data is isolated - Queues, tasks, attempts, stats and API keys all belong to a team. Two teams can each have a queue called `emails`. - Internally each team gets a random 12-character namespace, and its queues are stored as `:`. Queue names can't contain `:`, so no name a client sends can reach outside its own namespace. pushq strips the namespace from everything it returns, including error messages. - Receivers only ever see the short name: the `X-Pushq-Queue` header and the signed `webhook-id` use `emails`, not the stored name. - API keys created in the dashboard or through `/v1/api-keys` belong to the team that created them and only see its queues. A team's admin key manages that team's members, invites and keys. - A person removed from a team loses access at once; their sessions on that team stop working on the next request. ## Operator keys In SaaS mode, the keys in the config file (`api_keys` or `PUSHQ_API_KEYS`) are **operator keys** for you, the operator: - They aren't tied to any team and see every team's queues. Listings show stored names, `:`. - Teams never see them: the API keys page reports no config keys. - Only operator keys can read `/metrics` when it isn't public (see below). - Queues created with an operator key belong to no team. Keep them for your own tooling and monitoring. Team management (members, invites, team API keys) belongs to each team's admins, in the dashboard or with that team's admin key; don't use operator keys for it. ### Metrics `/metrics` is public by default (`metrics.public: true`). Its metrics are aggregate over the whole instance (no per-queue or per-team labels), but you likely don't want customers reading your instance's totals. Set `PUSHQ_METRICS_PUBLIC=false` (or `metrics: { public: false }`) and scrape with an operator key: ```bash curl https://pushq.example.com/metrics \ -H "Authorization: Bearer $PUSHQ_OPERATOR_KEY" ``` ## Switch an existing server to SaaS mode You can add the WorkOS settings to a server that already has data. What happens to it: - **Queues and tasks** are left untouched, but they belong to no team. Only operator keys can see and manage them, under their existing names. - **Dashboard accounts** are kept. When someone signs in through WorkOS with the same verified email, pushq links their existing account instead of creating a new one. Their password and old server-wide role no longer apply; they start with no team until they create one or accept an invite. - **API keys created in the dashboard** before the switch stop working: they belong to no team, and pushq refuses them in SaaS mode. Create new keys inside a team. - **Config-file keys** keep working and become operator keys. - **Pending invite and password-reset links** stop working. Plan the switch like a migration: create the teams, move workloads to queues created with each team's own keys, then update your apps to use those keys. --- # Queues API reference > pushq Queues API reference: create, upsert, get, list, patch, pause, resume, purge and delete queues and read queue stats, with SDK and curl examples. Source: https://pushqueue.dev/docs/reference/rest/queues/ The Queues API creates and manages pushq queues. A queue holds tasks and decides how they are delivered: how fast (`rate_limits`), how failures are retried (`retry`), where relative task paths point and which headers are forced (`target`), and where permanently failed tasks go (`dead_letter_queue`). To put work on a queue, see the [Tasks API reference](https://pushqueue.dev/docs/reference/rest/tasks/). All examples use the hosted API at `https://api.pushqueue.dev` and an API key in `$PUSHQ_API_KEY`. Self-hosted servers expose the same endpoints at their own URL. :::note[Queue names in paths] Queue names may contain `/` to group queues into folders (`user/instagram`). In a URL path the whole name is **one** segment, so encode the slash: `/v1/queues/user%2Finstagram`. An unencoded slash is read as a different route and returns `404 not_found` with a hint to encode it. The SDKs encode queue names for you. ::: ## Create an SDK client Every example on this page is shown in TypeScript, Python, Go, Java and .NET, plus the raw `curl` request. The SDK snippets assume a client named `pq`, created like this (see [install and configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/) for self-hosted URLs, timeouts and other options): **TypeScript** ```ts const pq = new Pushq({ apiKey: process.env.PUSHQ_API_KEY }); ``` **Python** ```python import os from pushq import Pushq, RateLimits, Retry, Target pq = Pushq(api_key=os.environ["PUSHQ_API_KEY"]) ``` **Go** ```go import ( "context" "os" pushq "github.com/blissfulrays/pushq/sdks/go" ) pq := pushq.New("", os.Getenv("PUSHQ_API_KEY")) // "" = https://api.pushqueue.dev ctx := context.Background() ``` **Java** ```java import io.pushq.*; Pushq pq = Pushq.builder().apiKey(System.getenv("PUSHQ_API_KEY")).build(); ``` **.NET** ```csharp using Pushq; using var pq = new PushqClient(apiKey: Environment.GetEnvironmentVariable("PUSHQ_API_KEY")); ``` Parameter tables on this page use the JSON field names (`rate_limits.max_dispatches_per_second`). The SDKs use their language's casing for the same fields: camelCase in TypeScript and Java (`maxDispatchesPerSecond`), snake_case in Python, PascalCase in Go and .NET (`MaxDispatchesPerSecond`). ## Queue API permissions | Endpoint | Writer API key | Admin API key | Dashboard roles | |---|---|---|---| | Create, upsert, patch, pause, resume, purge | yes | yes | member, admin | | Get a queue, get stats | yes | yes | viewer, member, admin | | List queues | no | yes | viewer, member, admin | | Delete a queue | no | yes | member, admin | A request without valid credentials gets `401 unauthenticated`; a key or role that lacks the permission gets `403 permission_denied`. On the hosted service each team has its own queue namespace: two teams can both have a queue called `emails` and never see each other's. ## Queue names and folders A queue name is 1–200 characters made of `/`-separated segments. Each segment starts with a lowercase letter or digit and contains only `a-z`, `0-9` and `-` (regex `^[a-z0-9][a-z0-9-]*(/[a-z0-9][a-z0-9-]*)*$`). Folders have no configuration of their own; they exist as long as some queue name uses them. Pass folder names to the SDKs as-is; they URL-encode the name as one path segment for you: **TypeScript** ```ts await pq.upsertQueue("user/instagram", { target: { baseUrl: "https://api.example.com" } }); await pq.createTask("user/instagram", { path: "/sync", jsonBody: { user_id: 42 } }); ``` **Python** ```python pq.upsert_queue("user/instagram", target=Target(base_url="https://api.example.com")) pq.create_task("user/instagram", path="/sync", json_body={"user_id": 42}) ``` **Go** ```go _, err := pq.UpsertQueue(ctx, "user/instagram", pushq.QueueConfig{ Target: &pushq.Target{BaseURL: "https://api.example.com"}, }) _, err = pq.CreateTask(ctx, "user/instagram", pushq.TaskCreate{ Path: "/sync", JSONBody: map[string]any{"user_id": 42}, }) ``` **Java** ```java pq.upsertQueue("user/instagram", QueueConfig.builder() .target(Target.builder().baseUrl("https://api.example.com").build()) .build()); pq.createTask("user/instagram", TaskCreate.builder() .path("/sync") .jsonBody(Map.of("user_id", 42)) .build()); ``` **.NET** ```csharp await pq.UpsertQueueAsync("user/instagram", new QueueConfig { Target = new Target { BaseUrl = "https://api.example.com" }, }); await pq.CreateTaskAsync("user/instagram", new TaskCreate { Path = "/sync", JsonBody = new { user_id = 42 } }); ``` **curl** ```bash curl -X PUT https://api.pushqueue.dev/v1/queues/user%2Finstagram \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{"target":{"base_url":"https://api.example.com"}}' curl -X POST https://api.pushqueue.dev/v1/queues/user%2Finstagram/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{"path":"/sync","json_body":{"user_id":42}}' ``` List one folder with `name_prefix=user/` on [list queues](#list-queues). For a full walkthrough, see [per-tenant queues](https://pushqueue.dev/docs/patterns/per-tenant-queues/). ## The queue object Every endpoint on this page except delete and stats returns a queue object. ```json { "name": "emails", "state": "running", "rate_limits": { "max_dispatches_per_second": 50, "max_burst_size": 50, "max_concurrent_dispatches": 20 }, "retry": { "max_attempts": 10, "max_retry_duration_seconds": 3600, "min_backoff_seconds": 1, "max_backoff_seconds": 300, "max_doublings": 5 }, "target": { "base_url": "https://app.example.com", "method": "POST", "headers": { "X-Source": "pushq" }, "has_signing_secret": true }, "dead_letter_queue": "emails-dead", "purged_at": "2026-11-27T09:00:00Z", "created_at": "2026-11-20T14:02:11.512Z", "updated_at": "2026-11-28T10:15:00.12Z" } ``` | Field | Type | Description | |---|---|---| | `name` | string | The queue name. | | `state` | string | `running` (dispatching), `paused` (accepting tasks, not dispatching) or `disabled` (rejects new tasks and force-runs). | | `rate_limits.max_dispatches_per_second` | number | Maximum rate at which tasks are started. | | `rate_limits.max_burst_size` | integer | Effective token-bucket size. If you configured `0` (auto), this is the resolved value: `ceil(max_dispatches_per_second)` clamped to 1–500. | | `rate_limits.max_concurrent_dispatches` | integer | Maximum requests in flight at once for this queue. | | `retry.max_attempts` | integer | Total attempts including the first. `-1` means unlimited. | | `retry.max_retry_duration_seconds` | number | Time limit for retrying, measured from the first attempt. `0` means unlimited. | | `retry.min_backoff_seconds` | number | Delay before the first retry. | | `retry.max_backoff_seconds` | number | Upper bound on any retry delay. | | `retry.max_doublings` | integer | How many times the backoff doubles before it grows linearly. | | `target.base_url` | string | Base URL that relative task `path`s are resolved against. Omitted when not set. | | `target.method` | string | HTTP method that overrides every task's method at dispatch. Omitted when not set. | | `target.headers` | object | Headers set on every dispatch; they win over task headers with the same name. Omitted when empty. | | `target.has_signing_secret` | boolean | Whether deliveries are signed. The secret itself is never returned. | | `dead_letter_queue` | string | Queue that receives a copy of each permanently failed task. Omitted when not set. | | `purged_at` | string (RFC 3339) | Time of the last purge. Omitted if the queue was never purged. | | `created_at` | string (RFC 3339) | When the queue was created. | | `updated_at` | string (RFC 3339) | When its configuration or state last changed. | For how these settings behave, see [how queues work](https://pushqueue.dev/docs/concepts/queues/), [rate limiting with queues](https://pushqueue.dev/docs/guides/rate-limits/), [retry backoff and max attempts](https://pushqueue.dev/docs/concepts/retries/) and [dead-letter queues](https://pushqueue.dev/docs/concepts/dead-letter-queues/). ## Queue configuration fields (rate limits, retry, target) The create, upsert and patch endpoints accept the same configuration fields. Ranges are enforced on the final configuration; an out-of-range value returns `400 invalid_argument` naming the field. | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `rate_limits.max_dispatches_per_second` | number | no | `500` | Must be greater than 0 and at most 10000. | | `rate_limits.max_burst_size` | integer | no | `0` (auto) | 0–10000. `0` derives the burst from the rate: `ceil(rate)` clamped to 1–500. | | `rate_limits.max_concurrent_dispatches` | integer | no | `1000` | 1–10000. | | `retry.max_attempts` | integer | no | `100` | `-1` (unlimited) or at least 1. Includes the first attempt. | | `retry.max_retry_duration_seconds` | number | no | `0` (unlimited) | At least 0. Measured from the first attempt. | | `retry.min_backoff_seconds` | number | no | `0.1` | At least 0. | | `retry.max_backoff_seconds` | number | no | `3600` | Must be at least `min_backoff_seconds`. | | `retry.max_doublings` | integer | no | `16` | 0–31. | | `target.base_url` | string | no | none | Absolute `http` or `https` URL. Lets tasks use a relative `path` instead of a full `url`. | | `target.method` | string | no | none | One of `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS` (case-insensitive; stored uppercase). Overrides each task's method; with `GET`, `HEAD`, `DELETE` or `OPTIONS` the task body is not sent. | | `target.headers` | object (string → string) | no | none | Headers added to every dispatch, overriding task headers of the same name. Names and values must be valid HTTP; `Host`, `Content-Length`, `Transfer-Encoding`, `Connection`, `Keep-Alive`, `Upgrade`, `TE` and `Trailer` are reserved. Total size of names and values at most 16 KiB. | | `target.signing_secret` | string | no | none | Secret used to sign deliveries with [Standard Webhooks](https://www.standardwebhooks.com/) headers (`webhook-id`, `webhook-timestamp`, `webhook-signature`). A `whsec_`-prefixed secret is base64-decoded; any other string is used as raw bytes. Write-only: responses show `has_signing_secret` instead. `""` removes it. | | `dead_letter_queue` | string | no | none | Name of another queue that receives a copy of each task that fails permanently. Must follow the queue name rules and cannot be the queue itself. It does not have to exist when you set it, but it must exist when a task fails, or the copy is dropped. `""` removes it. | ## Create a queue `POST /v1/queues` Creates a new queue and fails if the name is already taken. Use this when creating a queue should be a one-time, deliberate step (for example in a provisioning script that must notice name collisions). If you want "create it if missing, otherwise make it match this config", use [create or update a queue (upsert)](#create-or-update-a-queue-upsert) instead. A new queue always starts in the `running` state. **Who can call it:** writer or admin API key; dashboard member or admin. **Request body** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `name` | string | yes | — | The queue name; see [Queue name rules](#queue-names-and-folders). | | `rate_limits` | object | no | defaults below | Rate limits; see [Queue configuration fields](#queue-configuration-fields-rate-limits-retry-target). | | `rate_limits.max_dispatches_per_second` | number | no | `500` | (0, 10000]. | | `rate_limits.max_burst_size` | integer | no | `0` (auto) | [0, 10000]. | | `rate_limits.max_concurrent_dispatches` | integer | no | `1000` | [1, 10000]. | | `retry` | object | no | defaults below | Retry policy. | | `retry.max_attempts` | integer | no | `100` | `-1` or ≥ 1. | | `retry.max_retry_duration_seconds` | number | no | `0` | ≥ 0; `0` = unlimited. | | `retry.min_backoff_seconds` | number | no | `0.1` | ≥ 0. | | `retry.max_backoff_seconds` | number | no | `3600` | ≥ `min_backoff_seconds`. | | `retry.max_doublings` | integer | no | `16` | [0, 31]. | | `target` | object | no | none | Delivery target settings. | | `target.base_url` | string | no | none | Absolute http(s) URL for relative task paths. | | `target.method` | string | no | none | Method override. | | `target.headers` | object | no | none | Header overrides. | | `target.signing_secret` | string | no | none | Signing secret (write-only). | | `dead_letter_queue` | string | no | none | Dead-letter queue name. | The request body may be at most 256 KiB. **Example** **TypeScript** ```ts const queue = await pq.createQueue("emails", { rateLimits: { maxDispatchesPerSecond: 50, maxConcurrentDispatches: 20 }, retry: { maxAttempts: 10, minBackoffSeconds: 1, maxBackoffSeconds: 300 }, target: { baseUrl: "https://app.example.com", headers: { "X-Source": "pushq" }, signingSecret: process.env.PUSHQ_SIGNING_SECRET, }, deadLetterQueue: "emails-dead", }); ``` **Python** ```python queue = pq.create_queue( "emails", rate_limits=RateLimits(max_dispatches_per_second=50, max_concurrent_dispatches=20), retry=Retry(max_attempts=10, min_backoff_seconds=1, max_backoff_seconds=300), target=Target( base_url="https://app.example.com", headers={"X-Source": "pushq"}, signing_secret=os.environ["PUSHQ_SIGNING_SECRET"], ), dead_letter_queue="emails-dead", ) ``` **Go** ```go queue, err := pq.CreateQueue(ctx, "emails", pushq.QueueConfig{ RateLimits: &pushq.RateLimits{ MaxDispatchesPerSecond: pushq.Float64(50), MaxConcurrentDispatches: pushq.Int(20), }, Retry: &pushq.Retry{ MaxAttempts: pushq.Int(10), MinBackoffSeconds: pushq.Float64(1), MaxBackoffSeconds: pushq.Float64(300), }, Target: &pushq.Target{ BaseURL: "https://app.example.com", Headers: map[string]string{"X-Source": "pushq"}, SigningSecret: os.Getenv("PUSHQ_SIGNING_SECRET"), }, DeadLetterQueue: "emails-dead", }) ``` **Java** ```java Queue queue = pq.createQueue("emails", QueueConfig.builder() .rateLimits(RateLimits.builder().maxDispatchesPerSecond(50).maxConcurrentDispatches(20).build()) .retry(RetryConfig.builder().maxAttempts(10).minBackoffSeconds(1).maxBackoffSeconds(300).build()) .target(Target.builder() .baseUrl("https://app.example.com") .header("X-Source", "pushq") .signingSecret(System.getenv("PUSHQ_SIGNING_SECRET")) .build()) .deadLetterQueue("emails-dead") .build()); ``` **.NET** ```csharp var queue = await pq.CreateQueueAsync("emails", new QueueConfig { RateLimits = new RateLimits { MaxDispatchesPerSecond = 50, MaxConcurrentDispatches = 20 }, Retry = new RetryConfig { MaxAttempts = 10, MinBackoffSeconds = 1, MaxBackoffSeconds = 300 }, Target = new Target { BaseUrl = "https://app.example.com", Headers = new Dictionary { ["X-Source"] = "pushq" }, SigningSecret = Environment.GetEnvironmentVariable("PUSHQ_SIGNING_SECRET"), }, DeadLetterQueue = "emails-dead", }); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "emails", "rate_limits": { "max_dispatches_per_second": 50, "max_concurrent_dispatches": 20 }, "retry": { "max_attempts": 10, "min_backoff_seconds": 1, "max_backoff_seconds": 300 }, "target": { "base_url": "https://app.example.com", "headers": { "X-Source": "pushq" }, "signing_secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw" }, "dead_letter_queue": "emails-dead" }' ``` In Python, `create_queue` exists only on the synchronous `Pushq` client, not on `AsyncPushq`. To handle a taken name, catch the SDK's error and check for the `already_exists` code (see [error codes](https://pushqueue.dev/docs/reference/errors/)). **Response** `201 Created` with the [queue object](#the-queue-object): ```json { "name": "emails", "state": "running", "rate_limits": { "max_dispatches_per_second": 50, "max_burst_size": 50, "max_concurrent_dispatches": 20 }, "retry": { "max_attempts": 10, "max_retry_duration_seconds": 0, "min_backoff_seconds": 1, "max_backoff_seconds": 300, "max_doublings": 16 }, "target": { "base_url": "https://app.example.com", "headers": { "X-Source": "pushq" }, "has_signing_secret": true }, "dead_letter_queue": "emails-dead", "created_at": "2026-11-28T10:15:00.12Z", "updated_at": "2026-11-28T10:15:00.12Z" } ``` Response fields are described in [The queue object](#the-queue-object). **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | Invalid JSON, invalid name, or a configuration value out of range. | | 401 | `unauthenticated` | No valid API key or session. | | 403 | `permission_denied` | The key or role can't write (for example a viewer). | | 409 | `already_exists` | A queue with this name exists. | | 413 | `payload_too_large` | Body over 256 KiB. | See [API error codes](https://pushqueue.dev/docs/reference/errors/) for the error format. ## Create or update a queue (upsert) `PUT /v1/queues/{queue}` Makes the queue's configuration exactly match the body, creating the queue if it doesn't exist. It is idempotent, so you can call it on every deploy or even before every enqueue. PUT never changes the queue's `state`, so it can't accidentally resume a paused queue. Use this when your code owns the queue's configuration and you want "declare it and move on" semantics. Every SDK's upsert method (`upsertQueue`, `upsert_queue`, `UpsertQueue`, `UpsertQueueAsync`) calls this endpoint. :::caution[PUT replaces the whole configuration] Fields you leave out are reset to their defaults, not kept: omitting `target` clears `target.base_url`, `target.method` and `target.headers`, and omitting `dead_letter_queue` removes the dead-letter queue. The one exception is `target.signing_secret`: omit it to keep the stored secret, send `""` to remove it. To change a single setting, use [update queue settings with PATCH](#update-queue-settings-patch). ::: The response carries an `X-Pushq-Result` header: `created`, `updated` or `unchanged`. **Who can call it:** writer or admin API key; dashboard member or admin. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `queue` | string | yes | — | Queue name, URL-encoded as one segment (`user%2Finstagram`). | **Request body** Same fields as [Create a queue](#create-a-queue) without `name` (the name comes from the path). Every field is optional; an empty body `{}` sets every setting to its default. | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `rate_limits.max_dispatches_per_second` | number | no | `500` | (0, 10000]. | | `rate_limits.max_burst_size` | integer | no | `0` (auto) | [0, 10000]. | | `rate_limits.max_concurrent_dispatches` | integer | no | `1000` | [1, 10000]. | | `retry.max_attempts` | integer | no | `100` | `-1` or ≥ 1. | | `retry.max_retry_duration_seconds` | number | no | `0` | ≥ 0; `0` = unlimited. | | `retry.min_backoff_seconds` | number | no | `0.1` | ≥ 0. | | `retry.max_backoff_seconds` | number | no | `3600` | ≥ `min_backoff_seconds`. | | `retry.max_doublings` | integer | no | `16` | [0, 31]. | | `target.base_url` | string | no | none | Absolute http(s) URL. | | `target.method` | string | no | none | Method override. | | `target.headers` | object | no | none | Header overrides; replaces any existing set. | | `target.signing_secret` | string | no | keep existing | Omit to keep the stored secret; `""` to remove it; any other value replaces it. | | `dead_letter_queue` | string | no | none | Dead-letter queue name. | **Example** **TypeScript** ```ts const queue = await pq.upsertQueue("user/instagram", { rateLimits: { maxDispatchesPerSecond: 5, maxConcurrentDispatches: 2 }, retry: { maxAttempts: 5 }, target: { baseUrl: "https://worker.example.com" }, }); ``` **Python** ```python queue = pq.upsert_queue( "user/instagram", rate_limits=RateLimits(max_dispatches_per_second=5, max_concurrent_dispatches=2), retry=Retry(max_attempts=5), target=Target(base_url="https://worker.example.com"), ) ``` **Go** ```go queue, err := pq.UpsertQueue(ctx, "user/instagram", pushq.QueueConfig{ RateLimits: &pushq.RateLimits{ MaxDispatchesPerSecond: pushq.Float64(5), MaxConcurrentDispatches: pushq.Int(2), }, Retry: &pushq.Retry{MaxAttempts: pushq.Int(5)}, Target: &pushq.Target{BaseURL: "https://worker.example.com"}, }) ``` **Java** ```java Queue queue = pq.upsertQueue("user/instagram", QueueConfig.builder() .rateLimits(RateLimits.builder().maxDispatchesPerSecond(5).maxConcurrentDispatches(2).build()) .retry(RetryConfig.builder().maxAttempts(5).build()) .target(Target.builder().baseUrl("https://worker.example.com").build()) .build()); ``` **.NET** ```csharp var queue = await pq.UpsertQueueAsync("user/instagram", new QueueConfig { RateLimits = new RateLimits { MaxDispatchesPerSecond = 5, MaxConcurrentDispatches = 2 }, Retry = new RetryConfig { MaxAttempts = 5 }, Target = new Target { BaseUrl = "https://worker.example.com" }, }); ``` **curl** ```bash curl -X PUT https://api.pushqueue.dev/v1/queues/user%2Finstagram \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "rate_limits": { "max_dispatches_per_second": 5, "max_concurrent_dispatches": 2 }, "retry": { "max_attempts": 5 }, "target": { "base_url": "https://worker.example.com" } }' ``` The SDKs don't expose the `X-Pushq-Result` header; use `curl -i` or your own HTTP client if you need it. In Go, an empty `Target.SigningSecret` keeps the stored secret; set `Target.ClearSigningSecret: true` to remove it. **Response** `201 Created` when the queue was created, `200 OK` when it existed (whether or not anything changed). The body is the [queue object](#the-queue-object): ```json { "name": "user/instagram", "state": "running", "rate_limits": { "max_dispatches_per_second": 5, "max_burst_size": 5, "max_concurrent_dispatches": 2 }, "retry": { "max_attempts": 5, "max_retry_duration_seconds": 0, "min_backoff_seconds": 0.1, "max_backoff_seconds": 3600, "max_doublings": 16 }, "target": { "base_url": "https://worker.example.com", "has_signing_secret": false }, "created_at": "2026-11-28T10:15:00.12Z", "updated_at": "2026-11-28T10:15:00.12Z" } ``` | Header | Description | |---|---| | `X-Pushq-Result` | `created`, `updated` or `unchanged`. | Response fields are described in [The queue object](#the-queue-object). **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | Invalid JSON, invalid queue name, or a value out of range. | | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | The key or role can't write. | | 413 | `payload_too_large` | Body over 256 KiB. | ## Get a queue `GET /v1/queues/{queue}` Returns one queue's current configuration and state. Use it to check how a queue is configured or whether it is paused. Writer keys can read any queue they know by name, even though they can't list queues. **Who can call it:** writer or admin API key; dashboard viewer, member or admin. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `queue` | string | yes | — | Queue name, URL-encoded as one segment (`user%2Finstagram`). | **Example** **TypeScript** ```ts const queue = await pq.getQueue("emails"); ``` **Python** ```python queue = pq.get_queue("emails") ``` **Go** ```go queue, err := pq.GetQueue(ctx, "emails") ``` **Java** ```java Queue queue = pq.getQueue("emails"); ``` **.NET** ```csharp var queue = await pq.GetQueueAsync("emails"); ``` **curl** ```bash curl https://api.pushqueue.dev/v1/queues/emails \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `200 OK` with the [queue object](#the-queue-object): ```json { "name": "emails", "state": "paused", "rate_limits": { "max_dispatches_per_second": 50, "max_burst_size": 50, "max_concurrent_dispatches": 20 }, "retry": { "max_attempts": 10, "max_retry_duration_seconds": 0, "min_backoff_seconds": 1, "max_backoff_seconds": 300, "max_doublings": 16 }, "target": { "base_url": "https://app.example.com", "headers": { "X-Source": "pushq" }, "has_signing_secret": true }, "dead_letter_queue": "emails-dead", "created_at": "2026-11-20T14:02:11.512Z", "updated_at": "2026-11-28T09:40:03.004Z" } ``` Response fields are described in [The queue object](#the-queue-object). **Errors** | Status | Code | When | |---|---|---| | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | The caller has no read permission (for example a SaaS user with no team selected). | | 404 | `not_found` | No queue with this name. | ## List queues `GET /v1/queues` Lists queues in name order, one page at a time. Use `name_prefix` to list one folder (`user/`). Use this for dashboards, audits or cleanup scripts. Writer keys can't list queues; use an admin key. **Who can call it:** admin API key; dashboard viewer, member or admin. **Query parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `name_prefix` | string | no | none | Only queues whose name starts with this. `user/` lists the `user` folder. | | `page_size` | integer | no | `100` | Queues per page. Values above 1000 are capped at 1000; 0 or less means 100. | | `page_token` | string | no | none | `next_page_token` from the previous response. | **Example** **TypeScript** ```ts const page = await pq.listQueues({ namePrefix: "user/", pageSize: 50 }); // page.items, page.nextPageToken ``` **Python** ```python page = pq.list_queues(name_prefix="user/", page_size=50) # page.items, page.next_page_token ``` **Go** ```go queues, next, err := pq.ListQueues(ctx, pushq.ListQueuesParams{NamePrefix: "user/", PageSize: 50}) ``` **Java** ```java QueuePage page = pq.listQueues(ListQueuesParams.builder().namePrefix("user/").pageSize(50).build()); // page.getQueues(), page.getNextPageToken() ``` **.NET** ```csharp var page = await pq.ListQueuesAsync(new ListQueuesOptions { NamePrefix = "user/", PageSize = 50 }); // page.Items, page.NextPageToken ``` **curl** ```bash curl "https://api.pushqueue.dev/v1/queues?name_prefix=user/&page_size=50" \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `200 OK`: ```json { "queues": [ { "name": "user/instagram", "state": "running", "rate_limits": { "max_dispatches_per_second": 5, "max_burst_size": 5, "max_concurrent_dispatches": 2 }, "retry": { "max_attempts": 5, "max_retry_duration_seconds": 0, "min_backoff_seconds": 0.1, "max_backoff_seconds": 3600, "max_doublings": 16 }, "target": { "base_url": "https://worker.example.com", "has_signing_secret": false }, "created_at": "2026-11-28T10:15:00.12Z", "updated_at": "2026-11-28T10:15:00.12Z" } ], "next_page_token": "dXNlci9pbnN0YWdyYW0" } ``` The SDKs return a page object instead of the raw JSON: `items` and `nextPageToken` in TypeScript, `items` and `next_page_token` in Python, `getQueues()` and `getNextPageToken()` in Java, `Items` and `NextPageToken` in .NET; Go returns the slice and the next token as separate values. In Python, `list_queues` exists only on the synchronous `Pushq` client. | Field | Type | Description | |---|---|---| | `queues` | array of [queue objects](#the-queue-object) | This page of queues, ordered by name. Empty array when nothing matches. | | `next_page_token` | string | Pass as `page_token` to get the next page. Omitted on the last page. | **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | `page_size` is not an integer. | | 400 | `failed_precondition` | `page_token` is malformed. | | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | Writer API key, or a caller without list permission. | ## Update queue settings (patch) `PATCH /v1/queues/{queue}` Changes only the fields you send and leaves everything else as it is. Use it for targeted changes such as lowering the rate during an incident, or setting `state` to `disabled` (which pause/resume can't do). The merged result is validated before it is saved, so a patch can't leave the queue with an invalid configuration. **Who can call it:** writer or admin API key; dashboard member or admin. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `queue` | string | yes | — | Queue name, URL-encoded as one segment (`user%2Finstagram`). | **Request body** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `state` | string | no | unchanged | `running`, `paused` or `disabled`. A disabled queue rejects new tasks and force-runs. | | `rate_limits.max_dispatches_per_second` | number | no | unchanged | (0, 10000]. | | `rate_limits.max_burst_size` | integer | no | unchanged | [0, 10000]; `0` = auto. | | `rate_limits.max_concurrent_dispatches` | integer | no | unchanged | [1, 10000]. | | `retry.max_attempts` | integer | no | unchanged | `-1` or ≥ 1. | | `retry.max_retry_duration_seconds` | number | no | unchanged | ≥ 0; `0` = unlimited. | | `retry.min_backoff_seconds` | number | no | unchanged | ≥ 0. | | `retry.max_backoff_seconds` | number | no | unchanged | ≥ `min_backoff_seconds` (checked against the merged config). | | `retry.max_doublings` | integer | no | unchanged | [0, 31]. | | `target.base_url` | string | no | unchanged | Absolute http(s) URL; `""` removes it. | | `target.method` | string | no | unchanged | Method override; `""` removes it. | | `target.headers` | object | no | unchanged | Replaces the whole header-override map; `{}` removes all overrides. | | `target.signing_secret` | string | no | unchanged | New secret; `""` removes it. | | `dead_letter_queue` | string | no | unchanged | Dead-letter queue name; `""` removes it. | **Example** **TypeScript** ```ts const queue = await pq.patchQueue("emails", { rateLimits: { maxDispatchesPerSecond: 10 }, retry: { maxAttempts: 20 }, }); ``` **Python** ```python queue = pq.patch_queue( "emails", rate_limits=RateLimits(max_dispatches_per_second=10), retry=Retry(max_attempts=20), ) ``` **Go** ```go // The last argument is the new state ("" leaves it unchanged). queue, err := pq.PatchQueue(ctx, "emails", pushq.QueueConfig{ RateLimits: &pushq.RateLimits{MaxDispatchesPerSecond: pushq.Float64(10)}, Retry: &pushq.Retry{MaxAttempts: pushq.Int(20)}, }, "") ``` **Java** ```java Queue queue = pq.patchQueue("emails", QueuePatch.builder() .rateLimits(RateLimits.builder().maxDispatchesPerSecond(10).build()) .retry(RetryConfig.builder().maxAttempts(20).build()) .build()); ``` **.NET** ```csharp var queue = await pq.PatchQueueAsync("emails", new QueuePatch { RateLimits = new RateLimits { MaxDispatchesPerSecond = 10 }, Retry = new RetryConfig { MaxAttempts = 20 }, }); ``` **curl** ```bash curl -X PATCH https://api.pushqueue.dev/v1/queues/emails \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "rate_limits": { "max_dispatches_per_second": 10 }, "retry": { "max_attempts": 20 } }' ``` In Python, `patch_queue` exists only on the synchronous `Pushq` client. In Go, the fourth argument of `PatchQueue` sets `state` (`"running"`, `"paused"`, `"disabled"`, or `""` to leave it unchanged). :::caution[Clearing fields from the Go SDK] The Go SDK never sends empty strings or empty maps, so `PatchQueue` can't clear `target.base_url`, `target.method`, `target.headers` or `dead_letter_queue`. Use `UpsertQueue` with the full configuration, or send the PATCH over HTTP with `""` / `{}`. `Target.ClearSigningSecret: true` does clear the signing secret. ::: **Response** `200 OK` with the updated [queue object](#the-queue-object): ```json { "name": "emails", "state": "running", "rate_limits": { "max_dispatches_per_second": 10, "max_burst_size": 10, "max_concurrent_dispatches": 20 }, "retry": { "max_attempts": 20, "max_retry_duration_seconds": 0, "min_backoff_seconds": 1, "max_backoff_seconds": 300, "max_doublings": 16 }, "target": { "base_url": "https://app.example.com", "headers": { "X-Source": "pushq" }, "has_signing_secret": true }, "dead_letter_queue": "emails-dead", "created_at": "2026-11-20T14:02:11.512Z", "updated_at": "2026-11-28T10:20:41.88Z" } ``` Response fields are described in [The queue object](#the-queue-object). **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | Invalid JSON, unknown `state`, or the merged configuration is out of range. | | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | The key or role can't write. | | 404 | `not_found` | No queue with this name. | | 413 | `payload_too_large` | Body over 256 KiB. | ## Delete a queue `DELETE /v1/queues/{queue}` Deletes the queue and every task in it, immediately and permanently. Use it to remove a queue you no longer need; if you only want to drop its backlog and keep the configuration, [purge](#purge-a-queue) it instead. **Who can call it:** admin API key; dashboard member or admin. Writer keys can't delete queues. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `queue` | string | yes | — | Queue name, URL-encoded as one segment (`user%2Finstagram`). | **Example** **TypeScript** ```ts await pq.deleteQueue("user/instagram"); ``` **Python** ```python pq.delete_queue("user/instagram") ``` **Go** ```go err := pq.DeleteQueue(ctx, "user/instagram") ``` **Java** ```java pq.deleteQueue("user/instagram"); ``` **.NET** ```csharp await pq.DeleteQueueAsync("user/instagram"); ``` **curl** ```bash curl -X DELETE https://api.pushqueue.dev/v1/queues/user%2Finstagram \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `204 No Content` with an empty body. **Errors** | Status | Code | When | |---|---|---| | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | Writer key or viewer role. | | 404 | `not_found` | No queue with this name. | ## Pause a queue `POST /v1/queues/{queue}:pause` Stops dispatching. The queue keeps accepting new tasks, but nothing is delivered until you resume it. Use it when the receiving service is down or being deployed and you want work to pile up instead of failing and burning retries. Pausing an already-paused queue is a no-op. You can still [force-run](https://pushqueue.dev/docs/reference/rest/tasks/#run-a-task-now) individual tasks while paused. **Who can call it:** writer or admin API key; dashboard member or admin. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `queue` | string | yes | — | Queue name, URL-encoded as one segment (`user%2Finstagram`). | No request body. **Example** **TypeScript** ```ts const queue = await pq.pauseQueue("emails"); ``` **Python** ```python queue = pq.pause_queue("emails") ``` **Go** ```go queue, err := pq.PauseQueue(ctx, "emails") ``` **Java** ```java Queue queue = pq.pauseQueue("emails"); ``` **.NET** ```csharp var queue = await pq.PauseQueueAsync("emails"); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/emails:pause \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `200 OK` with the [queue object](#the-queue-object), now with `"state": "paused"`: ```json { "name": "emails", "state": "paused", "rate_limits": { "max_dispatches_per_second": 50, "max_burst_size": 50, "max_concurrent_dispatches": 20 }, "retry": { "max_attempts": 10, "max_retry_duration_seconds": 0, "min_backoff_seconds": 1, "max_backoff_seconds": 300, "max_doublings": 16 }, "target": { "base_url": "https://app.example.com", "has_signing_secret": true }, "created_at": "2026-11-20T14:02:11.512Z", "updated_at": "2026-11-28T10:22:00Z" } ``` Response fields are described in [The queue object](#the-queue-object). **Errors** | Status | Code | When | |---|---|---| | 400 | `failed_precondition` | The queue is `disabled`; a disabled queue can't be paused. | | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | The key or role can't write. | | 404 | `not_found` | No queue with this name. | ## Resume a queue `POST /v1/queues/{queue}:resume` Sets the queue back to `running` so due tasks start dispatching again. This also re-enables a `disabled` queue. Resuming a running queue is a no-op. **Who can call it:** writer or admin API key; dashboard member or admin. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `queue` | string | yes | — | Queue name, URL-encoded as one segment (`user%2Finstagram`). | No request body. **Example** **TypeScript** ```ts const queue = await pq.resumeQueue("emails"); ``` **Python** ```python queue = pq.resume_queue("emails") ``` **Go** ```go queue, err := pq.ResumeQueue(ctx, "emails") ``` **Java** ```java Queue queue = pq.resumeQueue("emails"); ``` **.NET** ```csharp var queue = await pq.ResumeQueueAsync("emails"); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/emails:resume \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `200 OK` with the [queue object](#the-queue-object), now with `"state": "running"`: ```json { "name": "emails", "state": "running", "rate_limits": { "max_dispatches_per_second": 50, "max_burst_size": 50, "max_concurrent_dispatches": 20 }, "retry": { "max_attempts": 10, "max_retry_duration_seconds": 0, "min_backoff_seconds": 1, "max_backoff_seconds": 300, "max_doublings": 16 }, "target": { "base_url": "https://app.example.com", "has_signing_secret": true }, "created_at": "2026-11-20T14:02:11.512Z", "updated_at": "2026-11-28T10:30:12.448Z" } ``` Response fields are described in [The queue object](#the-queue-object). **Errors** | Status | Code | When | |---|---|---| | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | The key or role can't write. | | 404 | `not_found` | No queue with this name. | ## Purge a queue `POST /v1/queues/{queue}:purge` Deletes every task created up to now, in any state, and keeps the queue and its configuration. Purged tasks disappear from the API at once and are removed from storage in the background; results of attempts that were in flight are discarded, and the purged task IDs can be reused right away. Tasks created after the purge are not affected. Use it to throw away a backlog you no longer want delivered, for example after a bad deploy enqueued garbage. **Who can call it:** writer or admin API key; dashboard member or admin. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `queue` | string | yes | — | Queue name, URL-encoded as one segment (`user%2Finstagram`). | No request body. **Example** **TypeScript** ```ts const queue = await pq.purgeQueue("emails"); ``` **Python** ```python queue = pq.purge_queue("emails") ``` **Go** ```go queue, err := pq.PurgeQueue(ctx, "emails") ``` **Java** ```java Queue queue = pq.purgeQueue("emails"); ``` **.NET** ```csharp var queue = await pq.PurgeQueueAsync("emails"); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/emails:purge \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `202 Accepted` with the [queue object](#the-queue-object); `purged_at` is the purge watermark: ```json { "name": "emails", "state": "running", "rate_limits": { "max_dispatches_per_second": 50, "max_burst_size": 50, "max_concurrent_dispatches": 20 }, "retry": { "max_attempts": 10, "max_retry_duration_seconds": 0, "min_backoff_seconds": 1, "max_backoff_seconds": 300, "max_doublings": 16 }, "target": { "base_url": "https://app.example.com", "has_signing_secret": true }, "purged_at": "2026-11-28T10:31:00Z", "created_at": "2026-11-20T14:02:11.512Z", "updated_at": "2026-11-28T10:31:00Z" } ``` Response fields are described in [The queue object](#the-queue-object). **Errors** | Status | Code | When | |---|---|---| | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | The key or role can't write. | | 404 | `not_found` | No queue with this name. | ## Get queue stats `GET /v1/queues/{queue}/stats` Returns live counts for the queue: how many tasks are due, running, scheduled for later, finished, and how many attempts ran and failed in the last minute and hour. Use it for monitoring and alerting (for example, alert when `oldest_due_age_seconds` grows, which means the queue is falling behind). Filter with `id_prefix` to see stats for one group of tasks if you give related tasks a common ID prefix. Counts cover tasks still stored on the server; finished tasks are removed after their retention period (on self-hosted servers, 24 hours for succeeded and 7 days for failed by default), and purged tasks are excluded. **Who can call it:** writer or admin API key; dashboard viewer, member or admin. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `queue` | string | yes | — | Queue name, URL-encoded as one segment (`user%2Finstagram`). | **Query parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `id_prefix` | string | no | none | Only count tasks whose ID starts with this. | **Example** **TypeScript** ```ts const stats = await pq.queueStats("emails", { idPrefix: "welcome-" }); ``` **Python** ```python stats = pq.queue_stats("emails", id_prefix="welcome-") ``` **Go** ```go stats, err := pq.QueueStats(ctx, "emails", "welcome-") ``` **Java** ```java QueueStats stats = pq.queueStats("emails", "welcome-"); ``` **.NET** ```csharp var stats = await pq.GetQueueStatsAsync("emails", idPrefix: "welcome-"); ``` **curl** ```bash curl "https://api.pushqueue.dev/v1/queues/emails/stats?id_prefix=welcome-" \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `200 OK`: ```json { "state": "running", "pending": 42, "running": 7, "succeeded": 15320, "failed": 12, "scheduled_future": 310, "oldest_due_at": "2026-11-28T10:29:58.12Z", "oldest_due_age_seconds": 2.88, "dispatched_last_1m": 410, "errors_last_1m": 3, "dispatched_last_1h": 21877, "errors_last_1h": 96, "last_purge": "2026-11-27T09:00:00Z" } ``` | Field | Type | Description | |---|---|---| | `state` | string | The queue's state: `running`, `paused` or `disabled`. | | `pending` | integer | Pending tasks that are due now or overdue. | | `running` | integer | Tasks currently being delivered. | | `succeeded` | integer | Succeeded tasks still retained. | | `failed` | integer | Permanently failed tasks still retained. | | `scheduled_future` | integer | Pending tasks scheduled for a later time. | | `oldest_due_at` | string (RFC 3339) | Schedule time of the oldest due task. Omitted when nothing is due. | | `oldest_due_age_seconds` | number | How long the oldest due task has been waiting. Omitted when nothing is due. | | `dispatched_last_1m` | integer | Delivery attempts started in the last minute. | | `errors_last_1m` | integer | Attempts in the last minute that did not get a 2xx response. | | `dispatched_last_1h` | integer | Delivery attempts started in the last hour. | | `errors_last_1h` | integer | Attempts in the last hour that did not get a 2xx response. | | `last_purge` | string (RFC 3339) | Time of the last purge. Omitted if never purged. | **Errors** | Status | Code | When | |---|---|---| | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | The caller has no read permission. | | 404 | `not_found` | No queue with this name. | ## Read more - [How queues work](https://pushqueue.dev/docs/concepts/queues/): states, folders and what each setting does. - [Rate limiting with queues](https://pushqueue.dev/docs/guides/rate-limits/): choose `max_dispatches_per_second` and `max_concurrent_dispatches`. - [Per-tenant queues](https://pushqueue.dev/docs/patterns/per-tenant-queues/): one queue per customer with folder names. - [Tasks API reference](https://pushqueue.dev/docs/reference/rest/tasks/): enqueue, inspect, run and delete tasks. - [API error codes](https://pushqueue.dev/docs/reference/errors/): the problem+json format and every `code`. --- # REST API overview > How the pushq REST API works: base URL, API key auth, URL-encoded queue names, pagination, errors and idempotency, plus every endpoint. Source: https://pushqueue.dev/docs/reference/api/ Everything pushq does is available over a JSON HTTP API. The SDKs and the dashboard use the same API. This page covers the conventions every endpoint shares and lists all endpoints; each group links to its detailed reference. Use the API directly when there's no SDK for your language, from shell scripts, or to debug what an SDK sends. - Interactive reference (Swagger UI): https://api.pushqueue.dev/docs - OpenAPI document: https://api.pushqueue.dev/openapi.json A self-hosted server serves the same two pages at `/docs` and `/openapi.json`, generated from its own routes. To get the document without running a server, use `pushq openapi > openapi.json`. ## API base URL | Server | Base URL | |---|---| | Hosted | `https://api.pushqueue.dev` | | Self-hosted | Your server, e.g. `http://localhost:8080` or `https://pushq.example.com` | API endpoints live under `/v1`. Health, metrics and documentation endpoints (`/healthz`, `/readyz`, `/metrics`, `/docs`, `/openapi.json`) sit at the root. ## Authenticate with an API key Send an API key as a bearer token: ```bash curl https://api.pushqueue.dev/v1/queues/emails \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` Keys look like `pq_...`. Create them in the dashboard under **Settings → API keys**, or, when self-hosting, in the server config. See [API keys](https://pushqueue.dev/docs/guides/api-keys/) for roles and rotation. A missing or unknown key returns `401 unauthenticated`. A valid key whose role doesn't allow the call returns `403 permission_denied`. The dashboard authenticates with a session cookie instead. Requests that change something with the cookie must also send `X-Requested-With: pushq`, which blocks cross-site request forgery. Requests with an `Authorization` header don't need it. A `pushq dev` server, or a fresh self-hosted server before its first admin account exists, accepts requests without a key. ### Who can call what The endpoint tables use these access levels: | Access | API keys | Dashboard users | |---|---|---| | Public | No credentials needed | | | Read | `admin`, `writer` | `admin`, `member`, `viewer` | | Write | `admin`, `writer` | `admin`, `member` | | List | `admin` | `admin`, `member`, `viewer` | | Delete queue | `admin` | `admin`, `member` | | Manage | `admin` | `admin` | | Signed-in user | Not allowed (`401`) | Any role, with a session cookie | A `writer` key works with queues it knows by name: it can create, change, pause, resume and purge queues and enqueue, run and delete tasks, but it can't list all queues or delete a queue. ## Request and response format - Request and response bodies are JSON. Send `Content-Type: application/json` with a body. - Field names are `snake_case`: `rate_limits.max_dispatches_per_second`, `delay_seconds`. The SDKs use their language's casing. - Timestamps are RFC 3339 strings in UTC, e.g. `2026-12-01T17:00:00Z`. - Durations are numbers of seconds and may be fractional: `"min_backoff_seconds": 0.1`. - Operations that aren't plain CRUD use a colon suffix on the resource, Google API style: `POST /v1/queues/emails:pause`, `POST /v1/queues/emails/tasks/welcome-user-42:run`. - Deletes answer `204 No Content`. `:purge` answers `202 Accepted`. Request bodies have size limits: 256 KiB for queue bodies, 8 MiB for a batch, and for a single task twice `limits.max_body_bytes` plus 64 KiB (the body is base64-encoded inside the JSON). A larger request fails with `413 payload_too_large`. The decoded task body itself must fit in `limits.max_body_bytes` (default 1 MiB). ## URL-encode queue names Queue names can contain `/` to form folders, such as `user/instagram`. In a URL path the whole name is **one** segment, so encode the slash as `%2F`: ```bash curl -X POST https://api.pushqueue.dev/v1/queues/user%2Finstagram/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{"path": "/hooks/post"}' ``` An unencoded slash produces a different path and returns `404 not_found` with a hint to encode it. Query parameters take the name as-is: `GET /v1/queues?name_prefix=user/` lists the folder. The SDKs encode queue names for you. If you run a reverse proxy, make sure it doesn't decode `%2F`; see [reverse proxy setup](https://pushqueue.dev/docs/self-hosting/deploy/#put-pushq-behind-a-reverse-proxy). Valid queue names are 1 to 200 characters of `/`-separated segments, each matching `[a-z0-9][a-z0-9-]*`. Task IDs match `[A-Za-z0-9_-]{1,500}`. ## Paginate list results `GET /v1/queues` and `GET /v1/queues/{queue}/tasks` return one page at a time: | Query parameter | Description | |---|---| | `page_size` | Items per page. Default 100, maximum 1000 (larger values are capped). | | `page_token` | The `next_page_token` from the previous response. | The response holds the items (`queues` or `tasks`) and a `next_page_token`. When `next_page_token` is missing, you have the last page. Keep your other filters (`state`, `id_prefix`, `name_prefix`) the same while you page. A malformed token returns `400 failed_precondition`. **TypeScript** ```ts let pageToken: string | undefined; do { const page = await pq.listTasks("emails", { state: "failed", pageSize: 500, pageToken }); for (const task of page.items) console.log(task.id); pageToken = page.nextPageToken; } while (pageToken); ``` **Python** ```python page_token = None while True: page = pq.list_tasks("emails", state="failed", page_size=500, page_token=page_token) for task in page.items: print(task.id) page_token = page.next_page_token if not page_token: break ``` **Go** ```go token := "" for { tasks, next, err := pq.ListTasks(ctx, "emails", pushq.ListTasksParams{State: "failed", PageSize: 500, PageToken: token}) if err != nil { return err } for _, t := range tasks { fmt.Println(t.ID) } if next == "" { break } token = next } ``` **Java** ```java String token = null; do { TaskPage page = pq.listTasks("emails", ListTasksParams.builder() .state("failed").pageSize(500).pageToken(token).build()); for (Task task : page.getTasks()) System.out.println(task.getId()); token = page.getNextPageToken(); } while (token != null && !token.isEmpty()); ``` **.NET** ```csharp string? token = null; do { var page = await pq.ListTasksAsync("emails", new ListTasksOptions { State = TaskState.Failed, PageSize = 500, PageToken = token, }); foreach (var task in page.Items) Console.WriteLine(task.Id); token = page.NextPageToken; } while (!string.IsNullOrEmpty(token)); ``` **curl** ```bash token="" while :; do resp=$(curl -s "https://api.pushqueue.dev/v1/queues/emails/tasks?state=failed&page_size=500&page_token=$token" \ -H "Authorization: Bearer $PUSHQ_API_KEY") echo "$resp" | jq -r '.tasks[].id' token=$(echo "$resp" | jq -r '.next_page_token // empty') [ -z "$token" ] && break done ``` Tasks are listed newest first. ## Error responses Every error is an [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) problem+json body with a stable machine-readable `code`: ```json { "type": "about:blank", "title": "Not Found", "status": 404, "code": "not_found", "detail": "not found", "instance": "/v1/queues/emails" } ``` Branch on `code`, not on `detail`. See [API error codes](https://pushqueue.dev/docs/reference/errors/) for every code and how to handle it. ## Idempotency and safe retries There is no `Idempotency-Key` header. Instead: - **Queue upserts** (`PUT /v1/queues/{queue}`) are idempotent: send the same config as often as you like. The response answers `201` when it created the queue and `200` otherwise, with an `X-Pushq-Result` header of `created`, `updated` or `unchanged`. An upsert never changes whether the queue is running or paused. - **Task creation** is deduplicated by `task_id`. If you retry an enqueue after a timeout or network error with the same `task_id`, a `409 already_exists` means the first request went through. The ID stays reserved for the server's dedup window (1 hour by default) after the task finishes or is deleted. Without a `task_id` the server generates one, and a retried request can create a duplicate task. - **Batch enqueue** (`POST /v1/queues/{queue}/tasks:batch`) is not atomic. It answers `200` with one result per task, in request order; each result holds either the created `task` or an `error` with a `code` and `detail`. Retry only the failed items, and give tasks IDs so retries are safe. Retry requests that fail with `5xx` or a network error, with backoff. Don't retry `4xx` errors without changing the request, except `429 rate_limited`. ## API endpoints ### Queue endpoints Details: [Queues reference](https://pushqueue.dev/docs/reference/rest/queues/). | Method | Path | Summary | Access | |---|---|---|---| | `POST` | `/v1/queues` | Create a queue (fails with `already_exists` if the name is taken) | Write | | `PUT` | `/v1/queues/{queue}` | Create or replace a queue's configuration | Write | | `GET` | `/v1/queues/{queue}` | Get a queue | Read | | `PATCH` | `/v1/queues/{queue}` | Update some of a queue's settings, including `state` | Write | | `DELETE` | `/v1/queues/{queue}` | Delete a queue and all its tasks | Delete queue | | `GET` | `/v1/queues` | List queues (`name_prefix`, `page_size`, `page_token`) | List | | `POST` | `/v1/queues/{queue}:pause` | Pause dispatching | Write | | `POST` | `/v1/queues/{queue}:resume` | Resume dispatching | Write | | `POST` | `/v1/queues/{queue}:purge` | Delete every task created up to now | Write | | `GET` | `/v1/queues/{queue}/stats` | Live queue statistics (`id_prefix`) | Read | ### Task endpoints Details: [Tasks reference](https://pushqueue.dev/docs/reference/rest/tasks/). | Method | Path | Summary | Access | |---|---|---|---| | `POST` | `/v1/queues/{queue}/tasks` | Enqueue a task | Write | | `POST` | `/v1/queues/{queue}/tasks:batch` | Enqueue up to 500 tasks | Write | | `GET` | `/v1/queues/{queue}/tasks` | List tasks, newest first (`state`, `id_prefix`, `view`, `page_size`, `page_token`) | Read | | `GET` | `/v1/queues/{queue}/tasks/{taskID}` | Get a task (`view=full` includes headers and body) | Read | | `DELETE` | `/v1/queues/{queue}/tasks/{taskID}` | Delete a task | Write | | `POST` | `/v1/queues/{queue}/tasks/{taskID}:run` | Dispatch a task now, bypassing rate limits and the paused state | Write | | `GET` | `/v1/queues/{queue}/tasks/{taskID}/attempts` | A task's delivery attempts, newest first | Read | ### API key endpoints Details: [API keys reference](https://pushqueue.dev/docs/reference/rest/api-keys/). | Method | Path | Summary | Access | |---|---|---|---| | `GET` | `/v1/api-keys` | List API keys | Manage | | `POST` | `/v1/api-keys` | Create an API key (the secret is returned once) | Manage | | `DELETE` | `/v1/api-keys/{id}` | Revoke an API key | Manage | ### Team and user endpoints Details: [Teams and users reference](https://pushqueue.dev/docs/reference/rest/teams-and-users/). Endpoints marked SaaS exist only on servers in [SaaS mode](https://pushqueue.dev/docs/self-hosting/saas-mode/), including the hosted service; those marked self-hosted exist only without it. | Method | Path | Summary | Access | |---|---|---|---| | `PATCH` | `/v1/me` | Change your name | Signed-in user | | `POST` | `/v1/me/password` | Change your password (self-hosted) | Signed-in user | | `GET` | `/v1/teams` | Your teams (SaaS) | Signed-in user | | `POST` | `/v1/teams` | Create a team (SaaS) | Signed-in user | | `POST` | `/v1/teams/{id}:switch` | Switch your session to another of your teams (SaaS) | Signed-in user | | `PATCH` | `/v1/teams/current` | Rename the current team (SaaS) | Manage | | `GET` | `/v1/users` | List members | Manage | | `PATCH` | `/v1/users/{id}` | Change a member's role | Manage | | `DELETE` | `/v1/users/{id}` | Remove a member | Manage | | `POST` | `/v1/users/{id}/reset-link` | Create a password-reset link (self-hosted) | Manage | | `GET` | `/v1/invites` | Pending invites | Manage | | `POST` | `/v1/invites` | Invite someone | Manage | | `DELETE` | `/v1/invites/{id}` | Revoke an invite | Manage | ### Sign-in endpoints Details: [Sign-in reference](https://pushqueue.dev/docs/reference/rest/auth/). These endpoints power the dashboard's sign-in pages. You don't need them to use queues and tasks. | Method | Path | Summary | Access | |---|---|---|---| | `GET` | `/v1/auth/session` | Who am I, and how does this server sign people in? | Public | | `POST` | `/v1/auth/setup` | Create the first admin account (self-hosted) | Public | | `POST` | `/v1/auth/login` | Sign in with email and password (self-hosted) | Public | | `POST` | `/v1/auth/logout` | Sign out | Public | | `GET` | `/v1/auth/invites/{token}` | Look up an invite or password-reset link (self-hosted) | Public | | `POST` | `/v1/auth/invites/{token}:accept` | Accept an invite or reset link (self-hosted) | Public | | `POST` | `/v1/auth/email-code` | Email a 6-digit sign-in code (SaaS) | Public | | `POST` | `/v1/auth/email-code:verify` | Sign in with the emailed code (SaaS) | Public | | `GET` | `/v1/auth/email-verification` | Is a sign-in waiting for an email verification code? (SaaS) | Public | | `POST` | `/v1/auth/email-verification` | Finish a sign-in with the emailed verification code (SaaS) | Public | | `GET` | `/v1/auth/workos/login` | Start signing in with GitHub (SaaS) | Public | | `GET` | `/v1/auth/workos/callback` | Where GitHub sign-in returns (SaaS) | Public | ### System endpoints Details: [System reference](https://pushqueue.dev/docs/reference/rest/system/). | Method | Path | Summary | Access | |---|---|---|---| | `GET` | `/healthz` | Liveness check (`ok`) | Public | | `GET` | `/readyz` | Readiness check; reports the dispatcher role | Public | | `GET` | `/metrics` | Prometheus metrics | Public by default; otherwise List (in SaaS mode, only the operator's config-file keys) | | `GET` | `/openapi.json` | The OpenAPI document | Public | | `GET` | `/docs` | Interactive API docs (Swagger UI) | Public | | `GET` | `/v1/version` | Server version, commit and database dialect | Read | ## Read more - [API error codes](https://pushqueue.dev/docs/reference/errors/): every `code` and how to handle it. - [Install & configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/): typed clients for TypeScript, Python, Go, Java and .NET. - [API keys](https://pushqueue.dev/docs/guides/api-keys/): create, scope and revoke keys. - [Queues](https://pushqueue.dev/docs/concepts/queues/) and [tasks](https://pushqueue.dev/docs/concepts/tasks/): what the fields mean. --- # API error codes > Every pushq API error code with its HTTP status, cause and fix, the problem+json error format, and how each SDK surfaces errors. Source: https://pushqueue.dev/docs/reference/errors/ When a request fails, the pushq API answers with a non-2xx status and an [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) problem+json body (`Content-Type: application/problem+json`). Every error carries a stable `code` that you can branch on. Use this page when you're deciding which failures to retry, which to treat as success (such as a duplicate `task_id`), and which point at a bug in your request. ## Problem+json error format ```bash curl -i -X POST https://api.pushqueue.dev/v1/queues/emails/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{"json_body": {"to": "a@example.com"}}' ``` ```http HTTP/1.1 400 Bad Request Content-Type: application/problem+json { "type": "about:blank", "title": "Bad Request", "status": 400, "code": "invalid_argument", "detail": "url or path is required", "instance": "/v1/queues/emails/tasks" } ``` | Field | Type | Description | |---|---|---| | `type` | string | Always `about:blank`. | | `title` | string | The standard reason phrase for the status, e.g. `Not Found`. | | `status` | integer | The HTTP status code, repeated in the body. | | `code` | string | Stable machine-readable error code. Branch on this. | | `detail` | string | Human-readable explanation. Its wording can change between versions, so show it or log it, but don't parse it. | | `instance` | string | The request path that failed. | Several codes share an HTTP status (`failed_precondition` and `invalid_argument` are both `400`), so check `code` rather than the status alone. ## Error code reference | Code | HTTP status | Retry? | |---|---|---| | [`invalid_argument`](#invalid_argument) | 400, 405 | No, fix the request | | [`failed_precondition`](#failed_precondition) | 400 | No, change the state first | | [`unauthenticated`](#unauthenticated) | 401 | No, fix the credentials | | [`permission_denied`](#permission_denied) | 403 | No, use a key or role that's allowed | | [`email_verification_required`](#email_verification_required) | 403 | Finish verification | | [`not_found`](#not_found) | 404 | No | | [`already_exists`](#already_exists) | 409 | No; often means success | | [`payload_too_large`](#payload_too_large) | 413 | No, shrink the request | | [`rate_limited`](#rate_limited) | 429 | Yes, after `Retry-After` | | [`internal`](#internal) | 500, 502, 503 | Yes, with backoff | ### invalid_argument **Status:** `400 Bad Request` (also `405 Method Not Allowed` for a method a path doesn't support). The request is malformed or a field fails validation. Examples: - The body isn't valid JSON, or a field has the wrong type. - A queue name doesn't match the naming rules, or a `task_id` doesn't match `[A-Za-z0-9_-]{1,500}`. - A task sets both `url` and `path`, or neither; `url` isn't an absolute http(s) URL; `path` doesn't start with `/`. - A task sets both `body_base64` and `json_body`, or both `schedule_time` and `delay_seconds`; or sends a body with a method that doesn't allow one. - The decoded body is larger than the server's `limits.max_body_bytes` (1 MiB by default), or headers exceed `limits.max_headers_bytes`. A reserved header such as `Host` or `Content-Length` is set. - `schedule_time` is further ahead than the server allows (1 year by default); `dispatch_deadline_seconds` is outside 15 to 1800. - A rate limit or retry setting is out of range, e.g. `max_dispatches_per_second` not in (0, 10000], `max_attempts` not `-1` or at least 1. - A queue names itself as its `dead_letter_queue`. - A list filter is invalid (`state` not one of `pending`, `running`, `succeeded`, `failed`; `page_size` not an integer), or a batch is empty or has more than 500 tasks. - A dashboard account field is invalid, such as a password that's too short. **Handle it:** don't retry. Read `detail`, which names the field and the rule, and fix the request. ### failed_precondition **Status:** `400 Bad Request`. The request is well-formed but the current state doesn't allow it. Examples: - Enqueueing to, or running a task in, a queue whose state is `disabled`. - `:pause` on a `disabled` queue. - `:run` on a task that is being delivered right now. - A task uses `path`, but its queue has no `target.base_url`. - A malformed `page_token`. - Self-hosted: first-time setup was already completed; removing or demoting the last admin of a team. - SaaS mode: WorkOS rejected a request (the detail starts with `couldn't …`), or an email verification expired and the person needs to sign in again. **Handle it:** don't retry as-is. Change the state the detail describes first, for example resume or re-enable the queue, set the queue's `target.base_url`, or restart pagination without a token. ### unauthenticated **Status:** `401 Unauthorized`. The server doesn't know who you are: - The `Authorization` header is missing, the key is unknown, or it was revoked. - An endpoint that needs a signed-in dashboard user (`/v1/me`, `/v1/teams`) was called with an API key. - Sign-in failed: wrong email or password, or (SaaS mode) a wrong or expired email code. **Handle it:** check that you send `Authorization: Bearer pq_...` with a current key, and that the SDK points at the right server: a key from the hosted service won't work on a self-hosted server and vice versa. ### permission_denied **Status:** `403 Forbidden`. You're authenticated, but not allowed to do this: - Your role lacks the permission. For example, a `writer` key calling `GET /v1/queues` (listing) or `DELETE /v1/queues/{queue}`, or a `viewer` trying to enqueue. The detail names your role. - A cookie-authenticated request that changes something is missing the `X-Requested-With` header. - Self-hosted: first-time setup on a server protected by config-file keys was attempted without one of its admin keys. - SaaS mode: a non-operator caller reading `/metrics` when metrics aren't public. **Handle it:** use an `admin` key or a role that allows the call. See [API keys](https://pushqueue.dev/docs/guides/api-keys/) and the [access levels for each endpoint](https://pushqueue.dev/docs/reference/api/#who-can-call-what). ### email_verification_required **Status:** `403 Forbidden`. SaaS mode only. An email-code sign-in is paused until the person enters the verification code WorkOS emailed them. Only the dashboard's sign-in flow sees this. **Handle it:** send the code to `POST /v1/auth/email-verification` to finish signing in. ### not_found **Status:** `404 Not Found`. - The queue, task, API key, member or invite doesn't exist. A task disappears once its retention runs out, so old tasks return `not_found`. - `:run` on a task that has already finished, was deleted or was purged. - No such endpoint. For a path under `/v1/queues/` that contains an unencoded `/`, the detail adds a hint to encode the queue name (`user/instagram` becomes `user%2Finstagram`). - An invite or password-reset link is invalid or expired. - The endpoint isn't available on this server: dashboard accounts aren't enabled, an endpoint is SaaS-only (teams, email codes, GitHub sign-in) on a self-hosted server, or self-hosted-only (passwords, setup) on a SaaS server. **Handle it:** check the name and ID, and that queue names in paths are URL-encoded. To make "create the queue if it's missing" safe, upsert it with `PUT /v1/queues/{queue}` before enqueueing. ### already_exists **Status:** `409 Conflict`. - `POST /v1/queues` for a name that's taken. Use `PUT /v1/queues/{queue}` to create-or-update instead. - `POST /v1/queues/{queue}/tasks` with a `task_id` that is already in use, or was used within the dedup window (1 hour by default) after that task finished or was deleted. - Creating an account with an email that already has one, or inviting someone who is already a member. **Handle it:** for task creation this is usually success: the task with that ID was already enqueued, for example by an earlier attempt of the same request. Treat it as done. ### payload_too_large **Status:** `413 Request Entity Too Large`. The raw request body is over the server's limit: 256 KiB for queue requests, 8 MiB for a batch, and twice `limits.max_body_bytes` plus 64 KiB for a single task. (A task body that fits in the request but exceeds `limits.max_body_bytes` once decoded is `invalid_argument`.) **Handle it:** send smaller task bodies (store large payloads elsewhere and pass a reference), or split a batch. ### rate_limited **Status:** `429 Too Many Requests`, with a `Retry-After: 6` header. Too many attempts on a sign-in endpoint from one IP address: password sign-in, first-time setup, accepting an invite, changing a password, and requesting or verifying email codes. Each IP gets 10 attempts, refilling one every 6 seconds. Queue and task endpoints don't return this code. **Handle it:** wait for the number of seconds in `Retry-After`, then try again. ### internal **Status:** `500 Internal Server Error`; `502 Bad Gateway` when WorkOS is unreachable in SaaS mode; `503 Service Unavailable` from `/readyz` when the database is unreachable. Something failed on the server. The detail is generic (`internal error`); self-hosters find the cause in the server log. **Handle it:** retry with exponential backoff. Give tasks a `task_id` so a retried enqueue can't create a duplicate. ## Errors in batch enqueue `POST /v1/queues/{queue}/tasks:batch` answers `200` even when some tasks fail. Each failed item has an `error` object with a `code` and `detail` instead of a `task`: ```json { "results": [ { "index": 0, "task": { "id": "welcome-user-42", "state": "pending" } }, { "index": 1, "error": { "code": "already_exists", "detail": "already exists" } }, { "index": 2, "error": { "code": "invalid_argument", "detail": "url or path is required" } } ] } ``` Item codes are `invalid_argument`, `already_exists`, `not_found`, `failed_precondition` and `internal`, with the same meanings as above. The whole request still fails with a problem+json error for problems with the batch itself, such as an empty list or a missing queue. ## Handle errors in the SDKs Every SDK turns a non-2xx response into an error that carries the HTTP status, the `code` and the `detail`: - **TypeScript:** rejects with `PushqError` (`status`, `code`, `detail`). - **Python:** raises `PushqError` (`status`, `code`, `detail`), from both `Pushq` and `AsyncPushq`. - **Go:** returns a `*pushq.Error` (`Status`, `Code`, `Detail`); `pushq.IsCode(err, "already_exists")` checks the code through wrapped errors. - **Java:** throws the unchecked `PushqException` (`getStatus()`, `getCode()`, `getDetail()`). Network failures throw it too, with status `0` and a `null` code. - **.NET:** throws `PushqException` (`Status`, `Code`, `Detail`). If a response isn't problem+json (for example an error page from a proxy), the TypeScript, Python, Go and .NET SDKs report the code as `internal` and put the start of the body in `detail`; Java leaves the code `null`. Apart from Java, network failures and timeouts surface as the language's usual HTTP client errors. This example treats a duplicate task ID as success and rethrows everything else: **TypeScript** ```ts try { await pq.createTask("emails", { taskId: "welcome-user-42", path: "/send" }); } catch (err) { if (err instanceof PushqError && err.code === "already_exists") { // already enqueued } else { throw err; } } ``` **Python** ```python from pushq import PushqError try: pq.create_task("emails", task_id="welcome-user-42", path="/send") except PushqError as e: if e.code != "already_exists": print(e.status, e.code, e.detail) raise ``` **Go** ```go _, err := pq.CreateTask(ctx, "emails", pushq.TaskCreate{TaskID: "welcome-user-42", Path: "/send"}) if pushq.IsCode(err, "already_exists") { err = nil // already enqueued } var pe *pushq.Error if errors.As(err, &pe) { log.Printf("pushq error %d %s: %s", pe.Status, pe.Code, pe.Detail) } if err != nil { return err } ``` **Java** ```java try { pq.createTask("emails", TaskCreate.builder().taskId("welcome-user-42").path("/send").build()); } catch (PushqException e) { if (!"already_exists".equals(e.getCode())) { System.err.printf("%d %s: %s%n", e.getStatus(), e.getCode(), e.getDetail()); throw e; } } ``` **.NET** ```csharp try { await pq.CreateTaskAsync("emails", new TaskCreate { TaskId = "welcome-user-42", Path = "/send" }); } catch (PushqException e) when (e.Code == "already_exists") { // already enqueued } ``` **curl** ```bash status=$(curl -s -o /tmp/resp.json -w '%{http_code}' -X POST https://api.pushqueue.dev/v1/queues/emails/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{"task_id": "welcome-user-42", "path": "/send"}') code=$(jq -r '.code // empty' /tmp/resp.json) if [ "$status" -ge 300 ] && [ "$code" != "already_exists" ]; then echo "failed: $status $code $(jq -r .detail /tmp/resp.json)" >&2 exit 1 fi ``` ## Read more - [REST API overview](https://pushqueue.dev/docs/reference/api/): authentication, pagination and idempotency. - [Tasks](https://pushqueue.dev/docs/concepts/tasks/): task IDs and deduplication. - [Install & configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/): error types in each language. - [Retries and backoff](https://pushqueue.dev/docs/concepts/retries/): delivery retries, which are separate from API errors. --- # Tasks API reference > pushq Tasks API reference: enqueue tasks singly or in batches, list, get, run now and delete them, and read delivery attempts, with examples. Source: https://pushqueue.dev/docs/reference/rest/tasks/ The Tasks API is how you put work on a pushq queue and follow it through delivery. A task is one HTTP request that pushq will send to your endpoint, on time, at the queue's rate, with retries. This page documents every task endpoint: enqueue a task, enqueue tasks in bulk, list and get tasks, run a task now, delete a task, and list its delivery attempts. **TypeScript** ```ts const task = await pq.createTask("emails", { taskId: "welcome-user-42", path: "/hooks/send-welcome", jsonBody: { user_id: 42 }, delaySeconds: 3600, }); ``` **Python** ```python task = pq.create_task( "emails", task_id="welcome-user-42", path="/hooks/send-welcome", json_body={"user_id": 42}, delay_seconds=3600, ) ``` **Go** ```go task, err := pq.CreateTask(ctx, "emails", pushq.TaskCreate{ TaskID: "welcome-user-42", Path: "/hooks/send-welcome", JSONBody: map[string]any{"user_id": 42}, DelaySeconds: pushq.Float64(3600), }) ``` **Java** ```java Task task = pq.createTask("emails", TaskCreate.builder() .taskId("welcome-user-42") .path("/hooks/send-welcome") .jsonBody(Map.of("user_id", 42)) .delaySeconds(3600) .build()); ``` **.NET** ```csharp PushqTask task = await pq.CreateTaskAsync("emails", new TaskCreate { TaskId = "welcome-user-42", Path = "/hooks/send-welcome", JsonBody = new { user_id = 42 }, Delay = TimeSpan.FromHours(1), }); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/emails/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{"task_id":"welcome-user-42","path":"/hooks/send-welcome","json_body":{"user_id":42},"delay_seconds":3600}' ``` The examples assume an SDK client named `pq` (and, in Go, a `ctx`), created as shown in [install and configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/). They use the hosted API at `https://api.pushqueue.dev`; self-hosted servers expose the same endpoints at their own URL. Parameter tables use the JSON field names (`dispatch_deadline_seconds`); the SDKs use their language's casing for the same fields: camelCase in TypeScript and Java (`dispatchDeadlineSeconds`), snake_case in Python, PascalCase in Go and .NET. :::note[Queue names in paths] Queue names may contain `/` (folders such as `user/instagram`). In a URL path the whole name is **one** segment, so encode the slash: `/v1/queues/user%2Finstagram/tasks`. The SDKs encode queue names for you. Task IDs never contain `/`. ::: ## Task API permissions | Endpoint | Writer API key | Admin API key | Dashboard roles | |---|---|---|---| | Enqueue, batch enqueue, run, delete | yes | yes | member, admin | | List, get, list attempts | yes | yes | viewer, member, admin | A request without valid credentials gets `401 unauthenticated`; a key or role without the permission gets `403 permission_denied`. ## The task object Every endpoint that returns a task uses this shape. ```json { "id": "welcome-user-42", "queue": "emails", "state": "pending", "url": "/hooks/send-welcome", "method": "POST", "headers": { "Content-Type": "application/json" }, "body_base64": "eyJ1c2VyX2lkIjo0Mn0=", "schedule_time": "2026-11-28T11:15:00.12Z", "created_at": "2026-11-28T10:15:00.12Z", "dispatch_deadline_seconds": 600, "retry": { "max_attempts": 3 }, "dispatch_count": 1, "response_count": 1, "first_attempt_at": "2026-11-28T11:15:00.304Z", "last_attempt": { "at": "2026-11-28T11:15:00.304Z", "status": 503, "error": "non_2xx: upstream unavailable" } } ``` | Field | Type | Description | |---|---|---| | `id` | string | Task ID: the `task_id` you sent, or a server-generated UUIDv7. | | `queue` | string | Queue name. | | `state` | string | `pending` (waiting for its time or a dispatch slot, including between retries), `running` (being delivered now), `succeeded` (got a 2xx) or `failed` (retries exhausted, or a task whose own headers can never be sent). | | `url` | string | The absolute `url`, or the `path` as sent (resolved against the queue's `target.base_url` at dispatch). | | `method` | string | HTTP method stored on the task. A queue-level `target.method` overrides it at dispatch. | | `headers` | object | Task headers. Only in the full view (and in create responses); omitted when empty. | | `body_base64` | string | Request body, base64-encoded. Only in the full view (and in create responses); omitted when empty. | | `schedule_time` | string (RFC 3339) | When the task is (or was) due. Moves forward on each retry, and to "now" on a force-run. | | `created_at` | string (RFC 3339) | When the task was created. | | `dispatch_deadline_seconds` | number | How long pushq waits for a response on each attempt. | | `retry` | object | The per-task retry override you sent (only the fields you set), not the effective policy. Omitted when there is none. Fields as in [retry fields](#enqueue-a-task). | | `dispatch_count` | integer | Attempts started so far. | | `response_count` | integer | Attempts that got an HTTP response (any status). | | `first_attempt_at` | string (RFC 3339) | When the first attempt started. Omitted before the first attempt. | | `finished_at` | string (RFC 3339) | When the task succeeded or failed for good. Omitted while it is pending or running. | | `last_attempt.at` | string (RFC 3339) | When the latest attempt started. `last_attempt` is omitted before the first attempt. | | `last_attempt.status` | integer | HTTP status of the latest attempt. Omitted when no response arrived. | | `last_attempt.error` | string | Error kind of the latest attempt, followed by up to 512 characters of detail (`non_2xx: `). Omitted on success. | ## Enqueue a task `POST /v1/queues/{queue}/tasks` Creates one task. pushq will send it as an HTTP request to `url` (or the queue's `target.base_url` + `path`) at `schedule_time`, within the queue's rate limits, and retry it on failure according to the queue's retry policy merged with any per-task `retry` override. Use this for every unit of background work: send an email, call a webhook, run a job later. Give the task a `task_id` when the same work might be enqueued twice (a retried request, a duplicate event): a second enqueue with the same ID in the same queue fails with `409 already_exists` instead of creating a duplicate. That makes `task_id` your idempotency key. See [deduplicate tasks with task IDs](https://pushqueue.dev/docs/patterns/deduplication/). Tasks can be added to a paused queue (they wait until it's resumed) but not to a disabled one. **Who can call it:** writer or admin API key; dashboard member or admin. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `queue` | string | yes | — | Queue name, URL-encoded as one segment (`user%2Finstagram`). The queue must exist. | **Request body** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `task_id` | string | no | server-generated UUIDv7 | Your ID for the task, `[A-Za-z0-9_-]`, 1–500 characters. Deduplicates within the queue (see below). | | `url` | string | one of `url`/`path` | — | Absolute `http` or `https` URL to call, at most 2083 characters. | | `path` | string | one of `url`/`path` | — | Path starting with `/`, appended to the queue's `target.base_url` at dispatch time. The queue must have a `target.base_url`. | | `method` | string | no | `POST` | `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD` or `OPTIONS` (case-insensitive). | | `headers` | object (string → string) | no | none | Request headers. Names and values must be valid HTTP; `Host`, `Content-Length`, `Transfer-Encoding`, `Connection`, `Keep-Alive`, `Upgrade`, `TE` and `Trailer` are reserved. Total size at most 16 KiB (self-hosted default). Queue `target.headers` override these at dispatch. | | `json_body` | any JSON value | no | none | Body to send as JSON. Sets `Content-Type: application/json` unless you set a `Content-Type` header. Can't be combined with `body_base64`. | | `body_base64` | string | no | none | Raw body, standard base64. Without a `Content-Type` header it is sent as `application/octet-stream`. Can't be combined with `json_body`. | | `schedule_time` | string (RFC 3339) | no | now | When to send it. A time in the past means "now". At most 1 year ahead (self-hosted default). Can't be combined with `delay_seconds`. | | `delay_seconds` | number | no | `0` | Send it this many seconds from now. At least 0; also limited by the 1-year schedule-ahead limit. | | `dispatch_deadline_seconds` | number | no | `600` | How long to wait for a response on each attempt before it counts as a `timeout`. 15–1800. | | `retry` | object | no | queue's policy | Per-task override of the queue's retry policy; set only the fields you want to change. | | `retry.max_attempts` | integer | no | queue's | `-1` (unlimited) or at least 1, including the first attempt. | | `retry.max_retry_duration_seconds` | number | no | queue's | At least 0; `0` = unlimited. Measured from the first attempt. | | `retry.min_backoff_seconds` | number | no | queue's | At least 0. | | `retry.max_backoff_seconds` | number | no | queue's | At least `min_backoff_seconds`. | | `retry.max_doublings` | integer | no | queue's | 0–31. | A body (`json_body` or `body_base64`) is only allowed with `POST`, `PUT` or `PATCH`, and may be at most 1 MiB once decoded (self-hosted default). The JSON request itself may be at most twice that plus 64 KiB. Per-task `retry` values are checked against the server's default retry policy when the task is created; the queue's policy fills in the fields you leave out when the task runs. See [retry backoff and max attempts](https://pushqueue.dev/docs/concepts/retries/). **How long a task ID stays taken.** A `task_id` is reserved in its queue for as long as a task with that ID is stored: while it is pending or running, after it finishes until retention cleanup removes it (self-hosted defaults: 24 hours after success, 7 days after failure), and for the dedup window after you [delete a task](#delete-a-task) (self-hosted default: 1 hour). [Purging the queue](https://pushqueue.dev/docs/reference/rest/queues/#purge-a-queue) frees all IDs immediately. Limits on the hosted service may differ from these self-hosted defaults. **Example** The example at the top of this page enqueues a JSON task with a delay. This one calls an absolute URL with a raw body at a fixed time: **TypeScript** ```ts const task = await pq.createTask("emails", { url: "https://api.example.com/hooks/digest", method: "PUT", headers: { "Content-Type": "text/plain" }, body: "weekly digest for user 42", // string or Uint8Array; the SDK base64-encodes it scheduleTime: new Date("2026-12-01T09:00:00Z"), dispatchDeadlineSeconds: 120, retry: { maxAttempts: 3 }, }); ``` **Python** ```python from datetime import datetime, timezone from pushq import Retry task = pq.create_task( "emails", url="https://api.example.com/hooks/digest", method="PUT", headers={"Content-Type": "text/plain"}, body=b"weekly digest for user 42", # raw bytes; the SDK base64-encodes them schedule_time=datetime(2026, 12, 1, 9, 0, tzinfo=timezone.utc), dispatch_deadline_seconds=120, retry=Retry(max_attempts=3), ) ``` **Go** ```go at := time.Date(2026, 12, 1, 9, 0, 0, 0, time.UTC) task, err := pq.CreateTask(ctx, "emails", pushq.TaskCreate{ URL: "https://api.example.com/hooks/digest", Method: "PUT", Headers: map[string]string{"Content-Type": "text/plain"}, Body: []byte("weekly digest for user 42"), // the SDK base64-encodes it ScheduleTime: &at, DispatchDeadlineSeconds: pushq.Float64(120), Retry: &pushq.Retry{MaxAttempts: pushq.Int(3)}, }) ``` **Java** ```java Task task = pq.createTask("emails", TaskCreate.builder() .url("https://api.example.com/hooks/digest") .method("PUT") .header("Content-Type", "text/plain") .body("weekly digest for user 42".getBytes(StandardCharsets.UTF_8)) // the SDK base64-encodes it .scheduleTime(Instant.parse("2026-12-01T09:00:00Z")) .dispatchDeadlineSeconds(120) .retry(RetryConfig.builder().maxAttempts(3).build()) .build()); ``` **.NET** ```csharp PushqTask task = await pq.CreateTaskAsync("emails", new TaskCreate { Url = "https://api.example.com/hooks/digest", Method = "PUT", Headers = new Dictionary { ["Content-Type"] = "text/plain" }, Body = Encoding.UTF8.GetBytes("weekly digest for user 42"), // the SDK base64-encodes it ScheduleTime = new DateTimeOffset(2026, 12, 1, 9, 0, 0, TimeSpan.Zero), DispatchDeadline = TimeSpan.FromSeconds(120), Retry = new RetryConfig { MaxAttempts = 3 }, }); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/emails/tasks \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://api.example.com/hooks/digest", "method": "PUT", "headers": { "Content-Type": "text/plain" }, "body_base64": "d2Vla2x5IGRpZ2VzdCBmb3IgdXNlciA0Mg==", "schedule_time": "2026-12-01T09:00:00Z", "dispatch_deadline_seconds": 120, "retry": { "max_attempts": 3 } }' ``` The SDKs take the raw body and do the base64 encoding for you. In .NET, `delay_seconds` and `dispatch_deadline_seconds` are `TimeSpan` properties named `Delay` and `DispatchDeadline`, and the task type is `PushqTask` (to avoid clashing with `System.Threading.Tasks.Task`). In Python, a naive `datetime` for `schedule_time` is treated as UTC. Some SDKs catch conflicting fields before sending: the Java builder rejects `url` with `path`, a body with `json_body`, and `schedule_time` with `delay_seconds`; .NET rejects the last two; TypeScript and Python reject a body with `json_body`. Everything else is validated by the server. **Response** `201 Created` with the [task object](#the-task-object). The create response always includes `headers` and `body_base64` when set: ```json { "id": "0193b6f2-7c1e-7a3d-9f4e-2b8c5d1a6e90", "queue": "emails", "state": "pending", "url": "https://api.example.com/hooks/digest", "method": "PUT", "headers": { "Content-Type": "text/plain" }, "body_base64": "d2Vla2x5IGRpZ2VzdCBmb3IgdXNlciA0Mg==", "schedule_time": "2026-12-01T09:00:00Z", "created_at": "2026-11-28T10:15:00.12Z", "dispatch_deadline_seconds": 120, "retry": { "max_attempts": 3 }, "dispatch_count": 0, "response_count": 0 } ``` Field descriptions are in [the task object](#the-task-object). **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | Invalid JSON; bad `task_id`; both or neither of `url`/`path`; invalid URL; `path` not starting with `/`; method not allowed; invalid or reserved header; headers or body too large; invalid base64; body with a method that doesn't allow one; both `schedule_time` and `delay_seconds`; schedule too far ahead; `dispatch_deadline_seconds` outside 15–1800; invalid `retry` values. | | 400 | `failed_precondition` | The task uses `path` but the queue has no `target.base_url`, or the queue is `disabled`. | | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | The key or role can't write. | | 404 | `not_found` | The queue doesn't exist. | | 409 | `already_exists` | A task with this `task_id` is already stored in the queue. | | 413 | `payload_too_large` | The request body is over the size limit. | See [API error codes](https://pushqueue.dev/docs/reference/errors/) for the error format. ## Enqueue tasks in bulk (batch) `POST /v1/queues/{queue}/tasks:batch` Creates up to 500 tasks in one request. Use it for fan-out (one task per user, per row, per webhook subscriber) to cut round trips. The batch is **not atomic**: each item succeeds or fails on its own, and the response lists a result per item in request order. A duplicate `task_id`, including one repeated inside the same batch, fails only that item with `already_exists`. See [bulk enqueue](https://pushqueue.dev/docs/patterns/bulk-enqueue/). **Who can call it:** writer or admin API key; dashboard member or admin. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `queue` | string | yes | — | Queue name, URL-encoded as one segment (`user%2Finstagram`). The queue must exist. | **Request body** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `tasks` | array | yes | — | 1–500 task definitions. | | `tasks[].*` | object | — | — | Each item takes exactly the fields of [Enqueue a task](#enqueue-a-task): `task_id`, `url`, `path`, `method`, `headers`, `json_body`, `body_base64`, `schedule_time`, `delay_seconds`, `dispatch_deadline_seconds`, `retry.*`. | The whole request may be at most 8 MiB. **Example** **TypeScript** ```ts const results = await pq.createTasks("emails", [ { taskId: "welcome-user-42", path: "/hooks/send-welcome", jsonBody: { user_id: 42 } }, { taskId: "welcome-user-43", path: "/hooks/send-welcome", jsonBody: { user_id: 43 } }, ]); for (const r of results) { if (r.error) console.warn(`#${r.index}: ${r.error.code} ${r.error.detail}`); else console.log(`#${r.index}: created ${r.task!.id}`); } ``` **Python** ```python results = pq.create_tasks("emails", [ {"task_id": "welcome-user-42", "path": "/hooks/send-welcome", "json_body": {"user_id": 42}}, {"task_id": "welcome-user-43", "path": "/hooks/send-welcome", "json_body": {"user_id": 43}}, ]) for r in results: if r.error: print(r.index, r.error.code, r.error.detail) else: print(r.index, r.task.id) ``` **Go** ```go results, err := pq.CreateTasks(ctx, "emails", []pushq.TaskCreate{ {TaskID: "welcome-user-42", Path: "/hooks/send-welcome", JSONBody: map[string]any{"user_id": 42}}, {TaskID: "welcome-user-43", Path: "/hooks/send-welcome", JSONBody: map[string]any{"user_id": 43}}, }) if err != nil { return err // the whole request failed } for _, r := range results { if r.Error != nil { log.Printf("item %d: %s: %s", r.Index, r.Error.Code, r.Error.Detail) continue } fmt.Println("created", r.Task.ID) } ``` **Java** ```java List results = pq.createTasks("emails", List.of( TaskCreate.builder().taskId("welcome-user-42").path("/hooks/send-welcome") .jsonBody(Map.of("user_id", 42)).build(), TaskCreate.builder().taskId("welcome-user-43").path("/hooks/send-welcome") .jsonBody(Map.of("user_id", 43)).build())); for (BatchResult r : results) { if (r.isSuccess()) { System.out.println(r.getIndex() + " -> " + r.getTask().getId()); } else { System.err.println(r.getIndex() + " failed: " + r.getError().getCode() + " " + r.getError().getDetail()); } } ``` **.NET** ```csharp IReadOnlyList results = await pq.CreateTasksAsync("emails", new[] { new TaskCreate { TaskId = "welcome-user-42", Path = "/hooks/send-welcome", JsonBody = new { user_id = 42 } }, new TaskCreate { TaskId = "welcome-user-43", Path = "/hooks/send-welcome", JsonBody = new { user_id = 43 } }, }); foreach (var r in results) { if (r.Error != null) Console.WriteLine($"#{r.Index} failed: {r.Error.Code} {r.Error.Detail}"); else Console.WriteLine($"#{r.Index} -> {r.Task!.Id}"); } ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/emails/tasks:batch \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "tasks": [ { "task_id": "welcome-user-42", "path": "/hooks/send-welcome", "json_body": { "user_id": 42 } }, { "task_id": "welcome-user-43", "path": "/hooks/send-welcome", "json_body": { "user_id": 43 } } ] }' ``` The SDK method is `createTasks` / `create_tasks` / `CreateTasks` / `CreateTasksAsync` and returns the `results` array directly. In Python each item is a dict using `create_task`'s keyword names; unknown keys are silently ignored. **Response** `200 OK`, even when some items failed: ```json { "results": [ { "index": 0, "task": { "id": "welcome-user-42", "queue": "emails", "state": "pending", "url": "/hooks/send-welcome", "method": "POST", "headers": { "Content-Type": "application/json" }, "body_base64": "eyJ1c2VyX2lkIjo0Mn0=", "schedule_time": "2026-11-28T10:15:00.12Z", "created_at": "2026-11-28T10:15:00.12Z", "dispatch_deadline_seconds": 600, "dispatch_count": 0, "response_count": 0 } }, { "index": 1, "error": { "code": "already_exists", "detail": "already exists" } } ] } ``` | Field | Type | Description | |---|---|---| | `results` | array | One entry per input task, in request order. | | `results[].index` | integer | Position of the task in the request (0-based). | | `results[].task` | [task object](#the-task-object) | The created task. Present only on success. | | `results[].error.code` | string | Present only on failure: `invalid_argument`, `already_exists`, `not_found`, `failed_precondition` or `internal`. | | `results[].error.detail` | string | Human-readable reason for the failure. | **Errors** These fail the whole request; per-item failures are reported in `results` instead. | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | Invalid JSON, `tasks` empty, or more than 500 tasks. | | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | The key or role can't write. | | 404 | `not_found` | The queue doesn't exist. | | 413 | `payload_too_large` | Request body over 8 MiB. | ## List tasks `GET /v1/queues/{queue}/tasks` Lists a queue's tasks, newest first, one page at a time. Filter by `state` to find failed tasks to inspect or retry, or by `id_prefix` to find a group of related tasks (for example everything for one user if your IDs start with the user ID). Deleted and purged tasks are not listed; finished tasks are listed until retention cleanup removes them. **Who can call it:** writer or admin API key; dashboard viewer, member or admin. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `queue` | string | yes | — | Queue name, URL-encoded as one segment (`user%2Finstagram`). | **Query parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `state` | string | no | all | `pending`, `running`, `succeeded` or `failed`. | | `id_prefix` | string | no | none | Only tasks whose ID starts with this. | | `view` | string | no | `basic` | `basic` omits `headers` and `body_base64`; `full` includes them. | | `page_size` | integer | no | `100` | Tasks per page. Values above 1000 are capped at 1000; 0 or less means 100. | | `page_token` | string | no | none | `next_page_token` from the previous response. | **Example** **TypeScript** ```ts const page = await pq.listTasks("emails", { state: "failed", idPrefix: "welcome-", pageSize: 50 }); for (const t of page.items) console.log(t.id, t.lastAttempt?.status, t.lastAttempt?.error); // page.nextPageToken -> pass as pageToken for the next page ``` **Python** ```python page = pq.list_tasks("emails", state="failed", id_prefix="welcome-", page_size=50) for t in page.items: print(t.id, t.last_attempt.status if t.last_attempt else None) # page.next_page_token -> pass as page_token for the next page ``` **Go** ```go tasks, next, err := pq.ListTasks(ctx, "emails", pushq.ListTasksParams{ State: "failed", IDPrefix: "welcome-", PageSize: 50, }) // pass next as PageToken for the next page ("" on the last page) ``` **Java** ```java TaskPage page = pq.listTasks("emails", ListTasksParams.builder() .state("failed") .idPrefix("welcome-") .pageSize(50) .build()); page.getTasks().forEach(t -> System.out.println(t.getId() + " " + t.getState())); // page.getNextPageToken() -> pageToken(...) for the next page ``` **.NET** ```csharp Page page = await pq.ListTasksAsync("emails", new ListTasksOptions { State = TaskState.Failed, IdPrefix = "welcome-", PageSize = 50, }); // page.NextPageToken -> ListTasksOptions.PageToken for the next page ``` **curl** ```bash curl "https://api.pushqueue.dev/v1/queues/emails/tasks?state=failed&id_prefix=welcome-&page_size=50" \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `200 OK`: ```json { "tasks": [ { "id": "welcome-user-43", "queue": "emails", "state": "failed", "url": "/hooks/send-welcome", "method": "POST", "schedule_time": "2026-11-28T10:42:51.004Z", "created_at": "2026-11-28T10:15:00.12Z", "dispatch_deadline_seconds": 600, "retry": { "max_attempts": 3 }, "dispatch_count": 3, "response_count": 3, "first_attempt_at": "2026-11-28T10:15:00.31Z", "finished_at": "2026-11-28T10:42:51.88Z", "last_attempt": { "at": "2026-11-28T10:42:51.004Z", "status": 500, "error": "non_2xx: template not found" } } ], "next_page_token": "MTI4Nzc" } ``` | Field | Type | Description | |---|---|---| | `tasks` | array of [task objects](#the-task-object) | This page, newest first. Empty array when nothing matches. | | `next_page_token` | string | Pass as `page_token` to get the next page. Omitted on the last page. | The SDKs return a page object: `items` / `nextPageToken` in TypeScript, `items` / `next_page_token` in Python, `getTasks()` / `getNextPageToken()` in Java, `Items` / `NextPageToken` in .NET; Go returns the slice and the next token separately. **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | Unknown `state`, or `page_size` not an integer. | | 400 | `failed_precondition` | `page_token` is malformed. | | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | The caller has no read permission. | | 404 | `not_found` | The queue doesn't exist. | ## Get a task `GET /v1/queues/{queue}/tasks/{taskID}` Returns one task's current state, schedule and last attempt. Use it to check whether a specific job ran, or (with `view=full`) to see exactly what will be sent. Deleted and purged tasks return `404`. **Who can call it:** writer or admin API key; dashboard viewer, member or admin. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `queue` | string | yes | — | Queue name, URL-encoded as one segment (`user%2Finstagram`). | | `taskID` | string | yes | — | The task's ID. | **Query parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `view` | string | no | `basic` | `basic` omits `headers` and `body_base64`; `full` includes them. | **Example** **TypeScript** ```ts const task = await pq.getTask("emails", "welcome-user-42"); const full = await pq.getTask("emails", "welcome-user-42", { view: "full" }); const body = full.body ? new TextDecoder().decode(full.body) : undefined; // Uint8Array ``` **Python** ```python task = pq.get_task("emails", "welcome-user-42") full = pq.get_task("emails", "welcome-user-42", view="full") print(full.headers, full.body) # body is decoded bytes ``` **Go** ```go task, err := pq.GetTask(ctx, "emails", "welcome-user-42") full, err := pq.GetTaskFull(ctx, "emails", "welcome-user-42") // includes headers + body body, _ := base64.StdEncoding.DecodeString(full.BodyBase64) ``` **Java** ```java Task task = pq.getTask("emails", "welcome-user-42"); Task full = pq.getTaskFull("emails", "welcome-user-42"); // includes headers + body byte[] body = full.getBodyBase64() == null ? new byte[0] : Base64.getDecoder().decode(full.getBodyBase64()); ``` **.NET** ```csharp PushqTask task = await pq.GetTaskAsync("emails", "welcome-user-42"); PushqTask full = await pq.GetTaskAsync("emails", "welcome-user-42", TaskView.Full); string? bodyText = full.Body == null ? null : Encoding.UTF8.GetString(full.Body); ``` **curl** ```bash curl "https://api.pushqueue.dev/v1/queues/emails/tasks/welcome-user-42?view=full" \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` Go and Java get the full view from a separate method (`GetTaskFull`, `getTaskFull`) and return the body as the base64 string; TypeScript, Python and .NET decode it into bytes for you. **Response** `200 OK` with the [task object](#the-task-object) (here with `view=full`): ```json { "id": "welcome-user-42", "queue": "emails", "state": "succeeded", "url": "/hooks/send-welcome", "method": "POST", "headers": { "Content-Type": "application/json" }, "body_base64": "eyJ1c2VyX2lkIjo0Mn0=", "schedule_time": "2026-11-28T11:15:00.12Z", "created_at": "2026-11-28T10:15:00.12Z", "dispatch_deadline_seconds": 600, "dispatch_count": 1, "response_count": 1, "first_attempt_at": "2026-11-28T11:15:00.304Z", "finished_at": "2026-11-28T11:15:00.511Z", "last_attempt": { "at": "2026-11-28T11:15:00.304Z", "status": 200 } } ``` **Errors** | Status | Code | When | |---|---|---| | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | The caller has no read permission. | | 404 | `not_found` | No such task (or it was deleted or purged), or no such queue. | ## Delete a task `DELETE /v1/queues/{queue}/tasks/{taskID}` Cancels a task. A pending task will never be sent; if it is being delivered right now, the delivery's result is discarded. You can also delete finished tasks. Use it to cancel scheduled work that is no longer needed, such as a reminder for an order that was already paid. The task ID stays reserved for the dedup window (1 hour by default on self-hosted servers), so re-enqueueing the same ID right away fails with `already_exists`. See [schedule and cancel tasks](https://pushqueue.dev/docs/patterns/scheduling-and-cancelling/). **Who can call it:** writer or admin API key; dashboard member or admin. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `queue` | string | yes | — | Queue name, URL-encoded as one segment (`user%2Finstagram`). | | `taskID` | string | yes | — | The task's ID. | **Example** **TypeScript** ```ts await pq.deleteTask("emails", "welcome-user-42"); ``` **Python** ```python pq.delete_task("emails", "welcome-user-42") ``` **Go** ```go err := pq.DeleteTask(ctx, "emails", "welcome-user-42") ``` **Java** ```java pq.deleteTask("emails", "welcome-user-42"); ``` **.NET** ```csharp await pq.DeleteTaskAsync("emails", "welcome-user-42"); ``` **curl** ```bash curl -X DELETE https://api.pushqueue.dev/v1/queues/emails/tasks/welcome-user-42 \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `204 No Content` with an empty body. **Errors** | Status | Code | When | |---|---|---| | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | The key or role can't write. | | 404 | `not_found` | No such task (or already deleted or purged), or no such queue. | ## Run a task now `POST /v1/queues/{queue}/tasks/{taskID}:run` Dispatches a pending task immediately: its `schedule_time` is set to now and it is sent right away, ignoring the queue's rate limits and its paused state. Use it to test a delivery, to skip the wait on a delayed or backing-off task, or to push one urgent task through a paused queue. Only `pending` tasks can be run. **Who can call it:** writer or admin API key; dashboard member or admin. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `queue` | string | yes | — | Queue name, URL-encoded as one segment (`user%2Finstagram`). | | `taskID` | string | yes | — | The task's ID. | No request body. **Example** **TypeScript** ```ts const task = await pq.runTask("emails", "welcome-user-42"); ``` **Python** ```python task = pq.run_task("emails", "welcome-user-42") ``` **Go** ```go task, err := pq.RunTask(ctx, "emails", "welcome-user-42") ``` **Java** ```java Task task = pq.runTask("emails", "welcome-user-42"); ``` **.NET** ```csharp PushqTask task = await pq.RunTaskAsync("emails", "welcome-user-42"); ``` **curl** ```bash curl -X POST https://api.pushqueue.dev/v1/queues/emails/tasks/welcome-user-42:run \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `200 OK` with the [task object](#the-task-object) in the full view, still `pending` with `schedule_time` set to now (the dispatch happens right after the response): ```json { "id": "welcome-user-42", "queue": "emails", "state": "pending", "url": "/hooks/send-welcome", "method": "POST", "headers": { "Content-Type": "application/json" }, "body_base64": "eyJ1c2VyX2lkIjo0Mn0=", "schedule_time": "2026-11-28T10:20:31.007Z", "created_at": "2026-11-28T10:15:00.12Z", "dispatch_deadline_seconds": 600, "dispatch_count": 0, "response_count": 0 } ``` **Errors** | Status | Code | When | |---|---|---| | 400 | `failed_precondition` | The task is being delivered right now, or the queue is `disabled`. | | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | The key or role can't write. | | 404 | `not_found` | No such task or queue, or the task already succeeded, failed, was deleted or was purged. | ## List a task's delivery attempts `GET /v1/queues/{queue}/tasks/{taskID}/attempts` Returns the task's delivery attempts, newest first (up to the 1000 most recent), with the status code, error kind, a snippet of the response body and the duration of each. Use it to debug why a task is failing or retrying. Attempts are kept as long as the task is. **Who can call it:** writer or admin API key; dashboard viewer, member or admin. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `queue` | string | yes | — | Queue name, URL-encoded as one segment (`user%2Finstagram`). | | `taskID` | string | yes | — | The task's ID. | **Example** **TypeScript** ```ts const attempts = await pq.listAttempts("emails", "welcome-user-42"); for (const a of attempts) console.log(a.number, a.responseStatus ?? a.errorKind, a.durationMs); ``` **Python** ```python for a in pq.list_attempts("emails", "welcome-user-42"): print(a.number, a.response_status, a.error_kind, a.duration_ms) ``` **Go** ```go attempts, err := pq.ListAttempts(ctx, "emails", "welcome-user-42") for _, a := range attempts { fmt.Println(a.Number, a.ResponseStatus, a.ErrorKind, a.DurationMS) } ``` **Java** ```java List attempts = pq.listAttempts("emails", "welcome-user-42"); for (Attempt a : attempts) { System.out.printf("#%d status=%s kind=%s %dms%n", a.getNumber(), a.getResponseStatus(), a.getErrorKind(), a.getDurationMs()); } ``` **.NET** ```csharp IReadOnlyList attempts = await pq.ListAttemptsAsync("emails", "welcome-user-42"); foreach (var a in attempts) Console.WriteLine($"#{a.Number} {a.ResponseStatus?.ToString() ?? a.ErrorKind} {a.DurationMs}ms"); ``` **curl** ```bash curl https://api.pushqueue.dev/v1/queues/emails/tasks/welcome-user-42/attempts \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` The SDKs return the list of attempts directly (no page object). **Response** `200 OK`: ```json { "attempts": [ { "number": 2, "dispatch_time": "2026-11-28T11:15:02.41Z", "response_time": "2026-11-28T11:15:02.598Z", "response_status": 200, "duration_ms": 188 }, { "number": 1, "dispatch_time": "2026-11-28T11:15:00.304Z", "response_time": "2026-11-28T11:15:00.511Z", "response_status": 503, "error_kind": "non_2xx", "error_snippet": "upstream unavailable", "duration_ms": 207 } ] } ``` | Field | Type | Description | |---|---|---| | `attempts` | array | Attempts, newest first. Empty array before the first attempt. | | `attempts[].number` | integer | Attempt number, starting at 1. | | `attempts[].dispatch_time` | string (RFC 3339) | When the request was sent. | | `attempts[].response_time` | string (RFC 3339) | When the response arrived. Omitted when there was no response. | | `attempts[].response_status` | integer | HTTP status code. Omitted when there was no response. | | `attempts[].error_kind` | string | Why the attempt failed: `non_2xx`, `timeout`, `connect`, `dns`, `tls`, `config` (the request couldn't be built, e.g. relative path with no `target.base_url`) or `lease_lost` (the worker stopped mid-delivery). Omitted on success. | | `attempts[].error_snippet` | string | Up to 4 KiB of the response body for `non_2xx`, or the error message otherwise. Omitted when empty. | | `attempts[].duration_ms` | integer | How long the attempt took, in milliseconds. | **Errors** | Status | Code | When | |---|---|---| | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | The caller has no read permission. | | 404 | `not_found` | No such task (or it was deleted or purged), or no such queue. | ## Read more - [How tasks work](https://pushqueue.dev/docs/concepts/tasks/): states, scheduling and task IDs. - [Delivery and request headers](https://pushqueue.dev/docs/concepts/delivery/): what your endpoint receives and how to respond. - [Deduplicate tasks with task IDs](https://pushqueue.dev/docs/patterns/deduplication/): use `task_id` as an idempotency key. - [Queues API reference](https://pushqueue.dev/docs/reference/rest/queues/): create and configure the queues tasks go into. - [API error codes](https://pushqueue.dev/docs/reference/errors/): every `code` and what to do about it. --- # API keys API reference > pushq API keys API reference: list, create and revoke writer and admin API keys with /v1/api-keys, including key roles, request examples and error codes. Source: https://pushqueue.dev/docs/reference/rest/api-keys/ The API keys API (`/v1/api-keys`) lists, creates and revokes pushq API keys. API keys authenticate programs that call pushq: your app server, a worker, a deploy script. Each key has a role, `writer` or `admin`, which decides what it can do. These endpoints manage keys created in the dashboard (or through this API). Most people create keys in the dashboard under **Settings → API keys**; use these endpoints when you want to automate key rotation or provisioning. See the [guide to creating and rotating API keys](https://pushqueue.dev/docs/guides/api-keys/) for the bigger picture. The SDKs don't wrap these endpoints; call them over HTTP. All examples use the hosted API at `https://api.pushqueue.dev`. ## API key roles: writer and admin | Capability | `writer` | `admin` | |---|---|---| | Create, upsert, patch, pause, resume and purge queues it knows by name | yes | yes | | Read a queue, its stats, tasks and attempts | yes | yes | | Enqueue, run and delete tasks | yes | yes | | `GET /v1/version` | yes | yes | | List queues (`GET /v1/queues`) | no | yes | | Delete queues | no | yes | | Manage API keys, team members and invites | no | yes | Give services a `writer` key unless they really need to list or delete queues. Keys look like `pq_` followed by 32 URL-safe characters. pushq stores only a SHA-256 hash, so the full key is shown once, when it is created. On the hosted service a key belongs to the team that was active when it was created and only sees that team's queues. Self-hosted servers can also define keys in the server config file; those are not listed or revocable here (see [server configuration](https://pushqueue.dev/docs/self-hosting/configuration/)). ## Who can manage API keys All three endpoints need the **manage** permission: an `admin` API key, or a dashboard user with the `admin` role. A writer key or a member/viewer gets `403 permission_denied`. On a self-hosted server without dashboard accounts enabled they return `404 not_found`. ## The API key object ```json { "id": 17, "name": "billing-service", "prefix": "pq_x7Kp2Qa9", "role": "writer", "created_by": "ana@example.com", "created_at": "2026-11-28T10:15:00.12Z", "last_used_at": "2026-11-28T11:02:44Z" } ``` | Field | Type | Description | |---|---|---| | `id` | integer | Key ID; use it to revoke the key. | | `name` | string | Label for what uses the key. | | `prefix` | string | First 11 characters of the key (`pq_` plus 8), so you can recognise it. | | `role` | string | `writer` or `admin`. | | `created_by` | string | Email of the dashboard user who created it. Omitted when an API key created it. | | `created_at` | string (RFC 3339) | When the key was created. | | `last_used_at` | string (RFC 3339) | When the key last authenticated a request. Updated at most once a minute. Omitted if never used. | ## List API keys `GET /v1/api-keys` Returns the dashboard-managed keys, newest first. On the hosted service you see only the current team's keys. Use it to audit which keys exist and spot ones that haven't been used in a long time. **Who can call it:** admin API key; dashboard admin. No parameters. **Example** ```bash curl https://api.pushqueue.dev/v1/api-keys \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `200 OK`: ```json { "keys": [ { "id": 17, "name": "billing-service", "prefix": "pq_x7Kp2Qa9", "role": "writer", "created_by": "ana@example.com", "created_at": "2026-11-28T10:15:00.12Z", "last_used_at": "2026-11-28T11:02:44Z" }, { "id": 12, "name": "deploy-pipeline", "prefix": "pq_Lm3vT0cE", "role": "admin", "created_at": "2026-10-02T08:00:00Z" } ], "config_keys": 0 } ``` | Field | Type | Description | |---|---|---| | `keys` | array of [API key objects](#the-api-key-object) | Dashboard-managed keys, newest first. | | `config_keys` | integer | How many additional keys the server config file defines (self-hosted). Always `0` on the hosted service. | **Errors** | Status | Code | When | |---|---|---| | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | Not an admin key or admin user. | | 404 | `not_found` | Dashboard accounts are not enabled on this server. | See [API error codes](https://pushqueue.dev/docs/reference/errors/) for the error format. ## Create an API key `POST /v1/api-keys` Creates a key and returns it once, in `secret`. Store it in your secret manager straight away; it can't be retrieved later. Use this to provision a key per service, or to rotate a key: create the new one, deploy it, then [revoke](#revoke-an-api-key) the old one. **Who can call it:** admin API key; dashboard admin. **Request body** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `name` | string | yes | — | What uses the key, e.g. `billing-service`. 1–100 characters after trimming spaces. | | `role` | string | yes | — | `writer` or `admin`. | **Example** ```bash curl -X POST https://api.pushqueue.dev/v1/api-keys \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "billing-service", "role": "writer" }' ``` **Response** `201 Created`: ```json { "key": { "id": 18, "name": "billing-service", "prefix": "pq_9bQe4Rz1", "role": "writer", "created_at": "2026-11-28T12:00:00Z" }, "secret": "pq_9bQe4Rz1Hk2mVxN7cTqL0aYwPf3sUe8D" } ``` | Field | Type | Description | |---|---|---| | `key` | [API key object](#the-api-key-object) | The new key's metadata. `created_by` is set when a dashboard user created it. | | `secret` | string | The API key itself. Shown only in this response. | **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | Invalid JSON, `name` empty or longer than 100 characters, or `role` not `writer`/`admin`. | | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | Not an admin key or admin user. | | 404 | `not_found` | Dashboard accounts are not enabled on this server. | | 413 | `payload_too_large` | Body over 16 KiB. | ## Revoke an API key `DELETE /v1/api-keys/{id}` Deletes a key. Requests that use it fail with `401 unauthenticated` from the next request on. Use it when a key leaks, when a service is retired, or as the last step of a rotation. On the hosted service you can only revoke keys that belong to your current team. **Who can call it:** admin API key; dashboard admin. An admin key can revoke itself. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `id` | integer | yes | — | The key's `id` from the list or create response. | **Example** ```bash curl -X DELETE https://api.pushqueue.dev/v1/api-keys/17 \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `204 No Content` with an empty body. **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | `id` is not a positive integer. | | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | Not an admin key or admin user. | | 404 | `not_found` | No such key in your team, or dashboard accounts are not enabled. | ## Read more - [Create and rotate API keys](https://pushqueue.dev/docs/guides/api-keys/): the dashboard flow and rotation checklist. - [Teams & users API reference](https://pushqueue.dev/docs/reference/rest/teams-and-users/): roles for people instead of programs. - [REST API overview](https://pushqueue.dev/docs/reference/api/): authentication, request format and conventions. - [API error codes](https://pushqueue.dev/docs/reference/errors/): `unauthenticated`, `permission_denied` and the rest. --- # Teams and users API reference > pushq Teams & users API reference: manage your profile, password, teams, team members and roles, password-reset links and invites, hosted or self-hosted. Source: https://pushqueue.dev/docs/reference/rest/teams-and-users/ The teams and users API manages people rather than queues: your own profile (`/v1/me`), the teams you belong to (`/v1/teams`), the members of a team (`/v1/users`) and pending invitations (`/v1/invites`). The dashboard uses all of them; you only need them directly if you are automating member management. For a walkthrough, see [managing team members](https://pushqueue.dev/docs/guides/team-members/). The SDKs don't wrap these endpoints; call them over HTTP. Examples use the hosted API at `https://api.pushqueue.dev`. ## Self-hosted vs hosted accounts pushq runs in one of two account modes, and some endpoints behave differently or exist in only one of them: - **Self-hosted** (no WorkOS configured): the server has one set of users with email/password sign-in. `/v1/users` lists every account on the server. Invites are single-use links you send yourself. - **Hosted / SaaS mode** (WorkOS configured, as on `api.pushqueue.dev`): people sign in with an emailed code or GitHub, and belong to one or more **teams**. Every request acts inside the session's current team; `/v1/users` lists that team's members, and WorkOS emails the invitations. Endpoints marked *self-hosted only* return `404 not_found` in SaaS mode, and endpoints marked *SaaS only* return `404 not_found` on a self-hosted server. All of them return `404 not_found` when dashboard accounts are disabled on a self-hosted server. ## Who can call the account endpoints | Endpoints | Who can call | |---|---| | `/v1/me`, `/v1/me/password`, `GET`/`POST /v1/teams`, `POST /v1/teams/{id}:switch` | A signed-in dashboard user only (session cookie). API keys get `401 unauthenticated`. | | `PATCH /v1/teams/current`, `/v1/users*`, `/v1/invites*` | The **manage** permission: an `admin` API key or a dashboard `admin`. Others get `403 permission_denied`. | Session requests send the `pushq_session` cookie that [sign-in](https://pushqueue.dev/docs/reference/rest/auth/) sets. Any session request that changes something (`POST`, `PATCH`, `DELETE`) must also send an `X-Requested-With` header with any non-empty value, or it fails with `403 permission_denied`; this blocks cross-site request forgery. Requests with an `Authorization` header don't need it. The session examples below use `$PUSHQ_SESSION` for the cookie value. ## Dashboard roles: viewer, member and admin | Role | Can do | |---|---| | `viewer` | See queues, stats, tasks and attempts, list queues. | | `member` | Everything a viewer can, plus create, change, pause, purge and delete queues and enqueue, run and delete tasks. | | `admin` | Everything a member can, plus manage members, invites and API keys. | ## The user object ```json { "id": 3, "email": "ana@example.com", "name": "Ana Lima", "role": "admin", "created_at": "2026-09-14T08:12:00Z", "last_login_at": "2026-11-28T09:01:12Z" } ``` | Field | Type | Description | |---|---|---| | `id` | integer | User ID; use it in `/v1/users/{id}`. | | `email` | string | Email address (lowercase). | | `name` | string | Display name; may be empty. | | `role` | string | `admin`, `member` or `viewer`. In SaaS mode, the role in the current team. | | `created_at` | string (RFC 3339) | When the account was created. | | `last_login_at` | string (RFC 3339) | Last sign-in. Omitted if the user never signed in. | ## The invite object ```json { "id": 9, "kind": "invite", "email": "sam@example.com", "role": "member", "created_at": "2026-11-28T10:00:00Z", "expires_at": "2026-12-05T10:00:00Z" } ``` | Field | Type | Description | |---|---|---| | `id` | integer | Invite ID; use it to revoke the invite. | | `kind` | string | `invite` (a new member) or `reset` (a password-reset link). | | `email` | string | Who it is for. | | `role` | string | Role the new member gets. Omitted for `reset` links. | | `created_at` | string (RFC 3339) | When it was created. | | `expires_at` | string (RFC 3339) | When it stops working. | ## Change your name `PATCH /v1/me` Updates the signed-in user's display name. The dashboard's profile page uses it. **Who can call it:** a signed-in dashboard user (session only). **Request body** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `name` | string | no | unchanged | New display name, at most 100 characters after trimming spaces. Omit to leave it as is. | **Example** ```bash curl -X PATCH https://api.pushqueue.dev/v1/me \ --cookie "pushq_session=$PUSHQ_SESSION" \ -H "X-Requested-With: pushq" \ -H "Content-Type: application/json" \ -d '{ "name": "Ana Lima" }' ``` **Response** `200 OK` with the updated [user object](#the-user-object): ```json { "id": 3, "email": "ana@example.com", "name": "Ana Lima", "role": "admin", "created_at": "2026-09-14T08:12:00Z", "last_login_at": "2026-11-28T09:01:12Z" } ``` **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | Invalid JSON or a name longer than 100 characters. | | 401 | `unauthenticated` | No session (API keys can't call this). | | 403 | `permission_denied` | Missing `X-Requested-With` header. | See [API error codes](https://pushqueue.dev/docs/reference/errors/) for the error format. ## Change your password `POST /v1/me/password` Sets a new password for the signed-in user after checking the current one, and signs them out on every other device (the current session stays valid). *Self-hosted only*: in SaaS mode there are no passwords. **Who can call it:** a signed-in dashboard user (session only). Rate-limited per client IP (10 attempts, then one every 6 seconds). **Request body** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `current_password` | string | yes | — | The user's current password. | | `new_password` | string | yes | — | At least 8 characters and at most 256 bytes. | **Example** ```bash curl -X POST https://pushq.example.com/v1/me/password \ --cookie "pushq_session=$PUSHQ_SESSION" \ -H "X-Requested-With: pushq" \ -H "Content-Type: application/json" \ -d '{ "current_password": "old-password", "new_password": "a-much-longer-passphrase" }' ``` **Response** `204 No Content` with an empty body. **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | Current password wrong, or the new one too short or too long. | | 401 | `unauthenticated` | No session. | | 403 | `permission_denied` | Missing `X-Requested-With` header. | | 404 | `not_found` | SaaS mode. | | 429 | `rate_limited` | Too many attempts; retry after the `Retry-After` seconds. | ## List your teams `GET /v1/teams` Lists the teams the signed-in user belongs to, with their role in each, oldest membership first. The dashboard's team switcher uses it. *SaaS only.* **Who can call it:** a signed-in dashboard user (session only). **Example** ```bash curl https://api.pushqueue.dev/v1/teams \ --cookie "pushq_session=$PUSHQ_SESSION" ``` **Response** `200 OK`: ```json { "teams": [ { "id": 4, "name": "Acme", "role": "admin" }, { "id": 11, "name": "Side project", "role": "viewer" } ] } ``` | Field | Type | Description | |---|---|---| | `teams[].id` | integer | Team ID. | | `teams[].name` | string | Team name. | | `teams[].role` | string | Your role in that team: `admin`, `member` or `viewer`. | **Errors** | Status | Code | When | |---|---|---| | 401 | `unauthenticated` | No session. | | 404 | `not_found` | Not in SaaS mode. | ## Create a team `POST /v1/teams` Creates a new team with the caller as its admin and switches the caller's session to it. Use it to separate environments or projects: each team has its own queues, API keys and members. *SaaS only.* Behind the scenes this creates a WorkOS Organization. **Who can call it:** a signed-in dashboard user (session only). **Request body** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `name` | string | yes | — | Team name, 1–100 characters. | **Example** ```bash curl -X POST https://api.pushqueue.dev/v1/teams \ --cookie "pushq_session=$PUSHQ_SESSION" \ -H "X-Requested-With: pushq" \ -H "Content-Type: application/json" \ -d '{ "name": "Acme staging" }' ``` **Response** `201 Created`: ```json { "id": 15, "name": "Acme staging", "role": "admin" } ``` | Field | Type | Description | |---|---|---| | `id` | integer | New team ID. | | `name` | string | Team name. | | `role` | string | Always `admin` for the creator. | **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | Name empty or longer than 100 characters, or the account isn't linked to WorkOS. | | 400 | `failed_precondition` | WorkOS rejected the request; `detail` explains why. | | 401 | `unauthenticated` | No session. | | 403 | `permission_denied` | Missing `X-Requested-With` header. | | 404 | `not_found` | Not in SaaS mode. | | 502 | `internal` | WorkOS is unavailable; try again. | ## Switch teams `POST /v1/teams/{id}:switch` Makes another of your teams the current team for this session. Every later request on the session (queues, keys, members) acts in that team, and it becomes the team you start in next time you sign in. *SaaS only.* **Who can call it:** a signed-in dashboard user (session only) who is a member of the target team. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `id` | integer | yes | — | ID of a team you belong to. | No request body. **Example** ```bash curl -X POST https://api.pushqueue.dev/v1/teams/11:switch \ --cookie "pushq_session=$PUSHQ_SESSION" \ -H "X-Requested-With: pushq" ``` **Response** `204 No Content` with an empty body. **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | `id` is not an integer. | | 401 | `unauthenticated` | No session. | | 403 | `permission_denied` | Missing `X-Requested-With` header. | | 404 | `not_found` | You aren't a member of that team, or not in SaaS mode. | ## Rename the current team `PATCH /v1/teams/current` Renames the team the caller is acting in (the session's current team, or the team an API key belongs to). The new name is also pushed to WorkOS. *SaaS only.* **Who can call it:** an `admin` API key of the team, or a dashboard admin of the team. **Request body** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `name` | string | yes | — | New team name, 1–100 characters after trimming spaces. | **Example** ```bash curl -X PATCH https://api.pushqueue.dev/v1/teams/current \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Acme production" }' ``` **Response** `200 OK`: ```json { "id": 4, "name": "Acme production", "role": "admin" } ``` | Field | Type | Description | |---|---|---| | `id` | integer | Team ID. | | `name` | string | The new name. | | `role` | string | The caller's role (for an API key, the key's role). | **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | Name empty or longer than 100 characters. | | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | Not an admin of the team. | | 404 | `not_found` | Not in SaaS mode. | ## List members `GET /v1/users` Self-hosted: lists every account on the server. SaaS mode: lists the current team's members, re-synced from WorkOS first (so people who accepted an invite show up), with `role` set to their role in the team. Both are ordered by email. Use it to audit who has access. **Who can call it:** admin API key; dashboard admin. **Example** ```bash curl https://api.pushqueue.dev/v1/users \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `200 OK`: ```json { "users": [ { "id": 3, "email": "ana@example.com", "name": "Ana Lima", "role": "admin", "created_at": "2026-09-14T08:12:00Z", "last_login_at": "2026-11-28T09:01:12Z" }, { "id": 8, "email": "sam@example.com", "name": "", "role": "viewer", "created_at": "2026-11-20T16:40:00Z" } ] } ``` | Field | Type | Description | |---|---|---| | `users` | array of [user objects](#the-user-object) | The members. | **Errors** | Status | Code | When | |---|---|---| | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | Not an admin. | | 404 | `not_found` | Dashboard accounts are not enabled. | ## Change a member `PATCH /v1/users/{id}` Changes a member's role (and, on a self-hosted server, their name). Use it to promote someone to admin or reduce someone to read-only. The last admin can't be demoted, so a team always keeps at least one admin. In SaaS mode only the role can change; names come from WorkOS. **Who can call it:** admin API key; dashboard admin. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `id` | integer | yes | — | The member's user ID. | **Request body** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `role` | string | no (yes in SaaS mode) | unchanged | `admin`, `member` or `viewer`. | | `name` | string | no | unchanged | Self-hosted only: new display name, at most 100 characters. Ignored in SaaS mode. | **Example** ```bash curl -X PATCH https://api.pushqueue.dev/v1/users/8 \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "role": "member" }' ``` **Response** `200 OK` with the updated [user object](#the-user-object): ```json { "id": 8, "email": "sam@example.com", "name": "", "role": "member", "created_at": "2026-11-20T16:40:00Z" } ``` **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | Invalid `id` or JSON, unknown role, name too long, or (SaaS mode) no `role` given. | | 400 | `failed_precondition` | The change would leave the team without an admin. | | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | Not an admin. | | 404 | `not_found` | No such user, or not a member of the current team. | ## Remove a member `DELETE /v1/users/{id}` Removes someone's access immediately. Self-hosted: deletes the account and all its sessions. SaaS mode: removes them from the current team (their sessions in that team lose access at once, and the WorkOS membership is deleted); their account and other teams are untouched. The last admin can't be removed. **Who can call it:** admin API key; dashboard admin. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `id` | integer | yes | — | The member's user ID. | **Example** ```bash curl -X DELETE https://api.pushqueue.dev/v1/users/8 \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `204 No Content` with an empty body. **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | `id` is not a positive integer. | | 400 | `failed_precondition` | They are the last admin. | | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | Not an admin. | | 404 | `not_found` | No such user, or not a member of the current team. | ## Create a password-reset link `POST /v1/users/{id}/reset-link` Creates a single-use link that lets a user set a new password, for when someone is locked out. Send them the link; opening it in the dashboard and choosing a password signs them out everywhere else. The link is valid for 24 hours and replaces any earlier reset link for that user. *Self-hosted only.* **Who can call it:** admin API key; dashboard admin. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `id` | integer | yes | — | The user's ID. | No request body. **Example** ```bash curl -X POST https://pushq.example.com/v1/users/8/reset-link \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `201 Created`: ```json { "link": { "id": 21, "kind": "reset", "email": "sam@example.com", "created_at": "2026-11-28T12:30:00Z", "expires_at": "2026-11-29T12:30:00Z" }, "path": "/invite#token=pqi_4p0yN8cJ2wqZbX1sRk7mT3vLhD9eF6aGuQ5iW0oYcEs" } ``` | Field | Type | Description | |---|---|---| | `link` | [invite object](#the-invite-object) | The reset link's metadata (`kind` is `reset`, no `role`). | | `path` | string | The single-use link, relative to your server. Prepend your server's URL before sending it. | **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | `id` is not a positive integer. | | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | Not an admin. | | 404 | `not_found` | No such user, SaaS mode, or dashboard accounts disabled. | ## List pending invites `GET /v1/invites` Lists invitations that haven't been accepted or expired yet. Self-hosted: invite links created with [Invite someone](#invite-someone), newest first. SaaS mode: the current team's pending WorkOS invitations. **Who can call it:** admin API key; dashboard admin. **Example** ```bash curl https://api.pushqueue.dev/v1/invites \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `200 OK`: ```json { "invites": [ { "id": 9, "kind": "invite", "email": "sam@example.com", "role": "member", "created_at": "2026-11-28T10:00:00Z", "expires_at": "2026-12-05T10:00:00Z" } ] } ``` | Field | Type | Description | |---|---|---| | `invites` | array of [invite objects](#the-invite-object) | Pending invites. | **Errors** | Status | Code | When | |---|---|---| | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | Not an admin. | | 404 | `not_found` | Dashboard accounts are not enabled. | | 502 | `internal` | SaaS mode: WorkOS is unavailable. | ## Invite someone `POST /v1/invites` Invites a person to join with a given role. Self-hosted: returns a single-use link (valid 7 days) that you send them yourself; opening it lets them pick a name and password. Inviting the same email again replaces the earlier invite. SaaS mode: WorkOS emails the invitation, and the role is applied when they join. **Who can call it:** admin API key; dashboard admin. **Request body** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `email` | string | yes | — | Email address to invite. | | `role` | string | yes | — | `admin`, `member` or `viewer`. | **Example** ```bash curl -X POST https://api.pushqueue.dev/v1/invites \ -H "Authorization: Bearer $PUSHQ_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "email": "sam@example.com", "role": "member" }' ``` **Response** `201 Created`. On a self-hosted server: ```json { "invite": { "id": 9, "kind": "invite", "email": "sam@example.com", "role": "member", "created_at": "2026-11-28T10:00:00Z", "expires_at": "2026-12-05T10:00:00Z" }, "path": "/invite#token=pqi_Zr8wK1nQ3yT0vB6xM2cL9pH4dF7aJ5sE1uG8iO3kYqA" } ``` In SaaS mode: ```json { "invite": { "id": 9, "kind": "invite", "email": "sam@example.com", "role": "member", "created_at": "2026-11-28T10:00:00Z", "expires_at": "2026-12-05T10:00:00Z" }, "emailed": true } ``` | Field | Type | Description | |---|---|---| | `invite` | [invite object](#the-invite-object) | The new invite. | | `path` | string | Self-hosted only: the single-use invite link, relative to your server. | | `emailed` | boolean | SaaS mode only: `true`, WorkOS emailed the invitation. | **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | Invalid email or role. | | 400 | `failed_precondition` | SaaS mode: WorkOS rejected the invitation; `detail` explains why. | | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | Not an admin. | | 404 | `not_found` | Dashboard accounts are not enabled. | | 409 | `already_exists` | Self-hosted: a user with that email already exists. | | 502 | `internal` | SaaS mode: WorkOS is unavailable. | ## Revoke an invite `DELETE /v1/invites/{id}` Cancels a pending invite so its link (or emailed invitation) no longer works. **Who can call it:** admin API key; dashboard admin. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `id` | integer | yes | — | The invite's `id`. | **Example** ```bash curl -X DELETE https://api.pushqueue.dev/v1/invites/9 \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `204 No Content` with an empty body. **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | `id` is not a positive integer. | | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | Not an admin. | | 404 | `not_found` | No such pending invite. | | 502 | `internal` | SaaS mode: WorkOS is unavailable. | ## Read more - [Managing team members](https://pushqueue.dev/docs/guides/team-members/): invite people and choose roles in the dashboard. - [Auth API reference](https://pushqueue.dev/docs/reference/rest/auth/): sign-in, setup and invite-link endpoints. - [API keys API reference](https://pushqueue.dev/docs/reference/rest/api-keys/): keys for programs instead of people. - [Running pushq in SaaS mode](https://pushqueue.dev/docs/self-hosting/saas-mode/): WorkOS teams on your own server. --- # Auth API reference > pushq Auth API reference for dashboard sign-in: session info, self-hosted setup, password login and invite links, and hosted email-code and GitHub sign-in. Source: https://pushqueue.dev/docs/reference/rest/auth/ The Auth API (`/v1/auth/*`) signs people in to the pushq dashboard: it reports the current session, runs first-time setup and password sign-in on self-hosted servers, and handles email-code and GitHub sign-in on the hosted service. They exist mainly for the dashboard's own sign-in pages; programs that call pushq should use an [API key](https://pushqueue.dev/docs/reference/rest/api-keys/) instead of a session. You'd call these directly to build a custom sign-in flow, to script first-time setup of a self-hosted server, or to debug sign-in. The SDKs don't wrap these endpoints; call them over HTTP. ## Self-hosted vs hosted sign-in endpoints pushq has two sign-in modes. Endpoints that don't apply to the server's mode return `404 not_found`. | Endpoint | Self-hosted | Hosted / SaaS mode | |---|---|---| | `GET /v1/auth/session` | yes | yes | | `POST /v1/auth/logout` | yes | yes | | `POST /v1/auth/setup` | yes | no | | `POST /v1/auth/login` | yes | no | | `GET /v1/auth/invites/{token}` | yes | no | | `POST /v1/auth/invites/{token}:accept` | yes | no | | `POST /v1/auth/email-code` | no | yes | | `POST /v1/auth/email-code:verify` | no | yes | | `GET /v1/auth/email-verification` | yes (always reports nothing pending) | yes | | `POST /v1/auth/email-verification` | no | yes | | `GET /v1/auth/workos/login` | no | yes | | `GET /v1/auth/workos/callback` | no | yes | *Self-hosted* means email-and-password accounts stored by your server (they also need dashboard accounts enabled; otherwise those endpoints return `404`). *SaaS mode* means WorkOS is configured, as on `https://api.pushqueue.dev`: people sign in with a code sent to their email or with GitHub, and there are no passwords. See [SaaS mode](https://pushqueue.dev/docs/self-hosting/saas-mode/) for running it yourself. ## Session cookies, CSRF protection and rate limits A successful sign-in sets the `pushq_session` cookie: `HttpOnly`, `SameSite=Strict`, `Path=/`, `Secure` when the request came over HTTPS (directly or via `X-Forwarded-Proto: https`). Sessions last 30 days and slide: a session used in its last 15 days is extended to 30 days again and the cookie is re-issued. Every `POST` to `/v1/auth/*` that doesn't carry an `Authorization` header must send an `X-Requested-With` header with any non-empty value (the dashboard sends `pushq`). Without it the request fails with `403 permission_denied`. Browsers only let same-origin scripts set custom headers, so this blocks cross-site forgery. The examples below send it and keep cookies in a file with `curl -c`/`-b`. Endpoints that check passwords or codes (`setup`, `login`, invite `:accept`, `email-code`, `email-code:verify`, `POST email-verification`) are rate-limited per client IP: 10 attempts, refilling one every 6 seconds. Over the limit they return `429 rate_limited` with `Retry-After: 6`. None of these endpoints need credentials. ## The sign-in response `setup`, `login`, invite `:accept` and `email-code:verify` all answer with the signed-in user: ```json { "user": { "id": 3, "email": "ana@example.com", "name": "Ana Lima", "role": "admin", "created_at": "2026-09-14T08:12:00Z", "last_login_at": "2026-11-28T09:01:12Z" } } ``` | Field | Type | Description | |---|---|---| | `user.id` | integer | User ID. | | `user.email` | string | Email address (lowercase). | | `user.name` | string | Display name; may be empty. | | `user.role` | string | `admin`, `member` or `viewer`. In SaaS mode this is the stored account role; the team role is in `GET /v1/auth/session`. | | `user.created_at` | string (RFC 3339) | When the account was created. | | `user.last_login_at` | string (RFC 3339) | Last sign-in. Omitted if never signed in. | ## Get the current session `GET /v1/auth/session` Tells the caller who they are and how this server signs people in. The dashboard calls it on load to decide whether to show first-time setup, the sign-in page, a team picker or the app. It never fails for lack of credentials; it reports `authenticated: false` instead. It also works with an API key, which makes it a handy way to check what a key is allowed to do. **Who can call it:** anyone. Applies in every mode. **Example** ```bash curl https://api.pushqueue.dev/v1/auth/session \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `200 OK`. For a hosted dashboard user: ```json { "mode": "saas", "setup_required": false, "setup_requires_key": false, "authenticated": true, "kind": "user", "role": "admin", "user": { "id": 3, "email": "ana@example.com", "name": "Ana Lima", "role": "admin", "created_at": "2026-09-14T08:12:00Z", "last_login_at": "2026-11-28T09:01:12Z" }, "permissions": { "read": true, "list": true, "write": true, "delete_queue": true, "manage": true }, "sso_providers": ["workos"], "team": { "id": 4, "name": "Acme", "role": "admin" }, "teams": [ { "id": 4, "name": "Acme", "role": "admin" }, { "id": 11, "name": "Side project", "role": "viewer" } ], "needs_team": false } ``` For a writer API key on a self-hosted server: ```json { "mode": "locked", "setup_required": false, "setup_requires_key": false, "authenticated": true, "kind": "api_key", "role": "writer", "key_name": "billing-service", "permissions": { "read": true, "list": false, "write": true, "delete_queue": false, "manage": false }, "sso_providers": [], "needs_team": false } ``` | Field | Type | Description | |---|---|---| | `mode` | string | `dev` (authentication disabled), `open` (self-hosted with no API keys and no accounts yet, so no credentials are needed), `locked` (self-hosted, credentials required) or `saas`. | | `setup_required` | boolean | Self-hosted: no dashboard account exists yet, so the dashboard should offer [first-time setup](#create-the-first-admin-account). Always `false` in SaaS and dev mode. | | `setup_requires_key` | boolean | Setup is required and the server has config-file API keys, so setup needs one of its admin keys. | | `authenticated` | boolean | Whether the request carried valid credentials (always `true` in `open` and `dev` mode). | | `kind` | string | `user` (session cookie), `api_key` or `open`. Omitted when not authenticated. | | `role` | string | The caller's role: user role, key role, or `admin` when open. In SaaS mode, the role in the current team. Omitted when there is none. | | `user` | object | The signed-in user ([user fields](#the-sign-in-response)). Omitted for API keys and anonymous callers. | | `key_name` | string | Name of the API key used (`config file` for keys from the server config). Omitted otherwise. | | `permissions.read` | boolean | Can view queues, stats, tasks and attempts by name. | | `permissions.list` | boolean | Can list every queue and read `/metrics`. | | `permissions.write` | boolean | Can create and change queues and enqueue, run and delete tasks. | | `permissions.delete_queue` | boolean | Can delete queues. | | `permissions.manage` | boolean | Can manage members, invites and API keys. | | `sso_providers` | array of strings | Single sign-on options for the sign-in page: `["workos"]` in SaaS mode, otherwise empty. | | `team` | object | SaaS mode: the current team (`id`, `name`, `role`). Omitted when there is none. | | `teams` | array | SaaS mode, signed-in users: every team the user belongs to (`id`, `name`, `role`). Omitted otherwise. | | `needs_team` | boolean | SaaS mode: the user is signed in but has no current team yet and must create or pick one. Until then they have no queue permissions. | **Errors** Only `500 internal` on a server-side failure. See [API error codes](https://pushqueue.dev/docs/reference/errors/). ## Create the first admin account `POST /v1/auth/setup` Creates the first dashboard account, as an `admin`, and signs it in. It works only while the server has no accounts at all; after that, add people with [invites](https://pushqueue.dev/docs/reference/rest/teams-and-users/#invite-someone). Creating the first account ends `open` mode: from then on every API request needs a session or an API key. *Self-hosted only.* If the server's config file defines API keys, the server is already protected, so setup also requires one of those keys with the `admin` role, in `api_key` or in an `Authorization: Bearer` header. This stops anyone who can reach the dashboard from claiming it. **Who can call it:** anyone (no credentials), subject to the rules above. Rate-limited. **Request body** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `email` | string | yes | — | Admin's email address (stored lowercase). | | `password` | string | yes | — | At least 8 characters and at most 256 bytes. | | `name` | string | no | `""` | Display name, at most 100 characters. | | `api_key` | string | only when config-file keys exist | — | An `admin` key from the server config. Can instead be sent as `Authorization: Bearer `. | **Example** ```bash curl -X POST https://pushq.example.com/v1/auth/setup \ -c cookies.txt \ -H "X-Requested-With: pushq" \ -H "Content-Type: application/json" \ -d '{ "email": "ana@example.com", "name": "Ana Lima", "password": "a-long-passphrase" }' ``` **Response** `201 Created` with the [sign-in response](#the-sign-in-response) and a `Set-Cookie: pushq_session=...` header. ```json { "user": { "id": 1, "email": "ana@example.com", "name": "Ana Lima", "role": "admin", "created_at": "2026-11-28T12:00:00Z", "last_login_at": "2026-11-28T12:00:00Z" } } ``` **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | Invalid JSON or email, password too short or long, name too long. | | 400 | `failed_precondition` | Setup is already done (an account exists). | | 403 | `permission_denied` | Config-file keys exist and no admin config key was given, or the `X-Requested-With` header is missing. | | 404 | `not_found` | SaaS mode, or dashboard accounts are disabled. | | 413 | `payload_too_large` | Body over 16 KiB. | | 429 | `rate_limited` | Too many attempts. | ## Sign in with email and password `POST /v1/auth/login` Checks an email and password and starts a session. *Self-hosted only.* Wrong email and wrong password give the same error, so the response doesn't reveal which accounts exist. **Who can call it:** anyone. Rate-limited. **Request body** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `email` | string | yes | — | Account email (case-insensitive). | | `password` | string | yes | — | Account password. | **Example** ```bash curl -X POST https://pushq.example.com/v1/auth/login \ -c cookies.txt \ -H "X-Requested-With: pushq" \ -H "Content-Type: application/json" \ -d '{ "email": "ana@example.com", "password": "a-long-passphrase" }' ``` **Response** `200 OK` with the [sign-in response](#the-sign-in-response) and a `Set-Cookie: pushq_session=...` header. ```json { "user": { "id": 1, "email": "ana@example.com", "name": "Ana Lima", "role": "admin", "created_at": "2026-11-28T12:00:00Z", "last_login_at": "2026-11-28T14:21:07Z" } } ``` **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | Invalid JSON. | | 401 | `unauthenticated` | Unknown email or wrong password. | | 403 | `permission_denied` | Missing `X-Requested-With` header. | | 404 | `not_found` | SaaS mode, or dashboard accounts are disabled. | | 429 | `rate_limited` | Too many attempts. | ## Sign out `POST /v1/auth/logout` Ends the current session on the server and clears the cookie. It succeeds even if there was no session. Applies in every mode. **Who can call it:** anyone. **Example** ```bash curl -X POST https://api.pushqueue.dev/v1/auth/logout \ -b cookies.txt \ -H "X-Requested-With: pushq" ``` **Response** `204 No Content` with an empty body and a `Set-Cookie` header that deletes `pushq_session`. **Errors** | Status | Code | When | |---|---|---| | 403 | `permission_denied` | Missing `X-Requested-With` header. | ## Look up an invite or reset link `GET /v1/auth/invites/{token}` Shows what an invite or password-reset link is for, without using it up. The dashboard's `/invite` page calls it to show "You've been invited as member" or "Reset the password for ana@example.com". Invite and reset links look like `https://pushq.example.com/invite#token=pqi_...`; the token is the part after `token=`. *Self-hosted only.* **Who can call it:** anyone holding the token. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `token` | string | yes | — | The `pqi_...` token from the link. | **Example** ```bash curl https://pushq.example.com/v1/auth/invites/pqi_Zr8wK1nQ3yT0vB6xM2cL9pH4dF7aJ5sE1uG8iO3kYqA ``` **Response** `200 OK`: ```json { "id": 9, "kind": "invite", "email": "sam@example.com", "role": "member", "created_at": "2026-11-28T10:00:00Z", "expires_at": "2026-12-05T10:00:00Z" } ``` | Field | Type | Description | |---|---|---| | `id` | integer | Invite ID. | | `kind` | string | `invite` (creates a new account) or `reset` (sets a new password for an existing one). | | `email` | string | The account email. | | `role` | string | Role the new account gets. Omitted for `reset`. | | `created_at` | string (RFC 3339) | When the link was created. | | `expires_at` | string (RFC 3339) | When it stops working (7 days for invites, 24 hours for reset links). | **Errors** | Status | Code | When | |---|---|---| | 404 | `not_found` | The link is invalid, already used or expired; or SaaS mode. | ## Accept an invite or reset link `POST /v1/auth/invites/{token}:accept` Uses an invite or reset link and signs the person in. For an invite it creates the account with the invited email and role. For a reset link it sets the new password and signs the user out of every other session. Each link works once. *Self-hosted only.* **Who can call it:** anyone holding the token. Rate-limited. **Path parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `token` | string | yes | — | The `pqi_...` token from the link. | **Request body** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `password` | string | yes | — | New password: at least 8 characters, at most 256 bytes. | | `name` | string | no | `""` | Display name, at most 100 characters. Used for new accounts; ignored by reset links. | **Example** ```bash curl -X POST https://pushq.example.com/v1/auth/invites/pqi_Zr8wK1nQ3yT0vB6xM2cL9pH4dF7aJ5sE1uG8iO3kYqA:accept \ -c cookies.txt \ -H "X-Requested-With: pushq" \ -H "Content-Type: application/json" \ -d '{ "name": "Sam Ortiz", "password": "another-long-passphrase" }' ``` **Response** `200 OK` with the [sign-in response](#the-sign-in-response) and a `Set-Cookie: pushq_session=...` header. ```json { "user": { "id": 8, "email": "sam@example.com", "name": "Sam Ortiz", "role": "member", "created_at": "2026-11-28T15:00:00Z", "last_login_at": "2026-11-28T15:00:00Z" } } ``` **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | Invalid JSON, password too short or long, name too long. | | 403 | `permission_denied` | Missing `X-Requested-With` header. | | 404 | `not_found` | The link is invalid, already used or expired; or SaaS mode. | | 409 | `already_exists` | An account with the invited email already exists. | | 429 | `rate_limited` | Too many attempts. | ## Email a sign-in code `POST /v1/auth/email-code` Emails a 6-digit sign-in code to the address. If the email has no account yet, one is created, so this is also how people sign up. The response is the same either way and doesn't reveal whether the address already had an account. Follow up with [Sign in with the emailed code](#sign-in-with-the-emailed-code). *SaaS only.* **Who can call it:** anyone. Rate-limited. **Request body** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `email` | string | yes | — | Email address; must contain `@`, no spaces, at most 254 characters. Case-insensitive. | **Example** ```bash curl -X POST https://api.pushqueue.dev/v1/auth/email-code \ -H "X-Requested-With: pushq" \ -H "Content-Type: application/json" \ -d '{ "email": "ana@example.com" }' ``` **Response** `200 OK`: ```json { "sent": true } ``` | Field | Type | Description | |---|---|---| | `sent` | boolean | Always `true` on success. | **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | Invalid JSON or email. | | 400 | `failed_precondition` | WorkOS rejected the request; `detail` explains why. | | 403 | `permission_denied` | Missing `X-Requested-With` header. | | 404 | `not_found` | Not in SaaS mode. | | 413 | `payload_too_large` | Body over 4 KiB. | | 429 | `rate_limited` | Too many attempts. | | 502 | `internal` | WorkOS is unavailable. | ## Sign in with the emailed code `POST /v1/auth/email-code:verify` Checks the code from the email and starts a session. Entering the code proves the person owns the inbox, so the email is marked verified. The session starts in the team the user last used (or their first team; `needs_team` in [the session](#get-the-current-session) tells you if they have none). *SaaS only.* If WorkOS needs a separate email-verification step, this answers `403 email_verification_required` and sets a short-lived `pushq_email_verify` cookie (15 minutes); finish with [Finish a paused sign-in](#finish-a-paused-sign-in). **Who can call it:** anyone. Rate-limited. **Request body** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `email` | string | yes | — | The address the code was sent to. | | `code` | string | yes | — | The 6-digit code. | **Example** ```bash curl -X POST https://api.pushqueue.dev/v1/auth/email-code:verify \ -c cookies.txt \ -H "X-Requested-With: pushq" \ -H "Content-Type: application/json" \ -d '{ "email": "ana@example.com", "code": "482913" }' ``` **Response** `200 OK` with the [sign-in response](#the-sign-in-response) and a `Set-Cookie: pushq_session=...` header. ```json { "user": { "id": 3, "email": "ana@example.com", "name": "Ana Lima", "role": "member", "created_at": "2026-09-14T08:12:00Z", "last_login_at": "2026-11-28T09:01:12Z" } } ``` **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | Invalid JSON, or email or code missing. | | 400 | `failed_precondition` | The sign-in can't complete, for example the email is linked to a different account; `detail` explains. | | 401 | `unauthenticated` | The code is wrong or expired. | | 403 | `email_verification_required` | WorkOS emailed a verification code; finish with `POST /v1/auth/email-verification`. | | 403 | `permission_denied` | Missing `X-Requested-With` header. | | 404 | `not_found` | Not in SaaS mode. | | 429 | `rate_limited` | Too many attempts. | | 502 | `internal` | WorkOS is unavailable. | ## Check for a paused sign-in `GET /v1/auth/email-verification` Reports whether this browser has a sign-in waiting for an email verification code, and which address the code went to. The sign-in page calls it after being sent to `/login?verify=1`. It reads the `pushq_email_verify` cookie, so without that cookie it reports nothing pending. **Who can call it:** anyone. Works in every mode, but only SaaS mode ever pauses a sign-in. **Example** ```bash curl https://api.pushqueue.dev/v1/auth/email-verification \ -b cookies.txt ``` **Response** `200 OK`: ```json { "pending": true, "email": "ana@example.com" } ``` | Field | Type | Description | |---|---|---| | `pending` | boolean | A sign-in is waiting for an email verification code. | | `email` | string | Where the verification code was sent. Empty when nothing is pending. | **Errors** None specific to this endpoint. ## Finish a paused sign-in `POST /v1/auth/email-verification` Completes a sign-in that was paused for email verification (after `email-code:verify` answered `email_verification_required`, or a GitHub sign-in redirected to `/login?verify=1`). Send the code from the verification email; the paused sign-in is identified by the `pushq_email_verify` cookie. *SaaS only.* **Who can call it:** anyone with the pending-verification cookie. Rate-limited. **Request body** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `code` | string | yes | — | The code from the verification email. | **Example** ```bash curl -X POST https://api.pushqueue.dev/v1/auth/email-verification \ -b cookies.txt -c cookies.txt \ -H "X-Requested-With: pushq" \ -H "Content-Type: application/json" \ -d '{ "code": "907315" }' ``` **Response** `200 OK` with a `Set-Cookie: pushq_session=...` header (and the pending-verification cookie cleared): ```json { "user": { "id": 3, "email": "ana@example.com", "name": "Ana Lima", "role": "member", "created_at": "2026-09-14T08:12:00Z", "last_login_at": "2026-11-28T09:01:12Z" }, "next": "/queues" } ``` | Field | Type | Description | |---|---|---| | `user` | object | The signed-in user ([user fields](#the-sign-in-response)). | | `next` | string | Dashboard path to go to next (from the original sign-in's `next`, or `/`). | **Errors** | Status | Code | When | |---|---|---| | 400 | `invalid_argument` | Invalid JSON. | | 400 | `failed_precondition` | No pending verification (cookie missing or older than 15 minutes), or the sign-in can't complete; `detail` explains. | | 401 | `unauthenticated` | The code is wrong or expired. | | 403 | `permission_denied` | Missing `X-Requested-With` header. | | 404 | `not_found` | Not in SaaS mode. | | 429 | `rate_limited` | Too many attempts. | | 502 | `internal` | WorkOS is unavailable. | ## Start GitHub sign-in `GET /v1/auth/workos/login` Starts a GitHub sign-in through WorkOS. This is a browser navigation, not an API call: link the "Sign in with GitHub" button to it. It sets a short-lived state cookie (10 minutes) and redirects to GitHub's consent screen. *SaaS only.* **Who can call it:** anyone (a browser). **Query parameters** | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `provider` | string | yes | — | Sign-in provider. Only `github` is supported. | | `next` | string | no | `/` | Dashboard path to return to afterwards. Must be a path on the same site (not `//host`, not under `/v1/`); anything else becomes `/`. | **Example** ```bash curl -i "https://api.pushqueue.dev/v1/auth/workos/login?provider=github&next=/queues" ``` **Response** `302 Found` with a `Location` header pointing at GitHub. An unknown `provider` redirects to `/login?error=Unknown%20sign-in%20option.` instead. **Errors** | Status | Code | When | |---|---|---| | 404 | `not_found` | Not in SaaS mode. | ## Handle the GitHub sign-in callback `GET /v1/auth/workos/callback` Where WorkOS sends the browser back after GitHub. It checks the state cookie set by [Start GitHub sign-in](#start-github-sign-in), exchanges the code with WorkOS, creates the session and redirects into the dashboard. You don't call it yourself, but its URL must be registered as a redirect URI in your WorkOS dashboard when you run [SaaS mode](https://pushqueue.dev/docs/self-hosting/saas-mode/). *SaaS only.* **Who can call it:** the browser, coming from WorkOS. **Query parameters** Set by WorkOS, not by you. | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | `code` | string | yes | — | Authorization code from WorkOS. | | `state` | string | yes | — | Must match the state cookie. | | `error` | string | no | — | Set by WorkOS when sign-in was cancelled or failed. | | `error_description` | string | no | — | Human-readable reason for `error`. | **Response** Always `302 Found`: | Redirect target | When | |---|---| | The `next` path from the login step (default `/`) | Signed in; `Set-Cookie: pushq_session=...` is included. | | `/login?verify=1` | WorkOS requires email verification first; finish with [Finish a paused sign-in](#finish-a-paused-sign-in). | | `/login?error=` | State cookie missing or expired, state mismatch, cancelled at GitHub, or WorkOS rejected the sign-in. | **Errors** | Status | Code | When | |---|---|---| | 404 | `not_found` | Not in SaaS mode. | ## Read more - [Using the dashboard](https://pushqueue.dev/docs/guides/dashboard/): what people see after signing in. - [Teams & users API reference](https://pushqueue.dev/docs/reference/rest/teams-and-users/): invites, roles and teams. - [Running pushq in SaaS mode](https://pushqueue.dev/docs/self-hosting/saas-mode/): set up WorkOS email-code and GitHub sign-in. - [Self-hosted server configuration](https://pushqueue.dev/docs/self-hosting/configuration/): config-file API keys and dev mode. --- # Health, metrics and version endpoints > pushq system endpoints: /healthz and /readyz health checks, Prometheus /metrics, /v1/version, and the /openapi.json spec with its /docs Swagger UI. Source: https://pushqueue.dev/docs/reference/rest/system/ pushq's system endpoints sit outside the queue and task API: liveness and readiness health checks, Prometheus metrics, the server version, and the OpenAPI spec with its Swagger UI. Use them for load-balancer health checks, Prometheus scraping, checking which server version you're talking to, and generating clients or browsing the API interactively. Most matter when you [run pushq yourself](https://pushqueue.dev/docs/self-hosting/operations/); `/v1/version`, `/openapi.json` and `/docs` are useful against the hosted API too. The SDKs don't wrap these endpoints; call them over HTTP. | Endpoint | Auth | Purpose | |---|---|---| | `GET /healthz` | none | Liveness: the process is up. | | `GET /readyz` | none | Readiness: the database is reachable. | | `GET /metrics` | none by default (configurable) | Prometheus metrics. | | `GET /v1/version` | API key or session | Server version and database type. | | `GET /openapi.json` | none | OpenAPI 3 document for the API. | | `GET /docs` | none | Interactive API reference (Swagger UI). | ## Check liveness (healthz) `GET /healthz` Answers `ok` as long as the process is running and serving HTTP. It doesn't touch the database. Use it as a liveness probe: if it stops answering, restart the process. **Who can call it:** anyone, no credentials. **Example** ```bash curl https://api.pushqueue.dev/healthz ``` **Response** `200 OK` with `Content-Type: text/plain` and the body: ```text ok ``` **Errors** None; if the process can't answer, the request fails at the network level. ## Check readiness (readyz) `GET /readyz` Pings the database and reports this replica's role. Use it as a readiness probe or load-balancer health check, so traffic only goes to replicas that can reach the database. **Who can call it:** anyone, no credentials. **Example** ```bash curl https://api.pushqueue.dev/readyz ``` **Response** `200 OK`: ```json { "role": "leader", "dialect": "postgres" } ``` | Field | Type | Description | |---|---|---| | `role` | string | `leader` on the replica currently running the dispatcher, `follower` on replicas waiting to take over, `stopped` while the dispatcher is shutting down, or `api` when the server runs without a dispatcher. | | `dialect` | string | Database backend: `sqlite` or `postgres`. | **Errors** | Status | Code | When | |---|---|---| | 503 | `internal` | The database is unreachable (`detail`: `database unreachable`). | See [API error codes](https://pushqueue.dev/docs/reference/errors/) for the error format. ## Scrape Prometheus metrics `GET /metrics` Serves Prometheus metrics in the text exposition format: dispatch counts by response class, errors by kind, dispatch latency, retries, dead-lettered tasks, expired leases, in-flight dispatches and active queues, plus standard Go runtime and process metrics. Use it to scrape a self-hosted server into Prometheus or Grafana. For per-queue numbers, use [queue stats](https://pushqueue.dev/docs/reference/rest/queues/#get-queue-stats) instead. **Who can call it:** anyone by default. When `metrics.public` is turned off in the server config (`PUSHQ_METRICS_PUBLIC=false`), it needs the **list** permission: an `admin` API key, or a dashboard viewer, member or admin. In SaaS mode with metrics not public, only the operator's config-file API keys can read it, since metrics cover every team on the instance. See [server configuration](https://pushqueue.dev/docs/self-hosting/configuration/). **Example** ```bash curl https://pushq.example.com/metrics \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `200 OK` with Prometheus text format (abridged): ```text # HELP pushq_dispatches_total Task dispatch attempts by response code class. # TYPE pushq_dispatches_total counter pushq_dispatches_total{code_class="2xx"} 15320 pushq_dispatches_total{code_class="5xx"} 41 # HELP pushq_dispatch_errors_total Failed dispatch attempts by error kind. # TYPE pushq_dispatch_errors_total counter pushq_dispatch_errors_total{error_kind="non_2xx"} 41 pushq_dispatch_errors_total{error_kind="timeout"} 3 # HELP pushq_dispatch_inflight Dispatches currently in flight. # TYPE pushq_dispatch_inflight gauge pushq_dispatch_inflight 7 ``` | Metric | Type | Description | |---|---|---| | `pushq_dispatches_total{code_class}` | counter | Dispatch attempts by response class: `2xx`, `3xx`, `4xx`, `5xx`, or `error` when no response arrived. | | `pushq_dispatch_errors_total{error_kind}` | counter | Failed attempts by error kind (`non_2xx`, `timeout`, `connect`, `dns`, `tls`, `config`). | | `pushq_dispatch_duration_seconds` | histogram | Dispatch round-trip latency. | | `pushq_tasks_claimed_total` | counter | Tasks leased by the dispatcher. | | `pushq_task_retries_total` | counter | Attempts rescheduled for retry. | | `pushq_tasks_dead_lettered_total` | counter | Tasks copied to a dead-letter queue. | | `pushq_leases_expired_total` | counter | Leases reclaimed by the sweeper. | | `pushq_dispatch_inflight` | gauge | Dispatches currently in flight. | | `pushq_active_queues` | gauge | Queues tracked by the scheduler. | **Errors** | Status | Code | When | |---|---|---| | 401 | `unauthenticated` | Metrics aren't public and no valid credentials were sent. | | 403 | `permission_denied` | The caller lacks the list permission (for example a writer key), or, in SaaS mode, isn't an operator key. | ## Get the server version `GET /v1/version` Returns the server's version, the commit it was built from, and its database backend. Use it to confirm which release you're talking to after an upgrade, or to include in bug reports. **Who can call it:** any API key (writer or admin) or dashboard user (viewer, member or admin). **Example** ```bash curl https://api.pushqueue.dev/v1/version \ -H "Authorization: Bearer $PUSHQ_API_KEY" ``` **Response** `200 OK`: ```json { "version": "1.0.0", "commit": "3f9c2ab", "dialect": "postgres" } ``` | Field | Type | Description | |---|---|---| | `version` | string | Release version (`dev` for local builds). | | `commit` | string | Git commit the binary was built from (`none` for local builds). | | `dialect` | string | Database backend: `sqlite` or `postgres`. | **Errors** | Status | Code | When | |---|---|---| | 401 | `unauthenticated` | No valid credentials. | | 403 | `permission_denied` | The caller has no read permission (for example a SaaS user with no team selected). | ## Download the OpenAPI spec `GET /openapi.json` Returns the OpenAPI document for the API, generated from the running server's routes, so it always matches the version you're calling. Use it to generate a client in a language without an SDK, to import the API into Postman or Insomnia, or to diff API changes between releases. **Who can call it:** anyone, no credentials. **Example** ```bash curl https://api.pushqueue.dev/openapi.json -o pushq-openapi.json ``` **Response** `200 OK` with `Content-Type: application/json` (abridged): ```json { "openapi": "3.1.0", "info": { "title": "pushq API", "version": "1.0.0" }, "components": { "securitySchemes": { "apiKey": { "type": "http", "scheme": "bearer" }, "session": { "type": "apiKey", "in": "cookie", "name": "pushq_session" } } }, "paths": { "/v1/queues": { "get": { "summary": "List queues" } } } } ``` The document describes every route on this site's REST reference: paths, parameters, request and response schemas, and which endpoints need an API key or session. **Errors** None specific to this endpoint. ## Browse the interactive API docs `GET /docs` Serves Swagger UI for `/openapi.json`, so you can browse every endpoint and try requests from the browser. Click **Authorize** and paste an API key to call the API. If you're signed in to the dashboard on the same server, "Try it out" also works with your session. The hosted version is at [api.pushqueue.dev/docs](https://api.pushqueue.dev/docs). **Who can call it:** anyone, no credentials. The requests you make from it need credentials as usual. **Example** ```bash open https://api.pushqueue.dev/docs ``` **Response** `200 OK` with an HTML page (`Content-Type: text/html`). **Errors** None specific to this endpoint. ## Read more - [Operating a self-hosted server](https://pushqueue.dev/docs/self-hosting/operations/): health checks, metrics and upgrades. - [Deploy pushq](https://pushqueue.dev/docs/self-hosting/deploy/): wire `/healthz` and `/readyz` into your platform. - [Going to production](https://pushqueue.dev/docs/guides/going-to-production/): monitoring and alerting checklist. - [REST API overview](https://pushqueue.dev/docs/reference/api/): authentication and conventions for every endpoint.