← ClaudeAtlas

idempotency-handlinglisted

Idempotent API operations with idempotency keys, Redis caching, DB constraints. Use for payment systems, webhook retries, safe retries, or encountering duplicate processing, race conditions, key expiry errors.
secondsky/claude-skills · ★ 248 · Code & Development · score 90
Install: claude install-skill secondsky/claude-skills
# Idempotency Handling Ensure operations produce identical results regardless of execution count. ## Idempotency Key Pattern ```javascript const redis = require('redis'); const client = redis.createClient(); async function idempotencyMiddleware(req, res, next) { const key = req.headers['idempotency-key']; if (!key) return next(); const cached = await client.get(`idempotency:${key}`); if (cached) { const { status, body } = JSON.parse(cached); return res.status(status).json(body); } // Store original send const originalSend = res.json.bind(res); res.json = async (body) => { await client.setEx( `idempotency:${key}`, 86400, // 24 hours JSON.stringify({ status: res.statusCode, body }) ); return originalSend(body); }; next(); } ``` ## Database-Backed Idempotency ```sql CREATE TABLE idempotency_keys ( key VARCHAR(255) PRIMARY KEY, request_hash VARCHAR(64) NOT NULL, response JSONB, status VARCHAR(20) DEFAULT 'processing', created_at TIMESTAMP DEFAULT NOW(), expires_at TIMESTAMP DEFAULT NOW() + INTERVAL '24 hours' ); CREATE INDEX idx_idempotency_expires ON idempotency_keys(expires_at); ``` ```javascript async function processPayment(idempotencyKey, payload) { const requestHash = crypto.createHash('sha256') .update(JSON.stringify(payload)).digest('hex'); // Try to insert with 'processing' status - only one request will succeed const insertResult = await db.query( `INSERT INTO idempotency_key