---
name: clay-known-pitfalls-628f7faf0b3c
description: |
  Identify and avoid Clay anti-patterns and common integration mistakes.
  Use when reviewing Clay code for issues, onboarding new developers,
  or auditing existing Clay integrations for best practices violations.
  Trigger with phrases like "clay mistakes", "clay anti-patterns",
  "clay pitfalls", "clay what not to do", "clay code review".
allowed-tools: Read, Grep
version: 1.0.0
license: MIT
author: Jeremy Longshore <jeremy@intentsolutions.io>
---

# Clay Known Pitfalls

## Overview
Common mistakes and anti-patterns when integrating with Clay.

## Prerequisites
- Access to Clay codebase for review
- Understanding of async/await patterns
- Knowledge of security best practices
- Familiarity with rate limiting concepts

## Pitfall #1: Synchronous API Calls in Request Path

### ❌ Anti-Pattern
```typescript
// User waits for Clay API call
app.post('/checkout', async (req, res) => {
  const payment = await clayClient.processPayment(req.body);  // 2-5s latency
  const notification = await clayClient.sendEmail(payment);   // Another 1-2s
  res.json({ success: true });  // User waited 3-7s
});
```

### ✅ Better Approach
```typescript
// Return immediately, process async
app.post('/checkout', async (req, res) => {
  const jobId = await queue.enqueue('process-checkout', req.body);
  res.json({ jobId, status: 'processing' });  // 50ms response
});

// Background job
async function processCheckout(data) {
  const payment = await clayClient.processPayment(data);
  await clayClient.sendEmail(payment);
}
```

---

## Pitfall #2: Not Handling Rate Limits

### ❌ Anti-Pattern
```typescript
// Blast requests, crash on 429
for (const item of items) {
  await clayClient.process(item);  // Will hit rate limit
}
```

### ✅ Better Approach
```typescript
import pLimit from 'p-limit';

const limit = pLimit(5);  // Max 5 concurrent
const rateLimiter = new RateLimiter({ tokensPerSecond: 10 });

for (const item of items) {
  await rateLimiter.acquire();
  await limit(() => clayClient.process(item));
}
```

---

## Pitfall #3: Leaking API Keys

### ❌ Anti-Pattern
```typescript
// In frontend code (visible to users!)
const client = new ClayClient({
  apiKey: 'sk_live_ACTUAL_KEY_HERE',  // Anyone can see this
});

// In git history
git commit -m "add API key"  // Exposed forever
```

### ✅ Better Approach
```typescript
// Backend only, environment variable
const client = new ClayClient({
  apiKey: process.env.CLAY_API_KEY,
});

// Use .gitignore
.env
.env.local
.env.*.local
```

---

## Pitfall #4: Ignoring Idempotency

### ❌ Anti-Pattern
```typescript
// Network error on response = duplicate charge!
try {
  await clayClient.charge(order);
} catch (error) {
  if (error.code === 'NETWORK_ERROR') {
    await clayClient.charge(order);  // Charged twice!
  }
}
```

### ✅ Better Approach
```typescript
const idempotencyKey = `order-${order.id}-${Date.now()}`;

await clayClient.charge(order, {
  idempotencyKey,  // Safe to retry
});
```

---

## Pitfall #5: Not Validating Webhooks

### ❌ Anti-Pattern
```typescript
// Trust any incoming request
app.post('/webhook', (req, res) => {
  processWebhook(req.body);  // Attacker can send fake events
  res.sendStatus(200);
});
```

### ✅ Better Approach
```typescript
app.post('/webhook',
  express.raw({ type: 'application/json' }),
  (req, res) => {
    const signature = req.headers['x-clay-signature'];
    if (!verifyClaySignature(req.body, signature)) {
      return res.sendStatus(401);
    }
    processWebhook(JSON.parse(req.body));
    res.sendStatus(200);
  }
);
```

---

## Pitfall #6: Missing Error Handling

### ❌ Anti-Pattern
```typescript
// Crashes on any error
const result = await clayClient.get(id);
console.log(result.data.nested.value);  // TypeError if missing
```

### ✅ Better Approach
```typescript
try {
  const result = await clayClient.get(id);
  console.log(result?.data?.nested?.value ?? 'default');
} catch (error) {
  if (error instanceof ClayNotFoundError) {
    return null;
  }
  if (error instanceof ClayRateLimitError) {
    await sleep(error.retryAfter);
    return this.get(id);  // Retry
  }
  throw error;  // Rethrow unknown errors
}
```

---

## Pitfall #7: Hardcoding Configuration

### ❌ Anti-Pattern
```typescript
const client = new ClayClient({
  timeout: 5000,  // Too short for some operations
  baseUrl: 'https://api.clay.com',  // Can't change for staging
});
```

### ✅ Better Approach
```typescript
const client = new ClayClient({
  timeout: parseInt(process.env.CLAY_TIMEOUT || '30000'),
  baseUrl: process.env.CLAY_BASE_URL || 'https://api.clay.com',
});
```

---

## Pitfall #8: Not Implementing Circuit Breaker

### ❌ Anti-Pattern
```typescript
// When Clay is down, every request hangs
for (const user of users) {
  await clayClient.sync(user);  // All timeout sequentially
}
```

### ✅ Better Approach
```typescript
import CircuitBreaker from 'opossum';

const breaker = new CircuitBreaker(clayClient.sync, {
  timeout: 10000,
  errorThresholdPercentage: 50,
  resetTimeout: 30000,
});

// Fails fast when circuit is open
for (const user of users) {
  await breaker.fire(user).catch(handleFailure);
}
```

---

## Pitfall #9: Logging Sensitive Data

### ❌ Anti-Pattern
```typescript
console.log('Request:', JSON.stringify(request));  // Logs API key, PII
console.log('User:', user);  // Logs email, phone
```

### ✅ Better Approach
```typescript
const redacted = {
  ...request,
  apiKey: '[REDACTED]',
  user: { id: user.id },  // Only non-sensitive fields
};
console.log('Request:', JSON.stringify(redacted));
```

---

## Pitfall #10: No Graceful Degradation

### ❌ Anti-Pattern
```typescript
// Entire feature broken if Clay is down
const recommendations = await clayClient.getRecommendations(userId);
return renderPage({ recommendations });  // Page crashes
```

### ✅ Better Approach
```typescript
let recommendations;
try {
  recommendations = await clayClient.getRecommendations(userId);
} catch (error) {
  recommendations = await getFallbackRecommendations(userId);
  reportDegradedService('clay', error);
}
return renderPage({ recommendations, degraded: !recommendations });
```

---

## Instructions

### Step 1: Review for Anti-Patterns
Scan codebase for each pitfall pattern.

### Step 2: Prioritize Fixes
Address security issues first, then performance.

### Step 3: Implement Better Approach
Replace anti-patterns with recommended patterns.

### Step 4: Add Prevention
Set up linting and CI checks to prevent recurrence.

## Output
- Anti-patterns identified
- Fixes prioritized and implemented
- Prevention measures in place
- Code quality improved

## Error Handling
| Issue | Cause | Solution |
|-------|-------|----------|
| Too many findings | Legacy codebase | Prioritize security first |
| Pattern not detected | Complex code | Manual review |
| False positive | Similar code | Whitelist exceptions |
| Fix breaks tests | Behavior change | Update tests |

## Examples

### Quick Pitfall Scan
```bash
# Check for common pitfalls
grep -r "sk_live_" --include="*.ts" src/        # Key leakage
grep -r "console.log" --include="*.ts" src/     # Potential PII logging
```

## Resources
- [Clay Security Guide](https://docs.clay.com/security)
- [Clay Best Practices](https://docs.clay.com/best-practices)

## Quick Reference Card

| Pitfall | Detection | Prevention |
|---------|-----------|------------|
| Sync in request | High latency | Use queues |
| Rate limit ignore | 429 errors | Implement backoff |
| Key leakage | Git history scan | Env vars, .gitignore |
| No idempotency | Duplicate records | Idempotency keys |
| Unverified webhooks | Security audit | Signature verification |
| Missing error handling | Crashes | Try-catch, types |
| Hardcoded config | Code review | Environment variables |
| No circuit breaker | Cascading failures | opossum, resilience4j |
| Logging PII | Log audit | Redaction middleware |
| No degradation | Total outages | Fallback systems |

---
Source attribution: Dicklesworthstone
Original project: https://github.com/Dicklesworthstone/pi_agent_rust/blob/f28fc46ee0db8e710d95b8b55592cd38d60f2b26/tests/ext_conformance/artifacts/plugins-community/plugins/saas-packs/clay-pack/skills/clay-known-pitfalls/SKILL.md
License: MIT
License information: https://opensource.org/license/mit
Original upstream instructions; downloaded from Mega AI Hub.

## Upstream license notice

MIT License (with OpenAI/Anthropic Rider)

Copyright (c) 2026 Jeffrey Emanuel

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

ADDITIONAL RIDER / RESTRICTION (OpenAI / Anthropic):

This rider is part of the "conditions" of this License. In the event of any
conflict between this rider and any other portion of this License, this rider
controls.

"Restricted Parties" means OpenAI, L.L.C.; Anthropic, PBC; any of their
respective Affiliates; and any person or entity acting directly or indirectly
on behalf of, for the benefit of, or under the direction of any of the
foregoing (including any officer, director, employee, contractor, agent,
consultant, service provider, or representative).

Notwithstanding any other provision of this License, no rights are granted to
any Restricted Party. Any purported license, sublicense, assignment, transfer,
or other permission to any Restricted Party is null and void absent the
express prior written permission of Jeffrey Emanuel.

You may not provide, disclose, distribute, sublicense, sell, lease, lend,
host, make available, or otherwise permit access to the Software or any
derivative work of the Software (as defined in applicable copyright law)
(collectively, "Derivative Works") to or for any Restricted Party.

For purposes of this rider, "use" includes, without limitation: copying,
modifying, merging, publishing, distributing, sublicensing, selling,
transferring, making available, hosting, deploying, executing, benchmarking,
testing, analyzing, indexing, or incorporating the Software or any Derivative
Works into any dataset, training corpus, evaluation harness, or pipeline for
machine learning or other automated systems.

This rider applies to the Software and all Derivative Works. As a condition of
use, you agree that this rider is a precondition to exercising any rights
under this License, and you agree that any distribution of the Software or any
Derivative Works must include this rider provision unmodified.

Any breach of this rider automatically and immediately terminates the
permissions granted by this License. Upon termination, you must immediately
cease all use and distribution of the Software and any Derivative Works and
destroy all copies under your control.

You agree that a breach of this rider would cause irreparable harm and that
Jeffrey Emanuel may seek injunctive or other equitable relief to enforce this
rider, in addition to any other remedies available at law. To the maximum
extent permitted by applicable law, the prevailing party in any action to
enforce this rider shall be entitled to recover reasonable attorneys' fees and
costs.

For purposes of this rider, "Affiliate" means any entity that directly or
indirectly controls, is controlled by, or is under common control with the
specified party. "Control" means ownership of more than 50% of the voting
securities or other ownership interest, or the power to direct management or
policies by contract or otherwise.

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.



# Mega AI Hub resource metadata

Creator / publisher: Dicklesworthstone
Original project: https://github.com/Dicklesworthstone/pi_agent_rust/blob/f28fc46ee0db8e710d95b8b55592cd38d60f2b26/tests/ext_conformance/artifacts/plugins-community/plugins/saas-packs/clay-pack/skills/clay-known-pitfalls/SKILL.md
Attribution basis: Source repository record

Fields of work: Development & Engineering, Product Management
Roles: Backend Developer, ML / AI Engineer, Product Manager
Specialties: Backend
Tools: Clay, Grep
Country applicability: Country not specified
Classification basis: Source catalog labels
Instruction SHA-256: c68767f6b3daecaeeb8f8fa0b1fb709c088475fecf1c0523571fe9d77f4dffa1
