К основному содержанию
скилл CX Codex

supabase-cost-tuning — скилл для Claude Code: установка и работа

Скилл supabase-cost-tuning разбирает расходы Supabase и помогает найти лишние траты в базе, хранилище, соединениях и Edge Functions.

MIT 1 установок ★ 2 935 обновлён 2026-11-01

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add jeremylongshore/tons-of-skills-marketplace --skill supabase-cost-tuning -a claude-code
Открыть на GitHub

Что делает supabase-cost-tuning

Скилл ведёт аудит расходов Supabase по трём шагам: сначала проверяет размер базы, таблицы, неиспользуемые индексы, dead tuples, подключения и хранилище, затем предлагает точечные изменения. Для базы используются SQL-запросы, для хранилища — клиент с service role key и скрипты очистки.

Дальше скилл помогает архивировать старые строки, запускать VACUUM ANALYZE, сжимать изображения перед загрузкой и удалять осиротевшие файлы. Для снижения трафика он заменяет select('*') явными колонками, считает записи через head: true и применяет .range().

На третьем шаге он разбирает connection pooling, режимы прямого, session- и transaction-подключения, а также кэширование и динамические импорты в Edge Functions. Для работы заранее нужны доступ к Dashboard и SQL Editor, установленный @supabase/supabase-js и service role key. Миграции могут требовать direct или session semantics, поэтому отправлять все операции в transaction pooling нельзя.

Какие задачи решает

  • проверить, какие таблицы и индексы расходуют ресурсы базы
  • найти мёртвые строки и подготовить очистку через VACUUM ANALYZE
  • удалить файлы в Supabase Storage, не связанные с записями
  • сократить трафик через выбор колонок и пагинацию
  • настроить пул соединений без преждевременного увеличения compute

Примеры запросов агенту

  • Проведи аудит расходов Supabase и покажи главные источники затрат.
  • Проверь базу, Storage и подключения, затем предложи изменения по шагам.
  • Разбери, можно ли уменьшить compute через pooling, архивирование и очистку файлов.

Как установить supabase-cost-tuning

1Через Skills CLI (Vercel)

npx skills add jeremylongshore/tons-of-skills-marketplace --skill supabase-cost-tuning -a claude-code

2Вручную: положить файлы

~/.claude/skills/supabase-cost-tuning/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/supabase-cost-tuning/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о supabase-cost-tuning

Как установить supabase-cost-tuning в Claude Code?

Выполните npx skills add jeremylongshore/tons-of-skills-marketplace --skill supabase-cost-tuning -a claude-code. Файл скилла будет доступен по пути ~/.claude/skills/supabase-cost-tuning/SKILL.md.

Что делает supabase-cost-tuning?

Он проводит аудит расходов Supabase, ищет лишний объём базы и Storage, проверяет подключения и подсказывает изменения для compute, трафика и Edge Functions.

Что нужно подготовить для работы скилла?

Нужны доступ к Supabase Dashboard и SQL Editor, пакет @supabase/supabase-js и service role key для операций с Storage и административных скриптов.

Исходный текст

SKILL.md · MIT
---
name: supabase-cost-tuning
description: 'Optimize Supabase costs through plan selection, database tuning, storage
  cleanup,

  connection pooling, and Edge Function optimization.

  Use when analyzing Supabase billing, reducing costs, right-sizing compute,

  or implementing usage tracking and budget alerts.

  Trigger with phrases like "supabase cost", "supabase billing",

  "reduce supabase costs", "supabase pricing", "supabase expensive", "supabase budget".

  '
allowed-tools: Read, Write, Edit, Grep, Bash(supabase:*)
version: 1.55.0
license: MIT
author: Jeremy Longshore <[email protected]>
tags:
  - saas
  - supabase
  - cost-optimization
compatibility: Designed for Claude Code
---

# Supabase Cost Tuning

## Overview

Reduce Supabase spend by auditing usage against plan limits, eliminating database and storage waste, and right-sizing compute resources. The three biggest levers: database optimization (vacuum, index cleanup, archival), storage lifecycle management (compress before upload, orphan cleanup), and connection pooling to reduce compute add-on requirements.

Work the three steps below in order — audit first to find where the money goes, then optimize the biggest offenders, then right-size compute. Each step keeps a representative snippet inline; the full query and script sets live in `references/` so this file stays scannable.

## Prerequisites

- Supabase project with Dashboard access (Settings > Billing)
- `@supabase/supabase-js` installed: `npm install @supabase/supabase-js`
- Service role key for admin operations (storage audit, cleanup scripts)
- SQL editor access (Dashboard > SQL Editor or `psql` connection)

## Pricing Reference

Reviewed 2026-10-22: use [current pricing](https://supabase.com/pricing) and the
project's actual billing dashboard rather than a universal hard-coded plan table.
Compute is billed hourly; paid organizations receive $10 of compute credits per
month, shared across projects, not a free compute instance for every project.
The [compute usage reference](https://supabase.com/docs/guides/platform/manage-your-usage/compute)
lists Small at $0.0206/hour (about $15 for 730 hours), Medium at $0.0822/hour
(about $60), and Large at $0.1517/hour (about $111), before plan fees, credits and
other usage. These dated estimates are not a billing quote or fixed monthly cap.

Read replicas have their own compute and usage costs, not a universal $25/month
price. Model the selected size, active hours, disk, egress, region and current plan
allowances before changing topology. Pooling can reduce connection overhead but
does not guarantee that a smaller compute size will satisfy the workload.

## Instructions

### Step 1: Audit current usage and identify cost drivers

Find where the database budget is going before changing anything. Run the audit queries in the SQL Editor to surface the biggest tables, unused indexes, dead-tuple bloat, and connection count. Start with total size:

```sql
select pg_size_pretty(pg_database_size(current_database())) as total_db_size;
```

Then audit storage per bucket with a service-role client, and read current spend under **Dashboard > Settings > Billing**. See [full audit queries and storage script](references/audit-queries.md) for the complete SQL set (table sizes, zero-scan indexes, dead-tuple ratio, connection count) and the per-bucket usage script.

### Step 2: Optimize database, storage, and bandwidth

Attack the biggest offenders from Step 1. Archive old rows before deleting, then VACUUM ANALYZE to make dead-tuple space reusable and refresh planner stats; ordinary VACUUM does not generally shrink the on-disk allocation:

```sql
vacuum (verbose, analyze) public.events;
```

For storage, compress images client-side before upload and schedule an orphan-cleanup job. For bandwidth, replace `select('*')` with explicit column lists, use `head: true` count queries for totals, and paginate with `.range()`. See [full optimization code](references/optimization.md) for the archival + VACUUM SQL, the compress/clean-orphans scripts, and the bandwidth-reduction patterns.

### Step 3: Right-size compute and distinguish invocation cost from latency

Prefer pooling and code fixes over a compute upgrade. Choose the appropriate direct or Supavisor session/transaction connection mode for the client. Migrations may require direct/session semantics; do not send every workflow to transaction pooling:

```typescript
// Copy the actual direct/session/transaction connection string from Dashboard.
// Do not derive the pooler hostname by changing only the port.
// Transaction pooling constraints (including prepared statements) need review.
```

Smaller imports and warm-instance caching can improve latency/resource use, but do
not themselves reduce hosted Edge Function invocation charges. Current
[invocation billing](https://supabase.com/docs/guides/platform/manage-your-usage/edge-function-invocations)
is based on invocation count (excluding preflight OPTIONS), with package rounding
for billable overage. Avoid unnecessary invocations and retry storms within the
application's correctness requirements; do not skip required work to reduce counts.
Treat historical optimization examples as resource/latency patterns, not evidence
of invocation savings. Use actual billing usage rather than a custom event table
as invoice authority.

## Output

After completing all three steps, the project has:

- Database size audit with table-level breakdown and dead tuple analysis
- Candidate unused indexes reviewed against representative workloads before any approved drop
- Approved archival and vacuum outcomes measured without promising physical disk shrinkage
- Storage orphans cleaned and upload compression implemented
- Bandwidth reduced through column selection and pagination
- Connection pooling configured to avoid unnecessary compute upgrades
- Edge Function cold starts minimized with dynamic imports and caching
- Usage monitoring table and daily summary view for spend visibility

## Error Handling

| Issue                                            | Cause                                        | Solution                                                                                                       |
| ------------------------------------------------ | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| Database approaching 500 MB (Free) or 8 GB (Pro) | Data growth without archival                 | Archive old records, VACUUM, drop unused indexes                                                               |
| Storage costs climbing monthly                   | Orphaned uploads accumulating                | Schedule cleanup job for files not linked to records                                                           |
| Unexpected bandwidth spike                       | `select('*')` on large tables                | Use specific column lists; add `.range()` pagination                                                           |
| Edge Function billing spike                      | Excess invocations or retry loops            | Inspect invocation counts and correctness-preserving admission/retry budgets; import size is a latency concern |
| Connection limit errors                          | Too many direct connections                  | Switch to pooler URL (port 6543); reduce client pool size                                                      |
| Spend cap reached                                | A capped usage surface reached its allowance | Review the current spend-cap coverage and response; it does not cap every charge                               |
| VACUUM not reclaiming space                      | Long-running transactions holding locks      | Check `pg_stat_activity` for idle-in-transaction; terminate stale sessions                                     |

## Examples

**Quick cost check** — inspect actual billing usage and an authorized database-size query; bucket count is not stored bytes.

**Cost estimation** — supply reviewed quantities, units, current rates, eligible credits and source/date to an explicitly scoped calculator. No universal Pro-tier total is supplied.

The [explicit-input examples](references/examples.md) validate arithmetic without embedding provider rates. Reconcile every included allowance, package/tier rounding, compute hour, credit and excluded charge against the current billing surface before using an estimate for a decision.

## Resources

- [Supabase Pricing](https://supabase.com/pricing) — plan comparison and calculator
- [Compute Add-ons](https://supabase.com/docs/guides/platform/compute-add-ons) — instance sizing guide
- [Spend Cap](https://supabase.com/docs/guides/platform/spend-cap) — prevent unexpected overage charges
- [Database Disk Usage](https://supabase.com/docs/guides/platform/database-size) — monitoring and management
- [Connection Pooling (Supavisor)](https://supabase.com/docs/guides/database/connecting-to-postgres#connection-pooler) — reduce connection overhead
- [Edge Functions Best Practices](https://supabase.com/docs/guides/functions/best-practices) — cold start and performance tips
- [supabase-js Reference](https://supabase.com/docs/reference/javascript/introduction) — `createClient` and SDK patterns

## Next Steps

For architecture patterns, see `supabase-reference-architecture`.
For performance tuning beyond cost, see `supabase-performance-tuning`.

© Jeremy Longshore · MIT · jeremylongshore/tons-of-skills-marketplace

Похожие скиллы

Все скиллы по теме «Данные и базы» →
supabase alinaqi Скилл для работы с Supabase CLI, миграциями PostgreSQL, политиками RLS и Deno Edge Functions. Пригодится при локальной разработке бэкенда. CX Codex +1 651установок supabase-cli fcakyon Скилл учит агента управлять проектами через Supabase CLI: поднимать локальный стек, писать миграции, тестировать edge functions и генерировать типы TypeScript. CX Codex +1 ★ 1 216звёзд репо supabase-server supabase Подсказывает агенту, как писать Edge Functions, Hono-приложения и вебхуки на @supabase/server: режимы auth, клиенты, проверка входящих запросов. CX Codex +1 11 200установок crontap-supabase-edge-function-cron Crontap Скилл crontap-supabase-edge-function-cron для Claude Code настраивает периодический вызов Supabase Edge Functions через внешний планировщик Crontap с повторами при сбоях и журналом запусков. CX Codex +1 1 300установок supabase-development Mindrally Скилл supabase-development задаёт агенту порядок работы с Supabase: схема базы, RLS-политики, авторизация, realtime-подписки и Edge Functions. CX Codex +1 740установок supabase-audit-functions yoanbernabeu Скилл supabase-audit-functions для аудита безопасности Supabase Edge Functions, работает в Claude Code. Находит открытые функции, проверяет JWT-авторизацию и валидацию ввода, ищет IDOR и раскрытие данных в ошибках. CX Codex +1 1 300установок

Из того же набора139

Весь набор →
granola-core-workflow-a Скилл granola-core-workflow-a помогает настроить шаблоны заметок, реципы для чата и контекст перед встречами в Granola. Пригодится при подготовке к 1:1 и созвонам с клиентами. CX Codex +1 1установок monitoring-cross-chain-bridges Скилл monitoring-cross-chain-bridges для Claude Code собирает данные о TVL, комиссиях, объёме и статусе переводов через кроссчейн-мосты. Сравнивает маршруты и проверяет транзакции. CX Codex +1 1установок vercel-cost-tuning Скилл vercel-cost-tuning для Claude Code разбирает счета Vercel и показывает, где возникают лишние расходы. Помогает урезать траты на функции, трафик и middleware. CX Codex +1 1установок linear-cost-tuning Скилл linear-cost-tuning снижает расход квот и нагрузку на API Linear: заменяет частый поллинг вебхуками и урезает избыточную сложность запросов GraphQL. CX Codex +1 1установок linear-prod-checklist Скилл linear-prod-checklist проверяет готовность интеграции Linear к запуску: доступы, данные, лимиты, вебхуки, восстановление и ответственность. CX Codex +1 1установок linear-observability Скилл linear-observability собирает метрики и алерты вокруг интеграции с Linear: вызовы API, вебхуки, очередь, сверка. Токены и текст задач в телеметрию не попадают. CX Codex +1 1установок supabase-webhooks-events Скилл supabase-webhooks-events помогает настроить вебхуки Supabase, асинхронные HTTP-запросы через pg_net, события LISTEN/NOTIFY и приёмники Edge Functions с проверкой HMAC-подписи. CX Codex +1 1установок sql-query-optimizer Скилл подсказывает, как оптимизировать SQL-запросы. Активируется сам, когда в запросе встречается «sql query optimizer», «sql optimizer» или просто «sql». CX Codex +1 1установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой