Skip to content

Daily

Delete old preview branches nightly

Preview branches past a set age are removed each night, and you get the list of what went.

Runs
Daily
Apps
Neon
AI
Not needed
Access
read+write

Send this to your assistant

Create a ClickRuntime automation: every night, delete Neon branches older than 14 days except main and anything starting with release-, and email me the names removed. Show me a dry run first.

Paste it into your assistant. It tells you what it will send or change before it runs live.

First time? Adding ClickRuntime to your assistant takes about two minutes.

Why use it

Why teams use this automation

Neon makes branching so cheap that preview branches pile up: one per pull request, one per demo, one for the contractor who left in the spring. Each holds a copy of data, counts toward your project's branch limit and storage, and some contain customer records copied from production. Nobody is responsible for deleting them, and a developer eventually hits the branch limit in the middle of a release.

Every day ClickRuntime lists the branches in your Neon project, filters for those that match a naming pattern such as preview/ and are older than 14 days, deletes them, and emails the list of what was removed. The main branch and anything that does not match the pattern are left alone.

Engineering leads who use Neon with per-pull-request environments use it as routine housekeeping.

What you get out of it

  • Branch limits stop interrupting releases

    Old previews are cleared before they reach the project cap. A developer can create the branch they need on release day without first hunting for something safe to delete. Release day does not start with a search for safe branches to delete.

  • Storage and compute costs stay predictable

    Every leftover branch keeps data that you pay to hold. Removing two-week-old previews each day stops forgotten copies from adding to the Neon bill month after month. Leftover branches keep data that you pay to store, month after month.

  • Stale copies of data are removed

    Preview branches often contain production-like records. Deleting them on a fixed schedule reduces how long personal data sits in places nobody remembers, which helps with data protection duties. That also shortens the list of places a data request would have to cover.

  • Nobody has to remember cleanup

    The task belongs to a schedule instead of the person who last complained. Teams stop relying on a quarterly clean-up day that only happens if someone is annoyed enough. Cleanup is owned by a schedule, not by whoever is annoyed enough.

  • A written record of every deletion

    The emailed list names each branch removed and when it was created. If a developer says their branch vanished, you can show it was past the age limit. Showing that a branch was past the limit settles any argument quickly.

How it works

What happens, step by step

  1. Every night ClickRuntime lists the branches in your Neon project.

  2. It picks out preview branches older than the age you set, matching the names you chose.

  3. It deletes them, or just lists what it would delete while you are trying it out.

  4. You get an email listing the branches removed.

Before it runs live

  • Connect Neon

What you get

RunsDaily
Delete old preview branches nightlytoday, 9:00Succeeded
Email · Branch clean-upWould delete 3 Neon branches preview/pr-412 preview/pr-418 feature-search

Build your own

Need it to work differently?

This template is a starting point. Copy the prompt and change it, or describe a different automation from scratch, with your own conditions, more apps or an AI step. Your assistant writes it, tests it and runs it on ClickRuntime.
  • Your own rules

    Conditions, thresholds, filters and exceptions, written the way you'd explain them to a colleague.

  • Any number of apps

    One automation can read from one app and update several others. Over 248 apps are ready, and anything with an API works too.

  • AI where it helps

    Summaries, classification, extraction and drafts use ClickRuntime's built-in AI, with no extra key.

  • On a schedule or on each event

    Runs as often as every 5 minutes, or the moment an app sends an event, and keeps track of what it already handled.

Changes you can ask for

  • Run it at a different time, more or less often, or only on weekdays
  • Add an AI step, for example to summarize, sort or draft a reply
  • Add another app, for example also send it to Slack
  • Combine it with other Neon steps into one automation

Under the hood

The code that runs this automation

This is the Python script that runs each time the automation starts. Your AI assistant writes it for you when you send the prompt, and you allow each step in your assistant. To change how the automation works, describe the change to your assistant and it updates the script for you. For every function it can use, see the script reference.
clean_up_old_branches.pyexample
from datetime import datetime, timedelta, timezone
from clickruntime import on_trigger, credentials, http, notify

NEON = "https://console.neon.tech/api/v2"

def neon(method, path, **kwargs):
    resp = http.request(method, f"{NEON}{path}", headers={"Authorization": f"Bearer {credentials.secret('NEON_API_KEY')}"}, **kwargs)
    resp.raise_for_status()
    return resp.json()

PROJECT_ID = "your-neon-project-id"
DRY_RUN = True  # set to False once the list looks right

@on_trigger
def run(event):
    cutoff = datetime.now(timezone.utc) - timedelta(days=14)
    removed = []
    for b in neon("GET", f"/projects/{PROJECT_ID}/branches")["branches"]:
        old = datetime.fromisoformat(b["created_at"].replace("Z", "+00:00")) < cutoff
        if old and not b.get("default") and b["name"] != "main" and not b["name"].startswith("release-"):
            if not DRY_RUN:
                neon("DELETE", f"/projects/{PROJECT_ID}/branches/{b['id']}")
            removed.append(b["name"])
    title = "Would delete" if DRY_RUN else "Deleted"
    notify.email_me(f"{title} {len(removed)} Neon branches", "\n".join(removed) or "Nothing to remove.")
    return {"dry_run": DRY_RUN, "branches": removed}

FAQ

Common questions

Can it protect specific branches?
Yes. It only touches branches that match your naming pattern and exceed the age, and it never deletes the default branch. You can also keep a list of names or prefixes, such as release/ or staging, that are always skipped.
Is deletion reversible?
Deleting a Neon branch is permanent, although you may be able to restore within the project's history window depending on plan. Choose an age that is clearly longer than any real use of a preview, and read the first emailed list.
How is a branch's age calculated?
It uses the branch's creation time reported by the Neon API. If you prefer inactivity, last-active time can be used instead, so a branch used yesterday is kept even if it is a month old.
What permissions does it need?
read+write. Nothing else in your accounts is used.
Does it need AI?
No. It runs without AI, so it doesn't use your plan's AI allowance.
How many runs does it use?
One run each time it runs (daily). Checks that find nothing to do and stop right away aren't counted.
Can I change how it works?
Yes. Describe the change to your AI assistant, for example a different schedule, channel or filter. It updates the automation, tests it and tells you what changed.

Set up “Delete old preview branches nightly” from your assistant

Copy the prompt above, or connect your assistant first. Free plan, no credit card.