• 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 スキルがインストールされていない場合は、以下から取得するか、下記のコマンドでインストールしてください:

npx skills add neondatabase/agent-skills --skill neon

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;

実行 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,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;

ページネーションの不足

問題: リストエンドポイントが 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 による重複

問題: 幅の広い親テーブルと子テーブルの 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 から転送されるデータ量(エグレス)を削減します。本番以外の環境でのもう 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 がブランチ作成時にこのポリシーを適用するため、新しい開発・プレビューブランチは自動的に安価な設定を継承します。

さらに詳しく

  • 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:

npx skills add neondatabase/agent-skills --skill neon

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 による自動翻訳です。