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

Reference

Create Extra Neki Server Groups with a Bigger Instance Size from the CLI

Use the PlanetScale CLI from a TypeScript script to add a dedicated Neki router group sized larger than the default group, then verify both groups report ready.

What you will build

A TypeScript script that automates the PlanetScale CLI to provision a Neki database and create an extra router group with a larger instance size than the default group.

pscale database create -> pscale branch router list -> pscale branch router sizes -> pscale branch router create -> poll -> pscale branch router list -> summary JSON

AI prompt

Build a TypeScript example that uses the PlanetScale CLI to create a Neki database, list router groups and sizes, create an additional router group with a bigger SKU than the default group, and verify the group reaches the ready state.

Prerequisites

  • Node.js 22 or later
  • PlanetScale CLI (pscale) 0.348.0 or later
  • A PlanetScale service token with write_database access
  • A PlanetScale organization that has joined the Neki Platform Preview

The router and cluster SKUs referenced below (e.g. NKR-1, PS-10-AWS-ARM-NEKI) come from the cluster-sizing guide; the reference example on scaling router groups under live traffic describes when to add a dedicated group versus resizing the default one.

Environment variables

  • PLANETSCALE_ORG: Your PlanetScale organization name
  • PLANETSCALE_SERVICE_TOKEN_ID (secret): PlanetScale service token ID
  • PLANETSCALE_SERVICE_TOKEN (secret): PlanetScale service token secret

1. Create the TypeScript project

Create the project directory, add package.json and tsconfig.json, install dependencies, and make sure pscale is installed.

mkdir -p neki-router-groups-example/src
cd neki-router-groups-example

# Ensure pscale is installed (macOS/Linux example)
curl -fsSL https://github.com/planetscale/cli/releases/download/v0.349.0/pscale_0.349.0_linux_amd64.tar.gz | tar -xz
install -m 755 pscale "$HOME/.local/bin/pscale"

npm init -y
npm install --save-dev typescript@^5.6.3 @types/node@^22.9.0

cat > tsconfig.json <<'EOF'
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true
  },
  "include": ["src/**/*"]
}
EOF

# Add a start script to package.json
npm pkg set scripts.start='npm run build && node dist/index.js'
npm pkg set scripts.build='tsc'
npm pkg set type='module'

2. Configure credentials

Export your PlanetScale organization and service token so the script can authenticate non-interactively.

export PLANETSCALE_ORG="your-org"
export PLANETSCALE_SERVICE_TOKEN_ID="your-token-id"
export PLANETSCALE_SERVICE_TOKEN="your-token-secret"

# Optional: reuse an existing Neki database instead of creating one
export NEKI_DATABASE="your-existing-database"

3. Implement src/index.ts

The script shells out to pscale, creates a Neki database if needed, discovers the default branch, lists the current router groups and available sizes, then creates a new router group with the next-larger SKU and polls until it is ready.

import { spawn } from "node:child_process";
import { env } from "node:process";

interface RouterGroup {
  type: string;
  name: string;
  default: boolean;
  sku: {
    name: string;
    display_name: string;
    cpu: string;
    ram: number;
    sort_order: number;
  };
  replicas_per_cell: number;
  autoscaling: boolean;
  max_replicas_per_cell: number | null;
  target_cpu_utilization: number | null;
  state: string;
  created_at: string;
  updated_at: string;
}

interface RouterSize {
  name: string;
  display_name: string;
  cpu: string;
  ram: number;
  sort_order: number;
  rate: number;
}

interface Branch {
  id: string;
  name: string;
  state: string;
  ready: boolean;
}

function run(command: string, args: string[]): Promise<{ stdout: string; stderr: string; exitCode: number }> {
  return new Promise((resolve) => {
    const child = spawn(command, args, { env: { ...env } });
    let stdout = "";
    let stderr = "";
    child.stdout.on("data", (data: Buffer) => { stdout += data.toString(); });
    child.stderr.on("data", (data: Buffer) => { stderr += data.toString(); });
    child.on("close", (exitCode) => { resolve({ stdout, stderr, exitCode: exitCode ?? 0 }); });
  });
}

function pscale(args: string[]): Promise<{ stdout: string; stderr: string; exitCode: number }> {
  return run("pscale", args);
}

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

async function waitForDatabase(database: string, org: string, timeoutSeconds = 600): Promise<void> {
  const deadline = Date.now() + timeoutSeconds * 1000;
  while (Date.now() < deadline) {
    const { stdout, exitCode } = await pscale(["database", "show", database, "--org", org, "--format", "json"]);
    if (exitCode === 0) {
      const payload = JSON.parse(stdout);
      if (payload.state === "ready") return;
    }
    await new Promise((resolve) => setTimeout(resolve, 10000));
  }
  throw new Error(`Timed out waiting for database ${database} to become ready`);
}

async function getDefaultBranch(database: string, org: string): Promise<string> {
  const { stdout, exitCode } = await pscale(["branch", "list", database, "--org", org, "--format", "json"]);
  if (exitCode !== 0) throw new Error("Failed to list branches");
  const branches: Branch[] = JSON.parse(stdout);
  const defaultBranch = branches.find((b) => b.ready);
  if (!defaultBranch) throw new Error("No ready branch found");
  return defaultBranch.name;
}

async function listRouterGroups(database: string, branch: string, org: string): Promise<RouterGroup[]> {
  const { stdout, exitCode } = await pscale([
    "branch", "router", "list", database, branch, "--org", org, "--format", "json",
  ]);
  if (exitCode !== 0) throw new Error("Failed to list router groups");
  return JSON.parse(stdout) as RouterGroup[];
}

async function listRouterSizes(database: string, branch: string, org: string): Promise<RouterSize[]> {
  const { stdout, exitCode } = await pscale([
    "branch", "router", "sizes", database, branch, "--org", org, "--format", "json",
  ]);
  if (exitCode !== 0) throw new Error("Failed to list router sizes");
  return JSON.parse(stdout) as RouterSize[];
}

async function createRouterGroup(
  database: string,
  branch: string,
  name: string,
  size: string,
  replicasPerCell: number,
  org: string
): Promise<RouterGroup> {
  const { stdout, stderr, exitCode } = await pscale([
    "branch", "router", "create", database, branch, name,
    "--size", size,
    "--replicas-per-cell", String(replicasPerCell),
    "--org", org,
    "--format", "json",
  ]);
  if (exitCode !== 0) throw new Error(`Failed to create router group: ${stdout} ${stderr}`);
  return JSON.parse(stdout) as RouterGroup;
}

async function pollRouterGroupReady(
  database: string,
  branch: string,
  name: string,
  org: string,
  timeoutSeconds = 300
): Promise<RouterGroup> {
  const deadline = Date.now() + timeoutSeconds * 1000;
  while (Date.now() < deadline) {
    const groups = await listRouterGroups(database, branch, org);
    const group = groups.find((g) => g.name === name);
    if (group && group.state === "ready") return group;
    await new Promise((resolve) => setTimeout(resolve, 10000));
  }
  throw new Error(`Timed out waiting for router group ${name} to become ready`);
}

function formatBytes(bytes: number): string {
  const units = ["B", "KB", "MB", "GB"];
  let value = bytes;
  let unitIndex = 0;
  while (value >= 1024 && unitIndex < units.length - 1) {
    value /= 1024;
    unitIndex++;
  }
  return `${Math.round(value)} ${units[unitIndex]}`;
}

async function main(): Promise<void> {
  const org = requireEnv("PLANETSCALE_ORG");
  requireEnv("PLANETSCALE_SERVICE_TOKEN_ID");
  requireEnv("PLANETSCALE_SERVICE_TOKEN");

  const versionResult = await pscale(["version"]);
  if (versionResult.exitCode !== 0) throw new Error("pscale CLI is not installed or not on PATH");
  console.log(`CLI: ${versionResult.stdout.trim()}`);

  const database = env.NEKI_DATABASE ?? `neki-router-groups-${Date.now()}`;
  const newGroupName = env.NEKI_ROUTER_GROUP_NAME ?? "api-routers";

  console.log(`\nUsing database: ${database}`);
  console.log(`Using organization: ${org}`);

  const existingDb = await pscale(["database", "show", database, "--org", org, "--format", "json"]);
  if (existingDb.exitCode !== 0) {
    console.log("\nCreating Neki database...");
    const createResult = await pscale([
      "database", "create", database,
      "--engine", "neki",
      "--org", org,
      "--region", "us-east",
      "--cluster-size", "PS-10-AWS-ARM-NEKI",
      "--replicas", "2",
      "--wait",
      "--format", "json",
    ]);
    if (createResult.exitCode !== 0) {
      console.error(createResult.stderr);
      throw new Error("Failed to create database");
    }
    const created = JSON.parse(createResult.stdout);
    console.log(`Created database: ${created.name} (state: ${created.state})`);
  } else {
    console.log("\nDatabase already exists, skipping creation.");
  }

  await waitForDatabase(database, org);
  console.log("Database is ready.");

  const branch = await getDefaultBranch(database, org);
  console.log(`Default branch: ${branch}`);

  const initialGroups = await listRouterGroups(database, branch, org);
  console.log("\nInitial router groups:");
  for (const group of initialGroups) {
    console.log(`  - ${group.name}: ${group.sku.display_name}, ${group.replicas_per_cell} replica(s)/cell, state=${group.state}`);
  }

  const defaultGroup = initialGroups.find((g) => g.default);
  if (!defaultGroup) throw new Error("No default router group found");

  const sizes = await listRouterSizes(database, branch, org);
  sizes.sort((a, b) => a.sort_order - b.sort_order);

  const currentSizeIndex = sizes.findIndex((s) => s.display_name === defaultGroup.sku.display_name);
  const targetSize = sizes[currentSizeIndex + 1];
  if (!targetSize) throw new Error("No larger router size available than the default");

  console.log("\nAvailable router sizes (sample):");
  for (const size of sizes) {
    const marker = size.display_name === defaultGroup.sku.display_name ? " <- default" : "";
    const targetMarker = size.display_name === targetSize.display_name ? " <- target" : "";
    console.log(`  - ${size.display_name}: ${size.cpu} vCPU, ${formatBytes(size.ram)} RAM${marker}${targetMarker}`);
  }

  const existingGroup = initialGroups.find((g) => g.name === newGroupName);
  if (existingGroup) {
    console.log(`\nRouter group '${newGroupName}' already exists. Skipping creation.`);
  } else {
    console.log(`\nCreating router group '${newGroupName}' with size ${targetSize.display_name}...`);
    const created = await createRouterGroup(database, branch, newGroupName, targetSize.display_name, 1, org);
    console.log(`Created: ${created.name} (state: ${created.state}, size: ${created.sku.display_name})`);
  }

  const readyGroup = await pollRouterGroupReady(database, branch, newGroupName, org);
  console.log(`Router group '${readyGroup.name}' is ready.`);

  const finalGroups = await listRouterGroups(database, branch, org);
  console.log("\nFinal router groups:");
  for (const group of finalGroups) {
    console.log(`  - ${group.name}: ${group.sku.display_name}, ${group.replicas_per_cell} replica(s)/cell, default=${group.default}, state=${group.state}`);
  }

  const summary = {
    database,
    branch,
    default_group: defaultGroup.name,
    default_size: defaultGroup.sku.display_name,
    new_group: readyGroup.name,
    new_size: readyGroup.sku.display_name,
    replicas_per_cell: readyGroup.replicas_per_cell,
    state: readyGroup.state,
  };
  console.log("\nSummary:");
  console.log(JSON.stringify(summary, null, 2));
}

main().catch((error) => {
  console.error(error instanceof Error ? error.message : String(error));
  process.exit(1);
});

4. Run the verified workflow

Compile and run the script. It creates a Neki database if needed, provisions a second router group one size larger than the default, and prints both groups.

npm start

Verify the result

Run against pscale 0.348.0; Neki Platform Preview on 2026-11-05.

npm start

Observed output:

CLI: pscale version 0.348.0 (build date: 2026-10-21T15:33:56Z commit: 68b31936)

Using database: neki-router-groups-1793849628873
Using organization: [REDACTED]

Creating Neki database...
Created database: neki-router-groups-1793849628873 (state: ready)
Database is ready.
Default branch: [REDACTED]

Initial router groups:
  - default: NKR-1, 1 replica(s)/cell, state=ready

Available router sizes (sample):
  - NKR-0: 1/32 vCPU, 115 MB RAM
  - NKR-1: 1/16 vCPU, 128 MB RAM <- default
  - NKR-2: 1/8 vCPU, 256 MB RAM <- target
  - NKR-5: 1/4 vCPU, 512 MB RAM
  - NKR-10: 1/2 vCPU, 1 GB RAM
  - NKR-20: 1 vCPU, 2 GB RAM
  - NKR-80: 3 vCPU, 5 GB RAM
  - NKR-160: 7 vCPU, 10 GB RAM
  - NKR-320: 14 vCPU, 19 GB RAM
  - NKR-640: 27 vCPU, 39 GB RAM

Creating router group 'api-routers' with size NKR-2...
Created: api-routers (state: ready, size: NKR-2)
Router group 'api-routers' is ready.

Final router groups:
  - default: NKR-1, 1 replica(s)/cell, default=true, state=ready
  - api-routers: NKR-2, 1 replica(s)/cell, default=false, state=ready

Summary:
{
  "database": "neki-router-groups-1793849628873",
  "branch": "[REDACTED]",
  "default_group": "default",
  "default_size": "NKR-1",
  "new_group": "api-routers",
  "new_size": "NKR-2",
  "replicas_per_cell": 1,
  "state": "ready"
}

Expected: A new Neki router group named api-routers with size NKR-2 is created alongside the default NKR-1 group, and both report state ready.

How it works

The script shells out to the PlanetScale CLI. It creates a Neki database if one is not supplied, discovers the default branch, lists the default router group and all available router SKUs, selects the next larger SKU, creates a new router group with one replica per cell, polls until the group reports ready, and lists both groups with their sizes and states.

What the run corrected

These are beliefs the documentation supported and the run disproved.

  • Assumed: The PLANETSCALE_DATABASE and PLANETSCALE_BRANCH environment variables pointed to an existing Neki database. Observed: Those values did not exist or did not identify a Neki branch, so the script creates a database and discovers the default branch dynamically. Evidence: pscale branch router list against the provided database/branch returned NOT_FOUND, while pscale database list returned an empty array.

  • Assumed: The default branch would be named main. Observed: The default branch name is returned by pscale branch list and is read dynamically rather than hard-coded. Evidence: The script calls pscale branch list and selects the first ready branch; the live response included the branch name in the name field.

  • Assumed: Router group creation might return state applying and require polling. Observed: The create response returned state ready immediately, but the script still polls to handle cases where the platform applies changes asynchronously. Evidence: The create response contained "state": "ready" and subsequent list calls also showed ready.

Common issues

pscale database create fails immediately

Cause: The PlanetScale organization has not joined the Neki Platform Preview or the service token lacks write_database access.

Fix: Ask an organization administrator to join the Neki preview and confirm the service token has write_database access.

Router group creation fails with a conflict error

Cause: A router group with the chosen name already exists on the branch.

Fix: Set NEKI_ROUTER_GROUP_NAME to a unique name, or reuse an existing group and call pscale branch router update instead.

Polling for ready state never completes

Cause: The size is being read from a non-existent top-level size field instead of sku.display_name.

Fix: Read the router size from sku.display_name in the JSON output, as shown in the list and create responses.

Next steps

  • Route traffic through the new group with pscale shell <db> <branch> --router api-routers
  • Resize the group vertically with pscale branch router update <db> <branch> api-routers --size NKR-5
  • Enable horizontal autoscaling with --autoscaling --max-replicas-per-cell and --target-cpu-utilization
  • Delete the demo database with pscale database delete <name> --force when you are finished
verification:
  status: verified
  tested_at: "2026-11-05"
  product_version: "pscale 0.348.0; Neki Platform Preview"
  command: "create a Neki database with pscale, discover the default branch, list router groups and sizes, create a new router group one size above the default, poll until ready, print final list and summary"
  expected_result: "default group is NKR-1 with 1 replica/cell; new group 'api-routers' created with size NKR-2 and reaches state=ready; final listing shows both groups ready; summary JSON reports default_size=NKR-1, new_size=NKR-2, state=ready"