[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M783TC3MS4HZM6Y2184CYZ0T":3,"skill-same:01M783TC3MS4HZM6Y2184CYZ0T":43},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":23,"commitSha":24,"skillDirectory":25,"forksCount":13,"repositoryHtmlUrl":26,"repositoryHomepageUrl":6,"ownerHtmlUrl":27,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":28,"install":29,"resources":42},"01M783TC3MS4HZM6Y2184CYZ0T","idempotency-handling",null,"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.","aibizmod\u002Faibizmod-service-web","aibizmod","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F295315630?v=4","01M7836CB8EQY701YQ7N88M591","01M7836CBVPZGNSJ8BRP2BT398",0,"MIT","https:\u002F\u002Fgithub.com\u002Faibizmod\u002Faibizmod-service-web\u002Fblob\u002Fmain\u002F.opencode\u002Fskill\u002Fclaude-skills\u002Fplugins\u002Fidempotency-handling\u002Fskills\u002Fidempotency-handling\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: idempotency-handling\ndescription: 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.\nlicense: MIT\n---\n\n# Idempotency Handling\n\nEnsure operations produce identical results regardless of execution count.\n\n## Idempotency Key Pattern\n\n```javascript\nconst redis = require('redis');\nconst client = redis.createClient();\n\nasync function idempotencyMiddleware(req, res, next) {\n  const key = req.headers['idempotency-key'];\n  if (!key) return next();\n\n  const cached = await client.get(`idempotency:${key}`);\n  if (cached) {\n    const { status, body } = JSON.parse(cached);\n    return res.status(status).json(body);\n  }\n\n  \u002F\u002F Store original send\n  const originalSend = res.json.bind(res);\n  res.json = async (body) => {\n    await client.setEx(\n      `idempotency:${key}`,\n      86400, \u002F\u002F 24 hours\n      JSON.stringify({ status: res.statusCode, body })\n    );\n    return originalSend(body);\n  };\n\n  next();\n}\n```\n\n## Database-Backed Idempotency\n\n```sql\nCREATE TABLE idempotency_keys (\n  key VARCHAR(255) PRIMARY KEY,\n  request_hash VARCHAR(64) NOT NULL,\n  response JSONB,\n  status VARCHAR(20) DEFAULT 'processing',\n  created_at TIMESTAMP DEFAULT NOW(),\n  expires_at TIMESTAMP DEFAULT NOW() + INTERVAL '24 hours'\n);\n\nCREATE INDEX idx_idempotency_expires ON idempotency_keys(expires_at);\n```\n\n```javascript\nasync function processPayment(idempotencyKey, payload) {\n  const requestHash = crypto.createHash('sha256')\n    .update(JSON.stringify(payload)).digest('hex');\n\n  \u002F\u002F Try to insert with 'processing' status - only one request will succeed\n  const insertResult = await db.query(\n    `INSERT INTO idempotency_keys (key, request_hash, status)\n     VALUES ($1, $2, 'processing')\n     ON CONFLICT (key) DO NOTHING\n     RETURNING *`,\n    [idempotencyKey, requestHash]\n  );\n\n  \u002F\u002F If we inserted the row (rowCount === 1), we're responsible for processing\n  if (insertResult.rowCount === 1) {\n    try {\n      \u002F\u002F Execute the payment\n      const result = await executePayment(payload);\n\n      \u002F\u002F Update to completed with response\n      await db.query(\n        'UPDATE idempotency_keys SET status = $1, response = $2 WHERE key = $3',\n        ['completed', JSON.stringify(result), idempotencyKey]\n      );\n\n      return result;\n    } catch (error) {\n      \u002F\u002F Mark as failed on error\n      await db.query(\n        'UPDATE idempotency_keys SET status = $1, response = $2 WHERE key = $3',\n        ['failed', JSON.stringify({ error: error.message }), idempotencyKey]\n      );\n      throw error;\n    }\n  }\n\n  \u002F\u002F Another request is\u002Fwas processing this key - check status\n  const existing = await db.query(\n    'SELECT * FROM idempotency_keys WHERE key = $1',\n    [idempotencyKey]\n  );\n\n  const row = existing.rows[0];\n  if (!row) {\n    throw new Error('Unexpected: idempotency key vanished');\n  }\n\n  \u002F\u002F Verify request hasn't changed\n  if (row.request_hash !== requestHash) {\n    throw new Error('Idempotency key reused with different request');\n  }\n\n  \u002F\u002F Check status\n  if (row.status === 'completed') {\n    return JSON.parse(row.response);\n  } else if (row.status === 'processing') {\n    throw new Error('Request already processing - retry later');\n  } else if (row.status === 'failed') {\n    const failedResponse = JSON.parse(row.response);\n    throw new Error(`Previous attempt failed: ${failedResponse.error}`);\n  }\n\n  throw new Error(`Unknown status: ${row.status}`);\n}\n```\n\n## When to Apply\n\n- Payment processing\n- Order creation\n- Webhook handling\n- Email sending\n- Any operation where duplicates cause issues\n\n## Best Practices\n\n- Require idempotency keys for mutations\n- Validate request body matches stored request\n- Set appropriate TTL (24 hours typical)\n- Use atomic database operations\n- Implement cleanup jobs to prevent table bloat\n\n### TTL Cleanup Strategy\n\nTo prevent unbounded table growth, implement periodic cleanup of expired keys:\n\n**Option 1: Scheduled Database Job (PostgreSQL)**\n```sql\n-- Run hourly via pg_cron or external scheduler\nDELETE FROM idempotency_keys\nWHERE expires_at \u003C NOW()\nLIMIT 1000; -- Batch delete to avoid long locks\n```\n\n**Option 2: Application Cleanup Job (Node.js)**\n```javascript\n\u002F\u002F Run via cron or job scheduler (e.g., node-cron, Bull)\nasync function cleanupExpiredKeys() {\n  try {\n    const result = await db.query(\n      'DELETE FROM idempotency_keys WHERE expires_at \u003C NOW()'\n    );\n    console.log(`Cleaned up ${result.rowCount} expired idempotency keys`);\n  } catch (error) {\n    console.error('Cleanup job failed:', error);\n  }\n}\n\n\u002F\u002F Schedule to run every hour\ncron.schedule('0 * * * *', cleanupExpiredKeys);\n```\n\n**Option 3: Application Cleanup Job (Python)**\n```python\nimport asyncio\nfrom datetime import datetime\n\nasync def cleanup_expired_keys():\n    \"\"\"Remove expired idempotency keys to prevent table bloat.\"\"\"\n    try:\n        result = await db.execute(\n            \"DELETE FROM idempotency_keys WHERE expires_at \u003C $1\",\n            datetime.now()\n        )\n        print(f\"Cleaned up {result} expired idempotency keys\")\n    except Exception as e:\n        print(f\"Cleanup job failed: {e}\")\n\n# Run with APScheduler, Celery, or similar\n# scheduler.add_job(cleanup_expired_keys, 'interval', hours=1)\n```\n\n**Cleanup Best Practices:**\n- Run cleanup during low-traffic periods to minimize lock contention\n- Use batched deletes (`LIMIT 1000`) for large tables\n- Monitor cleanup job execution and failures\n- Consider partitioning the table by created_at for easier cleanup\n- Set up alerts if table size grows unexpectedly\n","# Idempotency Handling\n\nEnsure operations produce identical results regardless of execution count.\n\n## Idempotency Key Pattern\n\n```javascript\nconst redis = require('redis');\nconst client = redis.createClient();\n\nasync function idempotencyMiddleware(req, res, next) {\n  const key = req.headers['idempotency-key'];\n  if (!key) return next();\n\n  const cached = await client.get(`idempotency:${key}`);\n  if (cached) {\n    const { status, body } = JSON.parse(cached);\n    return res.status(status).json(body);\n  }\n\n  \u002F\u002F Store original send\n  const originalSend = res.json.bind(res);\n  res.json = async (body) => {\n    await client.setEx(\n      `idempotency:${key}`,\n      86400, \u002F\u002F 24 hours\n      JSON.stringify({ status: res.statusCode, body })\n    );\n    return originalSend(body);\n  };\n\n  next();\n}\n```\n\n## Database-Backed Idempotency\n\n```sql\nCREATE TABLE idempotency_keys (\n  key VARCHAR(255) PRIMARY KEY,\n  request_hash VARCHAR(64) NOT NULL,\n  response JSONB,\n  status VARCHAR(20) DEFAULT 'processing',\n  created_at TIMESTAMP DEFAULT NOW(),\n  expires_at TIMESTAMP DEFAULT NOW() + INTERVAL '24 hours'\n);\n\nCREATE INDEX idx_idempotency_expires ON idempotency_keys(expires_at);\n```\n\n```javascript\nasync function processPayment(idempotencyKey, payload) {\n  const requestHash = crypto.createHash('sha256')\n    .update(JSON.stringify(payload)).digest('hex');\n\n  \u002F\u002F Try to insert with 'processing' status - only one request will succeed\n  const insertResult = await db.query(\n    `INSERT INTO idempotency_keys (key, request_hash, status)\n     VALUES ($1, $2, 'processing')\n     ON CONFLICT (key) DO NOTHING\n     RETURNING *`,\n    [idempotencyKey, requestHash]\n  );\n\n  \u002F\u002F If we inserted the row (rowCount === 1), we're responsible for processing\n  if (insertResult.rowCount === 1) {\n    try {\n      \u002F\u002F Execute the payment\n      const result = await executePayment(payload);\n\n      \u002F\u002F Update to completed with response\n      await db.query(\n        'UPDATE idempotency_keys SET status = $1, response = $2 WHERE key = $3',\n        ['completed', JSON.stringify(result), idempotencyKey]\n      );\n\n      return result;\n    } catch (error) {\n      \u002F\u002F Mark as failed on error\n      await db.query(\n        'UPDATE idempotency_keys SET status = $1, response = $2 WHERE key = $3',\n        ['failed', JSON.stringify({ error: error.message }), idempotencyKey]\n      );\n      throw error;\n    }\n  }\n\n  \u002F\u002F Another request is\u002Fwas processing this key - check status\n  const existing = await db.query(\n    'SELECT * FROM idempotency_keys WHERE key = $1',\n    [idempotencyKey]\n  );\n\n  const row = existing.rows[0];\n  if (!row) {\n    throw new Error('Unexpected: idempotency key vanished');\n  }\n\n  \u002F\u002F Verify request hasn't changed\n  if (row.request_hash !== requestHash) {\n    throw new Error('Idempotency key reused with different request');\n  }\n\n  \u002F\u002F Check status\n  if (row.status === 'completed') {\n    return JSON.parse(row.response);\n  } else if (row.status === 'processing') {\n    throw new Error('Request already processing - retry later');\n  } else if (row.status === 'failed') {\n    const failedResponse = JSON.parse(row.response);\n    throw new Error(`Previous attempt failed: ${failedResponse.error}`);\n  }\n\n  throw new Error(`Unknown status: ${row.status}`);\n}\n```\n\n## When to Apply\n\n- Payment processing\n- Order creation\n- Webhook handling\n- Email sending\n- Any operation where duplicates cause issues\n\n## Best Practices\n\n- Require idempotency keys for mutations\n- Validate request body matches stored request\n- Set appropriate TTL (24 hours typical)\n- Use atomic database operations\n- Implement cleanup jobs to prevent table bloat\n\n### TTL Cleanup Strategy\n\nTo prevent unbounded table growth, implement periodic cleanup of expired keys:\n\n**Option 1: Scheduled Database Job (PostgreSQL)**\n```sql\n-- Run hourly via pg_cron or external scheduler\nDELETE FROM idempotency_keys\nWHERE expires_at \u003C NOW()\nLIMIT 1000; -- Batch delete to avoid long locks\n```\n\n**Option 2: Application Cleanup Job (Node.js)**\n```javascript\n\u002F\u002F Run via cron or job scheduler (e.g., node-cron, Bull)\nasync function cleanupExpiredKeys() {\n  try {\n    const result = await db.query(\n      'DELETE FROM idempotency_keys WHERE expires_at \u003C NOW()'\n    );\n    console.log(`Cleaned up ${result.rowCount} expired idempotency keys`);\n  } catch (error) {\n    console.error('Cleanup job failed:', error);\n  }\n}\n\n\u002F\u002F Schedule to run every hour\ncron.schedule('0 * * * *', cleanupExpiredKeys);\n```\n\n**Option 3: Application Cleanup Job (Python)**\n```python\nimport asyncio\nfrom datetime import datetime\n\nasync def cleanup_expired_keys():\n    \"\"\"Remove expired idempotency keys to prevent table bloat.\"\"\"\n    try:\n        result = await db.execute(\n            \"DELETE FROM idempotency_keys WHERE expires_at \u003C $1\",\n            datetime.now()\n        )\n        print(f\"Cleaned up {result} expired idempotency keys\")\n    except Exception as e:\n        print(f\"Cleanup job failed: {e}\")\n\n# Run with APScheduler, Celery, or similar\n# scheduler.add_job(cleanup_expired_keys, 'interval', hours=1)\n```\n\n**Cleanup Best Practices:**\n- Run cleanup during low-traffic periods to minimize lock contention\n- Use batched deletes (`LIMIT 1000`) for large tables\n- Monitor cleanup job execution and failures\n- Consider partitioning the table by created_at for easier cleanup\n- Set up alerts if table size grows unexpectedly\n",{"name":5,"license":14,"description":7},"main","9f54582c8b485462d402d7e70feaef34801746b9",".opencode\u002Fskill\u002Fclaude-skills\u002Fplugins\u002Fidempotency-handling\u002Fskills\u002Fidempotency-handling","https:\u002F\u002Fgithub.com\u002Faibizmod\u002Faibizmod-service-web","https:\u002F\u002Fgithub.com\u002Faibizmod","2026-09-24 00:48:11",{"source":8,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add aibizmod\u002Faibizmod-service-web --skill idempotency-handling",{"tool":35,"command":36},"bunx","bunx skills add aibizmod\u002Faibizmod-service-web --skill idempotency-handling",{"tool":38,"command":39},"pnpm","pnpm dlx skills add aibizmod\u002Faibizmod-service-web --skill idempotency-handling","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Faibizmod\u002Faibizmod-service-web\u002Fblob\u002Fmain\u002F.opencode\u002Fskill\u002Fclaude-skills\u002Fplugins\u002Fidempotency-handling\u002Fskills\u002Fidempotency-handling\u002FSKILL.md",true,[],[44,51,58,65,72,79],{"skillNo":45,"name":46,"nameZh":6,"description":47,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":48,"categories":49,"keywords":50,"publishedAt":18},"01M7846EAPZWCQ8C6G3AAMMR57","{TODO=lowercase-hyphen-case-name}","[TODO: Write comprehensive description in third-person. Start with \"This skill provides...\" or \"This skill should be used when...\"]\n\n[TODO: Add \"Use when\" scenarios - specific situations where Claude should use this skill]\n\n[TODO: Add keywords - technologies, use cases, error messages that should trigger this skill]","https:\u002F\u002Fgithub.com\u002Faibizmod\u002Faibizmod-service-web\u002Fblob\u002Fmain\u002F.opencode\u002Fskill\u002Fclaude-skills\u002Ftemplates\u002Fskill-skeleton\u002Fskills\u002Fskill-name\u002FSKILL.md",[],[],{"skillNo":52,"name":53,"nameZh":6,"description":54,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":55,"categories":56,"keywords":57,"publishedAt":18},"01M7846A0WGDKJTDPD5QMHQVFV","zustand-state-management","Zustand state management for React with TypeScript. Use for global state, Redux\u002FContext API migration, localStorage persistence, slices pattern, devtools, Next.js SSR, or encountering hydration errors, TypeScript inference issues, persist middleware problems, infinite render loops.","https:\u002F\u002Fgithub.com\u002Faibizmod\u002Faibizmod-service-web\u002Fblob\u002Fmain\u002F.opencode\u002Fskill\u002Fclaude-skills\u002Fplugins\u002Fzustand-state-management\u002Fskills\u002Fzustand-state-management\u002FSKILL.md",[],[],{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":18},"01M78463GGSP9B3JSF146B2MG0","zod","TypeScript-first schema validation and type inference. Use for validating API requests\u002Fresponses, form data, env vars, configs, defining type-safe schemas with runtime validation, transforming data, generating JSON Schema for OpenAPI\u002FAI, or encountering missing validation errors, type inference issues, validation error handling problems. Zero dependencies (2kb gzipped).","https:\u002F\u002Fgithub.com\u002Faibizmod\u002Faibizmod-service-web\u002Fblob\u002Fmain\u002F.opencode\u002Fskill\u002Fclaude-skills\u002Fplugins\u002Fzod\u002Fskills\u002Fzod\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":18},"01M7845ZX17SVNNY7EDGPJHSBT","xss-prevention","XSS attack prevention with input sanitization, output encoding, Content Security Policy. Use for user-generated content, rich text editors, web application security, or encountering stored XSS, reflected XSS, DOM manipulation, script injection errors.","https:\u002F\u002Fgithub.com\u002Faibizmod\u002Faibizmod-service-web\u002Fblob\u002Fmain\u002F.opencode\u002Fskill\u002Fclaude-skills\u002Fplugins\u002Fxss-prevention\u002Fskills\u002Fxss-prevention\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":18},"01M7845ST1H37YHSXWWQ9N0V0S","wordpress-plugin-core","WordPress plugin development with hooks, security, REST API, custom post types. Use for plugin creation, $wpdb queries, Settings API, or encountering SQL injection, XSS, CSRF, nonce errors.","https:\u002F\u002Fgithub.com\u002Faibizmod\u002Faibizmod-service-web\u002Fblob\u002Fmain\u002F.opencode\u002Fskill\u002Fclaude-skills\u002Fplugins\u002Fwordpress-plugin-core\u002Fskills\u002Fwordpress-plugin-core\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":18},"01M7845PTWD5HWSTGP35Q8TFNY","woocommerce-dev-cycle","Run tests, linting, and quality checks for WooCommerce development. Use when running tests, fixing code style, or following the development workflow in WooCommerce projects.","https:\u002F\u002Fgithub.com\u002Faibizmod\u002Faibizmod-service-web\u002Fblob\u002Fmain\u002F.opencode\u002Fskill\u002Fclaude-skills\u002Fplugins\u002Fwoocommerce-dev-cycle\u002Fskills\u002Fwoocommerce-dev-cycle\u002FSKILL.md",[],[]]