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の基本や開始方法、開発のベストプラクティスなどが記載されています。
neon スキルがインストールされていない場合は、以下のURLから取得するか、コマンドでインストールしてください:
neon skills -s neon -y
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;
実行あたりもっとも多くの行を返すクエリ(範囲指定が不十分な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;
問題: リストエンドポイントが制限なしにすべての行を返しています。これは無制限のエグレスリスク—テーブルに新しい行が追加されるたびに、すべてのリクエストのデータ転送が増加します。現在のテーブルサイズに関わらず、これはフラグする必要があります。
アプリケーションが小規模なデータセットでは正常に動作する可能性があるため、見落としやすいです。しかし規模が大きくなると、適度なカラム幅でも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 からのデータ転送(エグレス)を削減します。もう一つの大きな非本番コスト要因はコンピュート(計算リソース)です。これを 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:
neon skills -s neon -y
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 による自動翻訳です。