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

Reference

Keep Neki Replica Reads in the Same Availability Zone as the Router

Route Neki read queries to replicas and require the chosen replica to live in the same availability zone (cell) as the router, cutting cross-zone latency.

What you will build

A TypeScript script that connects to Neki over TLS, configures replica routing with same-AZ locality, and runs a verified read query.

Connect with pg.Client -> SET __neki.target='replica' -> SET __neki.replica_locality='require' -> SELECT current_setting(...) and read query -> JSON output

AI prompt

Build a TypeScript example that connects to a Neki database, routes reads to replicas, requires the replica to be in the router's availability zone, and confirms the routing settings from a live query.

Prerequisites

  • Node.js 22 with npm
  • A Neki database branch with at least one replica
  • A Neki connection string from the PlanetScale dashboard or pscale role (TLS required)

The session variables used below (__neki.target, __neki.replica_locality, __neki.replica_recency, __neki.replica_affinity) are described in the replicas guide and the shard-targeting / fan-out guide; the rdonly target discussed in Next steps is covered in the read-only replicas reference.

Environment variables

  • NEKI_DATABASE_URL (secret): Neki connection string (e.g. postgresql://user:pass@host:5432/postgres?sslmode=verify-full)

1. Create the project and install dependencies

Set up a TypeScript project, add the Postgres driver, and configure ts-node so the example runs directly.

mkdir neki-same-zone-reads && cd neki-same-zone-reads
npm init -y
npm install pg@8.13.1
npm install -D typescript@5.6.3 ts-node@10.9.2 @types/pg@8.11.10

2. Add tsconfig.json

Use CommonJS module output so ts-node can run the pg client without ESM interoperability issues.

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "CommonJS",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "strict": true,
    "skipLibCheck": true,
    "outDir": "./dist"
  },
  "include": ["src/**/*.ts"]
}

3. Implement the same-zone read script

Read the connection string from the environment, connect with TLS verification enabled, then set the Neki routing session variables before running any read query. A bounded retry handles transient replica unavailability.

import { Client } from 'pg';

const DATABASE_URL = process.env.NEKI_DATABASE_URL;
if (!DATABASE_URL) {
  throw new Error('NEKI_DATABASE_URL is required');
}

const MAX_RETRIES = 3;
const RETRY_DELAY_MS = 500;

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

async function runSameZoneRead() {
  const client = new Client({
    connectionString: DATABASE_URL,
    ssl: { rejectUnauthorized: true },
    connectionTimeoutMillis: 10000,
  });

  try {
    await client.connect();

    // Send reads to replicas instead of shard primaries.
    await client.query("SET __neki.target = 'replica'");

    // Require the replica to be in the same availability zone (cell) as the router.
    await client.query("SET __neki.replica_locality = 'require'");

    // Optional: prefer the freshest replica tier and keep the session on one replica.
    await client.query("SET __neki.replica_recency = 'prefer'");
    await client.query("SET __neki.replica_affinity = 'session'");

    const settings = await client.query<{
      target: string;
      locality: string;
      recency: string;
      affinity: string;
    }>(
      `SELECT
        current_setting('__neki.target') AS target,
        current_setting('__neki.replica_locality') AS locality,
        current_setting('__neki.replica_recency') AS recency,
        current_setting('__neki.replica_affinity') AS affinity`
    );

    const result = await client.query<{ now: string; role: string }>(
      `SELECT now()::text AS now, current_user AS role`
    );

    return {
      settings: settings.rows[0],
      read: result.rows[0],
    };
  } finally {
    await client.end().catch(() => undefined);
  }
}

async function main() {
  let lastError: unknown;

  for (let attempt = 1; attempt <= MAX_RETRIES; attempt += 1) {
    try {
      const output = await runSameZoneRead();
      console.log(JSON.stringify(output));
      return;
    } catch (err) {
      lastError = err;
      const message = err instanceof Error ? err.message : String(err);
      if (
        message.toLowerCase().includes('no eligible replica') ||
        message.toLowerCase().includes('connection')
      ) {
        if (attempt < MAX_RETRIES) {
          await sleep(RETRY_DELAY_MS * attempt);
          continue;
        }
      }
      break;
    }
  }

  console.error(lastError instanceof Error ? lastError.message : String(lastError));
  process.exit(1);
}

main();

4. Run the verified workflow

Export the Neki connection string and run the script. The live output confirms the session is on the replica target with same-zone locality required.

export NEKI_DATABASE_URL="$NEKI_DATABASE_URL"
npm install
npx ts-node src/same-zone-read.ts

Verify the result

Run against pscale 0.349.0 / Neki on 2026-11-05.

export NEKI_DATABASE_URL="$NEKI_DATABASE_URL" && npm install && npx ts-node src/same-zone-read.ts

Observed output:

{"settings":{"target":"REPLICA","locality":"require","recency":"prefer","affinity":"session"},"read":{"now":"2026-11-05 03:31:46.330866+00","role":"postgres"}}

Expected: A successful read query with session settings showing target=REPLICA and locality=require

How it works

The example uses the standard Postgres wire protocol and the node-postgres driver. After connecting, it issues Neki-specific SET commands to route reads to replicas (__neki.target) and require the replica to be in the same availability zone/cell as the router (__neki.replica_locality=require). It then reads the session settings back from the live connection to confirm the configuration and executes a read query to prove the replica path works end to end. A bounded retry handles transient replica unavailability, which the docs note can happen during replica maintenance.

What the run corrected

These are beliefs the documentation supported and the run disproved.

  • Assumed: The replica target and locality values would stay lowercase as sent in the SET statements. Observed: current_setting returned REPLICA in uppercase for the target; locality stayed lowercase. Evidence: The live response contained {"target":"REPLICA","locality":"require","recency":"prefer","affinity":"session"} after sending lowercase 'replica'.

  • Assumed: The routing options had to be embedded in the connection URI's options parameter to take effect. Observed: Executing SET __neki.target = 'replica' and SET __neki.replica_locality = 'require' after connect worked and was reflected by current_setting. Evidence: The probe connected with only TLS configured, ran the SET statements, and then read back the configured values from Neki.

  • Assumed: A read-only replica target was needed for the same-zone latency use case. Observed: The same-zone locality setting applies to the replica target used for live read traffic; read-only replicas are a separate rdonly target for long-running work. Evidence: The docs distinguish replica and rdonly targets, and the live query succeeded with __neki.target = 'replica' plus locality=require.

Common issues

Query fails with no eligible replica

Cause: locality=require excludes every replica because none are in the router's availability zone or all are above the lag threshold.

Fix: Add replicas across the router's AZs, relax to SET __neki.replica_locality = 'prefer', or run the read from a router group in an AZ with replicas.

SET __neki.target fails with a transaction error

Cause: Neki does not allow changing target, locality, recency, or affinity inside a transaction.

Fix: Run the SET statements before BEGIN, or set them in the connection options at connect time.

Reads still go to the primary

Cause: The application opened the connection with the default target or a previous SET was overwritten.

Fix: Verify current_setting('__neki.target') and current_setting('__neki.replica_locality') after connect, and set them on a fresh connection.

Next steps

  • Move the SET commands into the connection URI's options parameter so every pool connection starts with the target and locality already configured.
  • Fail closed in your application when no same-zone replica is eligible, or fall back to locality=prefer with an alert.
  • Measure query latency with locality=require versus locality=prefer to confirm the cross-zone latency reduction in your region.
  • Apply the same locality requirement to read-only replica traffic (SET __neki.target = 'rdonly') for long-running analytics jobs.
verification:
  status: verified
  tested_at: "2026-11-05"
  product_version: "pscale 0.349.0 / Neki"
  command: "connect to NEKI_DATABASE_URL with TLS, set __neki.target='replica' + __neki.replica_locality='require' (plus recency/affinity), read session settings back via current_setting, and run a timestamp/current_user read"
  expected_result: "settings returns {target:'REPLICA', locality:'require', recency:'prefer', affinity:'session'}; read query returns a non-null now timestamp and the authenticated role"