Pub/Sub vs Cloud Tasks in GCP: Differences and When to Use Each
Pub/Sub broadcasts events to multiple subscribers. Cloud Tasks delivers individual jobs to one endpoint with rate limiting, retries, and scheduling. They solve different problems, and picking the wrong one creates friction you don’t need.
The core decision is simple: if multiple services need to react to the same event, use Pub/Sub. If you need to send one controlled job to one handler, especially with scheduling, rate limiting, or deduplication, use Cloud Tasks. In many architectures, you use both.
- Pub/Sub: one event, many listeners. Think “announce to everyone.”
- Cloud Tasks: one job, one handler, with delivery controls. Think “assign this work.”
Simple explanation
Pub/Sub is a restaurant ticket printer. When a customer places an order, the ticket prints at every station that needs it. The grill station, the salad station, and the drink station all get the same order independently. The waiter does not decide which stations get the ticket. Each station subscribes to the orders it cares about.
Cloud Tasks is the head chef handing out individual jobs. “You, plate this steak in 10 minutes. You, fire this appetizer now. Don’t plate more than 5 dishes per minute or we’ll overwhelm the pass.” Each job goes to one person, with specific timing and pacing.
Pub/Sub is for broadcasting. Cloud Tasks is for controlled delegation.
How Pub/Sub works
Pub/Sub is a fully managed publish-subscribe messaging service. Publishers send messages to a topic. One or more subscriptions attached to that topic each receive a copy of every message. This is fan-out: one message in, multiple independent deliveries out.
Key concepts:
- Topics and subscriptions. A topic is a named channel. Subscriptions are independent consumers attached to a topic. Each subscription gets every message, and subscribers within a subscription compete for messages (load balancing).
- Decoupling. The publisher does not know how many subscriptions exist or what they do. You can add a new subscriber without touching the publishing service. This is the foundation of event-driven architectures.
- At-least-once delivery. By default, Pub/Sub may deliver a message more than once. Subscribers must handle duplicates. An exactly-once delivery mode is available on pull subscriptions, but it adds latency and only works when subscribers connect to the same region as the subscription.
- Delivery modes. Pub/Sub supports both push and pull delivery. Push sends messages to an HTTP endpoint. Pull lets your application fetch messages on its own schedule.
- Ordering keys. Optional. Messages with the same ordering key are delivered in publish order. Messages with different keys have no ordering guarantee.
- Scale. Pub/Sub handles millions of messages per second without provisioning.
Typical architectures: decoupled microservices where multiple services react to the same event, streaming data into data pipelines via Dataflow, triggering Cloud Run or Cloud Functions services via push subscriptions, and feeding analytics systems with real-time event data.
# Publish a message to a topic
gcloud pubsub topics publish my-topic \
--message '{"event": "order.created", "order_id": "ord_001"}'
# Create a push subscription that delivers to a Cloud Run service
gcloud pubsub subscriptions create my-sub \
--topic my-topic \
--push-endpoint https://my-service-abc123-uc.a.run.app/events \
--ack-deadline 60How Cloud Tasks works
Cloud Tasks is a managed task queue. You create a task (an HTTP request aimed at a specific URL) and Cloud Tasks delivers it, retries on failure, and controls the delivery rate. Each task has exactly one consumer. There is no fan-out.
Key concepts:
- Explicit HTTP target. Every task specifies the exact URL it will hit. The task creator knows and controls the destination.
- One task, one handler. Unlike Pub/Sub, a task is not broadcast. It goes to one endpoint, once (barring retries).
- Queue controls. Each queue has configurable dispatch rate (up to 500 dispatches per second), max concurrent dispatches (default 1,000), and burst size. These settings protect downstream services from being overwhelmed.
- Retries. When a task fails (non-2xx response), Cloud Tasks retries with exponential backoff. You configure max retry attempts, min and max backoff intervals per queue.
- Scheduling. You can schedule a task up to 30 days in the future. Cloud Tasks holds the task and dispatches it at the specified time.
- Rate limiting. The queue’s
maxDispatchesPerSecondsetting caps how fast tasks are sent to the target. This is essential for protecting rate-limited APIs or preventing cost spikes on autoscaling services. - Task ID deduplication. If you assign a name to a task, Cloud Tasks rejects duplicate creation requests with the same name. After a task completes or is deleted, the name stays reserved for up to 24 hours. This prevents double-enqueuing.
Cloud Tasks does not guarantee execution order. Tasks may execute out of enqueue order. Do not treat Cloud Tasks as a FIFO queue. If you need ordering, use Pub/Sub ordering keys (per-key only) or build ordering logic into your application.
# Create a Cloud Task targeting a Cloud Run service
from google.cloud import tasks_v2
import json
import time
client = tasks_v2.CloudTasksClient()
parent = client.queue_path("my-project", "us-central1", "my-queue")
task = {
"http_request": {
"http_method": tasks_v2.HttpMethod.POST,
"url": "https://my-service-abc123-uc.a.run.app/process-order",
"headers": {"Content-Type": "application/json"},
"body": json.dumps({"order_id": "ord_001"}).encode(),
},
"schedule_time": { # Optional: deliver 1 hour from now
"seconds": int(time.time()) + 3600
}
}
response = client.create_task(request={"parent": parent, "task": task})Side-by-side comparison
| Dimension | Pub/Sub | Cloud Tasks | Why it matters |
|---|---|---|---|
| Core model | Publish-subscribe (event bus) | Task queue (job dispatch) | Determines whether you’re broadcasting events or dispatching controlled work |
| Producer knowledge of consumer | None. Publisher doesn’t know who subscribes | Full. Creator specifies the exact HTTP target | Pub/Sub decouples producers from consumers; Cloud Tasks couples them intentionally |
| Fan-out | Yes. Each subscription gets every message | No. Each task goes to one endpoint | Use Pub/Sub when multiple services need the same event |
| Delivery target | Push endpoint, pull client, or BigQuery/Cloud Storage export | One HTTP or App Engine endpoint per task | Cloud Tasks always delivers over HTTP to a known target |
| Push vs pull | Both. Push subscriptions or pull/StreamingPull | Push only (HTTP dispatch to target) | Pub/Sub lets consumers pull at their own pace; Cloud Tasks pushes on its schedule |
| Scheduling | No. Messages deliver immediately | Yes, up to 30 days in advance | Only Cloud Tasks can hold work and deliver it at a specific future time |
| Retry control | Subscription-level retry policy with backoff | Per-queue retry config with max attempts and backoff | Cloud Tasks gives finer control over how failures are handled |
| Rate limiting | No built-in dispatch rate control | Yes, up to 500 dispatches/sec per queue | Cloud Tasks protects downstream services from traffic spikes |
| Deduplication | Not built-in. Exactly-once mode available on pull subscriptions with trade-offs | Task name deduplication. Names reserved up to 24 hours | Cloud Tasks prevents duplicate enqueue at the queue level |
| Ordering | Optional ordering keys (per-key order only) | Not guaranteed | Neither guarantees global order; Pub/Sub offers per-key ordering |
| Payload size | Up to 10 MB per message | Up to 1 MiB per task (includes headers and metadata) | Store large payloads in Cloud Storage and pass a reference |
| Retention | 7 days default, up to 31 days max | Up to 31 days for unexecuted tasks | Both clean up eventually; monitor for stuck work |
| Delivery scale | Millions of messages per second | Up to 500 dispatches/sec per queue | Pub/Sub is built for massive throughput; Cloud Tasks prioritizes controlled delivery |
| Best fit | Event-driven architectures, data pipelines, multi-consumer fanout | Background jobs, webhooks, scheduled tasks, rate-limited delivery | Match the service to your delivery pattern |
| Bad fit | Single-consumer jobs needing rate limits or scheduling | Broadcasting events to multiple independent services | Using the wrong one adds complexity for no benefit |
When to use Pub/Sub
- Multiple services react to the same event. An order is placed and the inventory service, email service, and analytics service each need to process it independently. Each service has its own subscription.
- Event-driven architectures. Services publish events without knowing which other services consume them. New consumers are added by creating subscriptions, not by modifying publishers. See event-driven architectures in GCP.
- Data pipelines and streaming. Clickstream events, log entries, or IoT data stream into Pub/Sub and feed into Dataflow or BigQuery for processing. See designing data pipelines.
- Analytics and event streaming. High-volume event data that needs to flow to multiple destinations (dashboards, storage, ML pipelines) simultaneously.
- Loose coupling between teams. Team A publishes order events. Team B subscribes to build reports. Neither team coordinates deployments or knows each other’s implementation details.
When to use Cloud Tasks
- Background jobs off a web request. A user submits a form and you enqueue a task to process the upload, generate a PDF, or resize an image. The response returns immediately while the work happens in the background.
- Webhook and API calls to one endpoint. You need to call an external API reliably, with retries on failure and a cap on request rate.
- Delayed processing. Send a welcome email 10 minutes after signup. Charge a payment 24 hours after an order ships. Cloud Tasks holds the task and delivers it at the scheduled time.
- Rate-limited downstream systems. An external email provider allows 100 requests per second. Set
maxDispatchesPerSecondon the queue to 100 and Cloud Tasks enforces the limit for you. - Explicit retry control. You need specific retry behavior (max 5 attempts, 30 seconds between retries, give up after 1 hour) rather than Pub/Sub’s subscription-level retry policy.
- Dedupe-sensitive jobs. Assign a task name like
charge-order-12345and Cloud Tasks rejects duplicate creation attempts. Combined with idempotent handlers, this prevents double-processing.
When to use both together
Pub/Sub and Cloud Tasks are complementary. In many real architectures, Pub/Sub serves as the event bus and Cloud Tasks handles controlled downstream execution.
Pub/Sub decides who needs to know. Cloud Tasks decides how and when the work gets done. When you need both decisions, use both services.
E-commerce order flow
- The order service publishes an
order.createdevent to a Pub/Sub topic. - The inventory service subscribes and deducts stock immediately.
- The analytics service subscribes and records the sale.
- The notifications service subscribes and, instead of sending emails directly, enqueues Cloud Tasks: one to send a confirmation email now (rate-limited to protect the email provider) and another to send a shipping reminder 24 hours later.
Pub/Sub handles the fan-out. Cloud Tasks handles the pacing and scheduling.
User onboarding
- A
user.signed_upevent hits a Pub/Sub topic. - Multiple subscribers react: create a default project, provision storage, send a Slack notification to the sales team.
- The email service subscribes and enqueues a Cloud Tasks sequence: welcome email immediately, onboarding guide in 2 hours, check-in email in 3 days, each with retry protection.
Payment and webhook processing
- A payment gateway sends a webhook to your Cloud Run service.
- Your service publishes a
payment.receivedevent to Pub/Sub so the order service, accounting service, and fraud detection service all get it. - The accounting service creates a Cloud Task to call a third-party invoicing API with rate limiting (the API allows 50 requests per second) and automatic retries.
This pattern (Pub/Sub for broadcast, Cloud Tasks for controlled single-target delivery) appears in most production systems that use both services. You can learn more in the reference architecture for modern web applications.
Cloud Tasks vs Cloud Scheduler
Scheduling is a big part of why people compare Pub/Sub and Cloud Tasks, but Cloud Scheduler is a third service that matters here.
Cloud Tasks is a reminder on your phone. “Remind me to call the dentist at 3 PM tomorrow.” It fires once, at a time you chose when you created the reminder.
Cloud Scheduler is an alarm clock. “Wake me up at 7 AM every weekday.” It fires on a repeating schedule, regardless of what happened yesterday.
- Cloud Tasks schedules a one-off task for a specific future time. “Send this email at 3 PM tomorrow.” The task runs once and is done.
- Cloud Scheduler runs jobs on a recurring cron schedule. “Run this cleanup job every night at midnight.” It triggers an HTTP endpoint, a Pub/Sub topic, or a Cloud Tasks queue on a repeating cadence.
Use Cloud Tasks when each job has a unique delivery time determined at creation (like a delayed notification). Use Cloud Scheduler when you need a fixed recurring schedule (like a daily report or hourly health check).
They work well together: Cloud Scheduler triggers a Cloud Run service every hour, and that service enqueues individual Cloud Tasks for each item that needs processing, with rate limiting and retries.
Both Pub/Sub and Cloud Tasks deliver at least once. Your handlers must be idempotent. Processing the same message twice should produce the same result as processing it once. Use database upserts, idempotency keys, or transaction IDs. Skipping this step is the single most common source of bugs in async messaging systems.
Common mistakes
- Using Pub/Sub when only one controlled consumer is needed. If every job goes to one endpoint and you need rate limiting or scheduling, Cloud Tasks is the simpler choice. Pub/Sub with a single subscription works but gives you none of the queue controls. See the Cloud Tasks page for what queue controls look like in practice.
- Assuming Cloud Tasks is a broadcast system. Cloud Tasks delivers each task to one endpoint. If you need multiple services to react to the same event, you need Pub/Sub. There is no way to fan out a Cloud Task.
- Assuming either service is exactly-once by default. Pub/Sub is at-least-once by default. Cloud Tasks executes tasks at least once (over 99.999% are single-execution, but duplicates can happen). Always make your handlers idempotent. See troubleshooting Pub/Sub delivery failures for common delivery issues.
- Ignoring idempotency. Both services can deliver or execute work more than once. If processing the same message twice causes a double charge, a duplicate email, or corrupted data, your handler has a bug. Use database upserts, idempotency keys, or deduplication checks.
- Treating Cloud Tasks as FIFO. Cloud Tasks does not guarantee execution order. Tasks may run out of enqueue order. If you need strict ordering, build that logic into your application or use Pub/Sub ordering keys for per-key ordering.
- Skipping queue rate limits on Cloud Tasks. Without rate limiting, a burst of 100,000 tasks can dispatch simultaneously, overwhelming your Cloud Run service and causing unexpected autoscaling costs. Always set
maxDispatchesPerSecondto a value your target can handle. - Exceeding payload limits and failing silently. Pub/Sub messages max out at 10 MB. Cloud Tasks maxes out at 1 MiB per task (total, including headers and metadata). For large payloads, store the data in Cloud Storage and pass a reference in the message or task body.
Real-world decision guide
- Choose Pub/Sub if multiple services need the same event, you’re building event-driven architecture, you’re streaming high-volume data, or you want producers fully decoupled from consumers.
- Choose Cloud Tasks if each job goes to one endpoint, you need scheduling or delayed delivery, you need rate limiting to protect a downstream service, or you need task-level deduplication.
- Use both if you need fan-out (Pub/Sub) and some subscribers then need controlled single-target delivery with pacing, retries, or scheduling (Cloud Tasks).
- Add Cloud Scheduler if you have recurring jobs on a fixed cron schedule.
Monitor both with Cloud Monitoring. Watch unacknowledged message counts in Pub/Sub and queue depth in Cloud Tasks. Growing backlogs mean your consumers cannot keep up.
Frequently asked questions
What is the main difference between Pub/Sub and Cloud Tasks?
Pub/Sub is a publish-subscribe messaging system that broadcasts each message to every subscription on a topic. This is fan-out. Cloud Tasks is a task queue that delivers each task to exactly one HTTP endpoint with rate limiting, scheduling, and deduplication. Use Pub/Sub when multiple services need the same event. Use Cloud Tasks when one service needs controlled, reliable delivery of work.
Can Cloud Tasks replace Pub/Sub?
No. Cloud Tasks delivers each task to a single endpoint. It cannot fan out one piece of work to multiple independent consumers. If you need multiple services to react to the same event, you need Pub/Sub. Cloud Tasks is the right choice only when each job has one handler.
Can Pub/Sub schedule messages for future delivery?
No. Pub/Sub delivers messages as soon as possible after publishing. It has no built-in delay or scheduling mechanism. If you need to deliver work at a specific future time, use Cloud Tasks, which supports scheduling up to 30 days in advance. For recurring schedules, use Cloud Scheduler.
Which is better for sending webhooks?
Cloud Tasks. Webhooks go to a single HTTP endpoint and often need retry control, rate limiting, and deduplication, all of which Cloud Tasks provides out of the box. Pub/Sub push subscriptions can also hit HTTP endpoints, but they lack per-queue rate limiting and task-level scheduling.
Which is better for multiple consumers?
Pub/Sub. Each subscription on a Pub/Sub topic independently receives every message. You can add or remove subscribers without changing the publisher. Cloud Tasks has no fan-out. Each task goes to one endpoint only.