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

Reference

Set Neki Router Size and Replicas per Environment

Create a Neki staging branch from production, shrink its default router and data-node replica count, and compare the per-environment sizing from live PlanetScale API responses.

What you will build

A TypeScript CLI that provisions a fresh Neki staging branch, right-sizes its default router and data-node configuration profile, and prints a side-by-side comparison with production.

GET /branches -> POST /branches (from production) -> poll GET /branches/{staging} -> PATCH /routers/default -> PATCH /configuration-profiles/default -> GET /routers (production) -> JSON comparison

AI prompt

Build a TypeScript workflow that uses the PlanetScale API to provision a Neki staging branch with a smaller router size and fewer replicas than production, confirming the per-environment sizing from live API responses.

Prerequisites

  • Node.js 18+ (native fetch)
  • A PlanetScale service token with create_branch, write_database, and read_branch access
  • A Neki database with an existing production branch
  • tsx and TypeScript installed as dev dependencies

The PlanetScale cluster-sizing guide lists every supported router and cluster SKU; use the name field from that table (e.g. NKR_DEV, PS_DEV_AWS_ARM_NEKI) rather than the display name when you call the API.

Environment variables

  • PLANETSCALE_SERVICE_TOKEN (secret): PlanetScale service token from Settings -> Service tokens
  • PLANETSCALE_ORG: PlanetScale organization slug
  • PLANETSCALE_DATABASE: Neki database name

1. Create the project

Initialize a Node project and add TypeScript and tsx as dev dependencies. The script uses only the native fetch API, so no product SDK is required.

mkdir -p neki-env-sizing/src
cd neki-env-sizing
npm init -y
npm install --save-dev typescript@5.7.3 tsx@4.19.2 @types/node@22.10.5

2. Add the sizing script

Save src/right-size-neki-environments.ts. It reads the required environment variables, creates a fresh staging branch from production, polls until the branch is ready, then PATCHes the default router size/replicas and the default configuration profile size/replicas. Finally it prints a JSON comparison and cleans up the staging branch.

#!/usr/bin/env node
/**
 * Right-size Neki router groups and data-node replicas per branch.
 *
 * Neki branches are independent environments. This script creates a fresh
 * staging branch from production, shrinks its default router to a smaller
 * router size with fewer replicas per cell, and sets the default configuration
 * profile to zero data-node replicas. It then compares the production and
 * staging sizing so you can see the per-environment cost difference.
 */

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

const token = requireEnv("PLANETSCALE_SERVICE_TOKEN");
const org = requireEnv("PLANETSCALE_ORG");
const database = requireEnv("PLANETSCALE_DATABASE");

const productionBranchName =
  process.env.PLANETSCALE_PRODUCTION_BRANCH || undefined;
const stagingBranchName = process.env.PLANETSCALE_STAGING_BRANCH || undefined;

const stagingRouterSize = process.env.STAGING_ROUTER_SIZE || "NKR_DEV";
const stagingRouterReplicasPerCell = Number(
  process.env.STAGING_ROUTER_REPLICAS_PER_CELL ?? 1
);
const stagingConfigReplicas = Number(process.env.STAGING_CONFIG_REPLICAS ?? 0);
const stagingClusterSize =
  process.env.STAGING_CLUSTER_SIZE || "PS_DEV_AWS_ARM_NEKI";
const cleanup = (process.env.CLEANUP ?? "true").toLowerCase() === "true";

interface Branch {
  id: string;
  name: string;
  kind: string;
  state: string;
  ready: boolean;
  production: boolean;
  cluster_name: string;
  cluster_display_name: string;
  replicas: number;
  parent_branch: string | null;
}

interface Router {
  id: string;
  name: string;
  default: boolean;
  router_size: string;
  replicas_per_cell: number;
  autoscaling: boolean;
  max_replicas_per_cell: number | null;
  target_cpu_utilization: number | null;
  state: string;
  sku: {
    name: string;
    display_name: string;
    cpu: string;
    ram: number;
  };
}

interface ConfigProfile {
  id: string;
  name: string;
  default: boolean;
  cluster_size: string;
  cluster_display_name: string;
  replicas: number;
  read_only_replicas: number;
  state: string;
}

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

async function api(path: string, init: RequestInit = {}): Promise<unknown> {
  const url = `${BASE_URL}${path}`;
  const headers: Record<string, string> = {
    Authorization: `Bearer ${token}`,
    "Content-Type": "application/json",
    ...(init.headers as Record<string, string>),
  };

  const response = await fetch(url, { ...init, headers });
  let body: unknown;
  try {
    body = await response.json();
  } catch {
    body = await response.text();
  }

  if (!response.ok) {
    const detail =
      typeof body === "object" && body !== null
        ? JSON.stringify(body)
        : String(body);
    throw new Error(`PlanetScale API ${response.status} for ${url}: ${detail}`);
  }

  return body;
}

async function listBranches(): Promise<Branch[]> {
  const payload = (await api(
    `/organizations/${org}/databases/${database}/branches`
  )) as { data: Branch[] };
  return payload.data;
}

async function getBranch(name: string): Promise<Branch> {
  return (await api(
    `/organizations/${org}/databases/${database}/branches/${name}`
  )) as Branch;
}

async function createBranch(
  name: string,
  parentBranch: string
): Promise<Branch> {
  return (await api(`/organizations/${org}/databases/${database}/branches`, {
    method: "POST",
    body: JSON.stringify({
      name,
      parent_branch: parentBranch,
      kind: "neki",
    }),
  })) as Branch;
}

async function deleteBranch(name: string): Promise<void> {
  await api(`/organizations/${org}/databases/${database}/branches/${name}`, {
    method: "DELETE",
  });
}

async function pollBranchReady(
  name: string,
  maxAttempts = 30,
  delayMs = 10000
): Promise<Branch> {
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    const branch = await getBranch(name);
    if (branch.ready && branch.state === "ready") {
      return branch;
    }
    console.error(
      `  branch ${name} is ${branch.state} (ready=${branch.ready}), waiting...`
    );
    await sleep(delayMs);
  }
  throw new Error(`Branch ${name} did not become ready in time`);
}

async function listRouters(branch: string): Promise<Router[]> {
  return (await api(
    `/organizations/${org}/databases/${database}/branches/${branch}/routers`
  )) as Router[];
}

async function updateRouter(
  branch: string,
  routerName: string,
  body: { router_size: string; replicas_per_cell: number }
): Promise<Router> {
  return (await api(
    `/organizations/${org}/databases/${database}/branches/${branch}/routers/${routerName}`,
    { method: "PATCH", body: JSON.stringify(body) }
  )) as Router;
}

async function listConfigProfiles(branch: string): Promise<ConfigProfile[]> {
  return (await api(
    `/organizations/${org}/databases/${database}/branches/${branch}/configuration-profiles`
  )) as ConfigProfile[];
}

async function updateConfigProfile(
  branch: string,
  profileName: string,
  body: { cluster_size: string; replicas: number }
): Promise<ConfigProfile> {
  return (await api(
    `/organizations/${org}/databases/${database}/branches/${branch}/configuration-profiles/${profileName}`,
    { method: "PATCH", body: JSON.stringify(body) }
  )) as ConfigProfile;
}

function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

function pickProductionBranch(branches: Branch[]): Branch {
  if (productionBranchName) {
    const branch = branches.find((b) => b.name === productionBranchName);
    if (!branch) {
      throw new Error(`Production branch ${productionBranchName} not found`);
    }
    return branch;
  }
  const branch = branches.find((b) => b.production || b.name === "main");
  if (!branch) {
    throw new Error("Could not find a production branch");
  }
  return branch;
}

async function resolveStagingBranch(
  _branches: Branch[],
  productionName: string
): Promise<{ branch: Branch; created: boolean }> {
  if (stagingBranchName) {
    const branch = await getBranch(stagingBranchName);
    return { branch, created: false };
  }

  const name = `cost-staging-${Math.floor(Date.now() / 1000)}`;
  console.error(`Creating staging branch ${name} from ${productionName}...`);
  const branch = await createBranch(name, productionName);
  const ready = await pollBranchReady(branch.name);
  return { branch: ready, created: true };
}

async function main() {
  console.error("Listing branches...");
  const branches = await listBranches();
  const production = pickProductionBranch(branches);
  const { branch: staging, created: createdStaging } =
    await resolveStagingBranch(branches, production.name);

  console.error(
    `Production branch: ${production.name} (${production.cluster_display_name}, ${production.replicas} data replicas)`
  );
  console.error(
    `Staging branch:    ${staging.name} (${staging.cluster_display_name}, ${staging.replicas} data replicas)`
  );

  console.error("Fetching production default router...");
  const productionRouters = await listRouters(production.name);
  const productionRouter = productionRouters.find((r) => r.default);
  if (!productionRouter) {
    throw new Error("No default router found on production branch");
  }

  console.error("Right-sizing staging router...");
  const stagingRouters = await listRouters(staging.name);
  const stagingDefaultRouter = stagingRouters.find((r) => r.default);
  if (!stagingDefaultRouter) {
    throw new Error("No default router found on staging branch");
  }

  const rightSizedRouter = await updateRouter(staging.name, "default", {
    router_size: stagingRouterSize,
    replicas_per_cell: stagingRouterReplicasPerCell,
  });

  console.error("Right-sizing staging data-node configuration profile...");
  const stagingProfiles = await listConfigProfiles(staging.name);
  const stagingDefaultProfile = stagingProfiles.find((p) => p.default);
  if (!stagingDefaultProfile) {
    throw new Error("No default configuration profile found on staging branch");
  }

  const rightSizedProfile = await updateConfigProfile(staging.name, "default", {
    cluster_size: stagingClusterSize,
    replicas: stagingConfigReplicas,
  });

  const result = {
    production: {
      branch: production.name,
      cluster_size: production.cluster_name,
      data_replicas: production.replicas,
      default_router: {
        name: productionRouter.name,
        router_size: productionRouter.router_size,
        replicas_per_cell: productionRouter.replicas_per_cell,
        cpu: productionRouter.sku.cpu,
        ram_bytes: productionRouter.sku.ram,
      },
    },
    staging: {
      branch: staging.name,
      cluster_size: rightSizedProfile.cluster_size,
      data_replicas: rightSizedProfile.replicas,
      default_router: {
        name: rightSizedRouter.name,
        router_size: rightSizedRouter.router_size,
        replicas_per_cell: rightSizedRouter.replicas_per_cell,
        cpu: rightSizedRouter.sku.cpu,
        ram_bytes: rightSizedRouter.sku.ram,
      },
    },
  };

  console.log(JSON.stringify(result, null, 2));

  if (createdStaging && cleanup) {
    console.error(`Cleaning up staging branch ${staging.name}...`);
    await deleteBranch(staging.name);
  }
}

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

3. Run the sizing workflow

Export the PlanetScale credentials, then run the script. Progress messages go to stderr; the final JSON comparison is printed to stdout. Optional env vars let you override the staging SKU and replica counts.

export PLANETSCALE_SERVICE_TOKEN=$PLANETSCALE_SERVICE_TOKEN
export PLANETSCALE_ORG=your-org
export PLANETSCALE_DATABASE=your-neki-db
# optional overrides
# export STAGING_ROUTER_SIZE=NKR_DEV
# export STAGING_ROUTER_REPLICAS_PER_CELL=1
# export STAGING_CLUSTER_SIZE=PS_DEV_AWS_ARM_NEKI
# export STAGING_CONFIG_REPLICAS=0
npx tsx src/right-size-neki-environments.ts

Verify the result

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

npx tsx src/right-size-neki-environments.ts

Observed output:

{
  "production": {
    "branch": "[REDACTED]",
    "cluster_size": "PS_10_AWS_ARM_NEKI",
    "data_replicas": 2,
    "default_router": {
      "name": "default",
      "router_size": "NKR_1",
      "replicas_per_cell": 1,
      "cpu": "1/16",
      "ram_bytes": 134217728
    }
  },
  "staging": {
    "branch": "cost-staging-1793752710",
    "cluster_size": "PS_DEV_AWS_ARM_NEKI",
    "data_replicas": 0,
    "default_router": {
      "name": "default",
      "router_size": "NKR_DEV",
      "replicas_per_cell": 1,
      "cpu": "1/32",
      "ram_bytes": 120586240
    }
  }
}

Expected: A JSON comparison of production and staging router sizes, replicas per cell, cluster sizes, and data replica counts.

How it works

Neki treats each branch as an independent environment. The script finds the production branch, creates a new staging branch from it, and polls until the branch is ready. It then resizes the staging default router with the update_router endpoint, setting router_size and replicas_per_cell to smaller values, and resizes the staging default configuration profile with the update_shard_configuration_profile endpoint, setting cluster_size and replicas to smaller values. Finally it reads the production default router and the updated staging resources and emits a JSON comparison. The staging branch is deleted at the end unless CLEANUP is set to false.

What the run corrected

These are beliefs the documentation supported and the run disproved.

  • Assumed: Router and data-node sizing can be set at branch creation time via router_sizes and configuration_profile_sizes. Observed: Those fields only apply to Neki backup restores; normal branches inherit defaults and must be resized after creation. Evidence: A live POST /branches with router_sizes/configuration_profile_sizes returned 500, while creating the branch first and then PATCHing /routers/default and /configuration-profiles/default succeeded and appeared in the final comparison.

  • Assumed: A Neki or PlanetScale management SDK is needed to change router and configuration profile sizes. Observed: The management endpoints are plain REST under https://api.planetscale.com/v1 and the example uses native fetch with no product package. Evidence: The working script makes direct fetch calls to /routers and /configuration-profiles; no @planetscale management SDK was installed or used.

Common issues

POST /branches returns 500 when router_sizes or configuration_profile_sizes are included

Cause: The create-branch sizing fields are only valid for Neki backup restores, not for normal branch creation.

Fix: Create the branch without sizing fields, then PATCH /routers/default and /configuration-profiles/default after the branch is ready.

Branch is not ready immediately after creation

Cause: Neki branch provisioning can stay in the pending state for roughly 30-60 seconds.

Fix: Poll GET /branches/{branch} until state is ready and ready is true before updating routers or configuration profiles.

PATCH /routers/default fails with a SKU error

Cause: The display name (e.g. NKR-DEV) was used instead of the SKU name.

Fix: Use the name field from the cluster-sizing guide or GET /router-size-skus, such as NKR_DEV.

Next steps

  • Add dedicated non-default router groups for different workloads on the same branch and size them independently
  • Enable router autoscaling on production by PATCHing autoscaling, max_replicas_per_cell, and target_cpu_utilization after load testing
  • Wrap branch creation and sizing in a CI job that spins up a preview environment per pull request and tears it down on merge
  • Manage the sizing in the PlanetScale Terraform provider so infrastructure changes are reviewed like schema changes
verification:
  status: verified
  tested_at: "2026-11-04"
  product_version: "PlanetScale API v1, Neki Platform Preview"
  command: "list production branch and its default router, create cost-staging-<ts> from production, poll to ready, PATCH staging router to NKR_DEV with 1 replica per cell, PATCH staging configuration profile to PS_DEV_AWS_ARM_NEKI with 0 replicas, print JSON comparison"
  expected_result: "production on PS_10_AWS_ARM_NEKI with 2 data replicas and NKR_1 router (1/16 cpu); staging on PS_DEV_AWS_ARM_NEKI with 0 data replicas and NKR_DEV router (1/32 cpu); JSON comparison printed; staging branch deleted at end"