figma-reliability-patterns
Build resilient Figma integrations with circuit breakers, fallbacks, and graceful degradation. Use when implementing fault tolerance, handling Figma outages gracefully, or building production-grade reliability into Figma API consumers. Trigger with phrases like "figma reliability", "figma circuit breaker", "figma fallback", "figma resilience", "figma graceful degradation".
What this skill does
# Figma Reliability Patterns
## Overview
Production reliability patterns for Figma REST API integrations. Figma is an external dependency -- your application must handle its outages, rate limits, and slow responses without cascading failures.
## Prerequisites
- Working Figma API integration
- Understanding of circuit breaker pattern
- Cache or file system for fallback data
## Instructions
### Step 1: Circuit Breaker
```typescript
// Prevent cascading failures when Figma is down
class FigmaCircuitBreaker {
private failures = 0;
private lastFailure = 0;
private state: 'closed' | 'open' | 'half-open' = 'closed';
constructor(
private threshold = 5, // Open after 5 failures
private resetTimeMs = 30_000 // Try again after 30s
) {}
async execute<T>(fn: () => Promise<T>): Promise<T> {
if (this.state === 'open') {
if (Date.now() - this.lastFailure > this.resetTimeMs) {
this.state = 'half-open';
console.log('[figma-circuit] State: half-open (testing recovery)');
} else {
throw new Error('Figma circuit breaker is OPEN -- failing fast');
}
}
try {
const result = await fn();
if (this.state === 'half-open') {
this.state = 'closed';
this.failures = 0;
console.log('[figma-circuit] State: closed (recovered)');
}
return result;
} catch (error) {
this.failures++;
this.lastFailure = Date.now();
if (this.failures >= this.threshold) {
this.state = 'open';
console.warn(`[figma-circuit] State: OPEN after ${this.failures} failures`);
}
throw error;
}
}
getState() { return this.state; }
}
const figmaBreaker = new FigmaCircuitBreaker();
// Usage
async function safeFigmaCall<T>(fn: () => Promise<T>): Promise<T> {
return figmaBreaker.execute(fn);
}
```
### Step 2: Cached Fallback
```typescript
import { readFileSync, writeFileSync, existsSync } from 'fs';
// Serve cached data when Figma is unavailable
class FigmaFallbackCache {
constructor(private cacheDir = '.figma-cache') {}
private getPath(key: string) {
return `${this.cacheDir}/${key.replace(/[^a-zA-Z0-9]/g, '_')}.json`;
}
save(key: string, data: any) {
const { mkdirSync } = require('fs');
mkdirSync(this.cacheDir, { recursive: true });
writeFileSync(this.getPath(key), JSON.stringify({
data,
cachedAt: new Date().toISOString(),
}));
}
load(key: string): { data: any; cachedAt: string } | null {
const path = this.getPath(key);
if (!existsSync(path)) return null;
return JSON.parse(readFileSync(path, 'utf-8'));
}
}
const fallbackCache = new FigmaFallbackCache();
async function fetchWithFallback<T>(
cacheKey: string,
fetcher: () => Promise<T>
): Promise<{ data: T; fromCache: boolean; cachedAt?: string }> {
try {
const data = await safeFigmaCall(fetcher);
// Update cache with fresh data
fallbackCache.save(cacheKey, data);
return { data, fromCache: false };
} catch (error) {
console.warn(`Figma unavailable, loading cached ${cacheKey}`);
const cached = fallbackCache.load(cacheKey);
if (cached) {
return { data: cached.data as T, fromCache: true, cachedAt: cached.cachedAt };
}
throw new Error(`Figma unavailable and no cached data for ${cacheKey}`);
}
}
```
### Step 3: Retry with Backoff (Respecting Retry-After)
```typescript
async function figmaRetry<T>(
fn: () => Promise<Response>,
maxRetries = 3
): Promise<T> {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
const res = await fn();
if (res.ok) return res.json();
if (res.status === 429) {
const retryAfter = parseInt(res.headers.get('Retry-After') || '60');
if (attempt < maxRetries) {
console.warn(`429 -- waiting ${retryAfter}s (attempt ${attempt + 1}/${maxRetries})`);
await new Promise(r => setTimeout(r, retryAfter * 1000));
continue;
}
}
if (res.status >= 500 && attempt < maxRetries) {
const delay = Math.min(1000 * Math.pow(2, attempt), 30_000);
const jitter = Math.random() * 1000;
await new Promise(r => setTimeout(r, delay + jitter));
continue;
}
throw new FigmaApiError(res.status, await res.text());
}
throw new Error('Max retries exceeded');
}
```
### Step 4: Request Timeout
```typescript
// Prevent requests from hanging indefinitely
async function figmaFetchWithTimeout(
path: string,
token: string,
timeoutMs = 15_000
): Promise<Response> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
return await fetch(`https://api.figma.com${path}`, {
headers: { 'X-Figma-Token': token },
signal: controller.signal,
});
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') {
throw new Error(`Figma request timed out after ${timeoutMs}ms: ${path}`);
}
throw error;
} finally {
clearTimeout(timeout);
}
}
```
### Step 5: Health-Aware Request Routing
```typescript
// Only make non-critical Figma calls when the API is healthy
class FigmaHealthTracker {
private healthy = true;
private lastCheck = 0;
private checkIntervalMs = 30_000;
async isHealthy(token: string): Promise<boolean> {
if (Date.now() - this.lastCheck < this.checkIntervalMs) {
return this.healthy;
}
try {
const res = await figmaFetchWithTimeout('/v1/me', token, 5000);
this.healthy = res.ok;
} catch {
this.healthy = false;
}
this.lastCheck = Date.now();
return this.healthy;
}
}
const healthTracker = new FigmaHealthTracker();
async function conditionalFigmaCall<T>(
token: string,
critical: boolean,
fn: () => Promise<T>,
fallback: () => Promise<T>
): Promise<T> {
const healthy = await healthTracker.isHealthy(token);
if (!healthy && !critical) {
console.log('Figma unhealthy, using fallback for non-critical call');
return fallback();
}
return fetchWithFallback('default', fn).then(r => r.data);
}
```
## Output
- Circuit breaker preventing cascading failures
- Cached fallback serving stale data during outages
- Retry logic respecting Figma's `Retry-After` header
- Request timeouts preventing hung connections
- Health-aware routing for non-critical calls
## Error Handling
| Issue | Cause | Solution |
|-------|-------|----------|
| Circuit stays open | Threshold too low | Increase threshold or decrease reset time |
| Stale fallback data | Cache not refreshed | Refresh cache on successful calls |
| Retry loops | Not respecting Retry-After | Always use the header value |
| Timeout too short | Large file responses | Increase timeout for `/v1/files` calls |
## Resources
- [Circuit Breaker Pattern](https://martinfowler.com/bliki/CircuitBreaker.html)
- [Figma Rate Limits](https://developers.figma.com/docs/rest-api/rate-limits/)
- [Figma Status Page](https://status.figma.com)
## Next Steps
For policy enforcement, see `figma-policy-guardrails`.
Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.