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