Use the PlanetScale Query Insights API to compare Neki query patterns before and after a deploy, surfacing the fingerprints whose p99 latency or row-read ratio worsened.
What you will build
A TypeScript tracer that uses Neki Query Insights telemetry to compare query patterns before and after a deploy and surfaces the patterns that degraded.
GET /organizations/{org}/databases/{db}/branches/{branch} -> schema_last_updated_at as deploy boundary -> GET /.../insights?sort=totalTime&dir=desc -> for each fingerprint GET /.../insights/{fingerprint}/summary?keyspace=...&from=...&to=... twice (before/after) -> rank regressions by p99 delta
AI prompt
Build a TypeScript workflow that uses Neki's Query Insights API to find query patterns that degraded after a deploy. It should read the branch's last schema change as the deploy time, list the top query patterns, fetch per-pattern summaries for the windows before and after that time, and emit a ranked regression report.
Prerequisites
- Node.js 22+ (the script uses the built-in fetch API)
- A PlanetScale organization with a Neki database branch
- A PlanetScale service token with read_database access
- The database and branch slugs you want to analyze
Background on the per-pattern data this tracer reads lives in the Query Insights guide and the anomalies guide; the exact endpoints are documented in the list_branch_queries and get_query_summary API references, with auth setup covered in the API getting-started guide.
Environment variables
PLANETSCALE_SERVICE_TOKEN(secret): PlanetScale service token used to authenticate API callsPLANETSCALE_ORG: PlanetScale organization slug
1. Create the project and install dependencies
Set up a new Node project and install TypeScript plus tsx so you can run the tracer without a separate compile step.
mkdir neki-query-telemetry && cd neki-query-telemetry
npm init -y
npm install --save-dev typescript @types/node tsx
2. Add the tracer script
Save this as trace-slow-query.ts. It reads the branch's last schema change as the deploy boundary, lists the top query patterns by total time, then fetches per-pattern summaries for the before and after windows and ranks the regressions.
#!/usr/bin/env node
import { env } from "node:process";
interface Branch {
created_at: string;
schema_last_updated_at: string | null;
}
interface QueryPattern {
id: string;
fingerprint: string;
keyspace: string;
normalized_sql: string;
statement_type: string;
multishard: boolean;
query_count: number;
rows_read_per_returned: number;
p99_latency: number;
sum_total_duration_millis: number;
}
interface ListQueriesResponse {
data: QueryPattern[];
}
interface QuerySummary {
fingerprint: string;
keyspace: string;
normalized_sql: string;
query_count: number | null;
p99_latency: number | null;
rows_read_per_returned: number | null;
sum_total_duration_millis: number | null;
multishard: boolean;
}
function getEnv(name: string): string {
const value = env[name];
if (!value) {
throw new Error(`Missing environment variable: ${name}`);
}
return value;
}
async function psFetch<T>(path: string, params?: URLSearchParams): Promise<T> {
const base = "https://api.planetscale.com/v1";
const url = new URL(base + path);
if (params) {
url.search = params.toString();
}
const response = await fetch(url.toString(), {
headers: {
Authorization: `Bearer ${getEnv("PLANETSCALE_SERVICE_TOKEN")}`,
Accept: "application/json",
},
});
if (!response.ok) {
const body = await response.text();
throw new Error(`PlanetScale API ${response.status}: ${body}`);
}
return (await response.json()) as T;
}
function toNumber(value: number | null | undefined): number {
return typeof value === "number" ? value : 0;
}
async function main() {
const org = getEnv("PLANETSCALE_ORG");
const database = process.argv[2] ?? getEnv("PLANETSCALE_DATABASE");
const branch = process.argv[3] ?? getEnv("PLANETSCALE_BRANCH");
if (!database || !branch) {
throw new Error(
"Provide database and branch as arguments or set PLANETSCALE_DATABASE and PLANETSCALE_BRANCH"
);
}
// 1. Use the branch's last schema change as the deploy timestamp.
const branchInfo = await psFetch<Branch>(
`/organizations/${org}/databases/${database}/branches/${branch}`
);
const deployAt = branchInfo.schema_last_updated_at ?? branchInfo.created_at;
const branchStart = branchInfo.created_at;
const now = new Date().toISOString();
// 2. Find the top query patterns by total database time.
const topParams = new URLSearchParams({
sort: "totalTime",
dir: "desc",
per_page: "10",
});
const top = await psFetch<ListQueriesResponse>(
`/organizations/${org}/databases/${database}/branches/${branch}/insights`,
topParams
);
// 3. Compare each pattern before and after the deploy.
const comparisons = [];
for (const pattern of top.data) {
const beforeParams = new URLSearchParams({
keyspace: pattern.keyspace,
from: branchStart,
to: deployAt,
});
const afterParams = new URLSearchParams({
keyspace: pattern.keyspace,
from: deployAt,
to: now,
});
const [before, after] = await Promise.all([
psFetch<QuerySummary>(
`/organizations/${org}/databases/${database}/branches/${branch}/insights/${pattern.fingerprint}/summary`,
beforeParams
),
psFetch<QuerySummary>(
`/organizations/${org}/databases/${database}/branches/${branch}/insights/${pattern.fingerprint}/summary`,
afterParams
),
]);
const beforeCount = toNumber(before.query_count);
const afterCount = toNumber(after.query_count);
const beforeP99 = toNumber(before.p99_latency);
const afterP99 = toNumber(after.p99_latency);
const beforeRowsRatio = toNumber(before.rows_read_per_returned);
const afterRowsRatio = toNumber(after.rows_read_per_returned);
comparisons.push({
fingerprint: pattern.fingerprint,
keyspace: pattern.keyspace,
statement_type: pattern.statement_type,
normalized_sql: pattern.normalized_sql.slice(0, 120),
multishard: pattern.multishard,
before: {
query_count: beforeCount,
p99_latency: beforeP99,
rows_read_per_returned: beforeRowsRatio,
sum_total_duration_millis: toNumber(before.sum_total_duration_millis),
},
after: {
query_count: afterCount,
p99_latency: afterP99,
rows_read_per_returned: afterRowsRatio,
sum_total_duration_millis: toNumber(after.sum_total_duration_millis),
},
p99_delta: afterP99 - beforeP99,
rows_read_per_returned_delta: afterRowsRatio - beforeRowsRatio,
total_duration_delta_millis:
toNumber(after.sum_total_duration_millis) -
toNumber(before.sum_total_duration_millis),
});
}
// 4. Surface the patterns that degraded or are new after the deploy.
const regressions = comparisons
.filter((c) => c.after.query_count > 0)
.filter(
(c) =>
c.p99_delta > 0 ||
c.rows_read_per_returned_delta > 0 ||
(c.before.query_count === 0 && c.after.query_count > 0)
)
.sort((a, b) => b.p99_delta - a.p99_delta);
const report = {
deploy_at: deployAt,
branch_start: branchStart,
analyzed_patterns: comparisons.length,
regressions,
};
console.log(JSON.stringify(report, null, 2));
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
3. Run the tracer against a branch
With PLANETSCALE_SERVICE_TOKEN and PLANETSCALE_ORG exported in your environment, run the script against a Neki database and branch. The command below was verified against a live Neki branch.
npx tsx trace-slow-query.ts neki-tx-test-1793849075 code-example-1793860817171
Verify the result
Run against PlanetScale API v1 on 2026-11-05.
npx tsx trace-slow-query.ts neki-tx-test-1793849075 code-example-1793860817171
Observed output:
{
"deploy_at": "2026-11-05T07:06:35.501Z",
"branch_start": "2026-11-05T06:40:17.859Z",
"analyzed_patterns": 10,
"regressions": [
{
"fingerprint": "ef99aedad78d4ffdac0b2a24e8ada163c3c9581670ad537e84f72773871e766f",
"keyspace": "postgres.3aa0fbe45454184b",
"statement_type": "INSERT",
"normalized_sql": "INSERT INTO warehouse.fact_orders_demo (customer_id, order_id, source_updated_at, status, total_cents) VALUES (...)",
"multishard": false,
"before": {
"query_count": 0,
"p99_latency": 0,
"rows_read_per_returned": 0,
"sum_total_duration_millis": 0
},
"after": {
"query_count": 1,
"p99_latency": 19985.356022514854,
"rows_read_per_returned": 0,
"sum_total_duration_millis": 20001.854
},
"p99_delta": 19985.356022514854,
"rows_read_per_returned_delta": 0,
"total_duration_delta_millis": 20001.854
}
]
}
Expected: A JSON report showing which query patterns got slower after the deploy, with before/after p99 latency, query count, and total duration deltas.
How it works
The script uses the PlanetScale Query Insights API. It reads the branch's schema_last_updated_at timestamp as a deploy boundary, fetches the top query patterns by cumulative execution time, and then requests per-pattern summaries for the windows before and after that boundary. It compares p99 latency, rows read per row returned, and total duration to identify patterns that are new or slower after the deploy.
What the run corrected
These are beliefs the documentation supported and the run disproved.
Assumed: pscale insights anomalies would surface the slow-query anomaly to trace Observed: The anomalies list was empty for the test branches Evidence: pscale insights anomalies <db> <branch> --org <org> returned [] on every ready Neki branch we tested
Assumed: A query fingerprint alone uniquely identifies a pattern Observed: The same fingerprint appears multiple times with different keyspaces Evidence: The list queries response returned the same fingerprint with keyspaces such as postgres.3aa0fbe45454184b and postgres.e94b22581e69b5aa
Assumed: rows_read_per_returned is always reported in every summary window Observed: It can be 0 or null when the window has sparse executions Evidence: The after-deploy summary for the SELECT pattern returned rows_read_per_returned: 0 while the before window returned 3
Assumed: The PLANETSCALE_DATABASE and PLANETSCALE_BRANCH environment variables pointed to a telemetry-enabled Neki branch Observed: They pointed to a different database/branch and had to be overridden with explicit slugs Evidence: Using the environment values produced a branch-not-found error; the live run used neki-tx-test-1793849075 and code-example-1793860817171
Common issues
PlanetScale API returns 404 for the branch
Cause: The database or branch slug is wrong, or the service token lacks read_database access
Fix: List databases and branches with the PlanetScale API or pscale CLI and confirm the token permissions
Summary endpoint returns query_count 0 for a known pattern
Cause: The keyspace parameter does not match the keyspace returned by the list queries endpoint
Fix: Always pass the keyspace field from the list response when requesting /insights/{fingerprint}/summary
rows_read_per_returned is 0 or null in a window
Cause: The selected window has too few executions for the ratio to be reported
Fix: Treat null or missing values as 0 and rely on p99_latency and sum_total_duration_millis for sparse windows
Top results are dominated by one-off DDL statements
Cause: Sorting by totalTime still surfaces high-latency CREATE/ALTER patterns with very low counts
Fix: Filter by statement_type or sort by p99Latency and require a minimum query_count in your filter
Next steps
- Replace schema_last_updated_at with the real deploy timestamp from your CI/CD pipeline for a precise before/after boundary
- Cross-check the detected regressions against PlanetScale's anomaly list via /insights/anomalies
- Run EXPLAIN (NEKI_PLAN) on the top regressed fingerprints to inspect shard routing and index usage
- Schedule the tracer in a GitHub Action or cron job to flag regressions automatically after each deploy
verification:
status: verified
tested_at: "2026-11-05"
product_version: "PlanetScale API v1"
command: "fetch the branch's schema_last_updated_at as the deploy boundary, GET /insights?sort=totalTime&dir=desc for the top 10 fingerprints, then call /insights/{fingerprint}/summary with (branch_start, deploy_at) and (deploy_at, now), diff p99/row-ratio/duration, rank regressions"
expected_result: "report prints deploy_at + branch_start, analyzed_patterns=10, and a regressions array sorted by p99_delta: top entry is the new fact_orders_demo INSERT with before.query_count=0, after.query_count=1, p99_delta ~19985 ms, total_duration_delta_millis ~20001.854"