# 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<Void> 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<Void> exportChunk(@RequestBody Map<String, Object> 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/)
