@neon/skills 0.0.0 → 1.2.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,266 @@
1
+ ---
2
+ name: neon-postgres-egress-optimizer
3
+ description: >-
4
+ Diagnose and fix excessive Postgres egress (network data transfer) in a codebase.
5
+ Use when a user mentions high database bills, unexpected data transfer costs,
6
+ network transfer charges, egress spikes, "why is my Neon bill so high",
7
+ "database costs jumped", SELECT * optimization, query overfetching,
8
+ reduce Neon costs, optimize database usage, or wants to reduce data sent
9
+ from their database to their application. Also use when reviewing query
10
+ patterns for cost efficiency, even if the user doesn't explicitly mention
11
+ egress or data transfer.
12
+ metadata:
13
+ parent: neon
14
+ source: https://github.com/neondatabase/agent-skills/tree/main/skills/neon-postgres-egress-optimizer
15
+ ---
16
+
17
+ **FIRST**: Use the parent `neon` skill for a Neon overview, getting started with Neon, Neon development best practices, and more.
18
+
19
+ If the `neon` skill is not installed, fetch it from https://neon.com/docs/ai/skills/neon/SKILL.md or install it with:
20
+
21
+ ```bash
22
+ npx skills add neondatabase/agent-skills --skill neon
23
+ ```
24
+
25
+ # Postgres Egress Optimizer
26
+
27
+ Guide the user through diagnosing and fixing application-side query patterns that cause excessive data transfer (egress) from their Postgres database. Most high egress bills come from the application fetching more data than it uses.
28
+
29
+ Work the four steps in order: **diagnose** which queries transfer the most data, **analyze** the codebase behind them, **fix** the anti-patterns, then **verify** nothing broke and the transfer actually dropped.
30
+
31
+ ## Step 1: Diagnose
32
+
33
+ Identify which queries transfer the most data. The primary tool is the `pg_stat_statements` extension.
34
+
35
+ ### Check if pg_stat_statements is available
36
+
37
+ ```sql
38
+ SELECT 1 FROM pg_stat_statements LIMIT 1;
39
+ ```
40
+
41
+ If this errors, the extension needs to be created:
42
+
43
+ ```sql
44
+ CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
45
+ ```
46
+
47
+ On Neon the extension is available by default, but it may still need this CREATE EXTENSION step.
48
+
49
+ ### Handle empty stats
50
+
51
+ Stats are cleared when a Neon compute scales to zero and restarts. If the stats are empty or the compute recently woke up:
52
+
53
+ 1. Reset the stats to start a clean measurement window: `SELECT pg_stat_statements_reset();`
54
+ 2. Let the application run under representative traffic for at least an hour.
55
+ 3. Return and run the diagnostic queries below.
56
+
57
+ If the user has stats from a production database, use those. If they have no access to production stats, proceed to Step 2 and analyze the codebase directly — code-level patterns are often sufficient to identify the worst offenders.
58
+
59
+ ### Diagnostic queries
60
+
61
+ Run these to identify the top egress contributors. Focus on queries that return many rows, return wide rows (JSONB, TEXT, BYTEA columns), or are called very frequently.
62
+
63
+ **Queries returning the most total rows:**
64
+
65
+ ```sql
66
+ SELECT query, calls, rows AS total_rows, rows / calls AS avg_rows_per_call
67
+ FROM pg_stat_statements
68
+ WHERE calls > 0
69
+ ORDER BY rows DESC
70
+ LIMIT 10;
71
+ ```
72
+
73
+ **Queries returning the most rows per execution** (poorly scoped SELECTs, missing pagination):
74
+
75
+ ```sql
76
+ SELECT query, calls, rows AS total_rows, rows / calls AS avg_rows_per_call
77
+ FROM pg_stat_statements
78
+ WHERE calls > 0
79
+ ORDER BY avg_rows_per_call DESC
80
+ LIMIT 10;
81
+ ```
82
+
83
+ **Most frequently called queries** (candidates for caching):
84
+
85
+ ```sql
86
+ SELECT query, calls, rows AS total_rows, rows / calls AS avg_rows_per_call
87
+ FROM pg_stat_statements
88
+ WHERE calls > 0
89
+ ORDER BY calls DESC
90
+ LIMIT 10;
91
+ ```
92
+
93
+ **Longest running queries** (not a direct egress measure, but helps identify problem queries during a spike):
94
+
95
+ ```sql
96
+ SELECT query, calls, rows AS total_rows,
97
+ round(total_exec_time::numeric, 2) AS total_exec_time_ms
98
+ FROM pg_stat_statements
99
+ WHERE calls > 0
100
+ ORDER BY total_exec_time DESC
101
+ LIMIT 10;
102
+ ```
103
+
104
+ ### Interpret the results
105
+
106
+ Rank findings by estimated egress impact:
107
+
108
+ - **High row count + wide rows** = biggest egress. A query returning 1,000 rows where each row includes a 50KB JSONB column transfers ~50MB per call.
109
+ - **Extreme call frequency** on even small queries adds up. A query called 50,000 times/day returning 10 rows each = 500,000 rows/day.
110
+ - **Cross-reference with the schema** to identify which columns are wide. Look for JSONB, TEXT, BYTEA, and large VARCHAR columns.
111
+
112
+ ## Step 2: Analyze the Codebase
113
+
114
+ For each query identified in Step 1, or for each database query in the codebase if no stats are available, check:
115
+
116
+ - Does it select only the columns the response needs?
117
+ - Does it return a bounded number of rows (LIMIT/pagination)?
118
+ - Is it called frequently enough to benefit from caching?
119
+ - Does it fetch raw data that gets aggregated in application code?
120
+ - Does it use a JOIN that duplicates parent data across child rows?
121
+
122
+ ## Step 3: Fix
123
+
124
+ Apply the appropriate fix for each problem found. Below are the most common egress anti-patterns and how to fix them.
125
+
126
+ ### Unused columns (SELECT \*)
127
+
128
+ **Problem:** The query fetches all columns but the application only uses a few. Large columns (JSONB blobs, TEXT fields) get transferred over the wire and discarded.
129
+
130
+ **Fix:** Name only the columns the response needs.
131
+
132
+ **Before:**
133
+
134
+ ```sql
135
+ SELECT * FROM products;
136
+ ```
137
+
138
+ **After:**
139
+
140
+ ```sql
141
+ SELECT id, name, price, image_urls FROM products;
142
+ ```
143
+
144
+ ### Missing pagination
145
+
146
+ **Problem:** A list endpoint returns all rows with no LIMIT. This is an unbounded egress risk — every new row in the table increases data transfer on every request. Flag this regardless of current table size.
147
+
148
+ This is easy to miss because the application may work fine with small datasets. But at scale, an unpaginated endpoint returning 10,000 rows with even moderate column widths can transfer hundreds of megabytes per day.
149
+
150
+ **Fix:** Bound the result set with `ORDER BY` plus `LIMIT`/`OFFSET`.
151
+
152
+ **Before:**
153
+
154
+ ```sql
155
+ SELECT id, name, price FROM products;
156
+ ```
157
+
158
+ **After:**
159
+
160
+ ```sql
161
+ SELECT id, name, price FROM products
162
+ ORDER BY id
163
+ LIMIT 50 OFFSET 0;
164
+ ```
165
+
166
+ When adding pagination, check whether the consuming client already supports paginated responses. If not, pick sensible defaults and document the pagination parameters in the API.
167
+
168
+ ### High-frequency queries on static data
169
+
170
+ **Problem:** A query is called thousands of times per day but returns data that rarely changes. Every call transfers the same rows from the database. This pattern is only visible from `pg_stat_statements` — the code itself looks normal.
171
+
172
+ Look for queries with extremely high call counts relative to other queries. Common examples: configuration tables, category lists, feature flags, user role definitions.
173
+
174
+ **Fix:** Add a caching layer between the application and the database so it avoids hitting the database on every request.
175
+
176
+ ### Application-side aggregation
177
+
178
+ **Problem:** The application fetches all rows from a table and then computes aggregates (averages, counts, sums, groupings) in application code. The full dataset transfers over the wire even though the result is a small summary.
179
+
180
+ **Fix:** Push the aggregation into SQL.
181
+
182
+ **Before:** The application fetches entire tables and aggregates in code with loops or `.reduce()`.
183
+
184
+ **After:**
185
+
186
+ ```sql
187
+ SELECT p.category_id,
188
+ AVG(r.rating) AS avg_rating,
189
+ COUNT(r.id) AS review_count
190
+ FROM reviews r
191
+ INNER JOIN products p ON r.product_id = p.id
192
+ GROUP BY p.category_id;
193
+ ```
194
+
195
+ ### JOIN duplication
196
+
197
+ **Problem:** A JOIN between a wide parent table and a child table duplicates all parent columns across every child row. If a product has 200 reviews and the product row includes a 50KB JSONB column, the join sends that 50KB × 200 = ~10MB for a single request.
198
+
199
+ This is distinct from the SELECT \* problem. Even if you select only needed columns, a JOIN still repeats the parent data for every child row. The fix is structural: avoid the join entirely.
200
+
201
+ **Fix:** Split the join into two queries, one per table.
202
+
203
+ **Before:**
204
+
205
+ ```sql
206
+ SELECT * FROM products
207
+ LEFT JOIN reviews ON reviews.product_id = products.id
208
+ WHERE products.id = 1;
209
+ ```
210
+
211
+ **After (two separate queries):**
212
+
213
+ ```sql
214
+ SELECT id, name, price, description, image_urls FROM products WHERE id = 1;
215
+ SELECT id, user_name, rating, body FROM reviews WHERE product_id = 1;
216
+ ```
217
+
218
+ Two queries instead of one JOIN. The product data is fetched once. The reviews are fetched once. No duplication.
219
+
220
+ ## Step 4: Verify
221
+
222
+ After applying fixes:
223
+
224
+ 1. **Run existing tests** to confirm nothing broke.
225
+ 2. **Check the responses** — make sure the API still returns the same data shape. Column selection and pagination changes can break clients that depend on specific fields or full result sets.
226
+ 3. **Measure the improvement** — if pg_stat_statements data is available, reset it (`SELECT pg_stat_statements_reset();`), let traffic run, then re-run the diagnostic queries to compare before and after.
227
+
228
+ ## Neon Infrastructure as Code (`neon.ts`)
229
+
230
+ The fixes above cut **egress** (data transferred out of Postgres). The other big non-prod cost lever is **compute**, and you can codify it durably in `neon.ts` — Neon's infrastructure-as-code file (see the `neon` skill for the full reference) — so dev, preview, and CI branches stay cheap by default instead of relying on per-branch flags:
231
+
232
+ ```bash
233
+ npm i @neon/config
234
+ ```
235
+
236
+ ```typescript
237
+ // neon.ts
238
+ import { defineConfig } from "@neon/config/v1";
239
+
240
+ export default defineConfig({
241
+ branch: (branch) => {
242
+ if (branch.exists || branch.isDefault) return {}; // don't touch prod
243
+ return {
244
+ ttl: "7d", // ephemeral branches auto-expire instead of accruing storage
245
+ postgres: {
246
+ computeSettings: {
247
+ autoscalingLimitMinCu: 0.25, // scale to zero when idle
248
+ autoscalingLimitMaxCu: 1, // cap autoscaling on throwaway branches
249
+ suspendTimeout: "5m",
250
+ },
251
+ },
252
+ };
253
+ },
254
+ });
255
+ ```
256
+
257
+ ```bash
258
+ neon config apply # apply to the current branch (neon deploy is an alias)
259
+ ```
260
+
261
+ This is complementary, not a substitute: query-pattern fixes are what actually reduce egress charges, while these settings keep non-production compute and storage from quietly inflating the same bill. Because `neon checkout` applies the policy when it creates a branch, new dev/preview branches inherit the cheap profile automatically.
262
+
263
+ ## Further Reading
264
+
265
+ - https://neon.com/docs/introduction/network-transfer.md
266
+ - https://neon.com/docs/introduction/cost-optimization.md