Cloud Tasks in Google Cloud: Running Background Work Reliably, at the Right Speed
A complete, plain-English guide to Cloud Tasks: how queues and tasks work, how delivery, retries, scheduling and rate limits protect your services, how to secure and observe the pipeline, and how to design background processing that survives failures without overwhelming anything.
Picture a busy restaurant kitchen. Waiters take orders from the dining room and clip paper tickets onto a rail above the pass. The cooks pull tickets from the rail at a steady pace, one after another. If a rush of forty orders arrives at once, the waiters do not shout at the cooks or stand around waiting; they clip the tickets on the rail and return to their tables. The rail absorbs the rush, the cooks work at a pace they can sustain, and if a dish is burnt, the ticket goes back on the rail for another try. Cloud Tasks is that ticket rail for your software. Your web application clips a ticket describing some work, and the service makes sure the right worker receives it, at the right speed, with retries if something goes wrong.
This guide assumes you know nothing about the topic. We explain every new word, give everyday comparisons, and build up from the basic idea to production-grade practice. By the end you will understand what queues and tasks are, how a task travels from your code to a handler, why handlers must be safe to run twice, how rate limits and retries protect your systems, how to secure and watch the pipeline, how Cloud Tasks differs from its neighbours, and which mistakes cause the most painful backlogs.
1What Cloud Tasks Is and Why It Exists
Cloud Tasks is a managed service that lets you hand off units of work to be done later, reliably, and at a speed you control.
The problem it solves
Imagine a customer presses a button to place an order. Your website must save the order, send a confirmation email, update a stock count, tell a shipping partner, and resize the product photo for a receipt. If the website does all of that before replying, the customer waits, and if any step fails, the whole request may fail. A better design replies quickly after the essential step and does the rest in the background. Background work is called asynchronous processing, meaning the caller does not wait for it to finish.
Doing background work well is harder than it sounds. You need somewhere to store the pending work so it is not lost if a server restarts. You need to deliver it to a worker, retry when the worker fails, and avoid flooding a fragile partner system with thousands of calls at once. Building all of that yourself is slow and error-prone. Cloud Tasks provides it as a ready-made service.
Think of a post office. You drop a letter in the box and walk away. You do not wait for the letter to arrive, and you trust the system to hold it safely, deliver it, and try again if nobody answers the door. Cloud Tasks is a post office for jobs: you post a job, and it takes responsibility for delivering it.
What the service actually does
You create a queue, which is a named holding area for jobs. Your code adds tasks to the queue. A task contains the address of a handler and any data the handler needs. Cloud Tasks then sends each task to its handler, which is simply a web endpoint you own, such as a Cloud Run service or a Cloud Run function. If the handler replies with a success code, the task is finished and removed. If it fails or does not reply in time, Cloud Tasks waits a while and tries again, according to rules you set.
The service is fully managed, so there are no queue servers to run, patch or scale. You pay for what you use, and you control the pace at which tasks are sent, which protects both your own services and any outside systems they call.
With Cloud Tasks, the sender decides exactly which handler will run each task. That is the main difference from publish and subscribe messaging, where the sender announces an event and does not know who listens. We compare the two in detail later.
2Where It Fits in the Google Cloud Family
Cloud Tasks works with several neighbours, and confusing them is the most common beginner mistake.
Cloud Run and Cloud Run functions
The most common handlers. They receive tasks as ordinary web requests and scale up to meet the flow.
Pub/Sub
A messaging service for announcing events to many unknown listeners. Different job from explicit task delivery.
Cloud Scheduler
Runs jobs on a repeating timetable, like a cron job. It triggers things at times, while Cloud Tasks manages individual units of work.
Workflows
Coordinates multi-step processes with decisions and waiting. It can create tasks as one step in a larger flow.
Identity and Access Management
Decides who may create tasks, manage queues, and which identity Cloud Tasks uses when it calls your handler.
Cloud Logging and Monitoring
Record what happened to each task attempt and chart queue depth, so you can see problems early.
In a hospital, the alarm clock that wakes a nurse at six each morning is Cloud Scheduler. The notice board that announces “emergency in room four” for any staff member to see is Pub/Sub. The individual task slips handed to specific nurses with instructions and deadlines are Cloud Tasks. The care plan that sequences many steps is Workflows. They overlap but are not the same thing.
Cloud Tasks versus Pub/Sub, in one sentence
Use Cloud Tasks when your code knows exactly which handler must do a piece of work and you want control over timing, speed and retries. Use Pub/Sub when you want to announce that something happened and let any number of independent listeners react without the sender knowing about them.
Cloud Tasks versus Cloud Scheduler
Cloud Scheduler fires on a clock: every night at two, every five minutes. Cloud Tasks handles work created by events: this particular customer, this particular file, in fifteen minutes. A common pairing is a scheduler job that wakes at night and creates thousands of tasks, one for each item that needs processing.
flowchart LR
P["Your application"] -->|"Create task"| Q["Cloud Tasks queue"]
Q -->|"Dispatch at controlled rate"| H["Handler on Cloud Run or similar"]
H -->|"Success code"| Q
Q --> L["Cloud Logging and Monitoring"]
S["Cloud Scheduler"] -.->|"Optional trigger"| P
W["Workflows"] -.->|"Optional step"| Q
3Core Concepts and Vocabulary
A small set of words unlocks the whole service.
Queue
A named holding area for tasks, with its own speed limits and retry rules. Think of it as one lane of a conveyor belt.
Task
One unit of work waiting in a queue. It holds the handler address, optional data, and optional timing.
Handler
The web endpoint you own that receives a task and does the work. It replies with a code that says whether it succeeded.
Dispatch
The act of Cloud Tasks sending a task to its handler. Each try is called a dispatch attempt.
Enqueue
The act of your code adding a task to a queue. The caller who enqueues is called the producer.
Rate Limit
A cap on how fast tasks are dispatched and how many run at the same time. Protects handlers from floods.
Retry Policy
Rules for how many times and how often a failed task is retried, with growing waits between tries.
Schedule Time
An optional moment before which the task must not run. Used for delays such as a reminder in an hour.
Idempotent
Safe to run more than once with the same result as running once. The most important property of a good handler.
Backlog
The pile of tasks waiting in a queue. A growing backlog is a warning sign.
At a parcel depot, a lane on the sorting belt is a queue. Each parcel is a task with an address label, which is the handler address. The delivery van is the dispatch. The speed of the belt is the rate limit, and the rule “try three more times, waiting longer each time” is the retry policy. A parcel marked “do not deliver before Monday” has a schedule time.
The queue owns the rules about speed and retries. The task owns the details of the specific job. Separating them lets you change behaviour for thousands of tasks by editing one queue.
4Anatomy of Queues and Tasks
Knowing exactly what lives in a queue and in a task removes most early confusion.
What a queue holds
A queue lives in one project and one location, a geographic region. Its location is chosen when it is created and cannot be changed later, so pick the region near your handlers. A queue has a name, a state (running, paused or disabled), a rate limit policy, a retry policy, and optional settings for logging. Names can be reused only after a waiting period once a queue is deleted, so choose names with care.
| Queue setting | What it controls | Why it matters |
|---|---|---|
| Maximum dispatches per second | Average speed of sending tasks | Protects handlers and partners from floods |
| Maximum concurrent dispatches | How many tasks run at the same moment | Prevents overloading a database or a slow service |
| Maximum burst size | How many tasks can go out at once after a quiet period | Smooths sudden spikes |
| Maximum attempts | How many times a task may be tried | Stops endless retrying of broken work |
| Minimum and maximum backoff | Shortest and longest wait between tries | Gives failing systems time to recover |
| Maximum retry duration | Total time allowed for retrying | Drops work that has become too old to matter |
What a task holds
Target address
Where to send the task: the web address of your handler, plus the method such as POST.
Body and headers
The data the handler needs. The size of one task is limited to a small amount, around one megabyte at the time of writing.
Schedule time
Optional moment before which the task will not run. It can be set up to a limited number of days ahead.
Name
Optional. If you give a name, Cloud Tasks uses it to refuse duplicates. If you omit it, the service creates a name.
Dispatch deadline
How long the handler may take to answer before the attempt counts as failed.
Authentication settings
Which service identity Cloud Tasks should use to prove itself to the handler.
A courier company sets the rules per delivery lane: how many vans leave per hour, how many retries at a closed door. Each parcel carries its own label and contents. The company rules are the queue settings, and the label with its contents is the task.
A task is a note, not a suitcase. Put large files in storage and place only a reference, such as a file name, inside the task. Small tasks are faster, cheaper, and stay under the size limit.
Create queues in the same region as the handlers they call. A queue far from its handlers adds delay, and some features and policies depend on region, so confirm details in the current documentation.
5Architecture and Components
Four roles take part in every task: the producer, the queue, the dispatcher and the handler.
Although Cloud Tasks is fully managed, picturing its parts helps explain its behaviour. Each part has a clear job.
The producer
Your application, a function, or a workflow that decides some work should happen later. It creates a task using a client library or the service interface.
The queue
Durable storage managed by Google. Once your create request succeeds, the task is safely held even if your producer disappears.
The dispatcher
The managed engine that decides when each task is due, applies speed limits, sends the request to the handler, and records the outcome.
The handler
Your web endpoint that does the work and answers with a success or failure code.
The observers
Logs and metrics that show attempts, delays and backlog, so people can see what the system is doing.
flowchart LR
subgraph You["Your code"]
PR["Producer"]
HD["Handler"]
end
subgraph GC["Cloud Tasks"]
QU["Queue storage"]
DP["Dispatcher with rate limits and retries"]
end
PR -->|"Create task"| QU
QU --> DP
DP -->|"HTTP request"| HD
HD -->|"Response code"| DP
DP --> OB["Logs and metrics"]
A school has a teacher who hands in homework requests (producer), a locked cabinet that holds them safely (queue), a monitor who hands each request to a classroom at the right time (dispatcher), and the classroom helpers who do the work (handler). A noticeboard records who finished what (observers).
The handler is a normal web service
One of the nicest things about Cloud Tasks is that handlers need no special software. A handler is simply a web endpoint that accepts a request and replies with a status. This means you can write it in any language, test it with ordinary tools, and host it wherever it can receive web requests, most commonly on Cloud Run or as a Cloud Run function. It also means that anyone who can call that endpoint could, in principle, send it work, which is why authentication matters, as we will see.
Keep your handler small and focused on one kind of job. Many small handlers, each behind its own queue with its own rate limit, are easier to tune than one giant handler that does everything.
6Internal Working: The Life of One Task
Follow a single task from creation to completion, including what happens when things go wrong.
Let us trace an example. A customer places an order, and your website wants to send a confirmation email in the background. Here is the life of that email task.
The producer creates the task
Right after saving the order, the website adds a task to the email queue. The task names the handler address and carries the order number.
The service stores it safely
Cloud Tasks confirms that the task is saved. From this moment the website can reply to the customer without waiting.
The task becomes due
With no schedule time, it is due at once. The dispatcher checks the queue’s speed and concurrency limits.
The dispatcher calls the handler
It sends a web request to the handler, including headers that say which queue and task this is and how many times it has been tried.
The handler does the work
It sends the email and replies with a success code before the deadline.
The task is removed
A success reply marks the task finished and it leaves the queue.
If it fails, it waits and tries again
On an error or a timeout, the task stays in the queue and is retried after a growing wait, until it succeeds or the retry limits are reached.
sequenceDiagram
participant W as Website
participant Q as Cloud Tasks queue
participant H as Email handler
W->>Q: Create task with order number
Q-->>W: Task stored
W-->>W: Reply to customer immediately
Q->>H: Dispatch attempt 1
H-->>Q: Error response
Note over Q: Wait with backoff
Q->>H: Dispatch attempt 2
H-->>Q: Success response
Q->>Q: Remove task
What the handler learns from headers
Each request carries information that helps the handler behave well. Headers tell it the queue name, the task name, how many times the task has been retried, how many times it has been executed, and when it was scheduled. A handler can use these to log context, to give up on tasks that have been tried too often, and to detect that a request came from Cloud Tasks and not from a stranger. Check the current documentation for the exact header names.
Many beginners think the producer waits for the task to finish. It does not. A successful create call only means the task was stored. The work happens later, and the producer never sees its result directly. If you need the result, design a way for the handler to record it, for example in a database.
7Targets and Handlers: HTTP and App Engine
Cloud Tasks can deliver to two kinds of targets, and the success rule is the same for both.
HTTP targets
HTTP target tasks go to any web endpoint that Cloud Tasks can reach, such as a Cloud Run service, a Cloud Run function, a service on a virtual machine, or even an endpoint outside Google Cloud. You specify the address and the method. This is the most flexible and most common option today.
App Engine targets
Tasks can also be sent to a handler inside an App Engine application, with routing based on the service and version. This option is tied to App Engine, and it offers features such as routing to a particular version and longer deadlines on some scaling types. If you do not already use App Engine, you will almost always choose HTTP targets.
| Aspect | HTTP target | App Engine target |
|---|---|---|
| Where handlers run | Any reachable endpoint | Inside an App Engine application |
| Authentication | Identity tokens or access tokens from a service account | Handled within App Engine |
| Flexibility | Very high | Tied to the platform |
| Typical choice today | Cloud Run, functions, custom servers | Existing App Engine applications |
A courier can deliver to any street address in the city (HTTP target) or only to offices inside one particular business park, using the park’s internal mail system (App Engine target). Most customers want the first, because it reaches everywhere.
What counts as success
The rule is simple. A handler that replies with a success status, any code in the two hundreds, tells Cloud Tasks that the work is done. Any other reply, such as a client error, a server error or a timeout, is treated as a failure and the task is retried. This means the handler controls its own fate through the status it returns.
Success code
The task is finished and removed. Use only when the work is truly complete or safely recorded.
Server error
The task is retried after waiting. Use for temporary problems such as a database that is briefly unavailable.
Client error
Also retried by default. For a permanently bad task, consider recording the problem and returning success so it does not retry forever.
Timeout
If the handler is too slow, the attempt is counted as failed and the task will be retried, possibly while the first attempt is still running.
Reply as soon as the work is safely accepted. A handler that holds the connection open for a long time risks hitting the deadline, which triggers a retry while the first attempt may still be running. Keep the handler fast, or make long jobs resumable.
A task that can never succeed, such as one pointing at a customer who no longer exists, should be logged and answered with success. Otherwise it consumes retries and noise. We cover this idea fully in the chapter on poison tasks.
8Delivery Guarantees, Idempotency and Ordering
Cloud Tasks promises that your task will be delivered at least once, which has a big consequence for how you write handlers.
At least once, not exactly once
The service is designed to deliver every task at least once. In rare cases a task may be delivered more than once, for example when a handler does the work but the success reply is lost on the network, or when a slow handler times out and the task is retried while the first attempt is still running. From the dispatcher’s point of view, no success was seen, so it tries again. This is a deliberate design choice: it is far better to deliver twice than to lose the work.
A courier rings your doorbell and you sign for the parcel, but the courier’s signature machine fails to save your signature. The courier cannot tell whether you got the parcel, so the next day the courier brings it again. Two parcels might arrive. A sensible household checks whether it already has the item before accepting another.
Idempotent handlers: the golden rule
A handler is idempotent if running it twice with the same task has the same effect as running it once. Sending the same welcome email twice is annoying, and charging a customer twice is a serious problem. Writing idempotent handlers is the single most important habit in background processing.
Record what is done
Store a marker for each completed task in a database, using the task name or a business identifier. Check it before acting.
Use unique business keys
Use an order number or request identifier so repeated work is recognised and ignored.
Prefer set over add
Design updates as “set status to shipped” rather than “add one to the count”, so repeating them changes nothing.
Pass identifiers to partners
When calling an outside system, send a unique key that lets that system refuse a duplicate request.
About ordering
Cloud Tasks does not promise that tasks run in the exact order they were added. Tasks are dispatched roughly in order of their due time, but retries, parallel dispatch and scheduling mean the order can vary. If your work depends on strict order, such as applying edits to one document in sequence, do not rely on queue order. Instead, include a sequence number in the task, have the handler apply changes only in the right order, or use a service that offers ordering guarantees for that case.
flowchart TD
T["Task arrives at handler"] --> C{"Already processed this business key?"}
C -->|Yes| S["Skip the work and return success"]
C -->|No| W["Do the work"]
W --> R["Record completion with the key"]
R --> OK["Return success"]
Problem
A handler charges a customer’s card and sends a receipt, with no record of whether this task was already handled.
Why It’s Harmful
If the success reply is lost or the handler times out, the retry charges the customer a second time. Angry customers, refunds and lost trust follow.
Correct Approach
Record a unique key for each payment before or as part of the work, check it first on every attempt, and pass the same key to the payment provider so duplicates are refused.
9Rate Limits: Controlling Speed and Concurrency
The queue is a pressure valve that protects everything downstream.
Why speed control matters
Imagine ten thousand tasks arrive in one minute, each needing to call a partner system that can handle only fifty requests per second. If all ten thousand were sent at once, the partner would fail, your handlers would fail, retries would pile up, and the failure would spread. Rate limits turn a dangerous spike into a smooth, safe flow.
A motorway on-ramp has a traffic light that lets one car on every few seconds. Without it, a convoy of cars floods the motorway and everything jams. The queue’s rate limit is that traffic light for your tasks.
The three dials
Maximum dispatches per second
The average number of tasks sent each second. Set it to what your slowest dependency can sustain.
Maximum concurrent dispatches
The most tasks that may be running at the same time. Protects shared resources like database connections.
Maximum burst size
How many tasks may be sent at once after a quiet period. Tasks are released using a token bucket, a store of permission slips that refills at the steady rate.
flowchart LR
A["Tasks waiting in queue"] --> B["Token bucket refills at the set rate"]
B --> C{"Token available and concurrency below limit?"}
C -->|Yes| D["Dispatch task to handler"]
C -->|No| E["Task waits in queue"]
E --> C
Choosing the numbers
Begin with the capacity of your weakest link. If a partner allows one hundred requests per second, set the rate lower, perhaps eighty, to leave room for other users of the same partner. If your database allows twenty connections for background work, cap concurrency near that. Then watch the backlog and latency and adjust gradually. A queue with a very high rate limit is not a bad thing in itself, but it gives no protection to a fragile dependency.
Put tasks that call different dependencies in different queues. A slow partner then backs up only its own queue, and other work keeps flowing. This isolation is one of the best uses of separate queues.
A queue can dispatch faster than your handler can scale. Check the handler’s maximum instances and concurrency, and set the queue limits so that the handler is never asked to do more than it can accept, or tasks will fail and retry in waves.
10Retries and Backoff
Failure is normal in distributed systems, so retrying wisely is a core feature, not an afterthought.
Why tasks fail
A handler may fail for many reasons: a database is restarting, a partner system is overloaded, the network drops a packet, a deployment is in progress, or the task itself contains bad data. Most of these problems are temporary. If you wait a little and try again, the work succeeds. Retrying is therefore the right first response to a failure.
Backoff: waiting longer each time
If a system is struggling, hammering it with instant retries makes things worse. Exponential backoff means the wait doubles after each failure, up to a ceiling. A task might wait a fraction of a second, then a second, then two, then four, and so on, until the maximum wait is reached. This gives a failing service room to recover and prevents a retry storm.
If you phone a friend and get no answer, you do not redial every second. You wait a few minutes, then try again, then wait longer. Constant redialling is annoying and useless. Backoff is the polite, sensible way of calling again.
The retry settings on a queue
| Setting | Meaning | Typical thinking |
|---|---|---|
| Maximum attempts | Total number of tries before the task is dropped | High enough to ride out outages, low enough to stop hopeless tasks |
| Maximum retry duration | Total time the service keeps retrying | Set to the age beyond which the work is no longer useful |
| Minimum backoff | Shortest wait between tries | Short for quick recovery, longer for fragile partners |
| Maximum backoff | Longest wait between tries | Caps how stale a retry can become |
| Maximum doublings | How many times the wait doubles before growing steadily | Controls how fast the wait increases |
flowchart TD
A["Dispatch attempt"] --> B{"Handler returned success?"}
B -->|Yes| C["Task finished and removed"]
B -->|No| D{"Attempts or time limit reached?"}
D -->|Yes| E["Task dropped"]
D -->|No| F["Wait with growing backoff"]
F --> A
Matching retry rules to the kind of work
Time-sensitive
A reminder text that is useless after an hour. Use a short total retry duration so stale work is dropped.
Must eventually succeed
Recording a payment in a ledger. Use many attempts and a long maximum retry duration, with strong alerting on backlog.
Calls to fragile partners
Use a longer minimum backoff and a low rate so retries never become an attack on the partner.
Best-effort
Optional analytics. Allow only a few attempts, and accept that some will be lost.
When a downstream system fails, every queued task retries, and new tasks keep arriving. Without rate limits and backoff, the combined load can keep the failing system down. Rate limits and backoff together are your defence against this storm.
The handler can read how many times the task has been tried. After a certain number of tries, it can raise an alert or move the task to a safe place for human review, instead of failing silently.
11Scheduling, Delays and Deadlines
Tasks can wait for a chosen moment, and every attempt has a time limit.
Delaying a task
Each task can carry a schedule time, a moment before which it must not run. This is wonderful for delayed actions: send a reminder in thirty minutes, check on an order tomorrow, retry a partner call after an hour. The delay is limited to a maximum number of days into the future, documented as about thirty days at the time of writing, so very long waits need a different design.
A postdated cheque cannot be cashed before its date. A task with a schedule time is a postdated instruction: it sits safely in the queue and becomes active only when its time arrives.
Dispatch deadline: how long a handler may take
Every attempt has a deadline, the time Cloud Tasks will wait for the handler’s reply. If the handler does not answer within the deadline, the attempt is counted as failed. For HTTP targets the deadline has a default and a maximum, documented in minutes at the time of writing, and it can be set per task within those limits. App Engine targets have their own limits depending on how the application scales. Always confirm the current numbers in the documentation.
Short deadlines
Good for quick jobs. They detect stuck handlers fast and free capacity for retries.
Long deadlines
For slower jobs. But a long deadline hides stuck handlers and can leave tasks hanging for a long time.
Long-running work
If a job takes longer than the maximum deadline, do not simply increase the deadline and hope. Split the work into smaller tasks, or have the handler accept the task, start the work elsewhere, and reply right away. Long jobs are better handled by a task that triggers a dedicated job service and then records its progress.
Split into chunks
Process a thousand records as ten tasks of a hundred, so each finishes comfortably within the deadline.
Make progress resumable
Record how far the job got, so a retry continues instead of starting from zero.
Hand off heavy work
Let the task start a separate job service and reply quickly, tracking completion with a status record.
When a slow handler times out, the task is retried while the first attempt may still be running. Two copies could run together. This is another strong reason to keep handlers idempotent and fast.
The handler’s own request timeout, for example on Cloud Run, should be at least as long as the task deadline you expect, or the platform may cut the request before the queue’s deadline passes.
12Task Names and Deduplication
A task name can act as a safety latch that refuses accidental duplicates at creation time.
Named and unnamed tasks
When you create a task you may give it a name, or leave it out and let the service make one. A name that you choose becomes a unique identity within the queue. If your code tries to create another task with the same name while the first still exists, the service refuses with an already-exists answer. This protects you when a producer runs twice, for example after its own retry.
A restaurant gives each order a ticket number. If a waiter tries to hand in the same numbered ticket twice, the kitchen notices and ignores the second one. A task name is that ticket number.
How to choose a name
Pick a name from a stable business key, such as an order number combined with the kind of work. For example, “confirm-email for order 8841” always produces the same name for the same job, so duplicates are refused. Avoid names that include the current time or a random value, because those are always unique and give no protection.
| Naming approach | Duplicate protection | Notes |
|---|---|---|
| No name given | None at creation time | Fast and simple, handler must be idempotent |
| Name from a business key | Strong while the task exists | Best for work that must happen once per item |
| Name with a random value | None | Gives a name but no protection |
Limits of name-based protection
Deduplication by name works only for a limited time. Once a task has been completed or deleted, its name cannot be reused for a period of time, documented as roughly an hour at the time of writing, and after that the name is free again. Therefore name-based protection does not replace idempotent handlers. It is an extra safety net at creation time, while the handler’s own check is the safety net at execution time.
A name stops duplicate creation, not duplicate delivery. A single task can still be delivered twice due to network issues. Always combine named tasks with idempotent handlers.
When creation fails because the name already exists, treat it as a calm success for your producer. It means the work is already queued, which is exactly what you wanted.
13Queue Lifecycle: Pause, Resume, Purge and Disable
A queue has controls that let you stop the flow, clear the backlog, or switch it off entirely.
Running
The normal state. Tasks are accepted and dispatched according to the rules.
Paused
Tasks can still be added and are stored safely, but no dispatching happens. Perfect for pausing during an incident or a partner outage.
Disabled
A stronger state used when a queue is being retired or its configuration is from an old system. Its tasks wait but are not dispatched.
Purged
A one-time action that deletes every task in the queue. It cannot be undone.
stateDiagram-v2
[*] --> Running
Running --> Paused: Pause
Paused --> Running: Resume
Running --> Disabled: Disable
Disabled --> Running: Enable again
Running --> Running: Purge removes all tasks
Disabled --> [*]: Delete queue
A conveyor belt in a factory has a pause button, which stops the belt while parcels keep arriving and wait on the side. Purging is throwing all waiting parcels in the bin. Disabling is shutting the line for refurbishment. Pause is the gentle control you will use most.
When to pause
Partner outage
Pause the queue that calls the failing partner so you stop wasting retries, then resume when it recovers.
Bad deployment
Pause while you fix or roll back a broken handler, preventing tasks from failing and burning attempts.
Data repair
Pause while you correct data that tasks depend on, then resume with no loss.
Planned maintenance
Pause during windows when dependencies are intentionally unavailable.
Purging deletes every waiting task with no undo, including tasks that came from other parts of your system. Before purging, confirm what is in the queue, and consider whether pausing and fixing the handler would be safer.
After a queue is deleted, its name may not be usable again for a waiting period. Choose clear, lasting queue names, and avoid throwaway names for experiments in your production project.
14Authentication and Access Control
Two questions must be answered: who may add tasks, and how does your handler know a request really came from Cloud Tasks?
Who may do what with queues
Access is managed through Identity and Access Management using predefined roles. A good design gives each identity only the role it needs.
| Role idea | What it allows | Typical holder |
|---|---|---|
| Administrator | Full control of queues and tasks | A small platform team |
| Queue administrator | Create and configure queues, but not manage individual tasks | Platform engineers |
| Enqueuer | Add tasks to queues | Producer applications |
| Task runner | Force a task to run now | Operators during investigation |
| Task deleter | Delete individual tasks | Operators |
| Viewer | See queues and tasks | Support, analysts, auditors |
In a post office, customers may drop letters in the box (enqueuer), sorting staff may reorganise the lanes (queue administrator), and only a supervisor may empty the whole room (administrator). Matching powers to jobs keeps mistakes small.
Proving who is calling the handler
Your handler is a web endpoint, and anyone who learns its address might call it. To prevent that, Cloud Tasks can attach a signed token to every request, created for a service account that you choose. The handler, or the platform in front of it, checks the token before doing anything. For handlers on Cloud Run and Cloud Run functions, you generally use an identity token and grant that service account permission to invoke the service. For Google APIs, an access token is used instead.
Create a dedicated service account
One identity used only by this queue or this family of queues to call handlers.
Allow that account to invoke the handler
Grant the invoker permission on the specific service, not on the whole project.
Let producers use it when creating tasks
The producer’s identity needs permission to act as that service account, in addition to the enqueuer role.
Require authentication on the handler
Keep the handler private, so only requests with a valid token from the right account are accepted.
Problem
The handler is open to the whole internet with no authentication, because it was easier during testing.
Why It’s Harmful
Anyone who finds the address can send fake tasks, trigger emails, modify data or run up costs. Cloud Tasks cannot protect a handler that accepts everyone.
Correct Approach
Require authentication, use a dedicated service account with narrow permission, and verify the caller before doing any work.
If task creation fails with a permission message about acting as a service account, the producer lacks permission to use that account. Grant the narrow service account user permission on that single account.
15Network Security and Payload Hygiene
What you put in a task and where the handler lives both affect your security.
Private and public handlers
Handlers that are reachable from the internet are simplest to use, but you can lock them down by requiring authentication, as discussed. For handlers that live inside a private network, Cloud Tasks offers options to reach them without exposing them publicly. Availability and setup details depend on the current features, so consult the documentation before designing around them. Many teams keep handlers private to the platform, accepting only authenticated calls.
A factory with a goods entrance for couriers can keep that door locked and open it only to couriers who show a valid badge. Authenticated handlers behave like that locked door, whereas an open handler is a door propped open with a brick.
What belongs inside a task
Good Contents
- Identifiers such as an order number or file name.
- Small instructions such as the kind of work to do.
- A correlation identifier for tracing across systems.
- A version number of the task format.
Poor Contents
- Passwords, tokens or secret keys.
- Full personal records when an identifier would do.
- Large files or long documents.
- Data that will be stale by the time the task runs.
Why identifiers beat copies of data
Tasks may sit in a queue for minutes, hours or days, may be retried, and show up in logs and troubleshooting tools. If a task carries a full copy of a customer record, that copy may be stale by the time it runs and may also appear in places you did not intend. A task that carries only an identifier lets the handler fetch the freshest data and keeps sensitive content in one controlled place.
Never put credentials inside a task body or header. Anyone with permission to view tasks, and any log that records them, could expose those secrets. Let the handler fetch secrets from a secret store using its own identity.
Include a small version number in the task data. When you later change the format, handlers can support both old and new tasks that are still waiting in the queue, which avoids failures during deployments.
16Observability: Logs, Metrics and Alerts
A background queue is out of sight, so it must be well lit.
Because background work happens away from the user, problems can grow quietly for hours. Good observability tells you early. Three sources matter: logs of each attempt, metrics about the queue, and your own handler records.
Logs of task attempts
Cloud Tasks can write a log record for task attempts, showing the queue, the task, the attempt number, the response code and the timing. Logging has a sampling setting that controls what share of attempts is recorded, so you can balance detail against volume and cost. Turn it on for important queues, and make sure your handler also logs its own decisions with the task name.
Metrics that matter
Queue depth
How many tasks are waiting. A growing line means tasks arrive faster than they are processed.
Attempt count and response codes
How many tries, and how many succeeded or failed. A rising failure share signals a problem.
Attempt delay
The gap between when a task was due and when it was actually sent. Long delays mean limits or capacity are too tight.
Oldest task age
How long the oldest waiting task has been in the queue. A strong measure of how far behind you are.
A queue at a bank is judged by how long people wait, not only by how many are standing there. Queue depth is the number of people, and age of the oldest task is the longest wait. Customers care about the wait, and so should you.
Alerts worth having
Backlog growing
Alert when queue depth or oldest task age rises above a level that matters to your business.
High failure rate
Alert when the share of failed attempts passes a set limit for a sustained period.
Tasks near the retry limit
Alert from your handler when a task has been tried many times, before it is dropped.
Queue paused too long
Alert when a queue stays paused beyond an agreed time, so nobody forgets to resume it.
flowchart LR
Q["Queue activity"] --> M["Queue metrics"]
Q --> L["Attempt logs"]
H["Handler logs"] --> L
M --> D["Dashboard"]
M --> A["Alerting policies"]
L --> A
A --> O["On-call engineer"]
Put a correlation identifier in the task and log it in both producer and handler. Then a single customer action can be followed from the website through the queue to the final result.
17Poison Tasks and Dead-letter Patterns
Some tasks can never succeed, and a good design decides what happens to them.
What is a poison task?
A poison task is one that fails every time, no matter how often it is retried. Perhaps it refers to a record that was deleted, contains malformed data, or triggers a bug in the handler. Left alone, it consumes retries, adds noise to logs, and may hide real problems. After the maximum attempts, the service drops the task, which means the failure could pass unnoticed.
A parcel addressed to a house that has been demolished will never be delivered, however many times the courier tries. A sensible depot, after a few attempts, puts the parcel in a “problem shelf” for a person to investigate instead of driving it round forever.
Dead letters: the problem shelf
A dead-letter store is a place where failed work is kept for human review. Cloud Tasks does not provide a built-in dead-letter queue at the time of writing, so check the current documentation, and design your own pattern when you need one.
Handler gives up deliberately
When the retry count reaches a limit, the handler writes the task details to a database table or a storage bucket, raises an alert, and returns success so the queue stops retrying.
Permanent errors recorded at once
When the handler can tell the task is hopeless, such as invalid data, it records the problem immediately and returns success.
Review and replay
A support tool lets people inspect stored failures, fix the cause, and recreate tasks safely.
flowchart TD
T["Task attempt arrives"] --> W{"Work succeeded?"}
W -->|Yes| OK["Return success"]
W -->|No| P{"Permanent error or retry limit reached?"}
P -->|No| RT["Return error and let queue retry"]
P -->|Yes| DL["Save task details to dead-letter store and raise alert"]
DL --> OK2["Return success to stop retries"]
Problem
The team lets failed tasks exhaust their retries and vanish, with no record and no alert.
Why It’s Harmful
Customers silently miss emails, orders or updates. Nobody knows work was lost until complaints arrive, and nothing remains to reconstruct what happened.
Correct Approach
Record tasks that reach the retry limit, alert the team, and provide a way to review and replay them.
Because handlers are idempotent, replaying a task is safe. Make replay a regular, well-tested tool, not a late-night improvisation.
18Cloud Tasks Compared with Pub/Sub, Scheduler and Workflows
Choosing the right tool saves months of pain.
| Question | Cloud Tasks | Pub/Sub | Cloud Scheduler | Workflows |
|---|---|---|---|---|
| Main idea | Explicit delivery of a job to a chosen handler | Announce events to any number of listeners | Run something on a clock | Coordinate multi-step processes |
| Who decides the receiver | The sender | The subscribers | The job definition | The workflow definition |
| Rate control per receiver | Built in | Limited, receiver controls its own pull speed | Not applicable | Managed by steps |
| Delay a single item | Yes, schedule time on each task | Not as a core feature | Recurring schedules, not per-item | Yes, with wait steps |
| Fan-out to many listeners | No, one handler per task | Yes | No | Possible by design |
| Typical use | Emails, partner calls, delayed actions, throttled work | Event streams and decoupled services | Nightly jobs, periodic checks | Order processing with decisions and waiting |
Cloud Tasks is a personal assistant who hands a specific note to a specific person at the right time. Pub/Sub is a town crier who shouts news to everyone listening. Cloud Scheduler is an alarm clock. Workflows is a project manager coordinating many steps. Each is excellent at its own job.
flowchart TD
Q1{"Do you know exactly which handler must do the work?"}
Q1 -->|Yes| Q2{"Need control over speed, retries or delay per item?"}
Q1 -->|No| PS["Use Pub/Sub for event announcements"]
Q2 -->|Yes| CT["Use Cloud Tasks"]
Q2 -->|No| Q3{"Is it a repeating schedule?"}
Q3 -->|Yes| CS["Use Cloud Scheduler"]
Q3 -->|No| Q4{"Many steps with decisions and waiting?"}
Q4 -->|Yes| WF["Use Workflows"]
Q4 -->|No| CT
They often work together
Real systems combine these tools. A scheduler job wakes at night and creates tasks for each customer. A workflow handles a complex order, using tasks for the throttled partner calls. A Pub/Sub event announces that an order was placed, and one subscriber responds by creating tasks. Treat them as parts of a toolkit.
Using Pub/Sub when you need per-item delay, strict rate limits to one partner and explicit deduplication leads to custom code that reinvents Cloud Tasks. Using Cloud Tasks to broadcast an event to many unknown listeners leads to the opposite pain. Match the tool to the need.
19Setting Up Cloud Tasks Step by Step
A calm, ordered path from an empty project to a working queue.
Setup is simple when done in the right order. Think of it as setting up a new mail room in an office: you choose the room, label the pigeonholes, decide who may post and who may collect, and test a letter before relying on it.
Choose the project and turn on the service
Enable the Cloud Tasks service in your project and make sure billing is active.
List your kinds of background work
Group work by what it calls and how fast it can go: emails, image processing, partner calls, reminders. Each group is a candidate for its own queue.
Pick a region and names
Place each queue near its handler, and choose clear, lasting names.
Create the queue with sensible limits
Set dispatch rate, concurrency, burst, retry attempts and backoff based on what your slowest dependency can handle.
Prepare the handler
Deploy a handler that accepts the task format, is idempotent, replies quickly, and requires authentication.
Set up identities
Create a service account for dispatching, allow it to invoke the handler, and allow producers to enqueue and to act as that account.
Create a test task
Add one harmless task and watch it arrive at the handler. Confirm headers, authentication and success.
Turn on logging and alerts
Enable attempt logging for important queues and create alerts for backlog, failures and paused queues.
Write the runbook
Document who owns each queue, how to pause and resume, how to replay failed tasks, and what the limits mean.
A new mail room is first tested with a few dummy letters, to check that each pigeonhole works and that staff know what to do when a letter bounces. The single test task is your dummy letter.
Use separate projects or clearly separate queue names for development, staging and production. A test task landing in a production handler is an avoidable embarrassment.
A queue that has never carried a real task is untested. Many problems, such as a missing invoker permission or a handler that rejects the headers, only show up with a real delivery. Test before moving real work.
20Design Patterns for Reliable Background Work
Good background processing comes from a handful of repeatable habits.
Pattern 1: Reply fast, work later
Keep the user-facing request short by doing only the essential step, then enqueue everything else. The customer sees a quick response, and background tasks finish in their own time.
Pattern 2: One queue per dependency or kind of work
Give each fragile partner or distinct workload its own queue with its own rate limit and retry rules. A slow partner then delays only its own queue.
Pattern 3: Idempotent handlers with business keys
Record completed work against a stable business key and check it first. This makes duplicate delivery, retries and manual replays harmless.
Pattern 4: Pass identifiers, not data
Put only an identifier in the task and let the handler fetch fresh data. Tasks stay small and secrets and personal data stay out of the queue.
Pattern 5: Fan-out through a coordinator
One coordinator task, or a scheduled job, creates many small tasks, one per item. The queue’s rate limit then spreads the load safely instead of hitting the system all at once.
Pattern 6: Delayed follow-up
Use a schedule time to check later on something, such as confirming payment status in ten minutes, or sending a reminder the day before an appointment.
Pattern 7: Throttled calls to outside systems
Put calls to a rate-limited partner behind a queue whose limits are slightly below the partner’s quota, and let backoff handle temporary errors.
Pattern 8: Self-managed dead-letter storage
Handlers record permanently failing tasks and alert the team, so no work is silently lost.
Pattern 9: Chunked long jobs
Split long jobs into small tasks that each finish well within the deadline, with progress records so retries resume rather than restart.
flowchart LR
S["Nightly scheduler job"] --> C["Coordinator handler"]
C -->|"Create one task per customer"| Q["Throttled queue"]
Q -->|"Rate limited"| H["Worker handler"]
H --> P["Partner system with fixed quota"]
H --> D["Database record of completed keys"]
A teacher marking two hundred exam papers does not shout all of them at the class. She hands out one batch per table, at a pace the helpers can manage, and keeps a list of who has handed back what. The coordinator, throttled queue and completion record work the same way.
21Anti-patterns: What Not to Do
These habits quietly cause duplicates, backlogs and outages.
Problem
All kinds of work share one queue with generous limits.
Why It’s Harmful
A slow or failing partner fills the queue with retrying tasks and delays unrelated, healthy work. One bad dependency stalls everything.
Correct Approach
Create separate queues for different dependencies and kinds of work, with limits tuned to each.
Problem
The handler takes many minutes to answer, holding the connection open until the work is done.
Why It’s Harmful
Deadlines expire, retries start while the first attempt still runs, and duplicates appear. Capacity is wasted waiting.
Correct Approach
Split long work into chunks, make progress resumable, or hand heavy work to a job service and reply quickly.
Problem
Queue limits are left at very high values, and the handler cannot keep up with that rate.
Why It’s Harmful
The queue floods the handler and its dependencies, tasks fail, retries pile up and the failure grows into a storm.
Correct Approach
Set rate and concurrency below the weakest link, and confirm the handler’s own scaling limits.
Problem
Every failure, including permanent ones, is answered with an error and left to retry for the full limit.
Why It’s Harmful
Hopeless tasks waste attempts and noise, hide real incidents, and may repeat harmful side effects many times.
Correct Approach
Tell temporary from permanent errors, record permanent ones, and stop their retries deliberately.
Problem
The team relies on strict queue order, for example applying edits to a record in the order they were created.
Why It’s Harmful
Retries and parallel dispatch change the order, so an older edit can overwrite a newer one, corrupting data.
Correct Approach
Include sequence numbers or timestamps, let the handler ignore stale updates, or use a design that guarantees order.
Problem
Tasks carry full copies of customer records, tokens or large documents.
Why It’s Harmful
Data may be stale when the task runs, secrets may leak into logs and views, and size limits are hit.
Correct Approach
Carry identifiers and let the handler fetch fresh data and secrets with its own identity.
Problem
Nobody watches queue depth, failure rates or paused queues.
Why It’s Harmful
A backlog can grow for days before anyone notices, and delayed emails, orders and updates reach customers too late.
Correct Approach
Alert on backlog, failure share and oldest task age, and review queues regularly.
22Best Practices and Common Mistakes
A checklist in plain words that any team can adopt.
Do
- Write idempotent handlers keyed by a business identifier.
- Give each dependency or workload its own queue.
- Set rate and concurrency below the weakest dependency.
- Reply quickly and chunk long work.
- Authenticate every handler with a dedicated service account.
- Carry identifiers in tasks, not secrets or big data.
- Record and alert on tasks that reach the retry limit.
- Watch queue depth and age of the oldest task.
Do Not
- Assume exactly-once delivery or strict ordering.
- Leave handlers open to the whole internet.
- Keep long connections open waiting for slow work.
- Mix unrelated work in one queue with huge limits.
- Rely on names alone to prevent duplicates.
- Purge a queue without checking its contents.
- Forget to resume a paused queue.
- Ignore the time zone and clock when scheduling tasks.
Common mistakes beginners make
Handler returns success too early or too late
Returning success before the work is safely recorded can lose work, and returning it after a very long time causes timeouts. Reply once the work is done or safely accepted.
Wrong region or address
A queue far from its handler adds delay, and a handler address with a typo sends tasks into a void where every attempt fails.
Missing invoker or act-as permission
The dispatch identity cannot call the handler, or the producer cannot use that identity. Both produce clear permission errors that are easy to fix once you know where to look.
Unlimited retries on a broken task
A bad task retries for days, hammering a dependency. Always set sensible limits and a dead-letter pattern.
Changing the task format without care
A deployment changes the expected fields while old tasks still wait in the queue, and the new handler rejects them. Version your payloads and support both for a while.
Forgetting the handler’s own scaling limits
The queue sends faster than the handler can scale, causing errors that look like application bugs.
Every quarter, review each queue: its owner, limits, backlog history, failure causes and dead-letter records. Adjust limits to match the real capacity of dependencies. This short meeting prevents most slow-burning problems.
23Real-world and Industry Examples
The same service supports very different businesses. These scenarios show how.
Online retail order confirmation
A shop saves an order, replies instantly, and creates tasks to send the confirmation email, update stock and notify the warehouse. Each task type has its own queue. If the email provider is slow, only the email queue backs up, and orders keep flowing.
Image and video processing
A photo-sharing app stores an uploaded picture and creates a task to make thumbnails. The handler fetches the original from storage using the identifier in the task. A modest concurrency limit stops a rush of uploads from overwhelming the processing service.
Calls to a rate-limited partner
A logistics company must call a carrier’s system that allows fifty requests per second. All calls go through a queue limited to forty per second. Spikes in orders are smoothed out, and partner errors trigger gentle retries with backoff.
Reminders and delayed actions
A clinic booking system creates a task with a schedule time of one day before each appointment. The handler checks that the appointment still exists, sends a reminder, and does nothing if the booking was cancelled.
Webhooks with dependable delivery
A software platform sends webhooks to customer systems. Each delivery is a task, retried with backoff when customers are down for a while. Deliveries that finally fail are recorded so customers can request a replay.
Nightly batch fan-out
A subscription business runs a nightly job that creates one task per account to calculate renewals. The queue spreads thousands of calculations over an hour so databases stay healthy.
A small startup
A tiny team uses a single queue and one Cloud Run handler to send emails and sync records in the background. They gain reliability and quick page responses without building any queue infrastructure.
flowchart LR
O["Order placed"] --> Q1["Email queue"]
O --> Q2["Stock queue"]
O --> Q3["Warehouse queue"]
Q1 --> H1["Email handler"]
Q2 --> H2["Stock handler"]
Q3 --> H3["Warehouse handler"]
24Cost, Quotas and Scale
The service is inexpensive for most teams, but design choices affect the bill and the limits you meet.
How charges usually work
Pricing is based on the number of billable operations, such as creating tasks and dispatching attempts, usually with a monthly free allowance and a price per million operations beyond it. Retries count as additional attempts, so a flapping handler raises both load and cost. Your handlers, logs, databases and network also cost money. Always check the current pricing page for exact figures, because they change.
Task volume
More tasks means more operations. Combine tiny tasks into batches where it makes sense.
Retries
Each retry is another attempt. Fixing flaky handlers lowers cost as well as noise.
Logging
Logging every attempt on very busy queues creates large log volumes. Use sampling for the busiest ones.
Handler compute
Handlers on Cloud Run or functions cost per request and per time used, which is often the larger part of the total.
A courier charges per delivery attempt. If a customer is never home, every extra attempt costs money. Fixing the address once is cheaper than paying for ten failed visits. Retries on a broken handler work the same way.
Quotas and limits
Cloud Tasks has limits on things such as the number of queues, the size of a task, how far ahead a task may be scheduled, and the rates at which you can create tasks and send them. Many limits are generous for normal use, and some can be raised on request. Review the current quota page before big launches, design producers to retry creation calls with short waits when they are throttled, and spread very large bursts of task creation over a little time.
Scaling to large volumes
Scale handlers first
Make sure the handler can scale and that its dependencies, such as databases, can take the load.
Raise queue limits gradually
Increase rate and concurrency in small steps while watching errors and latency.
Use multiple queues if needed
Spread very large flows across several queues for isolation and easier tuning, and avoid hot spots in naming.
Set billing alerts on the project. A sudden jump in operations is often the first sign of a retry storm or a loop in your own code.
A handler that creates new tasks for the same work can start an endless chain that grows quickly. Add limits, record what was created, and test fan-out logic carefully before production.
25Advantages, Disadvantages and Trade-offs
An honest comparison always includes the limits.
Advantages
- Fully managed, with no queue servers to run or patch.
- Explicit delivery to a handler you choose.
- Built-in rate limits, concurrency control and retries with backoff.
- Per-task scheduling for delayed actions.
- Name-based protection against duplicate creation.
- Works with Cloud Run, functions, App Engine and other web endpoints.
- Queues can be paused and resumed during incidents.
Disadvantages / Trade-offs
- At-least-once delivery means handlers must be idempotent.
- No strict ordering guarantee.
- One handler per task, so no fan-out to many listeners.
- No built-in dead-letter queue, so you design your own.
- Limits on task size and how far ahead tasks can be scheduled.
- Results are not returned to the producer.
How the options compare
| Approach | Strength | Limitation |
|---|---|---|
| Do everything inside the web request | Simple to build | Slow replies, failures hit the user, no retries |
| Your own queue in a database | Full control | You build polling, retries, rate limits and monitoring |
| Cloud Tasks | Managed queues with rate limits, retries and scheduling | At-least-once delivery, no strict order, one handler per task |
| Pub/Sub | Fan-out and decoupled event streams | Less per-item control of delay and receiver speed |
| Workflows | Multi-step orchestration with decisions | Not designed for very high volumes of tiny tasks |
Doing everything in the web request is cooking, serving and washing up while the customer stands at the counter. A homemade queue is building your own conveyor belt. Cloud Tasks is renting a professional conveyor belt with speed controls. Pub/Sub is a loudspeaker for announcements. Choose the tool that fits the job.
If you need to hand a specific piece of work to a specific handler, control its speed, delay it, and retry it safely, Cloud Tasks is usually the right choice. If you need broadcast or strict ordering, consider other services, and compare current features and prices before deciding.
26Troubleshooting Common Problems
When something looks wrong, follow the task from the producer to the handler, one link at a time.
flowchart TD
A["Tasks not completing as expected"] --> B{"Are tasks being created successfully?"}
B -->|No| C["Check enqueuer permission, act-as permission, queue name and region"]
B -->|Yes| D{"Is the queue running and not paused?"}
D -->|No| E["Resume the queue"]
D -->|Yes| F{"Are attempts reaching the handler?"}
F -->|No| G["Check handler address, invoker permission and authentication"]
F -->|Yes| H{"Is the handler returning success in time?"}
H -->|No| I["Fix errors, shorten work, align timeouts and deadlines"]
H -->|Yes| J{"Is backlog still growing?"}
J -->|Yes| K["Raise limits carefully or scale the handler and dependencies"]
J -->|No| L["Read attempt logs for the exact reason"]
Symptom: task creation fails
Check that the producer has the enqueuer role, that it may act as the service account named in the task, that the queue name and region are correct, and that the task is within size and schedule limits. Permission and name errors are the most common causes.
Symptom: tasks sit in the queue and nothing runs
First check whether the queue is paused or disabled. Then check the rate limits: a very low dispatch rate or concurrency limit makes the queue crawl. Finally check whether tasks are scheduled for a future time.
Symptom: every attempt fails with an authorisation error
The dispatch service account may lack permission to invoke the handler, or the handler may expect a different kind of token or audience. Confirm the identity, the invoker permission and the target address used in the token.
Symptom: duplicates appear
Timeouts are the usual cause: the handler was too slow, the attempt was counted as failed, and a retry started. Shorten the work, align timeouts, and make the handler idempotent.
Symptom: backlog keeps growing
Tasks arrive faster than they are completed. Check handler errors, handler scaling, dependency health, and queue limits. Raise limits only if the handler and dependencies can cope, otherwise you simply move the pain.
Problem
Tasks are created without error, but the handler never sees them and the backlog grows.
Why It’s Harmful
Common reasons are a paused queue, a wrong handler address, a missing invoker permission, or a very low rate limit. Meanwhile customer work stays undone.
Correct Approach
Check the queue state, then the rate limits, then the handler address and permissions, and read the attempt logs for the response codes.
27Responding to a Backlog or Retry Storm: A Simple Playbook
Preparation turns a frightening pile-up into a managed event.
Sooner or later a dependency fails, a bad release goes out, or a rush of tasks arrives. The queue starts to fill, retries multiply, and alerts begin to fire. A short written playbook helps the team act calmly.
Notice and confirm
An alert on queue depth, oldest task age or failure share fires. Confirm that the situation is real.
Find the cause
Look at response codes and handler logs. Is a dependency down, was there a deployment, or did the input volume jump?
Protect the dependency
If the cause is a failing partner or database, pause the affected queue or lower its limits, so retries stop hammering it.
Fix or roll back
Repair the handler, roll back the release, or restore the dependency. New tasks are still stored safely while the queue is paused.
Resume gradually
Resume with modest limits and watch error rates. Raise the speed in steps until the backlog drains, never releasing the full pile at once.
Verify and review
Check dead-letter records, replay anything lost, and hold a short review about alerts, limits and design.
sequenceDiagram
participant M as Monitoring
participant T as On-call team
participant Q as Queue
participant D as Dependency
M->>T: Alert on growing backlog
T->>T: Find cause in logs and metrics
T->>Q: Pause queue to stop retries
T->>D: Repair or wait for recovery
T->>Q: Resume with low limits
Q-->>M: Backlog shrinks steadily
T->>Q: Raise limits in steps
T->>T: Review and improve playbook
After a motorway accident is cleared, police do not let all queued cars go at once; they release them in groups so that a new jam does not form. Resuming a queue slowly is the same careful release.
Purging a queue to make the backlog disappear also deletes valid work. Pause, fix and drain instead, and use purge only when you are sure the tasks are worthless or can be recreated.
Once or twice a year, rehearse pausing and resuming a test queue. Knowing the exact steps under pressure is worth more than any document.
28Testing, Rollout and a Maturity Path
Introduce background processing carefully, prove that it works, and grow it in stages.
The riskiest moment of any queue project is the first launch, because mistakes show up as lost, delayed or duplicated work. A calm testing and rollout plan removes most of that risk.
What to test before launch
The happy path
A normal task is created, dispatched, handled and removed, with the right headers and authentication.
The temporary failure
Make the handler fail twice and then succeed. Confirm retries and backoff behave as planned.
The duplicate
Send the same task twice and confirm the handler’s effect happens only once.
The poison task
Send a hopeless task and confirm it ends in the dead-letter store with an alert.
The slow handler
Make the handler exceed the deadline and observe the retry and duplicate behaviour.
The pause and resume
Pause the queue, add tasks, resume, and confirm everything drains at the planned rate.
Before opening a new factory line, engineers run it with dummy items, jam a parcel on purpose, stop the belt, and restart it. Only after every drill works do they trust the line with real goods. These six tests are your drill.
A gentle rollout plan
Staging first
Deploy queues and handlers to staging and run the six tests.
Start with one low-risk flow
Move a harmless job, such as a reminder email, to the queue and watch it for a week.
Study the metrics
Check queue depth, response codes, delays and costs. Adjust limits from real data.
Expand step by step
Move more flows over, one at a time, each with its own queue and alerts.
Document and hand over
Write down owners, limits, reasons and the runbook, so knowledge outlives any one person.
flowchart LR
ST["Staging tests"] --> L1["One low-risk flow in production"]
L1 --> AN["Study metrics and costs"]
AN --> EX["Expand flow by flow"]
EX --> OP["Operate, review and retune"]
OP -.->|"Learn and adjust"| AN
A maturity path
| Stage | What it looks like | Next step |
|---|---|---|
| Stage 1: Inline | All work happens inside the web request | Move one slow, non-essential job to a queue |
| Stage 2: Queued | A few jobs use queues with default settings | Make handlers idempotent and add authentication |
| Stage 3: Tuned | Separate queues, tuned limits and retries, basic alerts | Add dead-letter storage and replay tools |
| Stage 4: Observed | Dashboards, backlog alerts, quarterly reviews and cost tracking | Rehearse the incident playbook |
| Stage 5: Resilient | Fan-out patterns, chunked long jobs and practised recovery | Share lessons across teams |
Cloud services change. Treat the official documentation, release notes, quota pages and pricing pages as the final word on features, limits and costs, and revisit them every few months.
The most common launch failure is a handler that works perfectly once and misbehaves on a retry. A single duplicate test in staging is the cheapest insurance in the whole project.
29Frequently Asked Questions
A queue is a named holding area with rules for speed and retries. A task is one unit of work inside the queue, with the handler address, data and optional timing.
No. A successful create call only means the task was stored safely. The work happens later, and the result is not returned to the producer.
Yes. Delivery is at least once, so a task may be delivered more than once in rare cases, especially after timeouts. Make handlers idempotent.
Not strictly. Retries and parallel dispatch can change the order. If order matters, include sequence information and let the handler ignore stale updates.
A success status in the two hundreds. Any other reply, or no reply within the deadline, is treated as a failure and the task is retried.
They cap the speed and concurrency of dispatch, protecting handlers and outside systems from floods and turning spikes into a steady flow.
Failed tasks wait with a growing delay and are tried again until they succeed or reach the limit of attempts or total retry time that you set on the queue.
Not built in at the time of writing, so check the current documentation. Teams usually build their own pattern by recording permanently failing tasks and alerting.
Cloud Tasks sends a job to a specific handler chosen by the sender, with control over speed, delay and retries. Pub/Sub announces events to any number of independent subscribers.
Require authentication, use a dedicated service account for dispatch with permission to invoke only that handler, and never rely on the secrecy of the address.
Yes, with a schedule time, up to a limited number of days ahead. For longer delays, store the intent and create the task closer to the time.
For most teams the cost is modest, often with a free monthly allowance and a price per million operations beyond it. Handler compute and logging may cost more. Check the current pricing page.
30Summary and Key Takeaways
Cloud Tasks is the reliable ticket rail of your cloud applications. Producers add small tasks to named queues, and the managed dispatcher delivers each task to a handler you control, at a speed you set, retrying with growing waits when something fails. Tasks can be delayed with a schedule time, protected against duplicate creation with names, and observed through logs and metrics. Delivery is at least once and order is not guaranteed, so handlers must be idempotent and must carry out their own checks. Good design separates queues by dependency, authenticates every handler, passes identifiers instead of secrets, records permanently failing tasks, and watches backlog and age. With these habits, background work becomes dependable, customer requests stay fast, and fragile partners stay safe.
Key Takeaways
- Queues own the rules, tasks own the job — speed limits, concurrency and retries live on the queue, while each task carries the handler address and small data.
- Assume at-least-once delivery — write idempotent handlers keyed by a business identifier, and never rely on exactly-once behaviour or strict ordering.
- Protect dependencies with limits — set dispatch rate and concurrency below the weakest link, and use separate queues for separate dependencies.
- Retry wisely — use backoff, sensible attempt and duration limits, and tell temporary errors from permanent ones.
- Reply fast, chunk long work — keep handlers within the deadline to avoid timeouts and duplicate runs.
- Secure the path — authenticate handlers with a dedicated service account, keep secrets and large data out of tasks, and limit who can enqueue.
- Watch and rehearse — alert on backlog, failure share and oldest task age, keep a dead-letter pattern, and practise pausing, resuming and replaying.