@neon/skills 1.2.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,340 @@
1
+ # Production hardening for Neon Functions
2
+
3
+ A Function has a public HTTPS URL. Authenticate the caller, then pick extra
4
+ protection from who actually calls it. This file is the production path; JWT
5
+ and trigger parsers stay in [SKILL.md](../SKILL.md) and
6
+ [function-triggers.md](function-triggers.md).
7
+
8
+ https://neon.com/docs/compute/functions/authentication.md
9
+
10
+ ## Choose the caller shape
11
+
12
+ Pick a row before writing code. Mixed routes: apply the matching row per
13
+ path, not one middleware for the whole Function.
14
+
15
+ | Caller | What to do | Do not |
16
+ | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
17
+ | Trusted app server (Vercel/Netlify route, server action, queue worker) that finishes within that host's duration | The server calls the Function. Browser never sees the Function URL or the origin secret. Function returns 401 before any work. | Put the secret in client code. Proxy a long agent, WebSocket, or SSE stream through the app host without checking that host's duration. |
18
+ | Function Triggers only | `parseTriggerDelivery` (both types). Keep this path outside JWT and `X-Secret` middleware. | Require a user JWT or `X-Secret` on the trigger path. Invent `x-neon-invocation-id`. Treat `invocation_id` as a secret. |
19
+ | Public consumers (Open API, MCP, third-party HTTP) | A Cloudflare Worker Custom Domain you own, **not** registered as a Neon custom domain, proxies to the native invocation URL, sets `X-Secret`, and rate-limits at the edge. Function requires `X-Secret`, then the route's existing consumer auth. | Orange-cloud a Neon-registered custom-domain CNAME. Assume the native URL is closed. Put a human challenge in front of MCP. |
20
+
21
+ Browser-direct JWT agents stay on the client-direct path in SKILL.md. They
22
+ are not the trusted-app-server row.
23
+
24
+ ## Native URL
25
+
26
+ The native invocation URL stays reachable after you add a custom domain or a
27
+ Worker. Application checks reject work; the request still occupies a Function
28
+ invocation until the handler returns.
29
+
30
+ Neon also enforces a default account-wide cap of 100 concurrent invocations
31
+ (`429`, body `per-account concurrency limit reached`, `Retry-After` in
32
+ seconds). That is not per-client DDoS protection.
33
+ https://neon.com/docs/compute/functions/reference/runtime-limits.md
34
+
35
+ Functions docs do not document a customer-configurable WAF, a switch to
36
+ disable the native URL, or a Functions ingress IP allowlist. Do not invent
37
+ those.
38
+
39
+ ## Trusted app server
40
+
41
+ Keep the Function URL and origin secret in **server** env on the app host and
42
+ in Function `env`. Authenticate the app route first. Then `fetch` the
43
+ Function.
44
+
45
+ Headers:
46
+
47
+ ```text
48
+ X-Secret: <server-only origin secret>
49
+ Authorization: <existing consumer credential, unchanged>
50
+ ```
51
+
52
+ `X-Secret` is application-defined. Use it for the server hop when
53
+ `Authorization` already carries a user or consumer bearer token.
54
+
55
+ If the Function currently only checks `Authorization: Bearer <API_KEY>` and
56
+ nothing forwards a user token, keep that check. Do not migrate that header.
57
+
58
+ Compare `X-Secret` before parsing the body or touching Postgres. Missing
59
+ `ORIGIN_SECRET` fails at startup. Do not add CORS if browsers must not call
60
+ this Function.
61
+
62
+ ```typescript
63
+ import { timingSafeEqual } from "node:crypto";
64
+
65
+ const originSecret = process.env.ORIGIN_SECRET;
66
+ if (!originSecret) throw new Error("ORIGIN_SECRET is required");
67
+ const expected = Buffer.from(originSecret);
68
+
69
+ function hasOriginSecret(request: Request): boolean {
70
+ const header = request.headers.get("x-secret");
71
+ if (header === null) return false;
72
+ const provided = Buffer.from(header);
73
+ if (provided.byteLength !== expected.byteLength) return false;
74
+ return timingSafeEqual(provided, expected);
75
+ }
76
+
77
+ export default {
78
+ async fetch(request: Request): Promise<Response> {
79
+ if (!hasOriginSecret(request)) {
80
+ return new Response("Unauthorized", { status: 401 });
81
+ }
82
+ return Response.json({ ok: true });
83
+ },
84
+ };
85
+ ```
86
+
87
+ Declare `ORIGIN_SECRET` in `neon.ts` `env` and on the app host.
88
+
89
+ Buffer the incoming body on the app-server `fetch`. Node `fetch` throws
90
+ `duplex option is required when sending a body` if you pass a streamed
91
+ `request.body`. `duplex: "half"` is Node-only; this hop is short, so
92
+ buffer instead. `redirect: "manual"` keeps `X-Secret` from following a
93
+ cross-origin redirect.
94
+
95
+ `NEON_FUNCTION_URL` is `invocation_url` from `neon functions get`. It ends
96
+ with `/`. This example calls that root. For a Function path, concatenate
97
+ onto that slash (`new URL("orders?limit=2", functionUrl)`). Do not copy the
98
+ app request's host or pathname onto the Function; a Next.js `/api/...` route
99
+ is not the Function path.
100
+
101
+ ```typescript
102
+ const functionUrl = process.env.NEON_FUNCTION_URL;
103
+ const originSecret = process.env.ORIGIN_SECRET;
104
+ if (!functionUrl || !originSecret) {
105
+ throw new Error("NEON_FUNCTION_URL and ORIGIN_SECRET are required");
106
+ }
107
+
108
+ const headers = new Headers({ "x-secret": originSecret });
109
+ const contentType = request.headers.get("content-type");
110
+ if (contentType) headers.set("content-type", contentType);
111
+ const authorization = request.headers.get("authorization");
112
+ if (authorization) headers.set("authorization", authorization);
113
+
114
+ return fetch(functionUrl, {
115
+ method: request.method,
116
+ headers,
117
+ body: request.body ? await request.arrayBuffer() : undefined,
118
+ redirect: "manual",
119
+ });
120
+ ```
121
+
122
+ ## Function Triggers only
123
+
124
+ Use the parsers in [function-triggers.md](function-triggers.md).
125
+ `parseTriggerDelivery` covers `schedule` and `storage_object_created`.
126
+ Hono `parseTrigger` and `parseTriggerInvocation` are schedule-only.
127
+
128
+ Neon POSTs to the native URL and does not send `X-Secret` or a user JWT. A
129
+ trigger path that requires those credentials drops real deliveries.
130
+
131
+ `invocation_id` is a correlation id. Presence of `x-neon-trigger-invocation-id`
132
+ after Neon strips client `x-neon-*` headers is the provenance check; matching
133
+ the body is consistency. https://neon.com/docs/compute/functions/triggers/overview.md
134
+
135
+ Local `neon dev` can send that header to simulate a tick. On the deployed
136
+ Function a client-supplied `x-neon-*` header is stripped.
137
+
138
+ ## Public consumers through a Worker
139
+
140
+ Consumers call a hostname you control. Volumetric filtering happens there.
141
+ The Function still authenticates.
142
+
143
+ DNS:
144
+
145
+ - A Neon Function custom-domain CNAME must be DNS-only (grey cloud). A proxied
146
+ (orange-cloud) record blocks Neon domain validation.
147
+ https://neon.com/docs/compute/functions/custom-domains.md
148
+ - Attach a [Cloudflare Worker Custom Domain](https://developers.cloudflare.com/workers/configuration/routing/custom-domains/)
149
+ that is **not** registered with Neon. The Worker fetches the **native**
150
+ invocation URL.
151
+
152
+ Worker:
153
+
154
+ - Preserve method, pathname, query, body, and consumer `Authorization`.
155
+ - Set `X-Secret`. Do not use it as the consumer credential.
156
+ - Build the upstream URL from a fixed origin. Assign `pathname` and `search`
157
+ separately so a request path cannot change the authority.
158
+ - Apply Cloudflare DDoS / WAF / rate-limiting rules on that Worker hostname.
159
+ The forwarding snippet does not configure those rules.
160
+ - Disable the Worker's `workers.dev` route and Preview URLs. Hostname-scoped
161
+ rules do not apply to those endpoints, and they still run this forwarding
162
+ code. Inventory clients on those URLs first.
163
+ https://developers.cloudflare.com/workers/configuration/routing/workers-dev.md
164
+ Dashboard: Worker → Settings → Domains & Routes. A later Wrangler deploy
165
+ without `workers_dev: false` turns `workers.dev` back on.
166
+ - Do not buffer a streaming body. Do not add a browser challenge MCP or API
167
+ clients cannot pass.
168
+
169
+ Wrangler:
170
+
171
+ ```jsonc
172
+ {
173
+ "workers_dev": false,
174
+ "preview_urls": false
175
+ }
176
+ ```
177
+
178
+ ```typescript
179
+ const FUNCTION_ORIGIN = "https://<invocation-host>"; // neon functions get
180
+
181
+ export default {
182
+ async fetch(
183
+ request: Request,
184
+ env: { ORIGIN_SECRET: string },
185
+ ): Promise<Response> {
186
+ const incoming = new URL(request.url);
187
+ const upstream = new URL(FUNCTION_ORIGIN);
188
+ upstream.pathname = incoming.pathname;
189
+ upstream.search = incoming.search;
190
+
191
+ const headers = new Headers(request.headers);
192
+ headers.set("x-secret", env.ORIGIN_SECRET);
193
+ headers.delete("host");
194
+
195
+ return fetch(upstream, {
196
+ method: request.method,
197
+ headers,
198
+ body: request.body,
199
+ redirect: "manual",
200
+ });
201
+ },
202
+ };
203
+ ```
204
+
205
+ Function: require `X-Secret` first (same helper as above), then apply **that
206
+ route's existing** consumer authentication. Browser preflight, OAuth
207
+ discovery, and intentionally public routes keep their current behavior. An
208
+ origin secret is not a user API key.
209
+
210
+ Requiring `X-Secret` on the native URL is a migration. Move legitimate
211
+ native-URL clients to the Worker first. Anyone who still hits the native URL
212
+ without the secret gets 401 after the request has reached Function compute.
213
+
214
+ HTTP-triggered Workers have no documented hard wall-clock duration while the
215
+ client stays connected. Still verify WebSocket, SSE, and long agent streams
216
+ against the chosen Worker before using this row for those workloads. If the
217
+ edge cannot hold the stream, keep client-direct JWT.
218
+
219
+ MCP: after switching consumers to the Worker hostname, confirm advertised
220
+ resource URLs, token audiences, existing client registrations, and one live
221
+ session as well as a fresh authorization. https://developers.cloudflare.com/workers/platform/limits/
222
+
223
+ ## Limit authenticated application work
224
+
225
+ Edge rate limiting drops traffic before Neon. A limiter **inside** the
226
+ Function runs after the request arrived. Use it to cap expensive work for a
227
+ **verified** principal (user id, org id, API-key hash). Never use a
228
+ caller-supplied id. A global budget can cap total capacity; one caller can
229
+ consume it for everyone.
230
+
231
+ Request-rate limits do not cap simultaneous long-running work. Bound in-flight
232
+ expensive operations separately, in a shared store, not in module-scope
233
+ counters (those are per-isolate and vanish on eviction).
234
+
235
+ A query to Postgres on every anonymous request adds database work to a flood.
236
+ Postgres can hold per-principal counters at low-to-moderate authenticated
237
+ volume when you already have it; measure before relying on it. Prefer Redis
238
+ or edge limits when a database round trip per request is too expensive.
239
+
240
+ Optional Upstash quota after credential checks, before expensive work.
241
+ `60` per minute and `timeout: 1_000` are example policy. `RATE_LIMIT_PREFIX`
242
+ is the application + environment + quota name; `NEON_BRANCH` (a branch
243
+ **name**) is appended so branches do not share counters.
244
+
245
+ `Redis.fromEnv()` reads `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`.
246
+ Upstash `reset` is milliseconds since epoch. Upstash can report a timeout as
247
+ a successful `limit()` result; check `reason` before `success`. Await the
248
+ admission decision; pass `pending` to `waitUntil` so background writes do not
249
+ delay the response.
250
+
251
+ ```typescript
252
+ import { waitUntil } from "@neon/functions";
253
+ import { Ratelimit } from "@upstash/ratelimit";
254
+ import { Redis } from "@upstash/redis";
255
+
256
+ const namespace = process.env.RATE_LIMIT_PREFIX;
257
+ if (!namespace) throw new Error("RATE_LIMIT_PREFIX is required");
258
+
259
+ const limiter = new Ratelimit({
260
+ redis: Redis.fromEnv(),
261
+ limiter: Ratelimit.slidingWindow(60, "1 m"),
262
+ prefix: `${namespace}:${process.env.NEON_BRANCH ?? "local"}`,
263
+ timeout: 1_000,
264
+ analytics: false,
265
+ });
266
+
267
+ export async function checkQuota(
268
+ authenticatedPrincipalId: string,
269
+ ): Promise<Response | null> {
270
+ let result: Awaited<ReturnType<typeof limiter.limit>>;
271
+ try {
272
+ result = await limiter.limit(authenticatedPrincipalId);
273
+ } catch (error) {
274
+ console.error("Rate-limit store failed", error);
275
+ return new Response("Rate limiter unavailable", {
276
+ status: 503,
277
+ headers: { "Retry-After": "1" },
278
+ });
279
+ }
280
+
281
+ waitUntil(result.pending);
282
+
283
+ if (result.reason === "timeout") {
284
+ console.error("Rate-limit store timed out");
285
+ return new Response("Rate limiter unavailable", {
286
+ status: 503,
287
+ headers: { "Retry-After": "1" },
288
+ });
289
+ }
290
+
291
+ if (result.success) return null;
292
+
293
+ const retryAfterSeconds = Math.max(
294
+ 1,
295
+ Math.ceil((result.reset - Date.now()) / 1000),
296
+ );
297
+ return new Response("Too Many Requests", {
298
+ status: 429,
299
+ headers: {
300
+ "Retry-After": String(retryAfterSeconds),
301
+ "RateLimit-Limit": String(result.limit),
302
+ "RateLimit-Remaining": String(result.remaining),
303
+ "RateLimit-Reset": String(retryAfterSeconds),
304
+ },
305
+ });
306
+ }
307
+ ```
308
+
309
+ Preserve CORS headers on these responses when the route already sets them.
310
+ Do not relabel limiter failures as `401` or as quota exhaustion. `Retry-After`
311
+ is required on `429`. `RateLimit-*` is optional metadata; `RateLimit-Reset`
312
+ here is seconds until the window renews.
313
+
314
+ Do not rate-limit in the Function by `X-Forwarded-For`. That header is not a
315
+ documented trustworthy client-IP on Functions. IP limits belong at the edge.
316
+
317
+ ## Preserve existing clients
318
+
319
+ - Direct-client JWT agents keep their token, JWKS, issuer, and audience.
320
+ Do not require `X-Secret` on those routes.
321
+ - CORS still has to succeed for legitimate browser origins, including on
322
+ 401/429. CORS is not authentication.
323
+ - Inventory production and preview origins before tightening an allowlist.
324
+ - WebSocket and SSE handshake, heartbeat, and reconnect stay as documented
325
+ in SKILL.md.
326
+ - MCP OAuth discovery, tokens, methods, and streaming stay as documented in
327
+ [mcp.md](mcp.md). Authenticate before the transport.
328
+ - Adding a Worker does not by itself change the API's consumer credentials.
329
+ - Stored rows stay authorized by the verified identity, not by a quota key.
330
+
331
+ ## Reject these
332
+
333
+ - Orange-cloud proxying a **Neon-registered** custom-domain CNAME.
334
+ - Shipping a server origin secret to the browser.
335
+ - Putting a long stream behind a host or Worker whose duration or transport
336
+ cannot hold it.
337
+ - Treating header/body equality as trigger provenance outside Neon's edge.
338
+ - In-memory counters as a cross-isolate quota.
339
+ - A Postgres lookup on every anonymous request as DDoS protection.
340
+ - Treating a native-URL `401` as traffic blocked before Function compute.
@@ -22,12 +22,12 @@ metadata:
22
22
  If the `neon` skill is not installed, fetch it from https://neon.com/docs/ai/skills/neon/SKILL.md or install it with:
23
23
 
24
24
  ```bash
25
- npx skills add neondatabase/agent-skills --skill neon
25
+ neon skills -s neon -y
26
26
  ```
27
27
 
28
28
  # Neon Object Storage
29
29
 
30
- This is a public beta feature, currently available in `us-east-2` and `eu-central-1`.
30
+ Currently available in `aws-us-east-2`, `aws-us-east-1`, `aws-eu-central-1`, and `aws-ap-southeast-1`.
31
31
 
32
32
  Neon Object Storage is S3-compatible object storage that branches with your projects: every branch gets its own isolated storage state, so files and database rows stay in sync across dev, preview, staging, and production.
33
33
 
@@ -53,7 +53,7 @@ If the files in question ship with the app itself — HTML, JS bundles, CSS, the
53
53
 
54
54
  ## Availability
55
55
 
56
- Check this precondition before setting anything up: Neon Object Storage is a public beta feature currently available in `us-east-2` and `eu-central-1`. Confirm the user's Neon project is in one of these regions before proceeding.
56
+ Check this precondition before setting anything up: Neon Object Storage is currently available in `aws-us-east-2`, `aws-us-east-1`, `aws-eu-central-1`, and `aws-ap-southeast-1`. Confirm the user's Neon project is in one of these regions before proceeding. Region coverage: https://neon.com/docs/get-started/backend-overview.md
57
57
 
58
58
  ## Architecture: Where Object Storage Fits
59
59
 
@@ -64,18 +64,16 @@ Neon (Object Storage included) is **backend primitives, not full-stack app hosti
64
64
 
65
65
  ## Setup
66
66
 
67
- Object storage is part of the `neon.ts` infrastructure-as-code config (see the `neon` skill for the branch-first workflow, `link`/`checkout`, and `neon.ts` basics). Declare buckets under `preview.buckets`, keyed by bucket name:
67
+ Object storage is part of the `neon.ts` infrastructure-as-code config (see the `neon` skill for the branch-first workflow, `link`/`checkout`, and `neon.ts` basics). Declare buckets under `buckets`, keyed by bucket name:
68
68
 
69
69
  ```typescript
70
70
  // neon.ts
71
71
  import { defineConfig } from "@neon/config/v1";
72
72
 
73
73
  export default defineConfig({
74
- preview: {
75
- buckets: {
76
- images: {}, // private by default
77
- "public-assets": { access: "public_read" },
78
- },
74
+ buckets: {
75
+ images: {}, // private by default
76
+ "public-assets": { access: "public_read" },
79
77
  },
80
78
  });
81
79
  ```
@@ -88,7 +86,7 @@ neon deploy # alias for `neon config apply`
88
86
 
89
87
  ## Neon Infrastructure as Code (`neon.ts`)
90
88
 
91
- The `preview.buckets` block above is part of `neon.ts`, Neon's infrastructure-as-code file — one TypeScript file declares your buckets alongside every other service the branch should have (see the `neon` skill for the full reference). Reconcile the declaration against a branch the Terraform way:
89
+ The `buckets` block above is part of `neon.ts`, Neon's infrastructure-as-code file — one TypeScript file declares your buckets alongside every other service the branch should have (see the `neon` skill for the full reference). Reconcile the declaration against a branch the Terraform way:
92
90
 
93
91
  ```bash
94
92
  neon config status # print the branch's live config (which buckets exist)
@@ -100,7 +98,7 @@ Buckets are **branch-scoped**: when a `neon.ts` is present, `neon checkout` appl
100
98
 
101
99
  ## Environment Variables
102
100
 
103
- When `preview.buckets` is declared, Neon injects **AWS-standard** S3 env vars so the AWS SDKs work from the environment with zero extra config. Inside a deployed Neon Function these are injected automatically; locally, pull them onto disk (or inject them at runtime) via the CLI:
101
+ When `buckets` is declared, Neon injects **AWS-standard** S3 env vars so the AWS SDKs work from the environment with zero extra config. Inside a deployed Neon Function these are injected automatically; locally, pull them onto disk (or inject them at runtime) via the CLI:
104
102
 
105
103
  ```bash
106
104
  neon env pull # writes the branch's vars into .env (or .env.local)
@@ -218,6 +216,7 @@ The Neon documentation is the source of truth and Object Storage is evolving rap
218
216
 
219
217
  ## Further Reading
220
218
 
219
+ - https://neon.com/docs/get-started/backend-overview.md
221
220
  - https://neon.com/docs/storage/overview.md
222
221
  - https://neon.com/docs/storage/get-started.md
223
222
  - https://neon.com/docs/storage/buckets.md
@@ -1,18 +1,15 @@
1
1
  ---
2
2
  name: neon-postgres
3
3
  description: >-
4
- Guides and best practices for working with Lakebase Postgres, the database
5
- behind Neon. Covers setup, connection methods and drivers, pooled vs direct
6
- connections, branching, schema migrations, autoscaling, scale-to-zero, instant
7
- restore, read replicas, connection pooling, IP allow lists, and logical
8
- replication. Also covers Lakebase Search: semantic vector search, full-text
9
- search with BM25 ranking, and hybrid search.
10
- Use when users ask about "Lakebase Postgres", "Neon setup", "connect to Neon",
11
- "Neon project", "DATABASE_URL", "serverless Postgres", "Neon CLI", "neon", "Neon MCP",
12
- "Neon Auth", "@neondatabase/serverless", "@neondatabase/neon-js",
13
- "scale to zero", "Neon autoscaling", "Neon read replica",
14
- "Neon connection pooling", "schema migrations", "semantic search", "vector
15
- search", "full-text search", "BM25", or "hybrid search".
4
+ Guides and best practices for working with Lakebase Postgres on Neon:
5
+ connections, pooled vs direct, schema migrations, branching, autoscaling,
6
+ scale-to-zero, instant restore, read replicas, IP allow lists, logical
7
+ replication, and Lakebase Search. Use when the work is an existing
8
+ DATABASE_URL, SQL, schema, inspect, or search. New backends, Auth, files,
9
+ Functions, and LLM calls go to the parent `neon` skill. Also use for
10
+ "@neondatabase/serverless", "@neondatabase/neon-js", "neon inspect db",
11
+ "semantic search", "vector search", "full-text search", "BM25", or
12
+ "hybrid search".
16
13
  metadata:
17
14
  parent: neon
18
15
  source: https://github.com/neondatabase/agent-skills/tree/main/skills/neon-postgres
@@ -23,7 +20,7 @@ metadata:
23
20
  If the `neon` skill is not installed, fetch it from https://neon.com/docs/ai/skills/neon/SKILL.md or install it with:
24
21
 
25
22
  ```bash
26
- npx skills add neondatabase/agent-skills --skill neon
23
+ neon skills -s neon -y
27
24
  ```
28
25
 
29
26
  # Lakebase Postgres
@@ -32,15 +29,21 @@ Lakebase Postgres is the database at the core of Neon. It runs on the lakebase a
32
29
 
33
30
  It is the same database whether you reach it through Neon or through Databricks; this skill covers the Neon access path.
34
31
 
32
+ Login, users, sessions, and `@neondatabase/auth` belong in `neon-auth`.
33
+
35
34
  ## Setup Flow
36
35
 
37
36
  ### 1. Select the organization and project
38
37
 
39
- Use the CLI (default) or MCP server to list organizations and projects. Let the user select an existing project or create a new one. Check the `.neon` file for an existing linked project or branch.
38
+ If a `DATABASE_URL` is already supplied (prompt, environment, or repo) or a `.neon` file points at a project, use it. Do not list organizations or create a second project for schema work.
39
+
40
+ Otherwise use the CLI (default) or MCP server to list organizations and projects. Let the user select an existing project or create a new one.
40
41
 
41
42
  ### 2. Get the connection string
42
43
 
43
- Use the CLI (default), `neon env pull`, or the MCP server to get the connection string. Store it in `.env` as `DATABASE_URL`. Read the file first before modifying it, to avoid overwriting existing values.
44
+ If a `DATABASE_URL` is already supplied, use it. Do not fetch another through the CLI or MCP.
45
+
46
+ Otherwise use the CLI (default), `neon env pull`, or the MCP server to get the connection string. Store it in `.env` as `DATABASE_URL`. Read the file first before modifying it, to avoid overwriting existing values.
44
47
 
45
48
  #### When to use pooled vs direct connections
46
49
 
@@ -56,11 +59,10 @@ Use the CLI (default), `neon env pull`, or the MCP server to get the connection
56
59
 
57
60
  ### 3. Pick the connection method and driver
58
61
 
59
- Always pair Neon with an ORM such as **Drizzle** for easy schema management and migrations. Refer to the connection methods guide to pick the correct driver based on how the runtime treats your code: https://neon.com/docs/connect/choose-connection.md.
62
+ Preserve the existing ORM and driver. For new TypeScript schema work with no established choice, Drizzle is a suggestion: https://neon.com/docs/guides/drizzle.md. Refer to the connection methods guide to pick the correct driver based on how the runtime treats your code: https://neon.com/docs/connect/choose-connection.md.
60
63
 
61
- Recommendations:
64
+ Driver notes:
62
65
 
63
- - Drizzle as ORM (see https://neon.com/docs/guides/drizzle.md)
64
66
  - On Vercel, use `node-postgres` (`npm install pg`) with Vercel Fluid compute and `import { attachDatabasePool } from "@vercel/functions";`
65
67
  - On Cloudflare, use `node-postgres` with Cloudflare Hyperdrive
66
68
  - On Neon Functions, use `node-postgres`, as the functions are long-running and reuse the pool across requests.
@@ -87,7 +89,7 @@ Link: https://neon.com/docs/introduction/branching.md
87
89
  For detailed branch creation workflows (normal vs schema-only branches, reset-from-parent, CLI/MCP selection), use the `neon-postgres-branches` skill. If it isn't installed, fetch it from https://neon.com/docs/ai/skills/neon-postgres-branches/SKILL.md or install it with:
88
90
 
89
91
  ```bash
90
- npx skills add neondatabase/agent-skills --skill neon-postgres-branches
92
+ neon skills -s neon-postgres-branches -y
91
93
  ```
92
94
 
93
95
  ## Migrations
@@ -96,6 +98,90 @@ Test a migration on a branch of production, against production-like data, before
96
98
 
97
99
  Use a **direct (non-pooled)** connection string when you run the migration, not a pooled one. `neon connection-string` returns the direct string by default; make sure the hostname does not include the `-pooler` suffix.
98
100
 
101
+ ## Troubleshooting and Neon-Specific Performance
102
+
103
+ Use Neon's predefined, read-only diagnostics before writing catalog queries by hand. The Neon CLI `neon inspect db` subcommands and the Neon MCP server's `inspect_database` tool run the same checks.
104
+
105
+ This section covers Neon-specific diagnostic tools, compute cache behavior, and platform signals. When the evidence points to generic Postgres work such as rewriting a query, choosing an index, changing a schema, or interpreting plan nodes, load the [`postgres-best-practices`](https://github.com/neondatabase/postgres-skills/tree/main/skills/postgres-best-practices) skill and carry the diagnostic evidence into that workflow.
106
+
107
+ Docs:
108
+
109
+ - CLI: https://neon.com/docs/cli/inspect.md
110
+ - Query performance: https://neon.com/docs/postgresql/query-performance.md
111
+ - `pg_stat_statements`: https://neon.com/docs/extensions/pg_stat_statements.md
112
+ - Neon Local File Cache: https://neon.com/docs/extensions/neon.md
113
+
114
+ ### Choose CLI or MCP
115
+
116
+ Prefer the Neon CLI when terminal access and authentication are available:
117
+
118
+ ```bash
119
+ neon inspect db <check>
120
+ ```
121
+
122
+ The CLI resolves the project and branch from the current Neon context. Use `--project-id`, `--branch`, and `--database-name` to override it. Omit `--database-name` to inspect every database on the branch. Use `--db-url` only when inspecting a Postgres database directly instead of resolving it through the Neon API.
123
+
124
+ When using Neon MCP, call `inspect_database` with `projectId` and one `check`. Pass `branchId`, `databaseName`, or `computeId` only when needed. Omit `databaseName` to inspect all databases on the branch. Increase `limit` only when the result says it was truncated.
125
+
126
+ ### Pick the Diagnostic
127
+
128
+ | Symptom or question | Checks |
129
+ | ---------------------------------------------- | ------------------------------------ |
130
+ | Which relations consume storage? | `table-sizes`, `index-sizes` |
131
+ | Is an index unused or a table scanned heavily? | `unused-indexes`, `seq-scans` |
132
+ | What has run for 5+ minutes or holds locks? | `long-running-queries`, `locks` |
133
+ | Which queries consume the most total time? | `outliers` |
134
+ | Which queries run most often? | `calls` |
135
+ | Does the active data fit in compute cache? | `lfc-hit-rate`, `working-set` |
136
+ | Is autovacuum behind or is space wasted? | `vacuum-stats`, `bloat` |
137
+ | Is logical replication healthy? | `replication-slots`, `subscriptions` |
138
+
139
+ Do not confuse these checks:
140
+
141
+ - `long-running-queries` reports statements running **right now** for more than five minutes.
142
+ - `outliers` ranks the top queries by cumulative execution time since statistics were reset. It does not rank by mean latency.
143
+ - `calls` ranks by execution count over the same statistics history.
144
+
145
+ `outliers` and `calls` require `pg_stat_statements`. `lfc-hit-rate` and `working-set` require the `neon` extension. If a check reports a missing extension, ask before running the suggested `CREATE EXTENSION` statement because installing an extension modifies the database.
146
+
147
+ ### Interpret Results Safely
148
+
149
+ - Treat `unused-indexes` as a candidate list, not permission to drop indexes. Confirm the observation window, constraints, and workload before removal.
150
+ - A sequential scan can be correct for a small table or a query reading much of a table. Check table size, selectivity, and the query plan before adding an index.
151
+ - `bloat` is a statistical estimate. Confirm the impact and plan locks or maintenance before `VACUUM FULL`, `REINDEX`, or similar remediation.
152
+ - Cache and Postgres statistics reset when compute restarts, including scale-to-zero suspension. Run a representative workload before interpreting fresh `lfc-hit-rate`, `working-set`, `vacuum-stats`, or `pg_stat_statements` results.
153
+ - Compute-wide checks (`lfc-hit-rate`, `working-set`, and `replication-slots`) run once even when inspecting every database.
154
+ - One failing database can fail an all-databases inspection; retry the relevant check with an explicit `databaseName` to isolate it.
155
+
156
+ ### Inspect Neon Cache Behavior Per Query
157
+
158
+ Standard `EXPLAIN (ANALYZE, BUFFERS)` reports Postgres shared-buffer activity, but it does not show Neon's Local File Cache (LFC) or page prefetching. For a safe read-only query, add Neon's `FILECACHE` and `PREFETCH` options:
159
+
160
+ ```sql
161
+ EXPLAIN (ANALYZE, BUFFERS, PREFETCH, FILECACHE)
162
+ SELECT ...;
163
+ ```
164
+
165
+ - `File cache: hits` counts pages found in the compute's LFC.
166
+ - `File cache: misses` counts pages not found in the LFC and fetched from database storage.
167
+ - `Prefetch: hits`, `misses`, `expired`, and `duplicates` show how effectively Neon fetched pages before the executor requested them.
168
+
169
+ `FILECACHE` and `PREFETCH` provide metrics for this query and do not require the `neon` extension. By contrast, `neon inspect db lfc-hit-rate` and `working-set` provide compute-wide statistics and do require the extension.
170
+
171
+ The MCP `explain_sql_statement` tool can produce a standard plan but does not expose `FILECACHE` or `PREFETCH` options. To collect those Neon-specific metrics through MCP, use `run_sql` with the explicit, read-only `EXPLAIN` statement above.
172
+
173
+ Because `ANALYZE` executes the statement, use it only when execution is safe; do not run it autonomously for mutating SQL. Compare cold- and warm-cache runs carefully because the first execution can populate the cache and materially change later results.
174
+
175
+ ### Performance Workflow
176
+
177
+ 1. Reproduce the symptom and note its time window.
178
+ 2. Run the smallest relevant `inspect` checks from the table above.
179
+ 3. Identify a specific query before changing schema or compute. Use MCP `explain_sql_statement` for a standard plan, or the Neon-specific `EXPLAIN` above when LFC or prefetch behavior matters.
180
+ 4. If the bottleneck is query shape, indexing, schema, locking, or vacuum behavior, load `postgres-best-practices` and carry forward the inspection results and query plan. Keep Neon compute, cache, connection, and platform decisions in this skill.
181
+ 5. Re-run the same check and workload to verify the change.
182
+
183
+ Use MCP `list_slow_queries` instead of `inspect_database` when the user specifically needs queries ranked by average execution time with a custom threshold and limit. Outside the explicit `EXPLAIN` case above, use `run_sql` only for read-only diagnostic SQL when the predefined checks do not answer the question.
184
+
99
185
  ## Autoscaling
100
186
 
101
187
  Use this when the user needs compute to scale automatically with workload and wants guidance on CU sizing and runtime behavior.
@@ -174,6 +260,7 @@ Use Lakebase Search for semantic, full-text, and hybrid search:
174
260
  - For semantic search, read [Vector search](references/vector-search.md).
175
261
  - For full-text search with BM25 ranking, read [Full-text search](references/full-text-search.md).
176
262
  - For combining semantic and lexical results, read [Hybrid search](references/hybrid-search.md).
263
+ - For managing any of the above through Drizzle ORM, read [Managing Lakebase Search with Drizzle](references/lakebase-search-drizzle.md).
177
264
 
178
265
  Links:
179
266