# Cloud Tasks vs Pub/Sub vs Workflows: The GCP Async Decision Framework

If you've been following the PulseCart series, you've already seen two of these in action. PulseCart uses Pub/Sub for event-driven fan-out (commerce events flowing to multiple consumers) and Cloud Tasks for delayed workflows (cart abandonment reminders scheduled two hours later). That combination covers a wide range of async patterns.

But there's a third option — Cloud Workflows — that neither of those posts covered, because PulseCart didn't need it. This post completes the picture: when each service belongs, where the boundaries are, and what you'd reach for if PulseCart grew more complex.

---

## The Decision Framework

Three questions narrow it down:

**1\. Does multiple independent consumers need to receive the same event?** Yes → Pub/Sub. It's built for fan-out. One message, many subscribers, each getting their own delivery.

**2\. Does the work need to happen at a specific time in the future, or does it need explicit per-task retry control?** Yes → Cloud Tasks. Scheduled execution, deterministic task names for deduplication, per-queue rate limiting.

**3\. Does the work involve a multi-step process with branching logic, conditional steps, or human approval gates?** Yes → Cloud Workflows. Orchestrated, stateful, step-by-step execution with error handling between steps.

|  | Pub/Sub | Cloud Tasks | Cloud Workflows |
| --- | --- | --- | --- |
| Fan-out to multiple consumers | ✅ | ❌ | ❌ |
| Delayed / scheduled execution | ❌ | ✅ | ✅ (with wait steps) |
| Multi-step orchestration | ❌ | ❌ | ✅ |
| Per-task deduplication | Manual (Redis) | ✅ (task name) | ✅ (execution ID) |
| Retry control | Subscription-level | Per-queue | Per-step |
| Observability | Cloud Monitoring | Cloud Monitoring | Built-in execution history |
| State between steps | None | None | Yes |

---

## Pub/Sub: Event-Driven Fan-Out

Pub/Sub's strength is decoupling — a producer publishes an event without knowing who consumes it. Multiple subscribers each receive the message independently.

In PulseCart, a single `order.placed` event flows to:

- A Cloud Run consumer that triggers a confirmation email
- A Cloud Run consumer that updates inventory
- An Airflow pull subscription for nightly aggregation

All three receive the same event. None of them know the others exist. Adding a fourth consumer is a new subscription, no producer changes required.

```python
# Producer — doesn't know what happens downstream
await publisher.publish(
    topic_path,
    data=event_json.encode(),
    ordering_key=user_id,
    event_type="order.placed",
)
```

**Use Pub/Sub when:**

- Multiple independent services need to react to the same event
- You want producers and consumers to be fully decoupled
- Events flow continuously and consumers should process as they arrive
- At-least-once delivery with consumer-managed idempotency is acceptable

**Where it doesn't fit:**

- Work that needs to happen at a specific future time (Cloud Tasks)
- Work that's a sequence of dependent steps (Cloud Workflows)
- Work that must reach exactly one consumer (use Cloud Tasks instead — Pub/Sub's fan-out means all subscribers receive every message)

---

## Cloud Tasks: Delayed and Retryable Work

Cloud Tasks is a task queue. You create a task, specify when it should execute, and Cloud Tasks delivers it to an HTTP endpoint at the scheduled time. Tasks have names — duplicate names within the deduplication window are rejected.

PulseCart's cart abandonment reminder is the canonical example: when `cart.abandoned` fires, a Cloud Tasks task is created to fire two hours later. The handler re-checks cart status before sending — if the user purchased in the meantime, the task exits cleanly.

```python
task = {
    "http_request": {
        "url": f"{HANDLER_URL}/tasks/cart-reminder",
        "body": json.dumps({"cart_id": cart_id, "event_id": event_id}).encode(),
        "oidc_token": {"service_account_email": SERVICE_ACCOUNT},
    },
    "schedule_time": scheduled_timestamp,
    "name": f"{QUEUE_PATH}/tasks/reminder-{event_id}",  # deterministic — free dedup
}
tasks_client.create_task(request={"parent": QUEUE_PATH, "task": task})
```

**Use Cloud Tasks when:**

- Work needs to happen at a specific future time
- You need to re-validate state at execution time (not just at event time)
- Per-task deduplication without a separate Redis layer
- Fine-grained retry configuration per queue
- Rate limiting on downstream calls (Cloud Tasks queues have configurable dispatch rates)

**Where it doesn't fit:**

- Fan-out to multiple consumers (Pub/Sub)
- Multi-step orchestration with branching (Cloud Workflows)
- High-throughput event streams (Pub/Sub handles millions of messages per day more gracefully than Cloud Tasks queues)

---

## Cloud Workflows: Orchestrated Multi-Step Processes

Cloud Workflows is the one teams reach for last and discover they needed earlier. It executes a sequence of steps defined in YAML or JSON — calling HTTP endpoints, running conditional logic, handling errors per step, waiting for external events, or pausing for human approval.

Where Pub/Sub and Cloud Tasks are stateless (each message or task is independent), Cloud Workflows maintains state across steps. The execution history shows every step, its input, its output, and any errors — without you writing any logging code.

A PulseCart scenario that would benefit from Cloud Workflows: a multi-step onboarding pipeline that runs when a new enterprise client signs up.

```yaml
# workflows/client-onboarding.yaml
main:
  params: [args]
  steps:
    - create_account:
        call: http.post
        args:
          url: ${sys.get_env("ACCOUNT_SERVICE_URL") + "/accounts"}
          body:
            client_id: ${args.client_id}
            plan: ${args.plan}
        result: account_response

    - check_account_created:
        switch:
          - condition: ${account_response.code == 200}
            next: provision_infrastructure
          - condition: true
            raise: ${"Account creation failed: " + account_response.body.error}

    - provision_infrastructure:
        call: http.post
        args:
          url: ${sys.get_env("INFRA_SERVICE_URL") + "/provision"}
          body:
            account_id: ${account_response.body.account_id}
        result: infra_response

    - wait_for_provisioning:
        call: sys.sleep
        args:
          seconds: 30

    - send_welcome_email:
        call: http.post
        args:
          url: ${sys.get_env("EMAIL_SERVICE_URL") + "/send"}
          body:
            account_id: ${account_response.body.account_id}
            template: "enterprise_welcome"

    - complete:
        return: ${account_response.body.account_id}
```

Each step calls a real HTTP endpoint. If step 2 fails, the workflow stops and the error is recorded in execution history. You can retry from the failed step, or the workflow can retry automatically based on retry configuration per step.

**Use Cloud Workflows when:**

- A process has multiple sequential steps that depend on each other
- You need to handle errors differently per step
- You want built-in execution history without writing your own logging
- The process involves waiting for an external event or human approval
- You're orchestrating calls to multiple services that need to happen in order

**Where it doesn't fit:**

- High-throughput event processing (Pub/Sub)
- Simple delayed tasks (Cloud Tasks is simpler and cheaper)
- Real-time reactive workflows (Cloud Workflows has execution latency not suitable for sub-second reaction)

---

## The PulseCart Pattern Extended

If PulseCart grew to include an enterprise tier with complex onboarding, the architecture would naturally extend:

```plaintext
order.placed (commerce event)
    │
    └──▶ Pub/Sub
           ├──▶ Cloud Run (confirmation email)       ← immediate reaction
           ├──▶ Cloud Run (inventory update)         ← immediate reaction
           └──▶ Cloud Tasks (cart reminder, +2hr)    ← delayed work

enterprise.client.signed_up
    │
    └──▶ Cloud Workflows
           ├── Create account
           ├── Provision infrastructure
           ├── Wait 30s
           └── Send welcome email                    ← orchestrated sequence
```

Pub/Sub for fan-out, Cloud Tasks for delayed single-consumer work, Cloud Workflows for multi-step orchestration. Each service doing exactly one thing well.
