vercel-reliability-patterns

0
0
Source

Implement Vercel reliability patterns including circuit breakers, idempotency, and graceful degradation. Use when building fault-tolerant Vercel integrations, implementing retry strategies, or adding resilience to production Vercel services. Trigger with phrases like "vercel reliability", "vercel circuit breaker", "vercel idempotent", "vercel resilience", "vercel fallback", "vercel bulkhead".

Install

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

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

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.

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

6814

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

2412

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

379

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

978

performing-security-audits

jeremylongshore

This skill allows Claude to conduct comprehensive security audits of code, infrastructure, and configurations. It leverages various tools within the security-pro-pack plugin, including vulnerability scanning, compliance checking, cryptography review, and infrastructure security analysis. Use this skill when a user requests a "security audit," "vulnerability assessment," "compliance review," or any task involving identifying and mitigating security risks. It helps to ensure code and systems adhere to security best practices and compliance standards.

86

django-view-generator

jeremylongshore

Generate django view generator operations. Auto-activating skill for Backend Development. Triggers on: django view generator, django view generator Part of the Backend Development skill category. Use when working with django view generator functionality. Trigger with phrases like "django view generator", "django generator", "django".

15

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

643969

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

591705

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318398

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

339397

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

451339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.