Cloud Tasks vs Pub/Sub on GCP: When a Queue Needs Delivery Order and When It Does Not
When a Cloud Run service needs to process something asynchronously, the first question we almost always get is "Pub/Sub or Cloud Tasks?", as if they were interchangeable and the answer came down to preference. They are not. Both solve the same underlying problem -decoupling whoever generates the work from whoever executes it- but they start from different delivery models, and picking the wrong one does not break anything right away. It shows up weeks later, once volume grows and it starts to matter in what order things get processed, or how many retries each individual task needs.
The delivery model is the real difference, not the client syntax
Pub/Sub is a publish-subscribe messaging system: a publisher writes a message to a topic, and any number of subscribers receive it, each independently. It is built for a many-to-many pattern, where it does not matter who consumes the message or how many consumers exist. Cloud Tasks is a point-to-point task queue: each task is created with a specific HTTP target and gets delivered to exactly that target, once per task, with retries configurable per individual task.
That difference in model has an immediate practical consequence. In Pub/Sub, if delivery order matters, you have to explicitly declare an ordering key per message, and Pub/Sub only guarantees order among messages that share that same key, not across different keys:
from google.cloud import pubsub_v1
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path("my-project", "orders-topic")
future = publisher.publish(
topic_path,
data=b'{"order_id": "4821", "event": "payment_confirmed"}',
ordering_key="order-4821",
)
If two events for the same order are published with the same ordering_key, Pub/Sub delivers them in the order they arrived. If they are published without an ordering_key, or with different keys, there is no ordering guarantee between them, even if they were published seconds apart. This is easy to miss because the publishing code compiles and runs the same with or without the key; the problem shows up in production when two events for the same order arrive in the reverse order from how they were published, because they landed in different internal partitions of the topic.
Cloud Tasks does not have this problem because it does not need to solve it the same way: a Cloud Tasks queue processes tasks in the order they were enqueued by default, with no key to declare, although this guarantee applies to dispatch order, not an absolute guarantee of sequential execution if several workers are consuming the same queue in parallel.
Retries: per individual task vs per entire subscription
The second difference that has bitten us the most in real projects is how retries get configured. In Cloud Tasks, each task can carry its own retry configuration at creation time, on top of the queue's default policy:
from google.cloud import tasks_v2
client = tasks_v2.CloudTasksClient()
queue_path = client.queue_path("my-project", "us-central1", "notification-dispatch")
task = {
"http_request": {
"http_method": tasks_v2.HttpMethod.POST,
"url": "https://notification-service-xyz.a.run.app/send",
"body": b'{"user_id": "991", "channel": "email"}',
},
}
response = client.create_task(parent=queue_path, task=task)
The retry policy -how many attempts, with what backoff, up to what time limit- is defined at the queue level with RetryConfig, and applies to every task in that queue unless stated otherwise. For a case where different task types need different retry policies -a low-priority notification that can be retried only a few times, a charge that needs more persistence- the practice we use is splitting those tasks into separate queues, each with its own RetryConfig, instead of trying to force a single queue to serve both cases.
In Pub/Sub, the retry and delivery policy -ackDeadline, exponential backoff retry policy, dead-letter topic- is configured at the subscription level, not per individual message. That means every message that reaches that subscription shares the same policy, regardless of its content or origin. If two very different event types -one that tolerates aggressive retries, another that should not be retried more than once because the operation is not idempotent- land on the same topic, the fix is not trying to tell them apart inside the subscriber's code, it is creating separate subscriptions, or separate topics, depending on the level of isolation needed.
# A subscription with its own dead-letter and retry policy
subscription: orders-sub-critical
topic: orders-topic
ackDeadlineSeconds: 60
retryPolicy:
minimumBackoff: 10s
maximumBackoff: 600s
deadLetterPolicy:
deadLetterTopic: projects/my-project/topics/orders-dlq
maxDeliveryAttempts: 5
At-least-once delivery, in both cases
Something that gets assumed wrong often: neither Pub/Sub nor Cloud Tasks guarantee exactly-once delivery by default. Both are at-least-once delivery systems (Pub/Sub offers an optional "exactly once delivery" mode within the same region, under specific conditions, but the default behavior -and the one that applies in most multi-region setups- is at least once). That means the code that processes the message or task has to be idempotent, regardless of which of the two services is used. A Cloud Tasks handler that processes a charge has to be able to receive the same task twice without charging twice, the same way a Pub/Sub subscriber that processes an inventory update has to be able to receive the same duplicated message without applying the change twice.
@app.post("/send")
def send_notification():
idempotency_key = request.headers.get("X-Task-Idempotency-Key")
if already_processed(idempotency_key):
return "", 200
# process and record idempotency_key as processed
return "", 200
Cloud Tasks helps a bit here because each task has a unique name that can be used as an idempotency key without having to generate it on the publisher's side, though only if that name is explicitly assigned when creating the task; if Cloud Tasks is left to auto-generate the name, there is no way to retrieve it before execution to use as a key.
When to use each one in a Cloud Run service
For a Cloud Run service that needs to execute a concrete action against a known HTTP target -sending an email, generating a PDF, calling an external webhook-, Cloud Tasks is the more direct choice: per-task control over retries, a configurable dispatch rate limit per queue (maxDispatchesPerSecond), and the ability to schedule a task for a specific future moment are use cases Cloud Tasks solves natively, and that require extra work in Pub/Sub.
For a service that needs to notify an event to one or more consumers that are not known in advance, or that can grow in number without the publisher needing to know -a domain event that today only one service consumes, but that tomorrow an analytics service and an audit service might also consume-, Pub/Sub is the right model, because the publisher does not have to change when a new subscriber is added.
What did not work the first time
The first time we needed to process events for the same order in strict order, we used Pub/Sub without an ordering_key because we assumed publish order was enough. It worked in local testing, where messages were published and processed nearly sequentially, and it failed in production once the topic started receiving enough volume to distribute messages across different internal partitions, which do not guarantee order relative to each other. The "payment confirmed" event for an order arrived before the "order created" event for the same order, and the subscriber tried to update a record that did not exist yet. We fixed it by adding an ordering_key per order_id, but that also changed behavior on the publisher's side: with ordering enabled, if a message with a given key fails to publish, Pub/Sub blocks publishing of subsequent messages with that same key until the failure is resolved, something that does not happen without ordering, and that we had to handle explicitly with resume_publish on the client.
What we check before choosing between the two
Before choosing between Cloud Tasks and Pub/Sub for a new asynchronous flow, we first check whether there is a single, known-in-advance target for each unit of work, because that points to Cloud Tasks, or whether the work needs to reach a variable number of consumers that can change over time, because that points to Pub/Sub. If delivery order matters, we check whether it can be solved with an ordering_key per entity in Pub/Sub, or whether it actually belongs to Cloud Tasks' sequential queue model, which needs no extra configuration for that. And in either case, we design the handler to be idempotent from day one, because both systems deliver at least once, and the question is not whether a duplicate will arrive, it is when.