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

Reference

How to Set a Custom Backup Schedule with Longer Retention in Neki

Create a Neki backup policy through the PlanetScale API that runs daily at 02:00 UTC and retains backups for one year, then verify the policy exists and clean up.

What you will build

A TypeScript workflow that configures a compliance-oriented Neki backup schedule by creating a PlanetScale backup policy with a daily run time and one-year retention.

GET /organizations/{org}/databases/{db}/backup-policies -> POST /organizations/{org}/databases/{db}/backup-policies -> DELETE /organizations/{org}/databases/{db}/backup-policies/{id} -> GET /organizations/{org}/databases/{db}/backup-policies

AI prompt

Build a TypeScript workflow that sets a custom Neki backup schedule with extended retention for compliance. Use the PlanetScale API to list existing backup policies, create a daily production backup policy with one-year retention, verify the response keys from a live run, and remove the test policy so the example is repeatable.

Prerequisites

  • Node.js 22 or later
  • A PlanetScale organization with a Neki database
  • A PlanetScale service token with read_backups and write_backups access for the database
  • npm or a compatible package manager

The Neki backups guide covers the immutable required policies and the full payload shape; the specific endpoints used below are documented in the list_backup_policies and create_backup_policy references.

Environment variables

  • PLANETSCALE_ORG: PlanetScale organization slug (for example acme)
  • PLANETSCALE_DATABASE: Neki database name slug (for example app-db)
  • PLANETSCALE_SERVICE_TOKEN_ID (secret): PlanetScale service token ID from Settings > Service tokens
  • PLANETSCALE_SERVICE_TOKEN (secret): PlanetScale service token secret shown when the token was created

1. Create the project

Set up a TypeScript project and install the runtime tooling. The example uses Node.js's built-in fetch, so no HTTP client package is required.

mkdir code-example && cd code-example
npm init -y
npm install --save-dev typescript@^5.6.0 @types/node@^22.9.0 tsx@^4.23.15
npx tsc --init --target ES2022 --module NodeNext --moduleResolution NodeNext --esModuleInterop true --strict true --outDir ./dist

2. Implement the backup policy script

Create src/neki-backup-policy.ts. It reads the credential from the environment, lists the current policies, creates a compliance-grade daily schedule with one-year retention, and deletes the test policy so the script can be rerun safely.

interface BackupPolicy {
  id: string;
  type: "BackupPolicy";
  display_name: string;
  name: string;
  target: "production" | "development";
  retention_value: number;
  retention_unit: "hour" | "day" | "week" | "month" | "year";
  frequency_value: number;
  frequency_unit: "hour" | "day" | "week" | "month";
  schedule_day: number | null;
  schedule_week: number | null;
  schedule_time: string | null;
  created_at: string;
  updated_at: string;
  last_ran_at: string | null;
  next_run_at: string | null;
  required: boolean;
}

interface ListBackupPoliciesResponse {
  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;
  data: BackupPolicy[];
}

interface RunResult {
  organization: string;
  database: string;
  existing_policies: BackupPolicy[];
  created_policy: BackupPolicy;
  deleted_policy_id: string;
  final_policies: BackupPolicy[];
}

const baseUrl = "https://api.planetscale.com/v1";
const organization = process.env.PLANETSCALE_ORG!;
const database = process.env.PLANETSCALE_DATABASE!;
const serviceTokenId = process.env.PLANETSCALE_SERVICE_TOKEN_ID!;
const serviceToken = process.env.PLANETSCALE_SERVICE_TOKEN!;

if (!organization || !database || !serviceTokenId || !serviceToken) {
  throw new Error(
    "Missing required environment variables: PLANETSCALE_ORG, PLANETSCALE_DATABASE, PLANETSCALE_SERVICE_TOKEN_ID, PLANETSCALE_SERVICE_TOKEN"
  );
}

// PlanetScale service tokens use "id:token", not a Bearer token.
const authHeader = `${serviceTokenId}:${serviceToken}`;

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

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

  return bodyText ? (JSON.parse(bodyText) as T) : (undefined as T);
}

async function listBackupPolicies(): Promise<ListBackupPoliciesResponse> {
  return api<ListBackupPoliciesResponse>(
    `/organizations/${organization}/databases/${database}/backup-policies`
  );
}

async function createBackupPolicy(
  policy: Partial<BackupPolicy>
): Promise<BackupPolicy> {
  return api<BackupPolicy>(
    `/organizations/${organization}/databases/${database}/backup-policies`,
    {
      method: "POST",
      body: JSON.stringify(policy),
    }
  );
}

async function deleteBackupPolicy(id: string): Promise<void> {
  await api<void>(
    `/organizations/${organization}/databases/${database}/backup-policies/${id}`,
    { method: "DELETE" }
  );
}

async function main(): Promise<RunResult> {
  const existing = await listBackupPolicies();

  const compliancePolicy = {
    name: "compliance-daily-1-year",
    target: "production" as const,
    frequency_value: 1,
    frequency_unit: "day" as const,
    schedule_time: "02:00",
    retention_value: 1,
    retention_unit: "year" as const,
  };

  const created = await createBackupPolicy(compliancePolicy);

  await deleteBackupPolicy(created.id);

  const final = await listBackupPolicies();

  return {
    organization,
    database,
    existing_policies: existing.data,
    created_policy: created,
    deleted_policy_id: created.id,
    final_policies: final.data,
  };
}

main()
  .then((result) => {
    console.log(JSON.stringify(result, null, 2));
  })
  .catch((err) => {
    console.error(err);
    process.exit(1);
  });

3. Run the verified workflow

Export the credentials, then run the TypeScript file with tsx. The output shows the existing required policies, the newly created compliance policy, and the policy list after cleanup.

export PLANETSCALE_ORG="your-org-slug"
export PLANETSCALE_DATABASE="your-neki-database-slug"
export PLANETSCALE_SERVICE_TOKEN_ID="your-token-id"
export PLANETSCALE_SERVICE_TOKEN="your-token-secret"
npx tsx src/neki-backup-policy.ts

Verify the result

Run against PlanetScale API v1 on 2026-11-04.

cd code-example && npx tsx src/neki-backup-policy.ts

Observed output:

{
  "organization": "[REDACTED]",
  "database": "[REDACTED]",
  "existing_policies": [
    {
      "id": "9u9z1jaxj635",
      "type": "BackupPolicy",
      "schedule_time": "19:35",
      "required": true,
      "display_name": "Backup policy Production daily",
      "name": "Production daily",
      "target": "production",
      "retention_value": 2,
      "retention_unit": "day",
      "frequency_value": 12,
      "frequency_unit": "hour",
      "schedule_day": null,
      "schedule_week": null,
      "created_at": "2026-11-03T19:50:48.011Z",
      "updated_at": "2026-11-03T20:35:03.641Z",
      "last_ran_at": "2026-11-03T20:35:03.641Z",
      "next_run_at": "2026-11-04T08:35:00.000Z"
    },
    {
      "id": "ugheqmb1uyq0",
      "type": "BackupPolicy",
      "schedule_time": "19:40",
      "required": true,
      "display_name": "Backup policy Development daily",
      "name": "Development daily",
      "target": "development",
      "retention_value": 2,
      "retention_unit": "day",
      "frequency_value": 12,
      "frequency_unit": "hour",
      "schedule_day": null,
      "schedule_week": null,
      "created_at": "2026-11-03T19:50:48.040Z",
      "updated_at": "2026-11-03T20:40:02.531Z",
      "last_ran_at": "2026-11-03T20:40:02.531Z",
      "next_run_at": "2026-11-04T08:40:00.000Z"
    }
  ],
  "created_policy": {
    "id": "o8ab5q2uuvsl",
    "type": "BackupPolicy",
    "schedule_time": "02:00",
    "required": false,
    "display_name": "Backup policy compliance-daily-1-year",
    "name": "compliance-daily-1-year",
    "target": "production",
    "retention_value": 1,
    "retention_unit": "year",
    "frequency_value": 1,
    "frequency_unit": "day",
    "schedule_day": null,
    "schedule_week": null,
    "created_at": "2026-11-04T00:26:41.940Z",
    "updated_at": "2026-11-04T00:26:41.940Z",
    "last_ran_at": null,
    "next_run_at": "2026-11-04T02:00:00.000Z"
  },
  "deleted_policy_id": "o8ab5q2uuvsl",
  "final_policies": [
    {
      "id": "9u9z1jaxj635",
      "type": "BackupPolicy",
      "schedule_time": "19:35",
      "required": true,
      "display_name": "Backup policy Production daily",
      "name": "Production daily",
      "target": "production",
      "retention_value": 2,
      "retention_unit": "day",
      "frequency_value": 12,
      "frequency_unit": "hour",
      "schedule_day": null,
      "schedule_week": null,
      "created_at": "2026-11-03T19:50:48.011Z",
      "updated_at": "2026-11-03T20:35:03.641Z",
      "last_ran_at": "2026-11-03T20:35:03.641Z",
      "next_run_at": "2026-11-04T08:35:00.000Z"
    },
    {
      "id": "ugheqmb1uyq0",
      "type": "BackupPolicy",
      "schedule_time": "19:40",
      "required": true,
      "display_name": "Backup policy Development daily",
      "name": "Development daily",
      "target": "development",
      "retention_value": 2,
      "retention_unit": "day",
      "frequency_value": 12,
      "frequency_unit": "hour",
      "schedule_day": null,
      "schedule_week": null,
      "created_at": "2026-11-03T19:50:48.040Z",
      "updated_at": "2026-11-03T20:40:02.531Z",
      "last_ran_at": "2026-11-03T20:40:02.531Z",
      "next_run_at": "2026-11-04T08:40:00.000Z"
    }
  ]
}

Expected: A new backup policy is created with target=production, frequency_value=1, frequency_unit=day, schedule_time=02:00, retention_value=1, retention_unit=year, and required=false, then deleted after verification.

How it works

The script lists the existing backup policies on a Neki database so you can see the immutable required schedules, then creates a custom production policy that runs daily at 02:00 UTC and retains backups for one year. It verifies the created policy's id, target, schedule, retention, and next_run_at from the live API response, then deletes the test policy so the example can be rerun without accumulating policies.

What the run corrected

These are beliefs the documentation supported and the run disproved.

  • Assumed: The API response would only contain the fields shown in the request body schema, without a type discriminator. Observed: Every backup policy object includes a type field with the value "BackupPolicy". Evidence: The live response for both existing and created policies included "type": "BackupPolicy" alongside id, name, and schedule fields.

  • Assumed: Service tokens authenticate with a standard Bearer <token> Authorization header. Observed: PlanetScale service tokens authenticate with Authorization: <SERVICE_TOKEN_ID>:<SERVICE_TOKEN>. Evidence: The initial attempt with Bearer returned 401; switching to the id:token format succeeded, matching the service-tokens documentation.

Common issues

401 Unauthorized or 403 Forbidden from the PlanetScale API

Cause: The Authorization header is sent as Bearer <token> instead of the service-token format id:token, or the service token lacks write_backups access on the database.

Fix: Use Authorization: <PLANETSCALE_SERVICE_TOKEN_ID>:<PLANETSCALE_SERVICE_TOKEN> and grant the token read_backups and write_backups access for the database.

Response says the default backup policies cannot be updated or deleted

Cause: Required system policies (required: true) are created automatically every 12 hours with 2-day retention and are immutable.

Fix: Create a new custom policy instead of modifying the required ones; custom policies have required: false.

Validation error when creating a weekly or monthly policy

Cause: Weekly and monthly frequencies require schedule_day, and monthly also requires schedule_week, in addition to schedule_time.

Fix: Provide schedule_day (0=Sunday through 6=Saturday) and schedule_week (0=first week through 3=fourth week) for weekly/monthly policies.

Next steps

  • Remove the deleteBackupPolicy call and keep the compliance policy for ongoing backups
  • Add schedule_day and schedule_week to the createBackupPolicy payload for weekly or monthly compliance schedules
  • Pin the created policy ID in the PlanetScale Terraform provider's planetscale_neki_backup_policy resource for infrastructure-as-code governance
  • Add an alert that fires when next_run_at stops advancing or a backup policy becomes required=false unexpectedly
verification:
  status: verified
  tested_at: "2026-11-04"
  product_version: "PlanetScale API v1 (Neki)"
  command: "list existing Neki backup policies, create a custom production policy (frequency=1 day, schedule_time=02:00, retention=1 year), then DELETE the created policy and re-list"
  expected_result: "existing policies include required 'Production daily' and 'Development daily' (frequency 12 hours, retention 2 days); new policy created with required=false, schedule_time=02:00, retention_value=1, retention_unit=year, next_run_at=2026-11-04T02:00:00Z; deleted; final list matches the initial list"