How to Automatically Cleanup Revisions in Cloud Run Functions & Firebase

When building scalable and serverless applications with Google Cloud Run and Firebase, it’s easy to accumulate dozens—or even hundreds—of old...

When building scalable and serverless applications with Google Cloud Run and Firebase, it’s easy to accumulate dozens—or even hundreds—of old revisions over time. These unused revisions can lead to increased costs, bloated dashboards, and unnecessary security exposure.

In this guide, we’ll walk through how to automatically clean up old revisions in Cloud Run, especially for Firebase projects using Firebase Functions (2nd gen), which are backed by Cloud Run.


🚨 Why You Should Care About Old Revisions

Every time you deploy a new version of a Cloud Run service or a Firebase function (2nd gen), Google Cloud creates a new revision. While this allows for safe rollbacks and traffic splitting, older revisions can:

  • Increase costs (storage + minor execution costs)
  • Pose security risks if they contain outdated dependencies
  • Clutter your Cloud Run dashboard

While Google Cloud doesn’t delete these automatically, the good news is: you can automate this cleanup.


🧠 Understanding Cloud Run Revisions in Firebase

If you’re using Firebase Functions (2nd gen), your functions are actually Cloud Run services under the hood. Each deployment creates a new revision in a Cloud Run service like:

ghs-<project-id>-<region>-<function-name>

You can manage these directly in the Cloud Run console or using the gcloud CLI.


🛠️ How to Automatically Cleanup Old Revisions

We’ll use Google Cloud Scheduler, Cloud Run, and a custom script to periodically delete older revisions.

🔧 Step 1: Set Up Permissions

Ensure your Cloud Run or cleanup service has the necessary permissions:

gcloud projects add-iam-policy-binding <PROJECT_ID> \
  --member="serviceAccount:<SERVICE_ACCOUNT_EMAIL>" \
  --role="roles/run.admin"

Also grant the account:

  • roles/iam.serviceAccountUser
  • roles/resourcemanager.projectViewer

📜 Step 2: Create a Cleanup Script

Create a script that deletes all but the latest N revisions (e.g., keep only the last 2).

Python Example:

import subprocess
import json

# Configuration
SERVICE_NAME = "ghs-your-function-name"
REGION = "us-central1"
PROJECT_ID = "your-project-id"
KEEP = 2

# Get all revisions
result = subprocess.run([
    "gcloud", "run", "revisions", "list",
    f"--service={SERVICE_NAME}",
    f"--region={REGION}",
    f"--project={PROJECT_ID}",
    "--format=json"
], capture_output=True, text=True)

revisions = sorted(json.loads(result.stdout), key=lambda r: r["createTime"], reverse=True)

# Delete old revisions
for revision in revisions[KEEP:]:
    name = revision["metadata"]["name"]
    print(f"Deleting: {name}")
    subprocess.run([
        "gcloud", "run", "revisions", "delete", name,
        f"--region={REGION}",
        f"--project={PROJECT_ID}",
        "--quiet"
    ])

Save this as cleanup_revisions.py.


🚀 Step 3: Deploy the Script as a Cloud Run Job (or Cloud Function)

You can:

  • Package the script in a Docker container
  • Deploy it as a Cloud Run job
  • Schedule it via Cloud Scheduler

Or, run it locally with a secure cron job using service account credentials.


📆 Step 4: Schedule the Job

Use Cloud Scheduler to run this cleanup weekly or monthly.

Example command:

gcloud scheduler jobs create http cleanup-old-revisions \
  --schedule="0 3 * * 0" \
  --http-method=POST \
  --uri=https://your-cleanup-service-url \
  --oidc-service-account-email=<SERVICE_ACCOUNT> \
  --project=<PROJECT_ID>

This runs the job every Sunday at 3 AM.


🧪 Bonus: Test It Manually First

Before automating, test your script in a staging environment. You can even add dry-run logic to avoid accidental deletions.


✅ Best Practices

  • 🛑 Don’t delete active revisions. Always check the traffic percentage.
  • 🔐 Use least privilege IAM roles. Only allow deletion from specific services.
  • 📦 Keep 1-2 older revisions. For rollback safety.
  • 🧹 Schedule cleanup monthly. Weekly may be too aggressive for some teams.

📚 Resources


🚀 Wrap-Up

Automating the cleanup of Cloud Run revisions, especially when using Firebase Functions (2nd gen), helps keep your environment clean, cost-effective, and secure. With a simple script and Cloud Scheduler, you can ensure your deployment history remains manageable.

Have questions or want a ready-to-deploy template? Let me know!


  • About
    Ajaay Ranaa

Leave A Reply

Your email address will not be published. Required fields are marked *


You May Also Like