PostgreSQLのエグレス(データベースから外部への通信量)が過剰になっている問題を診断し、修正するツールです。 次のような場合に使用: ユーザーが高いデータベース料金、予想外のデータ転送コスト、ネットワーク転送料金、通信量の急増、「Neonの請求額が高い理由」、「データベースコストが急上昇した」、SELECT文の最適化、クエリ過剰取得の問題、Neonコストの削減、データベース使用の最適化、またはデータベースからアプリケーションへ送信されるデータ量の削減について言及した場合。また、ユーザーが明示的にエグレスやデータ転送に触れていなくても、コスト効率を考慮したクエリのパターンを見直す場合にも使用します。
Diagnose and fix excessive Postgres egress (network data transfer) in a codebase. Use when a user mentions high database bills, unexpected data transfer costs, network transfer charges, egress spikes, "why is my Neon bill so high", "database costs jumped", SELECT * optimization, query overfetching, reduce Neon costs, optimize database usage, or wants to reduce data sent from their database to their application. Also use when reviewing query patterns for cost efficiency, even if the user doesn't explicitly mention egress or data transfer.
まず最初に: Neon の概要、使い始め方、開発のベストプラクティスなどについては、親となる neon スキルを使用してください。
neon スキルがインストールされていない場合は、以下から取得するか、下記のコマンドでインストールしてください:
npx skills add neondatabase/agent-skills --skill neon
ユーザーがアプリケーション側のクエリ実行パターンを診断・修正し、Postgres データベースからの過剰なデータ転送(エグレス)を減らすのをサポートします。データベース費用が高くなる大きな原因は、アプリケーションが必要以上のデータを取得していることです。
4つのステップを順に進めます: 診断(どのクエリが最もデータを転送しているか)、分析(そのクエリを実行するコード)、修正(悪いパターンを改善)、検証(動作確認と効果測定)。
どのクエリが最もデータを転送しているかを特定します。主なツールは pg_stat_statements 拡張機能(データベースの実行履歴を記録する機能)です。
SELECT 1 FROM pg_stat_statements LIMIT 1;
エラーが出た場合は、拡張機能を作成する必要があります:
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
Neon ではこの拡張機能はデフォルトで利用可能ですが、このCREATE EXTENSION ステップが必要な場合もあります。
Neon のコンピュートがゼロに縮小して再起動すると、統計データがクリアされます。統計データが空か、最近コンピュートが起動した場合:
SELECT pg_stat_statements_reset();本番データベースの統計データがあれば、それを使用してください。本番データベースへのアクセスがない場合は、ステップ 2 に進んでコードを直接分析してください。コードレベルのパターン分析だけでも、問題のある箇所を特定することができます。
以下を実行してデータ転送量が多いクエリを特定します。多くの行を返すクエリ、行の幅が広いクエリ(JSONB、TEXT、BYTEA カラム)、または非常に頻繁に実行されるクエリに注目してください。
最も多くの行を返すクエリ:
SELECT query, calls, rows AS total_rows, rows / calls AS avg_rows_per_call
FROM pg_stat_statements
WHERE calls > 0
ORDER BY rows DESC
LIMIT 10;
実行 1 回あたり最も多くの行を返すクエリ(スコープが広い SELECT、ページネーション不足):
SELECT query, calls, rows AS total_rows, rows / calls AS avg_rows_per_call
FROM pg_stat_statements
WHERE calls > 0
ORDER BY avg_rows_per_call DESC
LIMIT 10;
最も頻繁に実行されるクエリ(キャッシュの対象候補):
SELECT query, calls, rows AS total_rows, rows / calls AS avg_rows_per_call
FROM pg_stat_statements
WHERE calls > 0
ORDER BY calls DESC
LIMIT 10;
実行時間が最も長いクエリ(直接的なデータ転送の指標ではありませんが、トラブル時に問題クエリの特定に役立ちます):
SELECT query, calls, rows AS total_rows,
round(total_exec_time::numeric, 2) AS total_exec_time_ms
FROM pg_stat_statements
WHERE calls > 0
ORDER BY total_exec_time DESC
LIMIT 10;
推定データ転送量の影響度でランク付けしてください:
ステップ 1 で特定した各クエリ、または利用可能な統計データがない場合はコードベース内の各データベースクエリについて、以下を確認します:
ステップ 2 で見つかった各問題に対して適切な修正を適用します。以下は最も一般的なデータ転送問題のパターンと修正方法です。
問題: クエリがすべてのカラムを取得しているのに、アプリケーションは数個のカラムしか使用していない。大きなカラム(JSONB、TEXT フィールド)がネットワークを通じて転送され、その後破棄されます。
修正: 応答に必要なカラムだけを指定します。
修正前:
SELECT * FROM products;
修正後:
SELECT id, name, price, image_urls FROM products;
問題: リストエンドポイントが LIMIT なしですべての行を返している。これはデータ転送量が限定されていない危険な状態です。テーブルに新しい行が追加されるたびに、すべてのリクエストでデータ転送量が増えます。テーブルのサイズに関わらず、これは対処する必要があります。
小さなデータセット環境ではアプリケーションは問題なく動作するかもしれませんが、スケールすると、たとえカラム幅が中程度でも 10,000 行を返すページネーションなしエンドポイントは 1 日に数百メガバイトのデータを転送する可能性があります。
修正: ORDER BY と LIMIT/OFFSET で結果セットを制限します。
修正前:
SELECT id, name, price FROM products;
修正後:
SELECT id, name, price FROM products
ORDER BY id
LIMIT 50 OFFSET 0;
ページネーションを追加するときは、クライアント側がすでにページネーション対応の応答に対応しているかどうかを確認してください。対応していなければ、適切なデフォルト値を選択し、API ドキュメントにページネーションパラメータを記載してください。
問題: クエリが 1 日に何千回も実行されているのに、データはほとんど変わらない。毎回、データベースから同じ行が転送されます。このパターンは pg_stat_statements でのみ見えます。コード自体は通常に見えます。
他のクエリと比べて実行回数が極端に多いクエリを探してください。典型例: 設定テーブル、カテゴリリスト、機能フラグ、ユーザーロール定義。
修正: アプリケーションとデータベース間にキャッシュ層を追加し、リクエストのたびにデータベースに問い合わせることを避けます。
問題: アプリケーションがテーブル全体を取得してから、アプリケーションコードで集計(平均値、件数、合計、グループ化)を行っている。結果は小さなサマリーなのに、完全なデータセットがネットワークを通じて転送されます。
修正: 集計を SQL に移します。
修正前: アプリケーションがテーブル全体を取得してループや .reduce() などでコード側で集計。
修正後:
SELECT p.category_id,
AVG(r.rating) AS avg_rating,
COUNT(r.id) AS review_count
FROM reviews r
INNER JOIN products p ON r.product_id = p.id
GROUP BY p.category_id;
問題: 幅の広い親テーブルと子テーブルの JOIN が、すべての親カラムを子テーブルの行数分だけ繰り返します。商品に 200 件のレビューがあり、商品の行に 50KB の JSONB カラムがある場合、JOIN は 50KB × 200 = 約 10MB を 1 回のリクエストで転送します。
これは SELECT * の問題とは異なります。必要なカラムだけ選択しても、JOIN は親データを子行ごとに繰り返します。修正は構造的です: JOIN そのものを避けます。
修正: JOIN を 2 つのクエリに分割します。
修正前:
SELECT * FROM products
LEFT JOIN reviews ON reviews.product_id = products.id
WHERE products.id = 1;
修正後(2 つのクエリに分割):
SELECT id, name, price, description, image_urls FROM products WHERE id = 1;
SELECT id, user_name, rating, body FROM reviews WHERE product_id = 1;
1 つの JOIN ではなく 2 つのクエリ。商品データは 1 回だけ取得され、レビューも 1 回だけ取得されます。データ重複がありません。
修正を適用した後:
SELECT pg_stat_statements_reset();)トラフィックを実行し、診断クエリを再度実行して修正前後を比較してください。neon.ts)上記の修正は Postgres から転送されるデータ量(エグレス)を削減します。本番以外の環境でのもう 1 つの大きなコスト要因はコンピュートで、これは Neon のインフラストラクチャ・アズ・コード ファイル(neon スキルを参照)の neon.ts に明記することで、ブランチごとのフラグに頼るのではなく、開発・プレビュー・CI ブランチをデフォルトで安価に保つことができます:
npm i @neon/config
// neon.ts
import { defineConfig } from "@neon/config/v1";
export default defineConfig({
branch: (branch) => {
if (branch.exists || branch.isDefault) return {}; // 本番環境は変更しない
return {
ttl: "7d", // 一時的なブランチは保存料を積み上げるのではなく自動的に失効
postgres: {
computeSettings: {
autoscalingLimitMinCu: 0.25, // アイドル時にゼロにスケール
autoscalingLimitMaxCu: 1, // 一時的なブランチの自動スケールの上限を制限
suspendTimeout: "5m",
},
},
};
},
});
neon config apply # 現在のブランチに適用(neon deploy はエイリアス)
これは補完的なもので、代替ではありません。クエリパターンの修正はエグレス費用を実際に削減しますが、これらの設定は本番以外のコンピュートとストレージが同じ請求書に静かに積み上がるのを防ぎます。neon checkout がブランチ作成時にこのポリシーを適用するため、新しい開発・プレビューブランチは自動的に安価な設定を継承します。
FIRST: Use the parent neon skill for a Neon overview, getting started with Neon, Neon development best practices, and more.
If the neon skill is not installed, fetch it from https://neon.com/docs/ai/skills/neon/SKILL.md or install it with:
npx skills add neondatabase/agent-skills --skill neon
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.
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.
Identify which queries transfer the most data. The primary tool is the pg_stat_statements extension.
SELECT 1 FROM pg_stat_statements LIMIT 1;
If this errors, the extension needs to be created:
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
On Neon the extension is available by default, but it may still need this CREATE EXTENSION step.
Stats are cleared when a Neon compute scales to zero and restarts. If the stats are empty or the compute recently woke up:
SELECT pg_stat_statements_reset();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.
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.
Queries returning the most total rows:
SELECT query, calls, rows AS total_rows, rows / calls AS avg_rows_per_call
FROM pg_stat_statements
WHERE calls > 0
ORDER BY rows DESC
LIMIT 10;
Queries returning the most rows per execution (poorly scoped SELECTs, missing pagination):
SELECT query, calls, rows AS total_rows, rows / calls AS avg_rows_per_call
FROM pg_stat_statements
WHERE calls > 0
ORDER BY avg_rows_per_call DESC
LIMIT 10;
Most frequently called queries (candidates for caching):
SELECT query, calls, rows AS total_rows, rows / calls AS avg_rows_per_call
FROM pg_stat_statements
WHERE calls > 0
ORDER BY calls DESC
LIMIT 10;
Longest running queries (not a direct egress measure, but helps identify problem queries during a spike):
SELECT query, calls, rows AS total_rows,
round(total_exec_time::numeric, 2) AS total_exec_time_ms
FROM pg_stat_statements
WHERE calls > 0
ORDER BY total_exec_time DESC
LIMIT 10;
Rank findings by estimated egress impact:
For each query identified in Step 1, or for each database query in the codebase if no stats are available, check:
Apply the appropriate fix for each problem found. Below are the most common egress anti-patterns and how to fix them.
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.
Fix: Name only the columns the response needs.
Before:
SELECT * FROM products;
After:
SELECT id, name, price, image_urls FROM products;
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.
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.
Fix: Bound the result set with ORDER BY plus LIMIT/OFFSET.
Before:
SELECT id, name, price FROM products;
After:
SELECT id, name, price FROM products
ORDER BY id
LIMIT 50 OFFSET 0;
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.
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.
Look for queries with extremely high call counts relative to other queries. Common examples: configuration tables, category lists, feature flags, user role definitions.
Fix: Add a caching layer between the application and the database so it avoids hitting the database on every request.
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.
Fix: Push the aggregation into SQL.
Before: The application fetches entire tables and aggregates in code with loops or .reduce().
After:
SELECT p.category_id,
AVG(r.rating) AS avg_rating,
COUNT(r.id) AS review_count
FROM reviews r
INNER JOIN products p ON r.product_id = p.id
GROUP BY p.category_id;
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.
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.
Fix: Split the join into two queries, one per table.
Before:
SELECT * FROM products
LEFT JOIN reviews ON reviews.product_id = products.id
WHERE products.id = 1;
After (two separate queries):
SELECT id, name, price, description, image_urls FROM products WHERE id = 1;
SELECT id, user_name, rating, body FROM reviews WHERE product_id = 1;
Two queries instead of one JOIN. The product data is fetched once. The reviews are fetched once. No duplication.
After applying fixes:
SELECT pg_stat_statements_reset();), let traffic run, then re-run the diagnostic queries to compare before and after.neon.ts)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:
npm i @neon/config
// neon.ts
import { defineConfig } from "@neon/config/v1";
export default defineConfig({
branch: (branch) => {
if (branch.exists || branch.isDefault) return {}; // don't touch prod
return {
ttl: "7d", // ephemeral branches auto-expire instead of accruing storage
postgres: {
computeSettings: {
autoscalingLimitMinCu: 0.25, // scale to zero when idle
autoscalingLimitMaxCu: 1, // cap autoscaling on throwaway branches
suspendTimeout: "5m",
},
},
};
},
});
neon config apply # apply to the current branch (neon deploy is an alias)
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.
原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。