# 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<BatchResult> 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/)
