[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M796E3T095108DQJHYNDAS9F":3,"skill-same:01M796E3T095108DQJHYNDAS9F":56},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":33,"commitSha":34,"skillDirectory":35,"forksCount":36,"repositoryHtmlUrl":37,"repositoryHomepageUrl":6,"ownerHtmlUrl":38,"ownerBlogUrl":39,"ownerDescription":40,"updatedAt":41,"install":42,"resources":55},"01M796E3T095108DQJHYNDAS9F","supabase-cost-tuning",null,"Optimize Supabase costs through plan selection, database tuning, storage cleanup,\nconnection pooling, and Edge Function optimization.\nUse when analyzing Supabase billing, reducing costs, right-sizing compute,\nor implementing usage tracking and budget alerts.\nTrigger with phrases like \"supabase cost\", \"supabase billing\",\n\"reduce supabase costs\", \"supabase pricing\", \"supabase expensive\", \"supabase budget\".","jukeyman\u002Fjukeyman-skills","jukeyman","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F142960420?v=4","01M78FR4Y3DHMMCBCC0GXXNB3F","RICK JEFFERSON","01M78FR4Z8RVQRAD31Y5J7V6EB",1,"MIT","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--supabase-pack--supabase-cost-tuning\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: supabase-cost-tuning\ndescription: |\n  Optimize Supabase costs through plan selection, database tuning, storage cleanup,\n  connection pooling, and Edge Function optimization.\n  Use when analyzing Supabase billing, reducing costs, right-sizing compute,\n  or implementing usage tracking and budget alerts.\n  Trigger with phrases like \"supabase cost\", \"supabase billing\",\n  \"reduce supabase costs\", \"supabase pricing\", \"supabase expensive\", \"supabase budget\".\nallowed-tools: Read, Write, Edit, Grep, Bash(supabase:*)\nversion: 1.0.0\nlicense: MIT\nauthor: Jeremy Longshore \u003Cjeremy@intentsolutions.io>\ncompatible-with: claude-code, codex, openclaw\ntags: [saas, supabase, cost-optimization]\n---\n\n# Supabase Cost Tuning\n\n## Overview\n\nReduce 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.\n\n## Prerequisites\n\n- Supabase project with Dashboard access (Settings > Billing)\n- `@supabase\u002Fsupabase-js` installed: `npm install @supabase\u002Fsupabase-js`\n- Service role key for admin operations (storage audit, cleanup scripts)\n- SQL editor access (Dashboard > SQL Editor or `psql` connection)\n\n## Pricing Reference\n\n| Resource | Free Tier | Pro ($25\u002Fmo) | Team ($599\u002Fmo) |\n|----------|-----------|--------------|----------------|\n| Database | 500 MB | 8 GB included, $0.125\u002FGB extra | 8 GB included |\n| Storage | 1 GB | 100 GB included, $0.021\u002FGB extra | 100 GB included |\n| Bandwidth | 5 GB | 250 GB included, $0.09\u002FGB extra | 250 GB included |\n| Edge Functions | 500K invocations | 2M invocations, $2\u002Fmillion extra | 2M invocations |\n| Realtime | 200 concurrent | 500 concurrent | 500 concurrent |\n| Auth MAU | 50,000 | 100,000 | 100,000 |\n\n**Compute add-ons** (Pro and above):\n\n| Instance | vCPUs | RAM | Price |\n|----------|-------|-----|-------|\n| Micro | 2 | 1 GB | Included with Pro |\n| Small | 2 | 2 GB | $25\u002Fmo |\n| Medium | 2 | 4 GB | $50\u002Fmo |\n| Large | 4 | 8 GB | $100\u002Fmo |\n| XL | 8 | 16 GB | $200\u002Fmo |\n| 2XL | 16 | 32 GB | $400\u002Fmo |\n\n**Decision framework:** Read replicas ($25\u002Fmo each) beat scaling up when reads dominate and you need geographic distribution. Connection pooling (Supavisor, free) reduces compute pressure from idle connections.\n\n## Instructions\n\n### Step 1: Audit Current Usage and Identify Cost Drivers\n\nRun these queries in the SQL Editor to understand where your database budget is going:\n\n```sql\n-- Total database size\nselect pg_size_pretty(pg_database_size(current_database())) as total_db_size;\n\n-- Database size by table (find the biggest offenders)\nselect\n  relname as table_name,\n  pg_size_pretty(pg_total_relation_size(relid)) as total_size,\n  pg_size_pretty(pg_relation_size(relid)) as table_size,\n  pg_size_pretty(pg_total_relation_size(relid) - pg_relation_size(relid)) as index_size,\n  n_live_tup as row_count\nfrom pg_stat_user_tables\norder by pg_total_relation_size(relid) desc\nlimit 20;\n\n-- Find unused indexes consuming space (zero scans since last stats reset)\nselect\n  schemaname || '.' || indexrelname as index_name,\n  pg_size_pretty(pg_relation_size(indexrelid)) as size,\n  idx_scan as scans_since_reset\nfrom pg_stat_user_indexes\nwhere idx_scan = 0\n  and schemaname = 'public'\norder by pg_relation_size(indexrelid) desc\nlimit 10;\n\n-- Check dead tuple bloat (high ratio means VACUUM is needed)\nselect\n  relname,\n  n_dead_tup,\n  n_live_tup,\n  round(n_dead_tup::numeric \u002F greatest(n_live_tup, 1) * 100, 1) as dead_pct\nfrom pg_stat_user_tables\nwhere n_dead_tup > 1000\norder by n_dead_tup desc;\n\n-- Connection count (high count may indicate pooling issues)\nselect count(*) as active_connections,\n  max_conn as max_allowed\nfrom pg_stat_activity,\n  (select setting::int as max_conn from pg_settings where name = 'max_connections') mc\ngroup by max_conn;\n```\n\nAudit storage usage programmatically:\n\n```typescript\nimport { createClient } from '@supabase\u002Fsupabase-js'\n\nconst supabaseAdmin = createClient(\n  process.env.SUPABASE_URL!,\n  process.env.SUPABASE_SERVICE_ROLE_KEY!\n)\n\n\u002F\u002F List storage usage per bucket\nconst { data: buckets } = await supabaseAdmin.storage.listBuckets()\n\nfor (const bucket of buckets ?? []) {\n  const { data: files } = await supabaseAdmin.storage\n    .from(bucket.name)\n    .list('', { limit: 1000 })\n\n  const totalSize = files?.reduce((sum, f) => sum + (f.metadata?.size || 0), 0) ?? 0\n  console.log(`${bucket.name}: ${(totalSize \u002F 1024 \u002F 1024).toFixed(1)} MB`)\n}\n```\n\nCheck your current spend: **Dashboard > Settings > Billing** shows usage against plan limits with a breakdown by resource category.\n\n### Step 2: Optimize Database, Storage, and Bandwidth\n\n**Database optimization — reclaim space and reduce bloat:**\n\n```sql\n-- Archive old data before deleting (preserve for compliance\u002Fanalytics)\ncreate table if not exists public.events_archive (like public.events including all);\n\ninsert into public.events_archive\nselect * from public.events\nwhere created_at \u003C now() - interval '6 months';\n\ndelete from public.events\nwhere created_at \u003C now() - interval '6 months';\n\n-- Run VACUUM ANALYZE to reclaim space and update query planner stats\nvacuum (verbose, analyze) public.events;\n\n-- Drop confirmed-unused indexes (verify idx_scan = 0 from Step 1)\n-- WARNING: always confirm the index is unused before dropping\ndrop index if exists idx_events_legacy_status;\n\n-- Remove soft-deleted records past retention period\ndelete from public.orders\nwhere deleted_at is not null\n  and deleted_at \u003C now() - interval '90 days';\n\nvacuum (analyze) public.orders;\n```\n\n**Storage optimization — compress before upload, clean orphans:**\n\n```typescript\n\u002F\u002F Compress images before upload (reduces storage + bandwidth)\nasync function uploadCompressed(\n  bucket: string,\n  path: string,\n  file: File\n): Promise\u003Cstring> {\n  \u002F\u002F Use client-side compression before uploading\n  const compressed = await compressImage(file, { maxWidth: 1920, quality: 0.8 })\n\n  const { data, error } = await supabaseAdmin.storage\n    .from(bucket)\n    .upload(path, compressed, {\n      contentType: file.type,\n      upsert: true,\n    })\n\n  if (error) throw error\n  return data.path\n}\n\n\u002F\u002F Clean orphaned files older than 30 days\nasync function cleanOrphanedUploads() {\n  const cutoff = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString()\n\n  const { data: orphans } = await supabaseAdmin\n    .from('storage.objects')\n    .select('name, created_at')\n    .eq('bucket_id', 'uploads')\n    .lt('created_at', cutoff)\n\n  if (orphans?.length) {\n    const paths = orphans.map(o => o.name)\n    \u002F\u002F Delete in batches of 100\n    for (let i = 0; i \u003C paths.length; i += 100) {\n      await supabaseAdmin.storage\n        .from('uploads')\n        .remove(paths.slice(i, i + 100))\n    }\n    console.log(`Cleaned ${orphans.length} orphaned files`)\n  }\n}\n```\n\n**Bandwidth reduction — select only what you need:**\n\n```typescript\n\u002F\u002F BAD: transfers entire row (wastes bandwidth)\nconst { data } = await supabase.from('products').select('*')\n\n\u002F\u002F GOOD: request only needed columns\nconst { data } = await supabase.from('products').select('id, name, price')\n\n\u002F\u002F Use count queries for totals (head: true = zero data transferred)\nconst { count } = await supabase\n  .from('orders')\n  .select('*', { count: 'exact', head: true })\n\n\u002F\u002F Paginate large result sets\nconst { data } = await supabase\n  .from('logs')\n  .select('id, message, created_at')\n  .order('created_at', { ascending: false })\n  .range(0, 49)  \u002F\u002F 50 rows per page\n```\n\n### Step 3: Right-Size Compute and Reduce Edge Function Costs\n\n**Connection pooling with Supavisor** (reduces need for compute upgrades):\n\n```typescript\n\u002F\u002F Use the pooler connection string instead of direct connection\n\u002F\u002F Dashboard > Settings > Database > Connection string > Mode: Transaction\n\n\u002F\u002F In your app, use the pooled connection URL (port 6543)\n\u002F\u002F Direct:   postgresql:\u002F\u002Fpostgres:pw@db.xxx.supabase.co:5432\u002Fpostgres\n\u002F\u002F Pooled:   postgresql:\u002F\u002Fpostgres:pw@db.xxx.supabase.co:6543\u002Fpostgres\n\n\u002F\u002F For @supabase\u002Fsupabase-js, connection pooling is handled automatically\n\u002F\u002F For direct pg connections (migrations, ORMs), use pooled URL:\nconst pool = new Pool({\n  connectionString: process.env.DATABASE_URL,  \u002F\u002F Use pooler URL\n  max: 10,  \u002F\u002F Limit client-side pool size too\n})\n```\n\n**Edge Function cold start reduction:**\n\n```typescript\n\u002F\u002F Minimize cold starts — keep imports lightweight\n\u002F\u002F BAD: importing heavy libraries unconditionally\nimport { parse } from 'some-huge-csv-library'\n\n\u002F\u002F GOOD: dynamic import only when needed\nDeno.serve(async (req) => {\n  const { action } = await req.json()\n\n  if (action === 'parse-csv') {\n    const { parse } = await import('some-huge-csv-library')\n    return new Response(JSON.stringify(parse(data)))\n  }\n\n  \u002F\u002F Fast path: no heavy import needed\n  return new Response(JSON.stringify({ status: 'ok' }))\n})\n\n\u002F\u002F Cache expensive computations across invocations\n\u002F\u002F Deno Deploy isolates persist for ~60 seconds between requests\nconst _cache = new Map\u003Cstring, { data: unknown; ts: number }>()\n\nfunction cached\u003CT>(key: string, ttlMs: number, fn: () => T): T {\n  const entry = _cache.get(key)\n  if (entry && Date.now() - entry.ts \u003C ttlMs) return entry.data as T\n  const data = fn()\n  _cache.set(key, { data, ts: Date.now() })\n  return data\n}\n```\n\n**Usage monitoring — track spend with a lightweight counter:**\n\n```sql\n-- Create usage tracking table\ncreate table public.api_usage (\n  id bigint generated always as identity primary key,\n  endpoint text not null,\n  method text not null,\n  user_id uuid references auth.users(id),\n  response_bytes int default 0,\n  created_at timestamptz default now()\n);\n\n-- Create partitioned index for efficient time-range queries\ncreate index idx_api_usage_created on public.api_usage (created_at desc);\n\n-- Materialized view for daily cost estimation\ncreate materialized view public.daily_usage_summary as\nselect\n  date_trunc('day', created_at) as day,\n  endpoint,\n  count(*) as requests,\n  sum(response_bytes) as total_bytes\nfrom public.api_usage\ngroup by 1, 2;\n\n-- Auto-refresh via pg_cron (enable extension first)\nselect cron.schedule(\n  'refresh-usage-summary',\n  '0 1 * * *',\n  'refresh materialized view concurrently public.daily_usage_summary;'\n);\n```\n\n## Output\n\nAfter completing all three steps, you will have:\n\n- Database size audit with table-level breakdown and dead tuple analysis\n- Unused indexes identified and dropped to reclaim storage\n- Old data archived and vacuumed to free database space\n- Storage orphans cleaned and upload compression implemented\n- Bandwidth reduced through column selection and pagination\n- Connection pooling configured to avoid unnecessary compute upgrades\n- Edge Function cold starts minimized with dynamic imports and caching\n- Usage monitoring table and daily summary view for spend visibility\n\n## Error Handling\n\n| Issue | Cause | Solution |\n|-------|-------|----------|\n| Database approaching 500 MB (Free) or 8 GB (Pro) | Data growth without archival | Archive old records, VACUUM, drop unused indexes |\n| Storage costs climbing monthly | Orphaned uploads accumulating | Schedule cleanup job for files not linked to records |\n| Unexpected bandwidth spike | `select('*')` on large tables | Use specific column lists; add `.range()` pagination |\n| Edge Function billing spike | Retry loops or heavy imports | Add circuit breaker with max 3 retries; dynamic imports |\n| Connection limit errors | Too many direct connections | Switch to pooler URL (port 6543); reduce client pool size |\n| Spend cap reached | Usage exceeded Pro included resources | Enable spend cap in Dashboard > Settings > Billing to prevent overage |\n| VACUUM not reclaiming space | Long-running transactions holding locks | Check `pg_stat_activity` for idle-in-transaction; terminate stale sessions |\n\n## Examples\n\n**Quick cost check for a growing project:**\n\n```typescript\nimport { createClient } from '@supabase\u002Fsupabase-js'\n\nconst supabase = createClient(\n  process.env.SUPABASE_URL!,\n  process.env.SUPABASE_SERVICE_ROLE_KEY!\n)\n\n\u002F\u002F Check database size against plan limit\nconst { data: dbSize } = await supabase.rpc('get_db_size')\n\u002F\u002F CREATE FUNCTION get_db_size() RETURNS text AS $$\n\u002F\u002F   SELECT pg_size_pretty(pg_database_size(current_database()));\n\u002F\u002F $$ LANGUAGE sql;\n\nconsole.log(`Database size: ${dbSize}`)\n\n\u002F\u002F Check if you're approaching storage limits\nconst { data: buckets } = await supabase.storage.listBuckets()\nconsole.log(`Storage buckets: ${buckets?.length ?? 0}`)\n```\n\n**Monthly cost estimation script:**\n\n```typescript\nfunction estimateMonthlyCost(usage: {\n  dbSizeGb: number\n  storageGb: number\n  bandwidthGb: number\n  edgeFnInvocations: number\n  mau: number\n}) {\n  const pro = {\n    base: 25,\n    dbOverage: Math.max(0, usage.dbSizeGb - 8) * 0.125,\n    storageOverage: Math.max(0, usage.storageGb - 100) * 0.021,\n    bandwidthOverage: Math.max(0, usage.bandwidthGb - 250) * 0.09,\n    edgeFnOverage: Math.max(0, usage.edgeFnInvocations - 2_000_000) \u002F 1_000_000 * 2,\n  }\n\n  const total = pro.base + pro.dbOverage + pro.storageOverage\n    + pro.bandwidthOverage + pro.edgeFnOverage\n\n  console.log('Estimated monthly cost breakdown:')\n  console.log(`  Base Pro plan:     $${pro.base}`)\n  console.log(`  DB overage:        $${pro.dbOverage.toFixed(2)}`)\n  console.log(`  Storage overage:   $${pro.storageOverage.toFixed(2)}`)\n  console.log(`  Bandwidth overage: $${pro.bandwidthOverage.toFixed(2)}`)\n  console.log(`  Edge Fn overage:   $${pro.edgeFnOverage.toFixed(2)}`)\n  console.log(`  TOTAL:             $${total.toFixed(2)}\u002Fmo`)\n\n  return total\n}\n\n\u002F\u002F Example: project with 12GB DB, 150GB storage, 300GB bandwidth\nestimateMonthlyCost({\n  dbSizeGb: 12,\n  storageGb: 150,\n  bandwidthGb: 300,\n  edgeFnInvocations: 1_500_000,\n  mau: 80_000,\n})\n\u002F\u002F Base Pro plan:     $25\n\u002F\u002F DB overage:        $0.50\n\u002F\u002F Storage overage:   $1.05\n\u002F\u002F Bandwidth overage: $4.50\n\u002F\u002F Edge Fn overage:   $0.00\n\u002F\u002F TOTAL:             $31.05\u002Fmo\n```\n\n## Resources\n\n- [Supabase Pricing](https:\u002F\u002Fsupabase.com\u002Fpricing) — plan comparison and calculator\n- [Compute Add-ons](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Fguides\u002Fplatform\u002Fcompute-add-ons) — instance sizing guide\n- [Spend Cap](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Fguides\u002Fplatform\u002Fspend-cap) — prevent unexpected overage charges\n- [Database Disk Usage](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Fguides\u002Fplatform\u002Fdatabase-size) — monitoring and management\n- [Connection Pooling (Supavisor)](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Fguides\u002Fdatabase\u002Fconnecting-to-postgres#connection-pooler) — reduce connection overhead\n- [Edge Functions Best Practices](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Fguides\u002Ffunctions\u002Fbest-practices) — cold start and performance tips\n- [supabase-js Reference](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Freference\u002Fjavascript\u002Fintroduction) — `createClient` and SDK patterns\n\n## Next Steps\n\nFor architecture patterns, see `supabase-reference-architecture`.\nFor performance tuning beyond cost, see `supabase-performance-tuning`.\n","# Supabase Cost Tuning\n\n## Overview\n\nReduce 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.\n\n## Prerequisites\n\n- Supabase project with Dashboard access (Settings > Billing)\n- `@supabase\u002Fsupabase-js` installed: `npm install @supabase\u002Fsupabase-js`\n- Service role key for admin operations (storage audit, cleanup scripts)\n- SQL editor access (Dashboard > SQL Editor or `psql` connection)\n\n## Pricing Reference\n\n| Resource | Free Tier | Pro ($25\u002Fmo) | Team ($599\u002Fmo) |\n|----------|-----------|--------------|----------------|\n| Database | 500 MB | 8 GB included, $0.125\u002FGB extra | 8 GB included |\n| Storage | 1 GB | 100 GB included, $0.021\u002FGB extra | 100 GB included |\n| Bandwidth | 5 GB | 250 GB included, $0.09\u002FGB extra | 250 GB included |\n| Edge Functions | 500K invocations | 2M invocations, $2\u002Fmillion extra | 2M invocations |\n| Realtime | 200 concurrent | 500 concurrent | 500 concurrent |\n| Auth MAU | 50,000 | 100,000 | 100,000 |\n\n**Compute add-ons** (Pro and above):\n\n| Instance | vCPUs | RAM | Price |\n|----------|-------|-----|-------|\n| Micro | 2 | 1 GB | Included with Pro |\n| Small | 2 | 2 GB | $25\u002Fmo |\n| Medium | 2 | 4 GB | $50\u002Fmo |\n| Large | 4 | 8 GB | $100\u002Fmo |\n| XL | 8 | 16 GB | $200\u002Fmo |\n| 2XL | 16 | 32 GB | $400\u002Fmo |\n\n**Decision framework:** Read replicas ($25\u002Fmo each) beat scaling up when reads dominate and you need geographic distribution. Connection pooling (Supavisor, free) reduces compute pressure from idle connections.\n\n## Instructions\n\n### Step 1: Audit Current Usage and Identify Cost Drivers\n\nRun these queries in the SQL Editor to understand where your database budget is going:\n\n```sql\n-- Total database size\nselect pg_size_pretty(pg_database_size(current_database())) as total_db_size;\n\n-- Database size by table (find the biggest offenders)\nselect\n  relname as table_name,\n  pg_size_pretty(pg_total_relation_size(relid)) as total_size,\n  pg_size_pretty(pg_relation_size(relid)) as table_size,\n  pg_size_pretty(pg_total_relation_size(relid) - pg_relation_size(relid)) as index_size,\n  n_live_tup as row_count\nfrom pg_stat_user_tables\norder by pg_total_relation_size(relid) desc\nlimit 20;\n\n-- Find unused indexes consuming space (zero scans since last stats reset)\nselect\n  schemaname || '.' || indexrelname as index_name,\n  pg_size_pretty(pg_relation_size(indexrelid)) as size,\n  idx_scan as scans_since_reset\nfrom pg_stat_user_indexes\nwhere idx_scan = 0\n  and schemaname = 'public'\norder by pg_relation_size(indexrelid) desc\nlimit 10;\n\n-- Check dead tuple bloat (high ratio means VACUUM is needed)\nselect\n  relname,\n  n_dead_tup,\n  n_live_tup,\n  round(n_dead_tup::numeric \u002F greatest(n_live_tup, 1) * 100, 1) as dead_pct\nfrom pg_stat_user_tables\nwhere n_dead_tup > 1000\norder by n_dead_tup desc;\n\n-- Connection count (high count may indicate pooling issues)\nselect count(*) as active_connections,\n  max_conn as max_allowed\nfrom pg_stat_activity,\n  (select setting::int as max_conn from pg_settings where name = 'max_connections') mc\ngroup by max_conn;\n```\n\nAudit storage usage programmatically:\n\n```typescript\nimport { createClient } from '@supabase\u002Fsupabase-js'\n\nconst supabaseAdmin = createClient(\n  process.env.SUPABASE_URL!,\n  process.env.SUPABASE_SERVICE_ROLE_KEY!\n)\n\n\u002F\u002F List storage usage per bucket\nconst { data: buckets } = await supabaseAdmin.storage.listBuckets()\n\nfor (const bucket of buckets ?? []) {\n  const { data: files } = await supabaseAdmin.storage\n    .from(bucket.name)\n    .list('', { limit: 1000 })\n\n  const totalSize = files?.reduce((sum, f) => sum + (f.metadata?.size || 0), 0) ?? 0\n  console.log(`${bucket.name}: ${(totalSize \u002F 1024 \u002F 1024).toFixed(1)} MB`)\n}\n```\n\nCheck your current spend: **Dashboard > Settings > Billing** shows usage against plan limits with a breakdown by resource category.\n\n### Step 2: Optimize Database, Storage, and Bandwidth\n\n**Database optimization — reclaim space and reduce bloat:**\n\n```sql\n-- Archive old data before deleting (preserve for compliance\u002Fanalytics)\ncreate table if not exists public.events_archive (like public.events including all);\n\ninsert into public.events_archive\nselect * from public.events\nwhere created_at \u003C now() - interval '6 months';\n\ndelete from public.events\nwhere created_at \u003C now() - interval '6 months';\n\n-- Run VACUUM ANALYZE to reclaim space and update query planner stats\nvacuum (verbose, analyze) public.events;\n\n-- Drop confirmed-unused indexes (verify idx_scan = 0 from Step 1)\n-- WARNING: always confirm the index is unused before dropping\ndrop index if exists idx_events_legacy_status;\n\n-- Remove soft-deleted records past retention period\ndelete from public.orders\nwhere deleted_at is not null\n  and deleted_at \u003C now() - interval '90 days';\n\nvacuum (analyze) public.orders;\n```\n\n**Storage optimization — compress before upload, clean orphans:**\n\n```typescript\n\u002F\u002F Compress images before upload (reduces storage + bandwidth)\nasync function uploadCompressed(\n  bucket: string,\n  path: string,\n  file: File\n): Promise\u003Cstring> {\n  \u002F\u002F Use client-side compression before uploading\n  const compressed = await compressImage(file, { maxWidth: 1920, quality: 0.8 })\n\n  const { data, error } = await supabaseAdmin.storage\n    .from(bucket)\n    .upload(path, compressed, {\n      contentType: file.type,\n      upsert: true,\n    })\n\n  if (error) throw error\n  return data.path\n}\n\n\u002F\u002F Clean orphaned files older than 30 days\nasync function cleanOrphanedUploads() {\n  const cutoff = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString()\n\n  const { data: orphans } = await supabaseAdmin\n    .from('storage.objects')\n    .select('name, created_at')\n    .eq('bucket_id', 'uploads')\n    .lt('created_at', cutoff)\n\n  if (orphans?.length) {\n    const paths = orphans.map(o => o.name)\n    \u002F\u002F Delete in batches of 100\n    for (let i = 0; i \u003C paths.length; i += 100) {\n      await supabaseAdmin.storage\n        .from('uploads')\n        .remove(paths.slice(i, i + 100))\n    }\n    console.log(`Cleaned ${orphans.length} orphaned files`)\n  }\n}\n```\n\n**Bandwidth reduction — select only what you need:**\n\n```typescript\n\u002F\u002F BAD: transfers entire row (wastes bandwidth)\nconst { data } = await supabase.from('products').select('*')\n\n\u002F\u002F GOOD: request only needed columns\nconst { data } = await supabase.from('products').select('id, name, price')\n\n\u002F\u002F Use count queries for totals (head: true = zero data transferred)\nconst { count } = await supabase\n  .from('orders')\n  .select('*', { count: 'exact', head: true })\n\n\u002F\u002F Paginate large result sets\nconst { data } = await supabase\n  .from('logs')\n  .select('id, message, created_at')\n  .order('created_at', { ascending: false })\n  .range(0, 49)  \u002F\u002F 50 rows per page\n```\n\n### Step 3: Right-Size Compute and Reduce Edge Function Costs\n\n**Connection pooling with Supavisor** (reduces need for compute upgrades):\n\n```typescript\n\u002F\u002F Use the pooler connection string instead of direct connection\n\u002F\u002F Dashboard > Settings > Database > Connection string > Mode: Transaction\n\n\u002F\u002F In your app, use the pooled connection URL (port 6543)\n\u002F\u002F Direct:   postgresql:\u002F\u002Fpostgres:pw@db.xxx.supabase.co:5432\u002Fpostgres\n\u002F\u002F Pooled:   postgresql:\u002F\u002Fpostgres:pw@db.xxx.supabase.co:6543\u002Fpostgres\n\n\u002F\u002F For @supabase\u002Fsupabase-js, connection pooling is handled automatically\n\u002F\u002F For direct pg connections (migrations, ORMs), use pooled URL:\nconst pool = new Pool({\n  connectionString: process.env.DATABASE_URL,  \u002F\u002F Use pooler URL\n  max: 10,  \u002F\u002F Limit client-side pool size too\n})\n```\n\n**Edge Function cold start reduction:**\n\n```typescript\n\u002F\u002F Minimize cold starts — keep imports lightweight\n\u002F\u002F BAD: importing heavy libraries unconditionally\nimport { parse } from 'some-huge-csv-library'\n\n\u002F\u002F GOOD: dynamic import only when needed\nDeno.serve(async (req) => {\n  const { action } = await req.json()\n\n  if (action === 'parse-csv') {\n    const { parse } = await import('some-huge-csv-library')\n    return new Response(JSON.stringify(parse(data)))\n  }\n\n  \u002F\u002F Fast path: no heavy import needed\n  return new Response(JSON.stringify({ status: 'ok' }))\n})\n\n\u002F\u002F Cache expensive computations across invocations\n\u002F\u002F Deno Deploy isolates persist for ~60 seconds between requests\nconst _cache = new Map\u003Cstring, { data: unknown; ts: number }>()\n\nfunction cached\u003CT>(key: string, ttlMs: number, fn: () => T): T {\n  const entry = _cache.get(key)\n  if (entry && Date.now() - entry.ts \u003C ttlMs) return entry.data as T\n  const data = fn()\n  _cache.set(key, { data, ts: Date.now() })\n  return data\n}\n```\n\n**Usage monitoring — track spend with a lightweight counter:**\n\n```sql\n-- Create usage tracking table\ncreate table public.api_usage (\n  id bigint generated always as identity primary key,\n  endpoint text not null,\n  method text not null,\n  user_id uuid references auth.users(id),\n  response_bytes int default 0,\n  created_at timestamptz default now()\n);\n\n-- Create partitioned index for efficient time-range queries\ncreate index idx_api_usage_created on public.api_usage (created_at desc);\n\n-- Materialized view for daily cost estimation\ncreate materialized view public.daily_usage_summary as\nselect\n  date_trunc('day', created_at) as day,\n  endpoint,\n  count(*) as requests,\n  sum(response_bytes) as total_bytes\nfrom public.api_usage\ngroup by 1, 2;\n\n-- Auto-refresh via pg_cron (enable extension first)\nselect cron.schedule(\n  'refresh-usage-summary',\n  '0 1 * * *',\n  'refresh materialized view concurrently public.daily_usage_summary;'\n);\n```\n\n## Output\n\nAfter completing all three steps, you will have:\n\n- Database size audit with table-level breakdown and dead tuple analysis\n- Unused indexes identified and dropped to reclaim storage\n- Old data archived and vacuumed to free database space\n- Storage orphans cleaned and upload compression implemented\n- Bandwidth reduced through column selection and pagination\n- Connection pooling configured to avoid unnecessary compute upgrades\n- Edge Function cold starts minimized with dynamic imports and caching\n- Usage monitoring table and daily summary view for spend visibility\n\n## Error Handling\n\n| Issue | Cause | Solution |\n|-------|-------|----------|\n| Database approaching 500 MB (Free) or 8 GB (Pro) | Data growth without archival | Archive old records, VACUUM, drop unused indexes |\n| Storage costs climbing monthly | Orphaned uploads accumulating | Schedule cleanup job for files not linked to records |\n| Unexpected bandwidth spike | `select('*')` on large tables | Use specific column lists; add `.range()` pagination |\n| Edge Function billing spike | Retry loops or heavy imports | Add circuit breaker with max 3 retries; dynamic imports |\n| Connection limit errors | Too many direct connections | Switch to pooler URL (port 6543); reduce client pool size |\n| Spend cap reached | Usage exceeded Pro included resources | Enable spend cap in Dashboard > Settings > Billing to prevent overage |\n| VACUUM not reclaiming space | Long-running transactions holding locks | Check `pg_stat_activity` for idle-in-transaction; terminate stale sessions |\n\n## Examples\n\n**Quick cost check for a growing project:**\n\n```typescript\nimport { createClient } from '@supabase\u002Fsupabase-js'\n\nconst supabase = createClient(\n  process.env.SUPABASE_URL!,\n  process.env.SUPABASE_SERVICE_ROLE_KEY!\n)\n\n\u002F\u002F Check database size against plan limit\nconst { data: dbSize } = await supabase.rpc('get_db_size')\n\u002F\u002F CREATE FUNCTION get_db_size() RETURNS text AS $$\n\u002F\u002F   SELECT pg_size_pretty(pg_database_size(current_database()));\n\u002F\u002F $$ LANGUAGE sql;\n\nconsole.log(`Database size: ${dbSize}`)\n\n\u002F\u002F Check if you're approaching storage limits\nconst { data: buckets } = await supabase.storage.listBuckets()\nconsole.log(`Storage buckets: ${buckets?.length ?? 0}`)\n```\n\n**Monthly cost estimation script:**\n\n```typescript\nfunction estimateMonthlyCost(usage: {\n  dbSizeGb: number\n  storageGb: number\n  bandwidthGb: number\n  edgeFnInvocations: number\n  mau: number\n}) {\n  const pro = {\n    base: 25,\n    dbOverage: Math.max(0, usage.dbSizeGb - 8) * 0.125,\n    storageOverage: Math.max(0, usage.storageGb - 100) * 0.021,\n    bandwidthOverage: Math.max(0, usage.bandwidthGb - 250) * 0.09,\n    edgeFnOverage: Math.max(0, usage.edgeFnInvocations - 2_000_000) \u002F 1_000_000 * 2,\n  }\n\n  const total = pro.base + pro.dbOverage + pro.storageOverage\n    + pro.bandwidthOverage + pro.edgeFnOverage\n\n  console.log('Estimated monthly cost breakdown:')\n  console.log(`  Base Pro plan:     $${pro.base}`)\n  console.log(`  DB overage:        $${pro.dbOverage.toFixed(2)}`)\n  console.log(`  Storage overage:   $${pro.storageOverage.toFixed(2)}`)\n  console.log(`  Bandwidth overage: $${pro.bandwidthOverage.toFixed(2)}`)\n  console.log(`  Edge Fn overage:   $${pro.edgeFnOverage.toFixed(2)}`)\n  console.log(`  TOTAL:             $${total.toFixed(2)}\u002Fmo`)\n\n  return total\n}\n\n\u002F\u002F Example: project with 12GB DB, 150GB storage, 300GB bandwidth\nestimateMonthlyCost({\n  dbSizeGb: 12,\n  storageGb: 150,\n  bandwidthGb: 300,\n  edgeFnInvocations: 1_500_000,\n  mau: 80_000,\n})\n\u002F\u002F Base Pro plan:     $25\n\u002F\u002F DB overage:        $0.50\n\u002F\u002F Storage overage:   $1.05\n\u002F\u002F Bandwidth overage: $4.50\n\u002F\u002F Edge Fn overage:   $0.00\n\u002F\u002F TOTAL:             $31.05\u002Fmo\n```\n\n## Resources\n\n- [Supabase Pricing](https:\u002F\u002Fsupabase.com\u002Fpricing) — plan comparison and calculator\n- [Compute Add-ons](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Fguides\u002Fplatform\u002Fcompute-add-ons) — instance sizing guide\n- [Spend Cap](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Fguides\u002Fplatform\u002Fspend-cap) — prevent unexpected overage charges\n- [Database Disk Usage](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Fguides\u002Fplatform\u002Fdatabase-size) — monitoring and management\n- [Connection Pooling (Supavisor)](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Fguides\u002Fdatabase\u002Fconnecting-to-postgres#connection-pooler) — reduce connection overhead\n- [Edge Functions Best Practices](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Fguides\u002Ffunctions\u002Fbest-practices) — cold start and performance tips\n- [supabase-js Reference](https:\u002F\u002Fsupabase.com\u002Fdocs\u002Freference\u002Fjavascript\u002Fintroduction) — `createClient` and SDK patterns\n\n## Next Steps\n\nFor architecture patterns, see `supabase-reference-architecture`.\nFor performance tuning beyond cost, see `supabase-performance-tuning`.\n",{"name":5,"tags":24,"author":28,"license":15,"version":29,"description":30,"allowed-tools":31,"compatible-with":32},[25,26,27],"saas","supabase","cost-optimization","Jeremy Longshore \u003Cjeremy@intentsolutions.io>","1.0.0","Optimize Supabase costs through plan selection, database tuning, storage cleanup,\nconnection pooling, and Edge Function optimization.\nUse when analyzing Supabase billing, reducing costs, right-sizing compute,\nor implementing usage tracking and budget alerts.\nTrigger with phrases like \"supabase cost\", \"supabase billing\",\n\"reduce supabase costs\", \"supabase pricing\", \"supabase expensive\", \"supabase budget\".\n","Read, Write, Edit, Grep, Bash(supabase:*)","claude-code, codex, openclaw","main","99825ad3f3bcc6597ddcc7294a14e6e922f2b67b","skills\u002Fsaas-packs--supabase-pack--supabase-cost-tuning",0,"https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills","https:\u002F\u002Fgithub.com\u002Fjukeyman","https:\u002F\u002FRJBUSINESSSOLUTIONS.ORG","Credit and Finance Expert | Developer\r\n\r\nI'm Rick Jefferson, a seasoned credit and finance expert with over a decade of experience in financial literacy,","2026-07-13 07:03:29",{"source":8,"skillName":5,"commands":43,"prompt":53,"zipAvailable":54},[44,47,50],{"tool":45,"command":46},"npx","npx skills add jukeyman\u002Fjukeyman-skills --skill supabase-cost-tuning",{"tool":48,"command":49},"bunx","bunx skills add jukeyman\u002Fjukeyman-skills --skill supabase-cost-tuning",{"tool":51,"command":52},"pnpm","pnpm dlx skills add jukeyman\u002Fjukeyman-skills --skill supabase-cost-tuning","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--supabase-pack--supabase-cost-tuning\u002FSKILL.md",true,[],[57,64,71,78,85,93],{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":19},"01M79ANS2SM329NEP5ZCX106RR","zustand-store-creator","Create zustand store creator operations. Auto-activating skill for Frontend Development.\nTriggers on: zustand store creator, zustand store creator\nPart of the Frontend Development skill category. Use when working with zustand store creator functionality. Trigger with phrases like \"zustand store creator\", \"zustand creator\", \"zustand\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzustand-store-creator\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M79AMZKP4YDEZ7EHG1Y7PP74","zero-trust-config-helper","Configure with zero trust config helper operations. Auto-activating skill for Security Advanced.\nTriggers on: zero trust config helper, zero trust config helper\nPart of the Security Advanced skill category. Use when configuring systems or services. Trigger with phrases like \"zero trust config helper\", \"zero helper\", \"zero\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-config-helper\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M79AMJSBCEJQNBTYNAHYN5HM","zapier-integration-helper","Assist with zapier integration helper operations. Auto-activating skill for Business Automation.\nTriggers on: zapier integration helper, zapier integration helper\nPart of the Business Automation skill category. Use when working with APIs or building integrations. Trigger with phrases like \"zapier integration helper\", \"zapier helper\", \"zapier\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzapier-integration-helper\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M79AHJZGVMARS13VFQYRR1MP","yaml-config-validator","Validate yaml config validator operations. Auto-activating skill for DevOps Basics.\nTriggers on: yaml config validator, yaml config validator\nPart of the DevOps Basics skill category. Use when configuring systems or services. Trigger with phrases like \"yaml config validator\", \"yaml validator\", \"yaml\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fyaml-config-validator\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":89,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M79AHGDZRN0020RDQSQDPAM8","xvary-stock-research","Thesis-driven equity analysis from public SEC EDGAR and market data; \u002Fanalyze, \u002Fscore, \u002Fcompare workflows with bundled Python tools (Claude Code, Cursor, Codex).","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":19},"01M79AHCYJ9FV9RMHQ24HDRN33","xss-vulnerability-scanner","Scan xss vulnerability scanner operations. Auto-activating skill for Security Fundamentals.\nTriggers on: xss vulnerability scanner, xss vulnerability scanner\nPart of the Security Fundamentals skill category. Use when working with xss vulnerability scanner functionality. Trigger with phrases like \"xss vulnerability scanner\", \"xss scanner\", \"xss\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxss-vulnerability-scanner\u002FSKILL.md",[],[]]