SU

supabase-reliability-patterns

Adds resilience to Supabase apps via circuit breakers, retry logic, offline queues, and graceful degradation.

Install

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

Installs to .claude/skills/supabase-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.

Build resilient Supabase integrations: circuit breakers wrapping createClient
77 charsno explicit “when” trigger
Advanced

Key capabilities

  • →Implement circuit breakers for Supabase services
  • →Queue offline writes using IndexedDB
  • →Serve cached data during outages for graceful degradation
  • →Add exponential backoff and jitter to retries
  • →Perform dual-writes to a secondary data store

How it works

The skill provides code patterns for circuit breakers to stop calls when Supabase is down, an offline queue to buffer writes, and retry logic with exponential backoff for transient errors. It also includes graceful degradation with cached fallbacks and dual-write patterns.

Inputs & outputs

You give it
Supabase client calls and application data
You get back
Resilient application behavior during Supabase outages or network issues

When to use supabase-reliability-patterns

  • →Implementing circuit breakers for Supabase clients
  • →Building offline-first data synchronization
  • →Adding retry logic for SDK calls
  • →Setting up dual-write patterns for data backup
  • →Creating health check endpoints

About this skill

Supabase Reliability Patterns

Overview

Use bounded retries for explicitly idempotent reads, and a circuit breaker that recognizes Supabase database queries' returned { data, error } failures. Do not retry arbitrary writes, Auth failures, or RLS denials. Browser/session clients must not be shared across unrelated server requests; use request-scoped SSR clients.

Prerequisites

  • A configured client scoped to the authenticated request or a stateless public read
  • Reviewed idempotency and retry budgets for each operation
  • Explicit UI treatment of unavailable/stale data; an outage is not an empty dataset

Instructions

Step 1: Bound Read Retries

This helper retries only returned error codes in the explicit transient-read set. PGRST301 is an invalid/undecodable JWT, not a connection failure. Auth, RLS, schema, and validation errors are not retried. A thrown transport exception propagates to the caller; deciding whether it is safe to retry requires an operation-specific policy. maxRetries means additional attempts after the first, capped here at five.

export type QueryResult<T> = {
  data: T | null;
  error: { code?: string; message?: string } | null;
};
export type RetryOptions = { maxRetries: number; baseDelayMs: number; maxDelayMs: number };
const TRANSIENT_READ_CODES = new Set(['08006', '53300', 'PGRST001', 'PGRST002', 'PGRST003']);

export async function withReadRetry<T>(
  fn: () => Promise<QueryResult<T>>,
  opts: RetryOptions = { maxRetries: 3, baseDelayMs: 200, maxDelayMs: 5000 },
  sleep: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
  random: () => number = Math.random,
): Promise<QueryResult<T>> {
  if (
    !Number.isInteger(opts.maxRetries) ||
    opts.maxRetries < 0 ||
    opts.maxRetries > 5 ||
    !Number.isFinite(opts.baseDelayMs) ||
    opts.baseDelayMs < 0 ||
    !Number.isFinite(opts.maxDelayMs) ||
    opts.maxDelayMs < opts.baseDelayMs
  ) {
    throw new Error('Invalid retry budget');
  }
  for (let attempt = 0; ; attempt++) {
    const result = await fn();
    if (
      !result.error ||
      !TRANSIENT_READ_CODES.has(result.error.code ?? '') ||
      attempt >= opts.maxRetries
    )
      return result;
    const jitter = random();
    if (!Number.isFinite(jitter) || jitter < 0 || jitter > 1) throw new Error('Invalid jitter');
    await sleep(Math.min(opts.maxDelayMs, opts.baseDelayMs * 2 ** attempt) * jitter);
  }
}

A deadline/abort policy is still required for each query and the whole request; finite attempts do not bound a stalled network call. The injectable sleep/random functions permit local deterministic tests without waiting or provider requests.

Step 2: Count Returned Errors in a Circuit Breaker

This single-process illustrative circuit throws a generic error for failed database results, so a returned SDK error cannot be counted as success. Only exhausted transient failures open it; nonretryable Auth/RLS failures propagate without being presented as an outage. One half-open probe runs at a time. This is not a distributed admission controller or a substitute for request cancellation. Generation and probe ownership fence older in-flight completions from changing a newer circuit state or releasing its half-open probe.

export class ReadCircuit {
  private failures = 0;
  private openedAt: number | null = null;
  private generation = 0;
  private probe: object | null = null;
  constructor(
    private threshold = 3,
    private resetMs = 30_000,
    private now: () => number = Date.now,
  ) {
    if (!Number.isInteger(threshold) || threshold < 1 || !Number.isFinite(resetMs) || resetMs < 0) {
      throw new Error('Invalid circuit budget');
    }
  }
  async call<T>(fn: () => Promise<QueryResult<T>>): Promise<T | null> {
    const generation = this.generation;
    const wasOpen = this.openedAt !== null;
    let ownedProbe: object | null = null;
    if (wasOpen) {
      if (this.now() - this.openedAt! < this.resetMs || this.probe !== null) {
        throw new Error('Circuit open');
      }
      ownedProbe = {};
      this.probe = ownedProbe;
    }
    const ownsState = () =>
      this.generation === generation && (!wasOpen || this.probe === ownedProbe);
    try {
      const result = await fn();
      if (result.error) {
        if (ownsState()) {
          if (TRANSIENT_READ_CODES.has(result.error.code ?? '')) {
            this.failures++;
            if (wasOpen || this.failures >= this.threshold) {
              this.openedAt = this.now();
              this.generation++;
            }
          } else if (wasOpen) {
            // Service responded, but this operation was denied/invalid.
            this.openedAt = null;
            this.failures = 0;
            this.generation++;
          }
        }
        throw new Error('Database read failed');
      }
      if (ownsState()) {
        this.failures = 0;
        this.openedAt = null;
        if (wasOpen) this.generation++;
      }
      return result.data;
    } catch (error) {
      if (wasOpen && ownsState() && this.openedAt !== null) {
        this.openedAt = this.now();
        this.generation++;
      }
      throw error;
    } finally {
      // A stale closed request cannot release another request's half-open probe.
      if (ownedProbe !== null && this.probe === ownedProbe) this.probe = null;
    }
  }
}

Thrown transport exceptions propagate; this example deliberately does not classify every exception as a transient outage. A failed half-open transport probe leaves the circuit open, and the next caller must still respect the reset budget.

Step 3: Compose Only an Authorized Read

import type { SupabaseClient } from '@supabase/supabase-js';
// Import the helpers above from your application's reliability module.

export async function listOwnTodos(client: SupabaseClient, circuit: ReadCircuit) {
  const {
    data: { user },
    error,
  } = await client.auth.getUser();
  if (error || !user) throw new Error('Verified user required');
  return circuit.call(() =>
    withReadRetry(
      async () =>
        await client
          .from('todos')
          .select('id, title, is_complete')
          .eq('user_id', user.id)
          .order('id')
          .limit(100),
    ),
  );
}

The existing table needs matching RLS. Do not share cached results across identities. Do not wrap .insert() in this read-retry helper: a timeout can follow a committed write. A write queue needs durable operation IDs, authorization on replay, bounded retention, reconciliation and application-owned idempotency before retries.

Output

  • Explicit attempt limits and nonretryable errors returned on the first failure
  • Returned SDK failures counted by the read circuit rather than mistaken for success
  • Unavailable data distinguished from a genuinely empty successful result
  • Separate reviewed write-replay, cache, deadline, and recovery policies

Error Handling

FailureDisposition
PGRST301 / auth / RLSCorrect identity/policy; no blind retry
Exhausted transient readSurface unavailable; circuit may open
Circuit openNo provider query; return an explicit unavailable state
Write timeoutReconcile operation ID before deciding whether to repeat
Stale cacheLabel age/scope; never pretend it is a fresh successful read

Examples

Test first-attempt success, zero retries, nonretryable first failure, exact exhaustion, transient recovery, thrown exceptions, returned-error opening, and half-open recovery with injected clock/sleep. Test cross-user isolation separately.

Additional patterns in offline recovery guidance need their own durability and replay review; illustrative dual writes alone cannot guarantee that critical data survives an outage or that effects happen exactly once.

Resources

Next Steps

Document operation-specific deadlines, recovery ownership, and safe write semantics before applying retries to additional surfaces.

Prerequisites

@supabase/supabase-js v2+ installedTypeScript project with Supabase client configuredBrowser environment with IndexedDB or server with Redis for offline queueSecondary data store (Redis, DynamoDB, or local SQLite) for dual-write

Limitations

  • →Circuit stays OPEN indefinitely during extended Supabase outages
  • →Offline queue can grow unbounded if not capped
  • →Preview branch creation fails if not on Pro plan

How it compares

This skill integrates specific reliability patterns directly into Supabase client interactions, offering automated fault tolerance beyond standard error handling.

Compared to similar skills

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

SkillInstallsUpdatedSafetyDifficulty
supabase-reliability-patterns (this skill)34moCautionAdvanced
flutter-development1,5558moNo flagsIntermediate
godot1,0448moReviewIntermediate
fastapi-templates5206moNo flagsIntermediate

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

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.

1,5551,991

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.

1,0441,947

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.

5201,086

software-architecture

davila7

Guide for quality focused software architecture. This skill should be used when users want to write code, design architecture, analyze code, in any case that relates to software development.

333868

drizzle

lobehub

Drizzle ORM schema and database guide. Use when working with database schemas (src/database/schemas/*), defining tables, creating migrations, or database model code. Triggers on Drizzle schema definition, database migrations, or ORM usage questions.

238873

frontend-design

anthropics

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

481544

Search skills

Search the agent skills registry