• Projects
  • Service
  • About
  • branding.bz
  • Podcast
  • Tips
  • FAQ
  • Recruit
  • Download
  • Contact
  • branding.bz(ブランド構築SaaS)
  • DESIGN NOW(デザインメディア)
  • X
  • LinkedIn
  • Spotify
  • Facebook

213-0011 神奈川県川崎市高津区久本3-6-7-303

© 2026 ID INC. All rights reserved

claude-skills/スキル
SKILLOfficialdatabase

neon-postgres-egress-optimizer

プラグイン
neon
ソース
GitHub で見る ↗
説明

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データ転送最適化ガイド

Postgresデータベースから過度なデータ転送(エグレス)を引き起こすアプリケーション側のクエリ構造を診断・修正するサポートを行います。高額なエグレス請求の大半は、アプリケーションが実際に使うより多くのデータをデータベースから取得していることが原因です。

以下の4ステップを順番に進めます:診断(どのクエリがもっともデータを転送しているか特定)→ 分析(背後にあるコードを調査)→ 修正(問題パターンを改善)→ 検証(修正が機能し、転送量が減ったことを確認)

ステップ1:診断

データ転送量が最も多いクエリを特定します。主な道具は pg_stat_statements 拡張機能です。

pg_stat_statements が利用可能か確認

SELECT 1 FROM pg_stat_statements LIMIT 1;

エラーが出た場合は、拡張機能を作成する必要があります:

CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

Neonではこの拡張機能がデフォルトで利用できますが、それでも CREATE EXTENSION ステップが必要な場合があります。

統計情報が空の場合の対応

Neonのコンピュート(計算リソース)がゼロにスケールダウンして再起動すると、統計情報がクリアされます。統計情報が空またはコンピュートが最近起動した場合:

  1. 統計情報をリセットして新しい測定期間を開始:SELECT pg_stat_statements_reset();
  2. アプリケーションを本番相当のトラフィック下で最低1時間実行
  3. 戻って、以下の診断クエリを実行

本番データベースの統計情報がある場合はそれを使用してください。本番統計へのアクセスがない場合は、ステップ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,000行を返すクエリで各行に50KBのJSONBカラムが含まれていると、1回の呼び出しで約50MBが転送されます。
  • 極めて高い呼び出し頻度 も積み重なります。1日50,000回呼ばれるクエリが1回あたり10行返す場合、1日500,000行が転送されます。
  • スキーマと照合 して行幅の広いカラムを特定します。JSONB、TEXT、BYTEA、大きなVARCHARカラムを探します。

ステップ2:コードベースの分析

ステップ1で特定した各クエリ、または統計情報がない場合はコードベース内の各データベースクエリについて、以下を確認します:

  • 応答に必要なカラムだけを選択しているか?
  • 行数が制限されているか(LIMIT/ページング)?
  • キャッシュの恩恵を受けるほど頻繁に呼ばれているか?
  • 生データを取得して、アプリケーションコードで集計しているか?
  • 親データを子行全体で重複させるJOINを使用しているか?

ステップ3:修正

ステップ2で見つかった各問題に適切な修正を適用します。以下は、もっとも一般的なエグレス問題パターンとその修正方法です。

未使用カラム(SELECT *)

問題: クエリがすべてのカラムを取得していますが、アプリケーションはそのうち数個しか使用していません。大きなカラム(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 による重複

問題: 行幅の広い親テーブルと子テーブルの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回取得されます。重複なし。

ステップ4:検証

修正を適用した後:

  1. 既存テストを実行 して、何も壊れていないことを確認します。
  2. レスポンスを確認 —APIが同じデータ形式を返しているか確認します。カラム選択とページング変更は、特定フィールドまたは完全な結果セットに依存するクライアントを壊す可能性があります。
  3. 改善を測定 —pg_stat_statements データが利用可能な場合、それをリセット(SELECT pg_stat_statements_reset();)して、トラフィックを実行した後、診断クエリを再実行して修正前後を比較します。

Neon インフラストラクチャ・アズ・コード(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 がブランチ作成時にこのポリシーを適用するため、新しい開発/プレビュー ブランチは自動的に低コストプロファイルを継承します。

参考資料

  • https://neon.com/docs/introduction/network-transfer.md
  • https://neon.com/docs/introduction/cost-optimization.md
原文(English)を表示

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

Postgres Egress Optimizer

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.

Step 1: Diagnose

Identify which queries transfer the most data. The primary tool is the pg_stat_statements extension.

Check if pg_stat_statements is available

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.

Handle empty stats

Stats are cleared when a Neon compute scales to zero and restarts. If the stats are empty or the compute recently woke up:

  1. Reset the stats to start a clean measurement window: SELECT pg_stat_statements_reset();
  2. Let the application run under representative traffic for at least an hour.
  3. Return and run the diagnostic queries below.

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.

Diagnostic queries

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;

Interpret the results

Rank findings by estimated egress impact:

  • 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.
  • Extreme call frequency on even small queries adds up. A query called 50,000 times/day returning 10 rows each = 500,000 rows/day.
  • Cross-reference with the schema to identify which columns are wide. Look for JSONB, TEXT, BYTEA, and large VARCHAR columns.

Step 2: Analyze the Codebase

For each query identified in Step 1, or for each database query in the codebase if no stats are available, check:

  • Does it select only the columns the response needs?
  • Does it return a bounded number of rows (LIMIT/pagination)?
  • Is it called frequently enough to benefit from caching?
  • Does it fetch raw data that gets aggregated in application code?
  • Does it use a JOIN that duplicates parent data across child rows?

Step 3: Fix

Apply the appropriate fix for each problem found. Below are the most common egress anti-patterns and how to fix them.

Unused columns (SELECT *)

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;

Missing pagination

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.

High-frequency queries on static data

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.

Application-side aggregation

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;

JOIN duplication

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.

Step 4: Verify

After applying fixes:

  1. Run existing tests to confirm nothing broke.
  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.
  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.

Neon Infrastructure as Code (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.

Further Reading

  • https://neon.com/docs/introduction/network-transfer.md
  • https://neon.com/docs/introduction/cost-optimization.md

原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。