# 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<String> failed = new ArrayList<>();
for (int start = 0; start < users.size(); start += 500) {
    List<User> chunk = users.subList(start, Math.min(start + 500, users.size()));
    List<TaskCreate> 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<string>();
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<string, TaskCreate[]>();
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<String, List<TaskCreate>> 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<String, List<TaskCreate>> e : byQueue.entrySet()) {
    List<TaskCreate> tasks = e.getValue();
    for (int start = 0; start < tasks.size(); start += 500) {
        List<BatchResult> 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/)
