Join us Nov 24 to watch Insights Agent turn slow queries into PRs. RSVP
Navigation

Reference

Delete Stale Neki Development Branches on a Schedule

List Neki database branches with the PlanetScale API, filter non-production branches by age and name prefix, and delete the stale ones from a TypeScript CLI.

What you will build

A TypeScript CLI that lists Neki database branches, identifies stale non-production branches, and deletes them.

Set credentials -> create test development branch -> GET /v1/organizations/{org}/databases/{db}/branches -> filter by production=false, age, and optional name prefix -> DELETE /v1/organizations/{org}/databases/{db}/branches/{branch}

AI prompt

Build a TypeScript cleanup script that connects to the PlanetScale API, lists Neki database branches, filters out production and protected branches older than a configurable age, optionally matches a name prefix, and deletes the stale development branches. Run it live and report the real response fields.

Prerequisites

  • Node.js 22 or later
  • A PlanetScale account with a Neki database
  • A PlanetScale service token with read_branch and delete_branch access
  • The service token ID for that token
  • npm or a compatible package manager

The endpoints the script hits are the PlanetScale list_branches and delete_branch references; see the broader Neki branching guide for the full life cycle around them.

Environment variables

  • PLANETSCALE_SERVICE_TOKEN (secret): PlanetScale service token secret
  • PLANETSCALE_SERVICE_TOKEN_ID (secret): PlanetScale service token ID used in the Authorization header
  • PLANETSCALE_ORG: PlanetScale organization slug
  • PLANETSCALE_DATABASE: Neki database name slug

1. Create the project and install dependencies

Initialize a Node.js project and install TypeScript with tsx so you can run TypeScript directly.

mkdir neki-branch-cleanup && cd neki-branch-cleanup
npm init -y
npm install --save-dev typescript tsx @types/node

2. Set your PlanetScale credentials

Export the credentials the script will read from the environment. You can create a service token in your PlanetScale organization settings.

export PLANETSCALE_SERVICE_TOKEN_ID="your_service_token_id"
export PLANETSCALE_SERVICE_TOKEN="your_service_token"
export PLANETSCALE_ORG="your_org"
export PLANETSCALE_DATABASE="your_database"

3. Add the cleanup script

Create src/cleanup.ts. It lists branches, pages through the results, filters for stale non-production branches, and deletes them. Pass --dry-run to preview what would be deleted.

interface Branch {
  id: string;
  type: string;
  kind: string;
  name: string;
  created_at: string;
  updated_at: string;
  production: boolean;
  deletion_protected: boolean;
  state: string;
  ready: boolean;
}

interface ListBranchesResponse {
  type: string;
  current_page: number;
  per_page: number;
  next_page: number | null;
  next_page_url: string | null;
  prev_page: number | null;
  prev_page_url: string | null;
  total_count: number;
  total_pages: number;
  data: Branch[];
}

const baseUrl = "https://api.planetscale.com/v1";

function requireEnv(name: string): string {
  const value = process.env[name];
  if (!value) {
    throw new Error(`Missing environment variable: ${name}`);
  }
  return value;
}

function authHeader(): string {
  const tokenId = process.env.PLANETSCALE_SERVICE_TOKEN_ID;
  const token = requireEnv("PLANETSCALE_SERVICE_TOKEN");
  return tokenId ? `${tokenId}:${token}` : `Bearer ${token}`;
}

async function api<T>(path: string, init: RequestInit = {}): Promise<T> {
  const url = `${baseUrl}${path}`;
  const response = await fetch(url, {
    ...init,
    headers: {
      Authorization: authHeader(),
      "Content-Type": "application/json",
      ...init.headers,
    },
  });

  if (!response.ok) {
    const body = await response.text();
    throw new Error(
      `PlanetScale API error: ${response.status} ${response.statusText} ${body}`,
    );
  }

  if (response.status === 204) {
    return undefined as T;
  }

  return (await response.json()) as T;
}

async function listBranches(
  org: string,
  database: string,
): Promise<Branch[]> {
  const path = `/organizations/${encodeURIComponent(org)}/databases/${encodeURIComponent(database)}/branches`;
  const all: Branch[] = [];
  let page: number | null = 1;
  while (page) {
    const res: ListBranchesResponse = await api<ListBranchesResponse>(
      `${path}?page=${page}`,
    );
    all.push(...res.data);
    page = res.next_page;
  }

  return all;
}

async function deleteBranch(
  org: string,
  database: string,
  branch: Branch,
  dryRun: boolean,
): Promise<void> {
  if (dryRun) {
    console.log(`[dry-run] would delete ${branch.name} (${branch.id})`);
    return;
  }

  console.log(`deleting ${branch.name} (${branch.id}) ...`);
  await api(
    `/organizations/${encodeURIComponent(org)}/databases/${encodeURIComponent(database)}/branches/${encodeURIComponent(branch.name)}`,
    { method: "DELETE" },
  );
  console.log(`deleted ${branch.name}`);
}

function parseArgs(): {
  maxAgeHours: number;
  dryRun: boolean;
  protectedToo: boolean;
  namePrefix: string | null;
} {
  const args = process.argv.slice(2);
  let maxAgeHours = 24 * 7; // default 7 days
  let dryRun = false;
  let protectedToo = false;
  let namePrefix: string | null = null;

  for (let i = 0; i < args.length; i++) {
    const arg = args[i];
    if (arg === "--max-age-hours" || arg === "-h") {
      maxAgeHours = Number(args[++i]);
    } else if (arg === "--max-age-days" || arg === "-d") {
      maxAgeHours = Number(args[++i]) * 24;
    } else if (arg === "--dry-run") {
      dryRun = true;
    } else if (arg === "--include-protected") {
      protectedToo = true;
    } else if (arg === "--name-prefix") {
      namePrefix = args[++i];
    } else if (arg === "--help") {
      console.log(`Usage: tsx src/cleanup.ts [options]

Options:
  --max-age-hours, -h <n>  Delete branches older than n hours (default: 168)
  --max-age-days, -d <n>   Delete branches older than n days
  --name-prefix <string>   Only consider branches whose names start with the prefix
  --dry-run                List branches that would be deleted without deleting them
  --include-protected      Also delete branches that have deletion protection enabled
`);
      process.exit(0);
    }
  }

  return { maxAgeHours, dryRun, protectedToo, namePrefix };
}

async function run(): Promise<void> {
  const org = requireEnv("PLANETSCALE_ORG");
  const database = requireEnv("PLANETSCALE_DATABASE");
  const { maxAgeHours, dryRun, protectedToo, namePrefix } = parseArgs();

  const now = Date.now();
  const maxAgeMs = maxAgeHours * 60 * 60 * 1000;

  console.log(
    `scanning ${org}/${database} for development branches older than ${maxAgeHours}h...`,
  );

  const branches = await listBranches(org, database);
  const stale = branches.filter((branch) => {
    if (branch.production) return false;
    if (branch.deletion_protected && !protectedToo) return false;
    if (namePrefix && !branch.name.startsWith(namePrefix)) return false;
    const ageMs = now - new Date(branch.created_at).getTime();
    return ageMs > maxAgeMs;
  });

  console.log(
    `found ${branches.length} branch(es), ${stale.length} stale development branch(es)`,
  );

  for (const branch of stale) {
    await deleteBranch(org, database, branch, dryRun);
  }

  console.log("done");
}

run().catch((err) => {
  console.error(err);
  process.exit(1);
});

4. Create a test branch and dry-run the cleanup

Create a disposable development branch so you can verify the script without touching production. Then run the script with --dry-run and a name prefix that matches only the test branch.

curl -sS -X POST \
  -H "Authorization: $PLANETSCALE_SERVICE_TOKEN_ID:$PLANETSCALE_SERVICE_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{"name":"stale-cleanup-test-default"}' \
  "https://api.planetscale.com/v1/organizations/$PLANETSCALE_ORG/databases/$PLANETSCALE_DATABASE/branches"

npx tsx src/cleanup.ts --max-age-hours 0 --name-prefix stale-cleanup-test- --dry-run

5. Delete stale branches

Remove --dry-run to delete the branches that matched the filter. For day-to-day use, set --max-age-days to 7 or whatever idle threshold your team agrees on.

npx tsx src/cleanup.ts --max-age-hours 0 --name-prefix stale-cleanup-test-

Verify the result

Run against PlanetScale API v1 (Neki) on 2026-11-04.

npx tsx src/cleanup.ts --max-age-hours 0 --name-prefix stale-cleanup-test-

Observed output:

scanning [REDACTED]/[REDACTED] for development branches older than 0h...
found 9 branch(es), 1 stale development branch(es)
deleting stale-cleanup-test-default (rqre9776lcna) ...
deleted stale-cleanup-test-default
done

Expected: The script lists branches, finds one stale non-production branch matching the prefix, deletes it, and prints confirmation.

How it works

The script reads a PlanetScale service token and token ID from the environment, builds an Authorization header in the format the API expects, and calls the list-branches endpoint. It pages through results if needed, filters out production and deletion-protected branches, optionally matches a name prefix, compares created_at to a configurable maximum age, and issues a DELETE for each stale branch. A --dry-run flag prints what would be deleted without making destructive calls.

What the run corrected

These are beliefs the documentation supported and the run disproved.

  • Assumed: The branch endpoints use Authorization: Bearer <token>. Observed: Service tokens use Authorization: <SERVICE_TOKEN_ID>:<SERVICE_TOKEN>. Evidence: The service-token docs specify the id:token format, and the live list/delete requests succeeded only with that format. The script falls back to Bearer if the ID is absent so both documented forms work.

  • Assumed: The branch object returned by the API includes sharded, keyspace_count, and vtgate_* fields as shown in the docs. Observed: The live Neki branch response omits those fields and includes cluster_architecture, cluster_display_name, frozen, deletion_protection_managed, default, and replicas. Evidence: The live list-branches response for the Neki database contained those keys and did not contain sharded or keyspace_count.

  • Assumed: A branch must be in the ready state before it can be deleted. Observed: DELETE succeeded while the test branch was still pending. Evidence: The create-branch response showed state: pending, and the subsequent cleanup DELETE returned 204 and removed the branch.

Common issues

403 Forbidden when deleting a branch

Cause: The service token does not have delete_branch access for the organization, database, or branch.

Fix: Create or update the service token with delete_branch access, or use an OAuth token with delete_branches scope.

Branches you wanted to keep were deleted

Cause: The script ran without --dry-run or without a --name-prefix to limit the blast radius.

Fix: Always run --dry-run first, and scope the cleanup with --name-prefix or additional filters such as parent branch.

422 or error when deleting a protected branch

Cause: The branch has deletion_protected set to true.

Fix: Disable deletion protection in the dashboard, or pass --include-protected only after reviewing each branch.

429 Too Many Requests

Cause: The PlanetScale API rate limit is 600 requests per minute.

Fix: Add a small delay between DELETE calls when cleaning up hundreds of branches.

Next steps

  • Schedule the script nightly via cron or a GitHub Action so stale branches are removed automatically
  • Post a Slack/Teams notification listing the branches that will be deleted before running the cleanup destructively
  • Use the deploy-requests endpoint to skip branches with open deploy requests
  • Replace creation-time aging with last-activity aging by querying query-insights or connection metrics
verification:
  status: verified
  tested_at: "2026-11-04"
  product_version: "PlanetScale API v1 (Neki)"
  command: "create a stale-cleanup-test- branch via POST /branches, then run the cleanup CLI with --max-age-hours 0 --name-prefix stale-cleanup-test- to list, filter, and DELETE matching branches"
  expected_result: "script scans the database, reports 9 total branches with 1 stale development branch matching the prefix, deletes stale-cleanup-test-default, prints 'deleted' confirmation and 'done'"