TL;DR
Master Google Cloud Run Jobs with this comprehensive guide covering batch processing, job execution, monitoring, and best practices for serverless workloads
Google Cloud Run Jobs: Complete Guide to Serverless Batch Processing
Executive Summary
Cloud Run jobs run containers to completion rather than in response to requests: data backfills, report generation, media processing, database migrations, and other batch work that starts, runs, and exits. This guide explains the execution model — a job, its executions, and parallel tasks — and the design rules that make batch work reliable on it: partitioning work by task index, building in idempotency and checkpointing, sizing CPU, memory, and timeouts, and triggering executions from schedules or pipelines. After reading it, you should be able to take an existing batch script, containerise it, and run it as a job that survives retries without double-processing its input.
Why This Matters
Batch jobs fail differently from services. A service degrades; a batch job silently produces a wrong or duplicated output and exits zero, and nobody notices until a downstream report or a customer does. The classic causes are retries that reprocess already-finished work, parallel tasks that overwrite each other's output, and a single oversized task that runs into its timeout after hours of compute. Cloud Run jobs give you managed parallelism and retries, but those features amplify bad design as easily as good design: automatic retries on a non-idempotent task are a data-corruption mechanism. The platform handles infrastructure; correctness under retry and parallelism is still yours.
Core Concepts
Jobs, Executions, and Tasks
A job is a reusable definition: a container image plus CPU, memory, timeout, environment, and retry settings. Running a job creates an execution. An execution can fan out into many parallel tasks, each a separate container instance that knows its own position through two environment variables Cloud Run injects: CLOUD_RUN_TASK_INDEX (this task's index) and CLOUD_RUN_TASK_COUNT (the total). The standard pattern is for each task to claim a deterministic slice of the input — a range of rows, a shard of files — based on its index, so tasks never need to coordinate with each other.
A job definition in YAML:
# job.yaml
apiVersion: run.googleapis.com/v1
kind: Job
metadata:
name: batch-processor
spec:
template:
spec:
containers:
- image: gcr.io/project-id/processor:latest
resources:
limits:
cpu: "1"
memory: "2Gi"
env:
- name: BATCH_SIZE
value: "100"
- name: INPUT_BUCKET
value: "gs://input-data"
- name: OUTPUT_BUCKET
value: "gs://processed-data"Partitioning Work by Task Index
The container code reads its index and processes only its slice:
import os
import time
from google.cloud import storage
def process_batch():
# Get environment variables
batch_size = int(os.getenv("BATCH_SIZE", "100"))
input_bucket = os.getenv("INPUT_BUCKET")
output_bucket = os.getenv("OUTPUT_BUCKET")
task_index = int(os.getenv("CLOUD_RUN_TASK_INDEX", "0"))
task_count = int(os.getenv("CLOUD_RUN_TASK_COUNT", "1"))
# Initialize storage client
storage_client = storage.Client()
# Calculate batch range for this task
start_index = task_index * batch_size
end_index = start_index + batch_size
try:
# Process batch
process_items(start_index, end_index)
return True
except Exception as e:
print(f"Error processing batch: {e}")
return False
if __name__ == "__main__":
success = process_batch()
exit(0 if success else 1)Two details decide whether this works in production. First, exit codes are the contract: exit non-zero on failure so the platform retries the task; never swallow an exception and exit zero. Second, keep tasks independent and roughly equal in size — the execution finishes when the slowest task finishes, so skewed partitions waste the parallelism you paid for.
Creating and Running Jobs Programmatically
Jobs can be managed with gcloud, the console, or the Cloud Run Admin API. Creating a parallel job from Python:
from google.cloud import run_v2
from google.cloud.run_v2 import Job, TaskTemplate
def create_parallel_job(
project: str,
location: str,
job_name: str,
image_uri: str,
task_count: int = 10,
):
client = run_v2.JobsClient()
parent = f"projects/{project}/locations/{location}"
job = Job(
template=TaskTemplate(
containers=[{
"image": image_uri,
"resources": {
"limits": {
"cpu": "1",
"memory": "2Gi"
}
}
}],
max_retries=3,
task_count=task_count,
),
labels={"environment": "production"}
)
operation = client.create_job(
parent=parent,
job_id=job_name,
job=job
)
return operation.result()Executions are triggered the same way — manually, from Cloud Scheduler for cron-style runs, from Workflows or Eventarc for event-driven runs, or from a CI/CD pipeline for tasks such as migrations:
from google.cloud import run_v2
def execute_job(
project: str,
location: str,
job_name: str,
):
client = run_v2.JobsClient()
request = run_v2.RunJobRequest(
name=f"projects/{project}/locations/{location}/jobs/{job_name}"
)
operation = client.run_job(request=request)
execution = operation.result()
print(f"Job execution completed with status: {execution.status}")
return executionIdempotency and Checkpointing
Because failed tasks are retried, every unit of work must be safe to run twice. The standard approach is a deterministic key per item and a processed-marker written atomically with the result:
def process_item(item_id: str):
# Generate deterministic execution ID
execution_id = hashlib.sha256(f"{item_id}".encode()).hexdigest()
# Check if already processed
if is_processed(execution_id):
return
try:
# Process item
result = perform_processing(item_id)
# Mark as processed
mark_processed(execution_id, result)
except Exception as e:
log_error(execution_id, e)
raiseFor long tasks, checkpoint progress so a retry resumes instead of restarting. Writing the checkpoint to Cloud Storage every N items bounds the repeated work:
def process_batch_with_checkpoint():
checkpoint_bucket = storage.Client().bucket("checkpoints")
checkpoint_blob = checkpoint_bucket.blob(f"job-{JOB_ID}/checkpoint")
# Load last checkpoint
last_processed = 0
if checkpoint_blob.exists():
last_processed = int(checkpoint_blob.download_as_text())
try:
# Process items from last checkpoint
for i in range(last_processed, TOTAL_ITEMS):
process_item(i)
# Save checkpoint every 100 items
if i % 100 == 0:
checkpoint_blob.upload_from_string(str(i))
except Exception as e:
# Save checkpoint on failure
checkpoint_blob.upload_from_string(str(last_processed))
raiseSizing and Timeouts
Tasks can be configured with up to 8 CPUs and 32 GiB of memory, and a task timeout of up to 24 hours. Size from measurement: watch memory headroom and task duration in Cloud Monitoring, and treat a task that regularly approaches its timeout as a design problem — split the input further rather than raising limits and hoping. Sensible operating targets:
| Metric | Target | Action if exceeded |
|---|---|---|
| Task duration | Under 30 minutes | Split the input into more, smaller tasks |
| Memory usage | Under 80% of the limit | Raise the limit or stream instead of loading data |
| Error rate | Under 1% of tasks | Stop, read the failed task logs, fix before rerunning |
Decision Framework
| Situation | Recommendation |
|---|---|
| Scheduled report, ETL step, or backfill | Cloud Run job triggered by Cloud Scheduler |
| Batch work under a few hours with parallelisable input | Cloud Run job with task-count partitioning |
| Event-driven file or message processing | Cloud Run job triggered via Eventarc/Workflows, or a Cloud Run service if per-event latency matters |
| Tightly coupled distributed computing (shuffling, iterative ML) | Dataflow or Dataproc, which manage worker coordination |
| One-off administrative task | Run the job manually; do not build a service for it |
Implementation Checklist
CLOUD_RUN_TASK_INDEX; tasks share no mutable stateTrade-offs
Cloud Run jobs are deliberately simple, and the limits follow from that. There is no built-in work queue between tasks, no dynamic task spawning mid-execution, and no inter-task communication — coordination patterns belong to Dataflow or a workflow engine. Cold start and per-task granularity mean very short tasks carry proportionally more overhead than they would on a long-lived worker. The 24-hour task ceiling is generous but real: work that cannot be partitioned below it does not fit. Finally, retries are a blunt instrument — they assume failure is transient, so a deterministic bug retries expensively before it fails visibly.
When Not to Use
Conclusion
Cloud Run jobs are the right home for batch work that is container-shaped and partitionable: define the job once, slice input by task index, make every item idempotent, and let the platform handle parallelism and retries. The design effort belongs in partitioning and failure semantics, not infrastructure. If your workload needs coordination between workers or never ends, reach for a data processing or streaming platform instead.
References
Why This Matters
Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.
Trade-offs to Consider
Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.
When NOT to Use This
Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.
Decision Framework
Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.