VE

vercel-reliability-patterns

Implements reliability patterns like circuit breakers and retry logic for Vercel serverless functions.

Install

mkdir -p .claude/skills/vercel-reliability-patterns && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/6000" && unzip -o skill.zip -d .claude/skills/vercel-reliability-patterns && rm skill.zip

Installs to .claude/skills/vercel-reliability-patterns

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Implement reliability patterns for Vercel deployments including circuit
71 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Implement circuit breakers for external dependencies.
  • Serve stale data using graceful degradation.
  • Prevent duplicate mutations with idempotency keys.
  • Automate health checks and instant rollbacks.

How it works

The skill provides code examples for implementing reliability patterns like circuit breakers, retry with exponential backoff, graceful degradation using stale cache, and idempotency keys. It also includes a script for deployment-level resilience with instant rollback based on health checks.

Inputs & outputs

You give it
Vercel serverless function code or deployment configuration
You get back
Code patterns for circuit breakers, retry logic, graceful degradation, idempotency, and a deployment rollback script

When to use vercel-reliability-patterns

  • Protecting external API calls with circuit breakers
  • Implementing service retry logic
  • Adding graceful degradation to serverless functions

About this skill

Vercel Reliability Patterns

Overview

Build fault-tolerant Vercel deployments with circuit breakers, retry logic, graceful degradation, and instant rollback integration. Addresses reliability at two levels: function-level resilience (protecting against dependency failures) and deployment-level resilience (protecting against bad deploys).

Prerequisites

  • Vercel project deployed to production
  • Understanding of failure modes in serverless
  • External dependencies (databases, APIs) identified

Instructions

Step 1: Circuit Breaker for External Dependencies

// lib/circuit-breaker.ts
type CircuitState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';

class CircuitBreaker {
  private state: CircuitState = 'CLOSED';
  private failures = 0;
  private lastFailure = 0;
  private readonly threshold: number;
  private readonly resetTimeMs: number;

  constructor(threshold = 5, resetTimeMs = 30000) {
    this.threshold = threshold;
    this.resetTimeMs = resetTimeMs;
  }

  async call<T>(fn: () => Promise<T>, fallback: () => T): Promise<T> {
    if (this.state === 'OPEN') {
      if (Date.now() - this.lastFailure > this.resetTimeMs) {
        this.state = 'HALF_OPEN';
      } else {
        console.warn('Circuit OPEN — returning fallback');
        return fallback();
      }
    }

    try {
      const result = await fn();
      this.onSuccess();
      return result;
    } catch (error) {
      this.onFailure();
      console.error('Circuit breaker caught error:', error);
      return fallback();
    }
  }

  private onSuccess(): void {
    this.failures = 0;
    this.state = 'CLOSED';
  }

  private onFailure(): void {
    this.failures++;
    this.lastFailure = Date.now();
    if (this.failures >= this.threshold) {
      this.state = 'OPEN';
      console.warn(`Circuit OPENED after ${this.failures} failures`);
    }
  }
}

// Usage in a serverless function:
const dbCircuit = new CircuitBreaker(3, 30000);

export default async function handler(req, res) {
  const users = await dbCircuit.call(
    () => db.user.findMany({ take: 10 }),
    () => [] // Fallback: empty array when DB is down
  );
  res.json({ users, degraded: users.length === 0 });
}

Important for serverless: Circuit breaker state lives in a single function instance. Different instances have independent circuits. For global circuit state, use Vercel KV or Edge Config.

Step 2: Retry with Exponential Backoff

// lib/retry.ts
interface RetryOptions {
  maxRetries?: number;
  baseDelayMs?: number;
  maxDelayMs?: number;
  retryOn?: (error: unknown) => boolean;
}

async function withRetry<T>(
  fn: () => Promise<T>,
  options: RetryOptions = {}
): Promise<T> {
  const { maxRetries = 3, baseDelayMs = 200, maxDelayMs = 5000, retryOn } = options;

  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error) {
      if (attempt === maxRetries) throw error;
      if (retryOn && !retryOn(error)) throw error;

      const delay = Math.min(
        baseDelayMs * Math.pow(2, attempt) + Math.random() * 200,
        maxDelayMs
      );
      await new Promise(r => setTimeout(r, delay));
    }
  }
  throw new Error('Unreachable');
}

// Usage:
const data = await withRetry(
  () => fetch('https://api.example.com/data').then(r => {
    if (!r.ok) throw new Error(`HTTP ${r.status}`);
    return r.json();
  }),
  {
    maxRetries: 3,
    retryOn: (err) => {
      // Only retry on network errors and 5xx, not 4xx
      if (err instanceof TypeError) return true; // network error
      return err.message?.includes('5');
    },
  }
);

Step 3: Graceful Degradation with Stale Cache

// api/products.ts — serve stale data when primary source is down
import { get, set } from '@vercel/kv';

export default async function handler(req, res) {
  const cacheKey = 'products:latest';

  try {
    // Try primary data source
    const freshData = await fetchProductsFromDB();

    // Update cache with fresh data
    await set(cacheKey, JSON.stringify(freshData), { ex: 3600 });

    res.setHeader('x-data-source', 'live');
    res.json(freshData);
  } catch (error) {
    // Primary failed — serve stale cache
    const cachedData = await get(cacheKey);

    if (cachedData) {
      console.warn('Serving stale cache — primary source unavailable');
      res.setHeader('x-data-source', 'cache-stale');
      res.json(JSON.parse(cachedData as string));
    } else {
      // No cache available — return degraded response
      res.setHeader('x-data-source', 'degraded');
      res.status(503).json({
        error: 'Service temporarily unavailable',
        degraded: true,
      });
    }
  }
}

Step 4: Idempotency Keys for Mutations

// api/orders/route.ts — idempotent order creation
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';

export async function POST(request: NextRequest) {
  const idempotencyKey = request.headers.get('idempotency-key');
  if (!idempotencyKey) {
    return NextResponse.json(
      { error: 'idempotency-key header required' },
      { status: 400 }
    );
  }

  // Check if this request was already processed
  const existing = await db.idempotencyRecord.findUnique({
    where: { key: idempotencyKey },
  });

  if (existing) {
    // Return the cached response — same status and body
    return NextResponse.json(JSON.parse(existing.responseBody), {
      status: existing.responseStatus,
      headers: { 'x-idempotent-replay': 'true' },
    });
  }

  // Process the order
  const body = await request.json();
  const order = await db.order.create({ data: body });

  // Cache the response for idempotency
  const responseBody = JSON.stringify({ order });
  await db.idempotencyRecord.create({
    data: { key: idempotencyKey, responseStatus: 201, responseBody },
  });

  return NextResponse.json({ order }, { status: 201 });
}

Step 5: Health Check with Dependency Status

// api/health/route.ts
export const dynamic = 'force-dynamic';

interface HealthCheck {
  name: string;
  check: () => Promise<boolean>;
}

const checks: HealthCheck[] = [
  {
    name: 'database',
    check: async () => {
      await db.$queryRaw`SELECT 1`;
      return true;
    },
  },
  {
    name: 'cache',
    check: async () => {
      await kv.ping();
      return true;
    },
  },
  {
    name: 'external-api',
    check: async () => {
      const r = await fetch('https://api.example.com/health', { signal: AbortSignal.timeout(3000) });
      return r.ok;
    },
  },
];

export async function GET() {
  const results: Record<string, 'ok' | 'error'> = {};

  await Promise.all(
    checks.map(async ({ name, check }) => {
      try {
        await check();
        results[name] = 'ok';
      } catch {
        results[name] = 'error';
      }
    })
  );

  const healthy = Object.values(results).every(v => v === 'ok');
  return Response.json(
    { status: healthy ? 'healthy' : 'degraded', checks: results },
    { status: healthy ? 200 : 503 }
  );
}

Step 6: Deployment-Level Resilience

# Instant rollback on health check failure (CI integration)
DEPLOY_URL=$(vercel --prod)
HEALTH=$(curl -s -o /dev/null -w "%{http_code}" "$DEPLOY_URL/api/health")

if [ "$HEALTH" != "200" ]; then
  echo "Health check failed ($HEALTH) — rolling back"
  vercel rollback
  exit 1
fi
echo "Deployment healthy"

Reliability Patterns Summary

PatternProtects AgainstVercel Implementation
Circuit breakerDependency degradationIn-function state or Edge Config
Retry + backoffTransient failureswithRetry wrapper
Stale cachePrimary source outageVercel KV with TTL
IdempotencyDuplicate mutationsDatabase record per request
Health checksBad deployments/api/health + rollback automation
Instant rollbackDeployment regressionvercel rollback in CI

Output

  • Circuit breaker protecting all external dependency calls
  • Retry logic with exponential backoff for transient failures
  • Graceful degradation serving stale data when primary fails
  • Idempotency preventing duplicate mutations
  • Automated health check + rollback pipeline

Error Handling

ErrorCauseSolution
Circuit opens too aggressivelyThreshold too lowIncrease failure threshold (e.g., 5 → 10)
Retry causes duplicate side effectsNo idempotencyAdd idempotency-key to mutation endpoints
Stale cache expiredTTL too short or never populatedIncrease TTL, seed cache on deploy
Health check false positiveTimeout too shortIncrease AbortSignal timeout to 5s
Rollback reverts good deploymentFlaky health checkAdd retry to health check before rollback

Resources

Next Steps

For policy guardrails, see vercel-policy-guardrails.

When not to use it

  • When global circuit state is required without Vercel KV or Edge Config.
  • When retry logic causes unintended duplicate side effects without idempotency.

Prerequisites

Vercel project deployed to productionUnderstanding of failure modes in serverlessExternal dependencies (databases, APIs) identified

Limitations

  • Circuit breaker state is per function instance without Vercel KV or Edge Config.
  • Retry logic can cause duplicate side effects if idempotency is not implemented.

How it compares

This skill provides specific Vercel-focused code patterns and a deployment rollback script, unlike generic reliability pattern descriptions.

Compared to similar skills

vercel-reliability-patterns side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
vercel-reliability-patterns (this skill)127dReviewIntermediate
caching-strategies05moReviewAdvanced
nextjs-developer3282moNo flagsAdvanced
payload732moReviewIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

caching-strategies

zhongyuhangcn

Dual-layer caching strategies for the Flare Stack Blog. Use when implementing CDN cache headers, KV caching with versioned invalidation, or debugging cache-related issues.

00

nextjs-developer

zenobi-us

Expert Next.js developer mastering Next.js 14+ with App Router and full-stack features. Specializes in server components, server actions, performance optimization, and production deployment with focus on building fast, SEO-friendly applications.

328531

payload

payloadcms

Use when working with Payload CMS projects (payload.config.ts, collections, fields, hooks, access control, Payload API). Use when debugging validation errors, security issues, relationship queries, transactions, or hook behavior.

73206

reviewing-nextjs-16-patterns

djankies

Review code for Next.js 16 compliance - security patterns, caching, breaking changes. Use when reviewing Next.js code, preparing for migration, or auditing for violations.

11106

backend-dev-guidelines

langfuse

Comprehensive backend development guide for Langfuse's Next.js 14/tRPC/Express/TypeScript monorepo. Use when creating tRPC routers, public API endpoints, BullMQ queue processors, services, or working with tRPC procedures, Next.js API routes, Prisma database access, ClickHouse analytics queries, Redis queues, OpenTelemetry instrumentation, Zod v4 validation, env.mjs configuration, tenant isolation patterns, or async patterns. Covers layered architecture (tRPC procedures → services, queue processors → services), dual database system (PostgreSQL + ClickHouse), projectId filtering for multi-tenant isolation, traceException error handling, observability patterns, and testing strategies (Jest for web, vitest for worker).

10100

frontend-developer

sickn33

Build React components, implement responsive layouts, and handle client-side state management. Masters React 19, Next.js 15, and modern frontend architecture. Optimizes performance and ensures accessibility. Use PROACTIVELY when creating UI components or fixing frontend issues.

2782

Search skills

Search the agent skills registry