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

vercel-cost-tuning — скилл для Claude Code

Скилл vercel-cost-tuning для Claude Code разбирает счета Vercel и показывает, где возникают лишние расходы. Помогает урезать траты на функции, трафик и middleware.

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

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

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

Скилл работает по модели Fluid Compute: смотрит, сколько CPU и памяти реально съедают функции, и ищет места, где платишь за простой. Умеет считать bandwidth, вызовы Edge Functions, оптимизации изображений и минуты сборки.

Внутри — пошаговая инструкция: сначала снять текущее использование через API curl -s -H "Authorization: Bearer $VERCEL_TOKEN" "https://api.vercel.com/v2/usage" | jq ., потом править vercel.json и код функций. Например, уменьшить память лёгким endpoint'ам до 128 МБ или перевести read-only эндпоинты на Edge Functions.

Для работы нужен доступ к биллинг-панели Vercel и токен для API. Скилл также настраивает spend management: лимит бюджета, жёсткую остановку проектов и письма при 50%, 75%, 90%, 100% расхода. Из-за того, что middleware выполняется на каждый запрос, его область советуют сужать через matcher.

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

  • Найти, какие ресурсы Vercel съедают больше всего денег
  • Снизить время выполнения serverless-функций
  • Убрать лишние вызовы функций через кэширование на edge
  • Настроить бюджет и алерты в spend management
  • Сузить matcher middleware, чтобы он не гонялся на каждый запрос

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

  • Посмотри, на что уходит бюджет в Vercel, и покажи топ затрат
  • Переведи простые read-only эндпоинты на Edge Functions
  • Добавь кэш-заголовки s-maxage в ответы API

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

1Через Skills CLI (Vercel)

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

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

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

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

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

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

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

Выполни npx skills add jeremylongshore/tons-of-skills-marketplace --skill vercel-cost-tuning -a claude-code, затем проверь файл ~/.claude/skills/vercel-cost-tuning/SKILL.md.

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

Разбирает модель ценообразования Vercel Fluid Compute и ищет, где можно платить меньше: память функций, кэширование, middleware, изображения, сборки.

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

Доступ к биллинг-панели Vercel и токен для API. Ещё пригодится понимание текущей архитектуры деплоя и доступ к Vercel Analytics.

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

SKILL.md · MIT
---
name: vercel-cost-tuning
description: 'Optimize Vercel costs through plan selection, function efficiency, and
  usage monitoring.

  Use when analyzing Vercel billing, reducing function execution costs,

  or implementing spend management and budget alerts.

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

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

  '
allowed-tools: Read, Write, Edit, Bash(vercel:*), Bash(curl:*), Grep
version: 1.18.0
license: MIT
author: Jeremy Longshore <[email protected]>
tags:
- saas
- vercel
- cost-optimization
- billing
- monitoring
compatibility: Designed for Claude Code
---
# Vercel Cost Tuning

## Overview

Optimize Vercel costs by understanding the Fluid Compute pricing model, reducing function execution time, leveraging edge caching to avoid function invocations, and configuring spend management. Covers plan comparison, cost drivers, and monitoring.

## Prerequisites

- Access to Vercel billing dashboard
- Understanding of current deployment architecture
- Access to Vercel Analytics for usage patterns

## Instructions

### Step 1: Understand the Pricing Model

Vercel uses **Fluid Compute** pricing (for new projects):

| Resource | Hobby (Free) | Pro ($20/member/mo) | Enterprise |
|----------|-------------|---------------------|------------|
| Bandwidth | 100 GB | 1 TB included | Custom |
| Serverless Execution | 100 GB-hrs | 1000 GB-hrs included | Custom |
| Edge Function invocations | 500K | 1M included | Custom |
| Edge Middleware invocations | 1M | 1M included | Custom |
| Image Optimizations | 1000 | 5000 included | Custom |
| Builds per day | 6000 | 6000 | Custom |
| Concurrent builds | 1 | 1 (more available) | Custom |

**Fluid Compute billing breakdown:**

- **Active CPU time**: charged per ms of actual CPU usage
- **Provisioned memory**: charged per GB-second of allocated memory
- Benefit: you pay for actual work, not idle waiting (e.g., waiting for a database response)

### Step 2: Identify Cost Drivers

```bash
# Check usage via API
curl -s -H "Authorization: Bearer $VERCEL_TOKEN" \
  "https://api.vercel.com/v2/usage" | jq .

# Top cost drivers on Vercel:
# 1. Serverless function execution time (CPU + memory)
# 2. Bandwidth (large responses, unoptimized images)
# 3. Edge Middleware invocations (runs on EVERY request)
# 4. Image optimizations (each unique transform costs)
# 5. Build minutes (frequent deploys or slow builds)
```

### Step 3: Reduce Function Execution Costs

```typescript
// 1. Right-size function memory — don't over-allocate
// vercel.json
{
  "functions": {
    "api/lightweight.ts": { "memory": 128 },    // Simple JSON responses
    "api/standard.ts": { "memory": 512 },       // Database queries
    "api/heavy.ts": { "memory": 1024 }          // Image processing
  }
}

// 2. Move read-only endpoints to Edge Functions (cheaper, no cold starts)
// api/config.ts
export const config = { runtime: 'edge' };
export default function handler() {
  return Response.json({ features: ['a', 'b'] });
}

// 3. Cache function responses at the edge
// Eliminates function invocations entirely for cached routes
export default function handler(req, res) {
  res.setHeader('Cache-Control', 's-maxage=3600, stale-while-revalidate=86400');
  res.json(data);
}
```

### Step 4: Reduce Bandwidth Costs

```json
// vercel.json — compress and cache aggressively
{
  "headers": [
    {
      "source": "/static/(.*)",
      "headers": [
        { "key": "Cache-Control", "value": "public, max-age=31536000, immutable" }
      ]
    }
  ],
  "images": {
    "sizes": [640, 750, 1080],
    "formats": ["image/avif", "image/webp"],
    "minimumCacheTTL": 86400
  }
}
```

Key bandwidth reducers:

- Use Vercel's image optimization (auto WebP/AVIF conversion)
- Set aggressive cache headers on static assets
- Use ISR to serve static HTML instead of SSR
- Compress API responses (Vercel auto-compresses with Brotli)

### Step 5: Optimize Middleware Costs

Middleware runs on **every matched request**. Minimize its scope:

```typescript
// middleware.ts — scope to specific paths only
export const config = {
  matcher: [
    // Only run middleware on API routes and protected pages
    '/api/:path*',
    '/dashboard/:path*',
    // Skip static files, images, and public assets
    '/((?!_next/static|_next/image|favicon.ico|public).*)',
  ],
};

export function middleware(request) {
  // Keep logic minimal — this runs on every matched request
  // Avoid: database queries, external API calls, heavy computation
  // Good: cookie checks, header modifications, redirects
}
```

### Step 6: Configure Spend Management

In the Vercel dashboard under **Settings > Billing > Spend Management**:

```
Default budget: $200/month on-demand usage
Options:
- Set custom budget limit
- Enable hard limit (pauses all projects when reached)
- Configure email alerts at 50%, 75%, 90%, 100%
```

```bash
# Check current usage against budget via API
curl -s -H "Authorization: Bearer $VERCEL_TOKEN" \
  "https://api.vercel.com/v2/usage?teamId=team_xxx" \
  | jq '{period: .period, bandwidth: .bandwidth, execution: .serverlessFunctionExecution}'
```

## Cost Optimization Checklist

| Action | Impact | Effort |
|--------|--------|--------|
| Add `s-maxage` cache headers | High — eliminates function invocations | Low |
| Use Edge Functions for simple endpoints | Medium — cheaper than serverless | Low |
| Right-size function memory | Medium — reduces GB-hr cost | Low |
| Scope middleware matcher | Medium — reduces edge invocations | Low |
| Enable image optimization | Medium — reduces bandwidth | Low |
| Use ISR instead of SSR | High — serves cached HTML | Medium |
| Optimize build speed | Low — reduces build minutes | Medium |
| Set spend management alerts | Safety — prevents surprise bills | Low |

## Output

- Function memory right-sized per endpoint
- Edge caching reducing function invocations
- Middleware scoped to minimize invocations
- Spend management configured with budget alerts
- Usage monitoring via API

## Error Handling

| Error | Cause | Solution |
|-------|-------|----------|
| Unexpected bill spike | Uncached high-traffic endpoint | Add `s-maxage` to the response |
| Projects paused | Hard spending limit reached | Increase limit or optimize usage |
| Image optimization quota exceeded | Too many unique image transforms | Reduce `sizes` array, increase cache TTL |
| Build minutes exceeded | Slow builds or too many deploys | Use `ignoreCommand` to skip non-code changes |

## Examples

### Reduce an invocation spike with a measurable rollback

For a high-traffic read endpoint, add a conservative `s-maxage` response policy in a preview deployment and compare invocation count, cache hit rate, and response correctness against the prior release using synthetic requests. Set spend alerts before rollout and avoid a hard account-wide pause unless the owner accepts its blast radius. If personalized content is accidentally cached, immediately roll back the header change, purge only the affected deployment cache where supported, and document the regression.

## Resources

- [Vercel Pricing](https://vercel.com/pricing)
- [Fluid Compute Pricing](https://vercel.com/docs/functions/usage-and-pricing)
- [Spend Management](https://vercel.com/docs/pricing#spend-management)
- [Limits](https://vercel.com/docs/limits)
- [Usage API](https://vercel.com/docs/rest-api)

## Next Steps

For reference architecture, see `vercel-reference-architecture`.

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

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

Все скиллы по теме «DevOps и инфраструктура» →
aws-billing-and-cost-management aws Скилл aws-billing-and-cost-management анализирует расходы в AWS, ищет резервы экономии и настраивает бюджеты. Помогает проверить аномалии цен, оценить Savings Plans и снизить затраты на инфраструктуру. CX Codex +1 10 300установок vercel-teams-billing bobmatnyc Скилл vercel-teams-billing для Claude Code помогает управлять аккаунтами, командами и тарифами Vercel. Контролирует лимиты расходов и права доступа участников. CX Codex +1 328установок cost-audit runpod Скилл cost-audit разбирает расходы аккаунта Runpod по ресурсам и находит причины списаний за простаивающие Pod или serverless-воркеры. Он пригодится, когда нужно понять, за что начисляется плата. CX Codex +1 3 700установок AWS Billing and Cost Management awslabs MCP-сервер, через который агент читает данные AWS Billing and Cost Management: расходы, бюджеты, аномалии, обязательства по скидкам и счета. CX Codex +1 ★ 9 939звёзд репо vercel-functions-runtime bobmatnyc Скилл vercel-functions-runtime обучает ИИ-агента настраивать serverless-функции, middleware и cron-задачи на Vercel. Пригодится при сборке бэкенд-эндпоинтов и Edge Runtime. CX Codex +1 346установок vercel-schedules vercel Помогает настроить запуск функций по расписанию в Vercel Schedules. Включается при добавлении cron-задач, фоновых процессов и разовых напоминаний. CX Codex +1 183установок

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

Весь набор →
email-parser Скилл помогает настраивать операции разбора email, готовить конфигурации и проверять результат. Он активируется по запросу про email parser. CX Codex +1 1установок granola-webhooks-events Скилл granola-webhooks-events для создания автоматизаций на основе событий из Granola через Zapier. Помогает обрабатывать уведомления о встречах в реальном времени и строить пользовательские интеграции. CX Codex +1 1установок 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установок 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установок

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

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