Asynchronous Task Queue Processing with GCP Cloud Tasks and Cloud Run
When building web APIs, long-running operations such as sending transactional emails, generating PDF reports, or calling third-party APIs should never block the main HTTP request-response cycle. Executing synchronous long tasks leads to high API latency and client timeouts.
Google Cloud Tasks paired with Cloud Run push targets provides a serverless task queuing engine with built-in concurrency controls, rate limiting, and exponential retry policies.
Key Components of Cloud Tasks Architecture
POST /tasks/process-email) via HTTP push, passing authentication OIDC tokens. [ User ] ──► [ Frontend API ] ──(Enqueues Task)──► [ Cloud Tasks Queue ]
│ │
(Fast HTTP 200 OK) (Controlled Push)
▼ ▼
[ Instant Response ] [ Worker Cloud Run ]Node.js Producer Code Example
import { CloudTasksClient } from '@google-cloud/tasks';
const client = new CloudTasksClient();
async function enqueueEmailTask(userEmail: string, templateId: string) {
const parent = client.queuePath('my-gcp-project', 'us-central1', 'email-queue');
const task = {
httpRequest: {
httpMethod: 'POST' as const,
url: 'https://worker-api-xyz-uc.a.run.app/tasks/email',
headers: { 'Content-Type': 'application/json' },
body: Buffer.from(JSON.stringify({ userEmail, templateId })).toString('base64'),
oidcToken: {
serviceAccountEmail: 'cloud-tasks-sa@my-gcp-project.iam.gserviceaccount.com'
}
}
};
await client.createTask({ parent, task });
}