[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6NW7VV14209RGEYYVNZ1574":3,"skill-same:01M6NW7VV14209RGEYYVNZ1574":62},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":35,"linkOnly":36,"markdownContent":37,"markdownBody":38,"frontMatter":39,"refName":40,"commitSha":41,"skillDirectory":42,"forksCount":14,"repositoryHtmlUrl":43,"repositoryHomepageUrl":6,"ownerHtmlUrl":44,"ownerBlogUrl":45,"ownerDescription":46,"updatedAt":47,"install":48,"resources":61},"01M6NW7VV14209RGEYYVNZ1574","resilience-patterns",null,"Circuit breaker, bulkhead, retry with jitter, graceful shutdown, health check patterns for production resilience.","rubicanjr\u002FFinCognis","rubicanjr","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F234912519?v=4","01M6NT156NND8J474G34SB3923","Rubi","01M6NT15B70RWXE1N3YV0BZY8A",0,"MIT","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fresilience-patterns\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"resilience","patterns","resilience patterns","Production","health","check","jitter","health check","shutdown","Circuit Breaker","with","retry","graceful shutdown","circuit","for","bulkhead","2026-11-10 10:12:30",false,"---\nname: resilience-patterns\ndescription: Circuit breaker, bulkhead, retry with jitter, graceful shutdown, health check patterns for production resilience.\n---\n\n# Resilience Patterns\n\nProduction-grade patterns for surviving failures without cascading.\n\n## Circuit Breaker\n\n```typescript\n\u002F\u002F States: CLOSED (normal) → OPEN (blocking) → HALF_OPEN (testing)\ntype CircuitState = 'CLOSED' | 'OPEN' | 'HALF_OPEN'\n\nclass CircuitBreaker {\n  private state: CircuitState = 'CLOSED'\n  private failureCount = 0\n  private lastFailureTime = 0\n  private successCount = 0\n\n  constructor(\n    private readonly failureThreshold = 5,\n    private readonly recoveryTimeout = 30_000,  \u002F\u002F ms\n    private readonly halfOpenMaxCalls = 3\n  ) {}\n\n  async call\u003CT>(fn: () => Promise\u003CT>): Promise\u003CT> {\n    if (this.state === 'OPEN') {\n      if (Date.now() - this.lastFailureTime > this.recoveryTimeout) {\n        this.state = 'HALF_OPEN'\n        this.successCount = 0\n      } else {\n        throw new Error('Circuit breaker is OPEN — request rejected')\n      }\n    }\n\n    try {\n      const result = await fn()\n      this.onSuccess()\n      return result\n    } catch (err) {\n      this.onFailure()\n      throw err\n    }\n  }\n\n  private onSuccess(): void {\n    if (this.state === 'HALF_OPEN') {\n      this.successCount++\n      if (this.successCount >= this.halfOpenMaxCalls) {\n        this.state = 'CLOSED'\n        this.failureCount = 0\n      }\n    } else {\n      this.failureCount = 0\n    }\n  }\n\n  private onFailure(): void {\n    this.failureCount++\n    this.lastFailureTime = Date.now()\n    if (this.failureCount >= this.failureThreshold) {\n      this.state = 'OPEN'\n    }\n  }\n\n  getState(): CircuitState { return this.state }\n}\n\n\u002F\u002F Usage with Opossum (production library)\n\u002F\u002F import CircuitBreaker from 'opossum'\n\u002F\u002F const breaker = new CircuitBreaker(riskyCall, { timeout: 3000, errorThresholdPercentage: 50 })\nconst paymentBreaker = new CircuitBreaker(5, 30_000)\n\nasync function chargeUser(userId: string, amount: number) {\n  return paymentBreaker.call(() => paymentService.charge(userId, amount))\n}\n```\n\n## Retry with Exponential Backoff + Jitter\n\n```typescript\ninterface RetryOptions {\n  maxAttempts?: number\n  baseDelayMs?: number\n  maxDelayMs?: number\n  jitter?: boolean\n  retryIf?: (error: unknown) => boolean\n}\n\nasync function withRetry\u003CT>(\n  fn: () => Promise\u003CT>,\n  options: RetryOptions = {}\n): Promise\u003CT> {\n  const {\n    maxAttempts = 3,\n    baseDelayMs = 500,\n    maxDelayMs = 15_000,\n    jitter = true,\n    retryIf = () => true\n  } = options\n\n  let lastError: unknown\n\n  for (let attempt = 1; attempt \u003C= maxAttempts; attempt++) {\n    try {\n      return await fn()\n    } catch (err) {\n      lastError = err\n\n      if (attempt === maxAttempts || !retryIf(err)) throw err\n\n      \u002F\u002F Exponential backoff: 500ms, 1s, 2s, 4s...\n      const base = Math.min(baseDelayMs * Math.pow(2, attempt - 1), maxDelayMs)\n      \u002F\u002F Full jitter: random between 0 and base (avoids synchronized retries)\n      const delay = jitter ? Math.random() * base : base\n\n      console.warn(`Attempt ${attempt}\u002F${maxAttempts} failed, retrying in ${Math.round(delay)}ms`)\n      await new Promise(resolve => setTimeout(resolve, delay))\n    }\n  }\n\n  throw lastError\n}\n\n\u002F\u002F Usage: only retry transient errors\nawait withRetry(\n  () => externalApi.fetchData(),\n  {\n    maxAttempts: 4,\n    retryIf: (err) => err instanceof NetworkError || (err as any)?.status >= 500\n  }\n)\n```\n\n## Bulkhead Pattern\n\n```typescript\n\u002F\u002F Isolate failure domains: separate thread pools \u002F queues per service\nclass Bulkhead {\n  private activeCount = 0\n  private queue: Array\u003C() => void> = []\n\n  constructor(\n    private maxConcurrent: number,\n    private maxQueueSize: number = 50\n  ) {}\n\n  async execute\u003CT>(fn: () => Promise\u003CT>): Promise\u003CT> {\n    if (this.activeCount >= this.maxConcurrent) {\n      if (this.queue.length >= this.maxQueueSize) {\n        throw new Error('Bulkhead queue full — request rejected')\n      }\n      await new Promise\u003Cvoid>((resolve, reject) => {\n        const timeout = setTimeout(\n          () => reject(new Error('Bulkhead queue timeout')),\n          5000\n        )\n        this.queue.push(() => { clearTimeout(timeout); resolve() })\n      })\n    }\n\n    this.activeCount++\n    try {\n      return await fn()\n    } finally {\n      this.activeCount--\n      if (this.queue.length > 0) {\n        const next = this.queue.shift()!\n        next()\n      }\n    }\n  }\n\n  getStats() {\n    return { activeCount: this.activeCount, queueLength: this.queue.length }\n  }\n}\n\n\u002F\u002F Separate bulkheads per downstream service\nconst paymentBulkhead = new Bulkhead(10, 20)\nconst emailBulkhead = new Bulkhead(5, 10)\nconst dbBulkhead = new Bulkhead(30, 100)\n```\n\n## Timeout Policies\n\n```typescript\n\u002F\u002F Never let a call hang indefinitely\nfunction withTimeout\u003CT>(\n  fn: () => Promise\u003CT>,\n  timeoutMs: number,\n  label = 'operation'\n): Promise\u003CT> {\n  return Promise.race([\n    fn(),\n    new Promise\u003Cnever>((_, reject) =>\n      setTimeout(\n        () => reject(new Error(`${label} timed out after ${timeoutMs}ms`)),\n        timeoutMs\n      )\n    )\n  ])\n}\n\n\u002F\u002F Connect timeout vs read timeout (different values)\nconst fetchWithTimeouts = async (url: string) => {\n  const controller = new AbortController()\n  const connectTimeout = setTimeout(() => controller.abort(), 2000)  \u002F\u002F connect: 2s\n\n  try {\n    const response = await fetch(url, { signal: controller.signal })\n    clearTimeout(connectTimeout)\n\n    \u002F\u002F Read timeout: 10s for body streaming\n    return await withTimeout(() => response.json(), 10_000, 'response body read')\n  } finally {\n    clearTimeout(connectTimeout)\n  }\n}\n```\n\n## Fallback Chain\n\n```typescript\nasync function getMarketData(id: string): Promise\u003CMarket> {\n  return withFallbacks([\n    { name: 'primary-db',   fn: () => primaryDb.market.findUnique({ where: { id } }) },\n    { name: 'redis-cache',  fn: () => redis.get(`market:${id}`).then(v => v ? JSON.parse(v) : null) },\n    { name: 'replica-db',   fn: () => replicaDb.market.findUnique({ where: { id } }) },\n    { name: 'stale-cache',  fn: () => staleCache.get(id) }\n  ])\n}\n\nasync function withFallbacks\u003CT>(\n  strategies: Array\u003C{ name: string; fn: () => Promise\u003CT | null> }>\n): Promise\u003CT> {\n  for (const { name, fn } of strategies) {\n    try {\n      const result = await fn()\n      if (result != null) return result\n    } catch (err) {\n      console.warn(`Strategy '${name}' failed:`, (err as Error).message)\n    }\n  }\n  throw new Error('All fallback strategies exhausted')\n}\n```\n\n## Health Check Endpoints\n\n```typescript\nimport express from 'express'\n\nconst app = express()\n\n\u002F\u002F Liveness: is the process alive? (k8s restarts if fails)\napp.get('\u002Flive', (_req, res) => {\n  res.json({ status: 'ok', timestamp: new Date().toISOString() })\n})\n\n\u002F\u002F Readiness: is the app ready to serve traffic? (k8s removes from LB if fails)\napp.get('\u002Fready', async (_req, res) => {\n  const checks = await Promise.allSettled([\n    checkDatabase(),\n    checkRedis(),\n    checkDependencies()\n  ])\n\n  const results = checks.map((c, i) => ({\n    name: ['database', 'redis', 'dependencies'][i],\n    status: c.status === 'fulfilled' ? 'ok' : 'fail',\n    error: c.status === 'rejected' ? (c.reason as Error).message : undefined\n  }))\n\n  const allHealthy = results.every(r => r.status === 'ok')\n  res.status(allHealthy ? 200 : 503).json({ status: allHealthy ? 'ready' : 'not-ready', checks: results })\n})\n\n\u002F\u002F Health: detailed diagnostics for ops team\napp.get('\u002Fhealth', async (_req, res) => {\n  const [dbMs, redisMs] = await Promise.all([pingDb(), pingRedis()])\n  res.json({\n    status: 'ok',\n    uptime: process.uptime(),\n    memory: process.memoryUsage(),\n    db: { latencyMs: dbMs },\n    redis: { latencyMs: redisMs }\n  })\n})\n\nasync function checkDatabase(): Promise\u003Cvoid> {\n  await db.$queryRaw`SELECT 1`\n}\n\nasync function checkRedis(): Promise\u003Cvoid> {\n  const pong = await redis.ping()\n  if (pong !== 'PONG') throw new Error('Redis ping failed')\n}\n```\n\n## Graceful Shutdown\n\n```typescript\n\u002F\u002F Handle SIGTERM (k8s, Docker stop) without dropping in-flight requests\nlet isShuttingDown = false\n\nasync function gracefulShutdown(server: http.Server): Promise\u003Cvoid> {\n  console.log('SIGTERM received, starting graceful shutdown...')\n  isShuttingDown = true\n\n  \u002F\u002F Stop accepting new requests\n  server.close(async () => {\n    console.log('HTTP server closed')\n\n    try {\n      \u002F\u002F Drain active jobs\n      await jobQueue.close()\n\n      \u002F\u002F Close DB connections\n      await db.$disconnect()\n\n      \u002F\u002F Close Redis\n      await redis.quit()\n\n      console.log('Graceful shutdown complete')\n      process.exit(0)\n    } catch (err) {\n      console.error('Error during shutdown:', err)\n      process.exit(1)\n    }\n  })\n\n  \u002F\u002F Force kill after 30s if drain stalls\n  setTimeout(() => {\n    console.error('Graceful shutdown timed out, forcing exit')\n    process.exit(1)\n  }, 30_000)\n}\n\n\u002F\u002F Reject new requests during shutdown\napp.use((_req, res, next) => {\n  if (isShuttingDown) {\n    res.setHeader('Connection', 'close')\n    return res.status(503).json({ error: 'Server is shutting down' })\n  }\n  next()\n})\n\nprocess.on('SIGTERM', () => gracefulShutdown(server))\nprocess.on('SIGINT', () => gracefulShutdown(server))\n```\n\n## Idempotency Keys\n\n```typescript\n\u002F\u002F Safe to retry without double-charging \u002F double-creating\nasync function processPaymentIdempotent(\n  idempotencyKey: string,\n  payload: PaymentPayload\n): Promise\u003CPaymentResult> {\n  const lockKey = `idempotency:${idempotencyKey}`\n\n  \u002F\u002F Check if already processed\n  const existing = await redis.get(lockKey)\n  if (existing) {\n    return JSON.parse(existing) as PaymentResult\n  }\n\n  const result = await paymentGateway.charge(payload)\n\n  \u002F\u002F Store result for 24 hours\n  await redis.setex(lockKey, 86_400, JSON.stringify(result))\n\n  return result\n}\n\n\u002F\u002F Client sends Idempotency-Key header, retry safe\nrouter.post('\u002Fpayments', async (req, res) => {\n  const key = req.headers['idempotency-key'] as string\n  if (!key) return res.status(400).json({ error: 'Idempotency-Key header required' })\n\n  const result = await processPaymentIdempotent(key, req.body)\n  res.json({ success: true, data: result })\n})\n```\n\n**Remember**: Resilience is composed — combine circuit breaker + retry + bulkhead + timeout for defense in depth. Never apply retry without a circuit breaker, or you'll amplify load on a failing service.\n","# Resilience Patterns\n\nProduction-grade patterns for surviving failures without cascading.\n\n## Circuit Breaker\n\n```typescript\n\u002F\u002F States: CLOSED (normal) → OPEN (blocking) → HALF_OPEN (testing)\ntype CircuitState = 'CLOSED' | 'OPEN' | 'HALF_OPEN'\n\nclass CircuitBreaker {\n  private state: CircuitState = 'CLOSED'\n  private failureCount = 0\n  private lastFailureTime = 0\n  private successCount = 0\n\n  constructor(\n    private readonly failureThreshold = 5,\n    private readonly recoveryTimeout = 30_000,  \u002F\u002F ms\n    private readonly halfOpenMaxCalls = 3\n  ) {}\n\n  async call\u003CT>(fn: () => Promise\u003CT>): Promise\u003CT> {\n    if (this.state === 'OPEN') {\n      if (Date.now() - this.lastFailureTime > this.recoveryTimeout) {\n        this.state = 'HALF_OPEN'\n        this.successCount = 0\n      } else {\n        throw new Error('Circuit breaker is OPEN — request rejected')\n      }\n    }\n\n    try {\n      const result = await fn()\n      this.onSuccess()\n      return result\n    } catch (err) {\n      this.onFailure()\n      throw err\n    }\n  }\n\n  private onSuccess(): void {\n    if (this.state === 'HALF_OPEN') {\n      this.successCount++\n      if (this.successCount >= this.halfOpenMaxCalls) {\n        this.state = 'CLOSED'\n        this.failureCount = 0\n      }\n    } else {\n      this.failureCount = 0\n    }\n  }\n\n  private onFailure(): void {\n    this.failureCount++\n    this.lastFailureTime = Date.now()\n    if (this.failureCount >= this.failureThreshold) {\n      this.state = 'OPEN'\n    }\n  }\n\n  getState(): CircuitState { return this.state }\n}\n\n\u002F\u002F Usage with Opossum (production library)\n\u002F\u002F import CircuitBreaker from 'opossum'\n\u002F\u002F const breaker = new CircuitBreaker(riskyCall, { timeout: 3000, errorThresholdPercentage: 50 })\nconst paymentBreaker = new CircuitBreaker(5, 30_000)\n\nasync function chargeUser(userId: string, amount: number) {\n  return paymentBreaker.call(() => paymentService.charge(userId, amount))\n}\n```\n\n## Retry with Exponential Backoff + Jitter\n\n```typescript\ninterface RetryOptions {\n  maxAttempts?: number\n  baseDelayMs?: number\n  maxDelayMs?: number\n  jitter?: boolean\n  retryIf?: (error: unknown) => boolean\n}\n\nasync function withRetry\u003CT>(\n  fn: () => Promise\u003CT>,\n  options: RetryOptions = {}\n): Promise\u003CT> {\n  const {\n    maxAttempts = 3,\n    baseDelayMs = 500,\n    maxDelayMs = 15_000,\n    jitter = true,\n    retryIf = () => true\n  } = options\n\n  let lastError: unknown\n\n  for (let attempt = 1; attempt \u003C= maxAttempts; attempt++) {\n    try {\n      return await fn()\n    } catch (err) {\n      lastError = err\n\n      if (attempt === maxAttempts || !retryIf(err)) throw err\n\n      \u002F\u002F Exponential backoff: 500ms, 1s, 2s, 4s...\n      const base = Math.min(baseDelayMs * Math.pow(2, attempt - 1), maxDelayMs)\n      \u002F\u002F Full jitter: random between 0 and base (avoids synchronized retries)\n      const delay = jitter ? Math.random() * base : base\n\n      console.warn(`Attempt ${attempt}\u002F${maxAttempts} failed, retrying in ${Math.round(delay)}ms`)\n      await new Promise(resolve => setTimeout(resolve, delay))\n    }\n  }\n\n  throw lastError\n}\n\n\u002F\u002F Usage: only retry transient errors\nawait withRetry(\n  () => externalApi.fetchData(),\n  {\n    maxAttempts: 4,\n    retryIf: (err) => err instanceof NetworkError || (err as any)?.status >= 500\n  }\n)\n```\n\n## Bulkhead Pattern\n\n```typescript\n\u002F\u002F Isolate failure domains: separate thread pools \u002F queues per service\nclass Bulkhead {\n  private activeCount = 0\n  private queue: Array\u003C() => void> = []\n\n  constructor(\n    private maxConcurrent: number,\n    private maxQueueSize: number = 50\n  ) {}\n\n  async execute\u003CT>(fn: () => Promise\u003CT>): Promise\u003CT> {\n    if (this.activeCount >= this.maxConcurrent) {\n      if (this.queue.length >= this.maxQueueSize) {\n        throw new Error('Bulkhead queue full — request rejected')\n      }\n      await new Promise\u003Cvoid>((resolve, reject) => {\n        const timeout = setTimeout(\n          () => reject(new Error('Bulkhead queue timeout')),\n          5000\n        )\n        this.queue.push(() => { clearTimeout(timeout); resolve() })\n      })\n    }\n\n    this.activeCount++\n    try {\n      return await fn()\n    } finally {\n      this.activeCount--\n      if (this.queue.length > 0) {\n        const next = this.queue.shift()!\n        next()\n      }\n    }\n  }\n\n  getStats() {\n    return { activeCount: this.activeCount, queueLength: this.queue.length }\n  }\n}\n\n\u002F\u002F Separate bulkheads per downstream service\nconst paymentBulkhead = new Bulkhead(10, 20)\nconst emailBulkhead = new Bulkhead(5, 10)\nconst dbBulkhead = new Bulkhead(30, 100)\n```\n\n## Timeout Policies\n\n```typescript\n\u002F\u002F Never let a call hang indefinitely\nfunction withTimeout\u003CT>(\n  fn: () => Promise\u003CT>,\n  timeoutMs: number,\n  label = 'operation'\n): Promise\u003CT> {\n  return Promise.race([\n    fn(),\n    new Promise\u003Cnever>((_, reject) =>\n      setTimeout(\n        () => reject(new Error(`${label} timed out after ${timeoutMs}ms`)),\n        timeoutMs\n      )\n    )\n  ])\n}\n\n\u002F\u002F Connect timeout vs read timeout (different values)\nconst fetchWithTimeouts = async (url: string) => {\n  const controller = new AbortController()\n  const connectTimeout = setTimeout(() => controller.abort(), 2000)  \u002F\u002F connect: 2s\n\n  try {\n    const response = await fetch(url, { signal: controller.signal })\n    clearTimeout(connectTimeout)\n\n    \u002F\u002F Read timeout: 10s for body streaming\n    return await withTimeout(() => response.json(), 10_000, 'response body read')\n  } finally {\n    clearTimeout(connectTimeout)\n  }\n}\n```\n\n## Fallback Chain\n\n```typescript\nasync function getMarketData(id: string): Promise\u003CMarket> {\n  return withFallbacks([\n    { name: 'primary-db',   fn: () => primaryDb.market.findUnique({ where: { id } }) },\n    { name: 'redis-cache',  fn: () => redis.get(`market:${id}`).then(v => v ? JSON.parse(v) : null) },\n    { name: 'replica-db',   fn: () => replicaDb.market.findUnique({ where: { id } }) },\n    { name: 'stale-cache',  fn: () => staleCache.get(id) }\n  ])\n}\n\nasync function withFallbacks\u003CT>(\n  strategies: Array\u003C{ name: string; fn: () => Promise\u003CT | null> }>\n): Promise\u003CT> {\n  for (const { name, fn } of strategies) {\n    try {\n      const result = await fn()\n      if (result != null) return result\n    } catch (err) {\n      console.warn(`Strategy '${name}' failed:`, (err as Error).message)\n    }\n  }\n  throw new Error('All fallback strategies exhausted')\n}\n```\n\n## Health Check Endpoints\n\n```typescript\nimport express from 'express'\n\nconst app = express()\n\n\u002F\u002F Liveness: is the process alive? (k8s restarts if fails)\napp.get('\u002Flive', (_req, res) => {\n  res.json({ status: 'ok', timestamp: new Date().toISOString() })\n})\n\n\u002F\u002F Readiness: is the app ready to serve traffic? (k8s removes from LB if fails)\napp.get('\u002Fready', async (_req, res) => {\n  const checks = await Promise.allSettled([\n    checkDatabase(),\n    checkRedis(),\n    checkDependencies()\n  ])\n\n  const results = checks.map((c, i) => ({\n    name: ['database', 'redis', 'dependencies'][i],\n    status: c.status === 'fulfilled' ? 'ok' : 'fail',\n    error: c.status === 'rejected' ? (c.reason as Error).message : undefined\n  }))\n\n  const allHealthy = results.every(r => r.status === 'ok')\n  res.status(allHealthy ? 200 : 503).json({ status: allHealthy ? 'ready' : 'not-ready', checks: results })\n})\n\n\u002F\u002F Health: detailed diagnostics for ops team\napp.get('\u002Fhealth', async (_req, res) => {\n  const [dbMs, redisMs] = await Promise.all([pingDb(), pingRedis()])\n  res.json({\n    status: 'ok',\n    uptime: process.uptime(),\n    memory: process.memoryUsage(),\n    db: { latencyMs: dbMs },\n    redis: { latencyMs: redisMs }\n  })\n})\n\nasync function checkDatabase(): Promise\u003Cvoid> {\n  await db.$queryRaw`SELECT 1`\n}\n\nasync function checkRedis(): Promise\u003Cvoid> {\n  const pong = await redis.ping()\n  if (pong !== 'PONG') throw new Error('Redis ping failed')\n}\n```\n\n## Graceful Shutdown\n\n```typescript\n\u002F\u002F Handle SIGTERM (k8s, Docker stop) without dropping in-flight requests\nlet isShuttingDown = false\n\nasync function gracefulShutdown(server: http.Server): Promise\u003Cvoid> {\n  console.log('SIGTERM received, starting graceful shutdown...')\n  isShuttingDown = true\n\n  \u002F\u002F Stop accepting new requests\n  server.close(async () => {\n    console.log('HTTP server closed')\n\n    try {\n      \u002F\u002F Drain active jobs\n      await jobQueue.close()\n\n      \u002F\u002F Close DB connections\n      await db.$disconnect()\n\n      \u002F\u002F Close Redis\n      await redis.quit()\n\n      console.log('Graceful shutdown complete')\n      process.exit(0)\n    } catch (err) {\n      console.error('Error during shutdown:', err)\n      process.exit(1)\n    }\n  })\n\n  \u002F\u002F Force kill after 30s if drain stalls\n  setTimeout(() => {\n    console.error('Graceful shutdown timed out, forcing exit')\n    process.exit(1)\n  }, 30_000)\n}\n\n\u002F\u002F Reject new requests during shutdown\napp.use((_req, res, next) => {\n  if (isShuttingDown) {\n    res.setHeader('Connection', 'close')\n    return res.status(503).json({ error: 'Server is shutting down' })\n  }\n  next()\n})\n\nprocess.on('SIGTERM', () => gracefulShutdown(server))\nprocess.on('SIGINT', () => gracefulShutdown(server))\n```\n\n## Idempotency Keys\n\n```typescript\n\u002F\u002F Safe to retry without double-charging \u002F double-creating\nasync function processPaymentIdempotent(\n  idempotencyKey: string,\n  payload: PaymentPayload\n): Promise\u003CPaymentResult> {\n  const lockKey = `idempotency:${idempotencyKey}`\n\n  \u002F\u002F Check if already processed\n  const existing = await redis.get(lockKey)\n  if (existing) {\n    return JSON.parse(existing) as PaymentResult\n  }\n\n  const result = await paymentGateway.charge(payload)\n\n  \u002F\u002F Store result for 24 hours\n  await redis.setex(lockKey, 86_400, JSON.stringify(result))\n\n  return result\n}\n\n\u002F\u002F Client sends Idempotency-Key header, retry safe\nrouter.post('\u002Fpayments', async (req, res) => {\n  const key = req.headers['idempotency-key'] as string\n  if (!key) return res.status(400).json({ error: 'Idempotency-Key header required' })\n\n  const result = await processPaymentIdempotent(key, req.body)\n  res.json({ success: true, data: result })\n})\n```\n\n**Remember**: Resilience is composed — combine circuit breaker + retry + bulkhead + timeout for defense in depth. Never apply retry without a circuit breaker, or you'll amplify load on a failing service.\n",{"name":5,"description":7},"main","70e1c350500ee750987420bbae48837afa906b7e","skills\u002Fresilience-patterns","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis","https:\u002F\u002Fgithub.com\u002Frubicanjr","linktr.ee\u002Ffinanskodu","Industrial Engineer & CIO @FinansKodu. Architecting AI-driven financial agents and autonomous workflows. 🏗️ Building systems, not just prompts.","2026-06-09 13:50:15",{"source":8,"skillName":5,"commands":49,"prompt":59,"zipAvailable":60},[50,53,56],{"tool":51,"command":52},"npx","npx skills add rubicanjr\u002FFinCognis --skill resilience-patterns",{"tool":54,"command":55},"bunx","bunx skills add rubicanjr\u002FFinCognis --skill resilience-patterns",{"tool":57,"command":58},"pnpm","pnpm dlx skills add rubicanjr\u002FFinCognis --skill resilience-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fresilience-patterns\u002FSKILL.md",true,[],[63,79,88,104,129,148],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":35},"01M6NWS9DAXJTADT4T5MB49X8W","workflow-router","Goal-based workflow orchestration - routes tasks to specialist agents based on user goals","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fworkflow-router\u002FSKILL.md",[],[70,71,72,73,74,75,76,77,78],"workflow router","workflow","router","orchestration","goals","goal","user","workflow orchestration","tasks",{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":35},"01M6NWS3RETSC0SHP16HP66E14","wiring","Wiring Verification","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fwiring\u002FSKILL.md",[],[81,86,87],"verification","false",{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":35},"01M6NWS0XW9CVQZBDA1EGW0TWC","websocket-patterns","Connection management, room patterns, reconnection strategies, message buffering, and binary protocol design.","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fwebsocket-patterns\u002Fskill.md",[],[95,20,96,97,98,99,100,101,102,103],"websocket","websocket patterns","design","protocol","management","message","strategies","binary","connection",{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":35},"01M6NWRDQDX9ZNETAWRRMQWV52","visual-verdict","Screenshot comparison QA for frontend development. Takes a screenshot of the current implementation, scores it across multiple visual dimensions, and returns a structured PASS\u002FREVISE\u002FFAIL verdict with concrete fixes. Use when implementing UI from a design reference or verifying visual correctness.","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fvisual-verdict\u002FSKILL.md",[],[111,112,113,114,115,116,117,118,119,33,120,121,122,97,123,124,125,126,127,128],"visual","verdict","visual verdict","ui","across","revise","comparison","correctness","implementing","fixes","dimensions","frontend","development","qa","screenshot","returns","use","frontend development",{"skillNo":130,"name":131,"nameZh":6,"description":132,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":133,"categories":134,"keywords":135,"publishedAt":35},"01M6NWR8HSNRS7MNDK2J02QYMN","verification-loop","Comprehensive verification system covering build, types, lint, tests, security, and diff review before a PR.","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fverification-loop\u002FSKILL.md",[],[136,137,86,138,139,140,141,142,143,144,145,146,147],"verification loop","loop","lint","review","security","pr","system","diff","build","tests","diff review","types",{"skillNo":149,"name":150,"nameZh":6,"description":151,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":152,"categories":153,"keywords":154,"publishedAt":35},"01M6NWR4HHSFR0VR5EXFRWA747","vector-db-patterns","Embedding strategies, ANN algorithms, hybrid search, RAG chunking strategies, and reranking for semantic search and retrieval.","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fvector-db-patterns\u002Fskill.md",[],[155,156,157,158,20,159,160,161,162,101,163,164,165,166,167,33,168,169],"vector db patterns","vector db","db","vector","semantic search","search","embedding strategies","algorithms","chunking","semantic","retrieval","embedding","Hybrid Search","hybrid","rag"]