clay-reliability-patterns
Build fault-tolerant Clay integrations with circuit breakers, dead letter queues, and graceful degradation. Use when building production Clay pipelines that need resilience, implementing retry strategies, or adding fault tolerance to enrichment workflows. Trigger with phrases like "clay reliability", "clay circuit breaker", "clay resilience", "clay fallback", "clay fault tolerance", "clay dead letter queue".
Best use case
clay-reliability-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Build fault-tolerant Clay integrations with circuit breakers, dead letter queues, and graceful degradation. Use when building production Clay pipelines that need resilience, implementing retry strategies, or adding fault tolerance to enrichment workflows. Trigger with phrases like "clay reliability", "clay circuit breaker", "clay resilience", "clay fallback", "clay fault tolerance", "clay dead letter queue".
Teams using clay-reliability-patterns should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/clay-reliability-patterns/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How clay-reliability-patterns Compares
| Feature / Agent | clay-reliability-patterns | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Build fault-tolerant Clay integrations with circuit breakers, dead letter queues, and graceful degradation. Use when building production Clay pipelines that need resilience, implementing retry strategies, or adding fault tolerance to enrichment workflows. Trigger with phrases like "clay reliability", "clay circuit breaker", "clay resilience", "clay fallback", "clay fault tolerance", "clay dead letter queue".
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
SKILL.md Source
# Clay Reliability Patterns
## Overview
Production reliability patterns for Clay data enrichment pipelines. Clay's async enrichment model, credit-based billing, and dependency on 150+ external data providers require specific resilience strategies: credit budget circuit breakers, webhook delivery tracking, dead letter queues for failed batches, and graceful degradation when Clay is unavailable.
## Prerequisites
- Clay integration in production or pre-production
- Redis or similar for state tracking
- Understanding of Clay's async enrichment model
- Monitoring infrastructure (see `clay-observability`)
## Instructions
### Step 1: Credit Budget Circuit Breaker
Stop processing when credit burn exceeds budget to prevent runaway costs:
```typescript
// src/clay/circuit-breaker.ts
class CreditCircuitBreaker {
private state: 'closed' | 'open' | 'half-open' = 'closed';
private dailyCreditsUsed = 0;
private failureCount = 0;
private lastFailureAt: Date | null = null;
private readonly cooldownMs: number;
constructor(
private dailyLimit: number,
private failureThreshold: number = 5,
cooldownMinutes: number = 15,
) {
this.cooldownMs = cooldownMinutes * 60 * 1000;
}
canProcess(estimatedCredits: number): { allowed: boolean; reason?: string } {
// Check circuit state
if (this.state === 'open') {
// Check if cooldown has elapsed
if (this.lastFailureAt && Date.now() - this.lastFailureAt.getTime() > this.cooldownMs) {
this.state = 'half-open';
console.log('Circuit breaker: half-open (testing)');
} else {
return { allowed: false, reason: `Circuit OPEN. Cooldown until ${new Date(this.lastFailureAt!.getTime() + this.cooldownMs).toISOString()}` };
}
}
// Check budget
if (this.dailyCreditsUsed + estimatedCredits > this.dailyLimit) {
return { allowed: false, reason: `Daily credit limit reached: ${this.dailyCreditsUsed}/${this.dailyLimit}` };
}
return { allowed: true };
}
recordSuccess(creditsUsed: number) {
this.dailyCreditsUsed += creditsUsed;
if (this.state === 'half-open') {
this.state = 'closed';
this.failureCount = 0;
console.log('Circuit breaker: closed (recovered)');
}
}
recordFailure() {
this.failureCount++;
this.lastFailureAt = new Date();
if (this.failureCount >= this.failureThreshold) {
this.state = 'open';
console.error(`Circuit breaker: OPEN after ${this.failureCount} failures`);
}
}
resetDaily() {
this.dailyCreditsUsed = 0;
}
}
```
### Step 2: Dead Letter Queue for Failed Submissions
```typescript
// src/clay/dead-letter-queue.ts
interface DLQEntry {
row: Record<string, unknown>;
error: string;
webhookUrl: string;
failedAt: string;
retryCount: number;
maxRetries: number;
}
class ClayDLQ {
private entries: DLQEntry[] = [];
addToQueue(row: Record<string, unknown>, error: string, webhookUrl: string): void {
this.entries.push({
row,
error,
webhookUrl,
failedAt: new Date().toISOString(),
retryCount: 0,
maxRetries: 3,
});
console.warn(`DLQ: Added row (${this.entries.length} total). Error: ${error}`);
}
async retryAll(): Promise<{ retried: number; succeeded: number; permanentFailures: number }> {
let succeeded = 0, permanentFailures = 0;
const remaining: DLQEntry[] = [];
for (const entry of this.entries) {
if (entry.retryCount >= entry.maxRetries) {
permanentFailures++;
continue;
}
try {
const res = await fetch(entry.webhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(entry.row),
});
if (res.ok) {
succeeded++;
} else {
entry.retryCount++;
remaining.push(entry);
}
} catch {
entry.retryCount++;
remaining.push(entry);
}
await new Promise(r => setTimeout(r, 500)); // Pace retries
}
this.entries = remaining;
return { retried: this.entries.length + succeeded + permanentFailures, succeeded, permanentFailures };
}
getStats() {
return {
pending: this.entries.length,
byError: this.entries.reduce((acc, e) => {
acc[e.error] = (acc[e.error] || 0) + 1;
return acc;
}, {} as Record<string, number>),
};
}
}
```
### Step 3: Webhook Health Monitor
```typescript
// src/clay/health-monitor.ts
class WebhookHealthMonitor {
private successCount = 0;
private failureCount = 0;
private lastCheck: Date = new Date();
private readonly windowMs = 5 * 60 * 1000; // 5-minute window
record(success: boolean) {
if (success) this.successCount++;
else this.failureCount++;
}
getHealthScore(): { score: number; status: 'healthy' | 'degraded' | 'unhealthy' } {
const total = this.successCount + this.failureCount;
if (total === 0) return { score: 100, status: 'healthy' };
const score = (this.successCount / total) * 100;
// Reset window periodically
if (Date.now() - this.lastCheck.getTime() > this.windowMs) {
this.successCount = 0;
this.failureCount = 0;
this.lastCheck = new Date();
}
return {
score,
status: score > 95 ? 'healthy' : score > 80 ? 'degraded' : 'unhealthy',
};
}
}
```
### Step 4: Graceful Degradation When Clay Is Down
```typescript
// src/clay/fallback.ts
interface FallbackConfig {
cacheEnrichedData: boolean; // Cache previously enriched domains
queueForLater: boolean; // Queue submissions for when Clay recovers
useLocalFallback: boolean; // Fall back to local enrichment (limited)
}
class ClayWithFallback {
private cache = new Map<string, Record<string, unknown>>();
private offlineQueue: Record<string, unknown>[] = [];
async enrichOrFallback(
lead: Record<string, unknown>,
webhookUrl: string,
config: FallbackConfig,
): Promise<{ data: Record<string, unknown>; source: 'clay' | 'cache' | 'queued' | 'local' }> {
// Try Clay first
try {
const res = await fetch(webhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(lead),
signal: AbortSignal.timeout(10_000),
});
if (res.ok) {
return { data: lead, source: 'clay' };
}
} catch {
console.warn('Clay webhook unavailable — using fallback');
}
// Fallback 1: Check cache for this domain
const domain = lead.domain as string;
if (config.cacheEnrichedData && this.cache.has(domain)) {
return { data: { ...lead, ...this.cache.get(domain) }, source: 'cache' };
}
// Fallback 2: Queue for later processing
if (config.queueForLater) {
this.offlineQueue.push(lead);
return { data: lead, source: 'queued' };
}
// Fallback 3: Minimal local enrichment (domain -> company guess)
if (config.useLocalFallback) {
return {
data: { ...lead, company_name: domain.replace(/\.\w+$/, '').replace(/-/g, ' ') },
source: 'local',
};
}
return { data: lead, source: 'local' };
}
async drainOfflineQueue(webhookUrl: string): Promise<number> {
let drained = 0;
while (this.offlineQueue.length > 0) {
const lead = this.offlineQueue.shift()!;
try {
await fetch(webhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(lead),
});
drained++;
await new Promise(r => setTimeout(r, 200));
} catch {
this.offlineQueue.unshift(lead); // Put back
break;
}
}
return drained;
}
}
```
### Step 5: Combine All Patterns
```typescript
// src/clay/reliable-pipeline.ts
const circuitBreaker = new CreditCircuitBreaker(500); // 500 credits/day
const dlq = new ClayDLQ();
const healthMonitor = new WebhookHealthMonitor();
async function reliableEnrich(lead: Record<string, unknown>, webhookUrl: string): Promise<void> {
// Check circuit breaker
const { allowed, reason } = circuitBreaker.canProcess(6); // ~6 credits/lead
if (!allowed) {
dlq.addToQueue(lead, `Circuit breaker: ${reason}`, webhookUrl);
return;
}
try {
const res = await fetch(webhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(lead),
});
if (res.ok) {
circuitBreaker.recordSuccess(6);
healthMonitor.record(true);
} else {
throw new Error(`HTTP ${res.status}`);
}
} catch (err) {
circuitBreaker.recordFailure();
healthMonitor.record(false);
dlq.addToQueue(lead, (err as Error).message, webhookUrl);
}
}
```
## Error Handling
| Issue | Cause | Solution |
|-------|-------|----------|
| Runaway credit spend | No budget circuit breaker | Implement credit budget limiter |
| Lost leads during outage | No DLQ | Queue failed submissions for retry |
| Silent webhook failures | No health monitoring | Track success/failure rates |
| Clay outage blocks pipeline | No fallback | Implement cache + queue fallback |
## Resources
- [Clay Community](https://community.clay.com)
- [BullMQ Dead Letter Queue](https://docs.bullmq.io/guide/dead-letter-queue)
- [Circuit Breaker Pattern](https://martinfowler.com/bliki/CircuitBreaker.html)
## Next Steps
For policy guardrails, see `clay-policy-guardrails`.Related Skills
workhuman-sdk-patterns
Workhuman sdk patterns for employee recognition and rewards API. Use when integrating Workhuman Social Recognition, or building recognition workflows with HRIS systems. Trigger: "workhuman sdk patterns".
wispr-sdk-patterns
Wispr Flow sdk patterns for voice-to-text API integration. Use when integrating Wispr Flow dictation, WebSocket streaming, or building voice-powered applications. Trigger: "wispr sdk patterns".
windsurf-sdk-patterns
Apply production-ready Windsurf workspace configuration and Cascade interaction patterns. Use when configuring .windsurfrules, workspace rules, MCP servers, or establishing team coding standards for Windsurf AI. Trigger with phrases like "windsurf patterns", "windsurf best practices", "windsurf config patterns", "windsurfrules", "windsurf workspace".
windsurf-reliability-patterns
Implement reliable Cascade workflows with checkpoints, rollback, and incremental editing. Use when building fault-tolerant AI coding workflows, preventing Cascade from breaking builds, or establishing safe practices for multi-file AI edits. Trigger with phrases like "windsurf reliability", "cascade safety", "windsurf rollback", "cascade checkpoint", "safe cascade workflow".
webflow-sdk-patterns
Apply production-ready Webflow SDK patterns — singleton client, typed error handling, pagination helpers, and raw response access for the webflow-api package. Use when implementing Webflow integrations, refactoring SDK usage, or establishing team coding standards. Trigger with phrases like "webflow SDK patterns", "webflow best practices", "webflow code patterns", "idiomatic webflow", "webflow typescript".
vercel-sdk-patterns
Production-ready Vercel REST API patterns with typed fetch wrappers and error handling. Use when integrating with the Vercel API programmatically, building deployment tools, or establishing team coding standards for Vercel API calls. Trigger with phrases like "vercel SDK patterns", "vercel API wrapper", "vercel REST API client", "vercel best practices", "idiomatic vercel API".
vercel-reliability-patterns
Implement reliability patterns for Vercel deployments including circuit breakers, retry logic, and graceful degradation. Use when building fault-tolerant serverless functions, implementing retry strategies, or adding resilience to production Vercel services. Trigger with phrases like "vercel reliability", "vercel circuit breaker", "vercel resilience", "vercel fallback", "vercel graceful degradation".
veeva-sdk-patterns
Veeva Vault sdk patterns for REST API and clinical operations. Use when working with Veeva Vault document management and CRM. Trigger: "veeva sdk patterns".
vastai-sdk-patterns
Apply production-ready Vast.ai SDK patterns for Python and REST API. Use when implementing Vast.ai integrations, refactoring SDK usage, or establishing coding standards for GPU cloud operations. Trigger with phrases like "vastai SDK patterns", "vastai best practices", "vastai code patterns", "idiomatic vastai".
twinmind-sdk-patterns
Apply production-ready TwinMind SDK patterns for TypeScript and Python. Use when implementing TwinMind integrations, refactoring API usage, or establishing team coding standards for meeting AI integration. Trigger with phrases like "twinmind SDK patterns", "twinmind best practices", "twinmind code patterns", "idiomatic twinmind".
together-sdk-patterns
Together AI sdk patterns for inference, fine-tuning, and model deployment. Use when working with Together AI's OpenAI-compatible API. Trigger: "together sdk patterns".
techsmith-sdk-patterns
TechSmith sdk patterns for Snagit COM API and Camtasia automation. Use when working with TechSmith screen capture and video editing automation. Trigger: "techsmith sdk patterns".