acc-stability-patterns-knowledge

Stability Patterns knowledge base. Provides patterns, antipatterns, and PHP-specific guidelines for Circuit Breaker, Retry, Rate Limiter, Bulkhead, and resilience audits.

181 stars

Best use case

acc-stability-patterns-knowledge is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Stability Patterns knowledge base. Provides patterns, antipatterns, and PHP-specific guidelines for Circuit Breaker, Retry, Rate Limiter, Bulkhead, and resilience audits.

Teams using acc-stability-patterns-knowledge 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

$curl -o ~/.claude/skills/acc-stability-patterns-knowledge/SKILL.md --create-dirs "https://raw.githubusercontent.com/majiayu000/claude-skill-registry/main/skills/data/acc-stability-patterns-knowledge/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/acc-stability-patterns-knowledge/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How acc-stability-patterns-knowledge Compares

Feature / Agentacc-stability-patterns-knowledgeStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Stability Patterns knowledge base. Provides patterns, antipatterns, and PHP-specific guidelines for Circuit Breaker, Retry, Rate Limiter, Bulkhead, and resilience audits.

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.

SKILL.md Source

# Stability Patterns Knowledge Base

Quick reference for resilience and fault tolerance patterns in PHP applications.

## Core Patterns Overview

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                        STABILITY PATTERNS                                    │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│   ┌────────────────────────────────────────────────────────────────────┐    │
│   │                      REQUEST FLOW                                   │    │
│   │                                                                     │    │
│   │   Client  ──▶  Rate Limiter  ──▶  Circuit Breaker  ──▶  Service   │    │
│   │      │              │                   │                  │        │    │
│   │      │         Throttle            Monitor State       Actual      │    │
│   │      │         requests            Open/Closed         work        │    │
│   │      │              │                   │                  │        │    │
│   │      │              ▼                   ▼                  ▼        │    │
│   │      │         ┌────────┐          ┌────────┐         ┌────────┐   │    │
│   │      │         │Bulkhead│          │ Retry  │         │Timeout │   │    │
│   │      │         │Isolate │          │Pattern │         │Control │   │    │
│   │      │         └────────┘          └────────┘         └────────┘   │    │
│   └────────────────────────────────────────────────────────────────────┘    │
│                                                                              │
├─────────────────────────────────────────────────────────────────────────────┤
│   Pattern          │ Purpose                    │ Protects Against           │
│   ─────────────────┼────────────────────────────┼─────────────────────────── │
│   Rate Limiter     │ Throttle request rate      │ DDoS, overload, abuse     │
│   Circuit Breaker  │ Fail fast on failures      │ Cascading failures        │
│   Retry            │ Retry transient failures   │ Temporary outages         │
│   Bulkhead         │ Isolate resources          │ Resource exhaustion       │
│   Timeout          │ Limit wait time            │ Slow dependencies         │
└─────────────────────────────────────────────────────────────────────────────┘
```

## Pattern Relationships

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                    PATTERN INTERACTION                                       │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│                         ┌────────────────────┐                               │
│                         │   Rate Limiter     │                               │
│                         │  (Entry Point)     │                               │
│                         └─────────┬──────────┘                               │
│                                   │                                          │
│                                   ▼                                          │
│                         ┌────────────────────┐                               │
│                         │     Bulkhead       │                               │
│                         │ (Resource Limits)  │                               │
│                         └─────────┬──────────┘                               │
│                                   │                                          │
│           ┌───────────────────────┼───────────────────────┐                  │
│           │                       │                       │                  │
│           ▼                       ▼                       ▼                  │
│   ┌──────────────┐       ┌──────────────┐        ┌──────────────┐           │
│   │   Service A  │       │   Service B  │        │   Service C  │           │
│   │  ┌────────┐  │       │  ┌────────┐  │        │  ┌────────┐  │           │
│   │  │Circuit │  │       │  │Circuit │  │        │  │Circuit │  │           │
│   │  │Breaker │  │       │  │Breaker │  │        │  │Breaker │  │           │
│   │  └───┬────┘  │       │  └───┬────┘  │        │  └───┬────┘  │           │
│   │      │       │       │      │       │        │      │       │           │
│   │  ┌───▼────┐  │       │  ┌───▼────┐  │        │  ┌───▼────┐  │           │
│   │  │ Retry  │  │       │  │ Retry  │  │        │  │ Retry  │  │           │
│   │  │Pattern │  │       │  │Pattern │  │        │  │Pattern │  │           │
│   │  └────────┘  │       │  └────────┘  │        │  └────────┘  │           │
│   └──────────────┘       └──────────────┘        └──────────────┘           │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘
```

## Quick Reference

### Circuit Breaker States

| State | Behavior | Transitions To |
|-------|----------|----------------|
| **Closed** | Requests pass through, failures counted | Open (on threshold) |
| **Open** | Requests fail fast, no calls to service | Half-Open (after timeout) |
| **Half-Open** | Limited requests allowed for testing | Closed (on success) / Open (on failure) |

### Retry Backoff Strategies

| Strategy | Formula | Use Case |
|----------|---------|----------|
| **Fixed** | `delay` | Simple cases, known recovery time |
| **Linear** | `delay * attempt` | Gradual increase |
| **Exponential** | `delay * 2^(attempt-1)` | Unknown recovery, default choice |
| **Exponential + Jitter** | `exponential ± random` | High concurrency, prevents thundering herd |

### Rate Limiter Algorithms

| Algorithm | Precision | Memory | Burst Handling |
|-----------|-----------|--------|----------------|
| **Token Bucket** | Medium | Low | Allows bursts |
| **Sliding Window** | High | Medium | Smooth limiting |
| **Fixed Window** | Low | Low | Edge bursts |
| **Leaky Bucket** | High | Low | No bursts |

### Bulkhead Types

| Type | Isolation | Use Case |
|------|-----------|----------|
| **Semaphore** | Thread/request count | Single-process apps |
| **Thread Pool** | Dedicated threads | CPU-bound work |
| **Queue-based** | Request queue | Async processing |
| **Distributed** | Redis/shared state | Multi-instance apps |

## PHP Implementation Patterns

### Circuit Breaker with PSR Clock

```php
<?php

declare(strict_types=1);

namespace Infrastructure\Resilience;

use Psr\Clock\ClockInterface;

final class CircuitBreaker
{
    private CircuitState $state = CircuitState::Closed;
    private int $failures = 0;
    private ?\DateTimeImmutable $openedAt = null;

    public function __construct(
        private readonly string $name,
        private readonly int $failureThreshold,
        private readonly int $openTimeoutSeconds,
        private readonly ClockInterface $clock
    ) {}

    public function execute(callable $operation, ?callable $fallback = null): mixed
    {
        if (!$this->isAvailable()) {
            return $fallback ? $fallback() : throw new CircuitOpenException($this->name);
        }

        try {
            $result = $operation();
            $this->recordSuccess();
            return $result;
        } catch (\Throwable $e) {
            $this->recordFailure();
            throw $e;
        }
    }

    private function isAvailable(): bool
    {
        if ($this->state === CircuitState::Closed) return true;
        if ($this->state === CircuitState::Open) {
            if ($this->hasTimeoutElapsed()) {
                $this->state = CircuitState::HalfOpen;
                return true;
            }
            return false;
        }
        return true;
    }
}
```

### Retry with Exponential Backoff

```php
<?php

declare(strict_types=1);

namespace Infrastructure\Resilience;

final readonly class RetryExecutor
{
    public function execute(
        callable $operation,
        int $maxAttempts = 3,
        int $baseDelayMs = 100
    ): mixed {
        $attempt = 0;
        $lastException = null;

        while ($attempt < $maxAttempts) {
            try {
                return $operation();
            } catch (\Throwable $e) {
                $lastException = $e;
                $attempt++;

                if ($attempt < $maxAttempts) {
                    $delay = $baseDelayMs * (2 ** ($attempt - 1));
                    $jitter = random_int(0, (int)($delay * 0.3));
                    usleep(($delay + $jitter) * 1000);
                }
            }
        }

        throw $lastException;
    }
}
```

### Token Bucket Rate Limiter

```php
<?php

declare(strict_types=1);

namespace Infrastructure\Resilience;

final class TokenBucketRateLimiter
{
    private float $tokens;
    private int $lastRefill;

    public function __construct(
        private readonly int $capacity,
        private readonly float $refillRate,
        private readonly \Redis $redis,
        private readonly string $key
    ) {
        $this->tokens = $capacity;
        $this->lastRefill = time();
    }

    public function attempt(): bool
    {
        $this->refill();

        if ($this->tokens >= 1) {
            $this->tokens--;
            return true;
        }

        return false;
    }

    private function refill(): void
    {
        $now = time();
        $elapsed = $now - $this->lastRefill;
        $this->tokens = min(
            $this->capacity,
            $this->tokens + ($elapsed * $this->refillRate)
        );
        $this->lastRefill = $now;
    }
}
```

## Common Violations Quick Reference

| Violation | Where to Look | Severity |
|-----------|---------------|----------|
| No timeout on external calls | HTTP clients, DB queries | Critical |
| Retry without backoff | Retry implementations | Warning |
| No circuit breaker on external services | API clients, adapters | Critical |
| Unbounded connection pools | Database, HTTP pools | Warning |
| No fallback strategy | Circuit breaker usage | Warning |
| Retry non-idempotent operations | Command handlers | Critical |
| Rate limiting only in-memory | Multi-instance apps | Warning |
| No jitter in retry | High-concurrency systems | Warning |

## Detection Patterns

```bash
# Find resilience implementations
Glob: **/Resilience/**/*.php
Glob: **/CircuitBreaker/**/*.php
Grep: "CircuitBreaker|RateLimiter|Retry" --glob "**/*.php"

# Check for proper timeout usage
Grep: "CURLOPT_TIMEOUT|timeout|setTimeout" --glob "**/Http/**/*.php"

# Detect retry patterns
Grep: "retry|backoff|exponential" --glob "**/*.php"

# Find rate limiting
Grep: "RateLimiter|throttle|TokenBucket" --glob "**/*.php"

# Check for bulkhead patterns
Grep: "Semaphore|Bulkhead|maxConcurrent" --glob "**/*.php"

# Detect missing patterns
Grep: "->request\(|curl_exec|file_get_contents" --glob "**/Infrastructure/**/*.php"
```

## Configuration Guidelines

### Circuit Breaker Settings

| Service Type | Failure Threshold | Open Timeout | Success Threshold |
|--------------|-------------------|--------------|-------------------|
| Critical API | 3-5 | 30-60s | 3-5 |
| Background Job | 5-10 | 60-120s | 2-3 |
| Internal Service | 3-5 | 15-30s | 2-3 |
| Database | 2-3 | 10-20s | 1-2 |

### Retry Configuration

| Operation Type | Max Attempts | Base Delay | Max Delay |
|----------------|--------------|------------|-----------|
| HTTP API Call | 3 | 100ms | 10s |
| Database Query | 3 | 50ms | 5s |
| Message Queue | 5 | 1s | 60s |
| File Operation | 2 | 10ms | 100ms |

### Rate Limiter Settings

| Endpoint Type | Rate | Window | Burst |
|---------------|------|--------|-------|
| Public API | 100/min | 1 min | 20 |
| Authenticated API | 1000/min | 1 min | 100 |
| Admin API | 10000/min | 1 min | 1000 |
| Webhook | 60/min | 1 min | 10 |

## Integration Points

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                    INFRASTRUCTURE LAYER                                      │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│   src/Infrastructure/                                                        │
│   ├── Resilience/                                                           │
│   │   ├── CircuitBreaker/                                                   │
│   │   │   ├── CircuitBreaker.php                                           │
│   │   │   ├── CircuitBreakerConfig.php                                     │
│   │   │   ├── CircuitBreakerRegistry.php                                   │
│   │   │   └── CircuitState.php                                             │
│   │   ├── Retry/                                                            │
│   │   │   ├── RetryExecutor.php                                            │
│   │   │   ├── RetryPolicy.php                                              │
│   │   │   └── BackoffStrategy.php                                          │
│   │   ├── RateLimiter/                                                      │
│   │   │   ├── RateLimiterInterface.php                                     │
│   │   │   ├── TokenBucketRateLimiter.php                                   │
│   │   │   └── SlidingWindowRateLimiter.php                                 │
│   │   └── Bulkhead/                                                         │
│   │       ├── BulkheadInterface.php                                        │
│   │       ├── SemaphoreBulkhead.php                                        │
│   │       └── BulkheadRegistry.php                                         │
│   │                                                                         │
│   ├── Http/                                                                  │
│   │   ├── ResilientHttpClient.php    ◀── Uses CircuitBreaker + Retry       │
│   │   └── Middleware/                                                       │
│   │       └── RateLimitMiddleware.php                                       │
│   │                                                                         │
│   └── Payment/                                                               │
│       └── PaymentGatewayAdapter.php  ◀── Uses CircuitBreaker + Bulkhead    │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘
```

## References

For detailed information, load these reference files:

- `references/circuit-breaker.md` — Circuit Breaker implementation details
- `references/retry-patterns.md` — Retry strategies and backoff algorithms
- `references/rate-limiting.md` — Rate limiting algorithms and configurations
- `references/bulkhead.md` — Bulkhead isolation patterns

## Assets

- `assets/report-template.md` — Structured audit report template

Related Skills

advanced-patterns

181
from majiayu000/claude-skill-registry

Advanced T-SQL patterns and techniques for SQL Server. Use this skill when: (1) User needs help with CTEs or recursive queries, (2) User asks about APPLY operator, (3) User wants MERGE or OUTPUT clause help, (4) User works with temporal tables, (5) User needs In-Memory OLTP guidance, (6) User asks about advanced grouping (ROLLUP, CUBE, GROUPING SETS).

advanced-js-mocking-patterns

181
from majiayu000/claude-skill-registry

Advanced mocking patterns for Jest and Vitest including module mocking, spies, and fake timers. PROACTIVELY activate for: (1) Module mocking, (2) Partial mocking with spies, (3) Mock lifecycle management, (4) Fake timers for time-dependent code, (5) Complex mock implementations. Triggers: "jest.mock", "vi.mock", "spyOn", "fakeTimers", "mockImplementation", "mockReturnValue", "mock lifecycle"

Advanced GetX Patterns

181
from majiayu000/claude-skill-registry

Advanced GetX features including Workers, GetxService, SmartManagement, GetConnect, GetSocket, bindings composition, and testing patterns

adr-knowledge-base

181
from majiayu000/claude-skill-registry

ADR知見の体系的参照・適用。主要ADR抜粋(ADR_010, 013, 016, 019, 020, 021)・ADR検索・参照方法・技術決定パターン集・ADR作成判断基準。Phase C以降の技術決定時に使用。

add-knowledge

181
from majiayu000/claude-skill-registry

Add notes and learnings to Tim's work knowledge base at Spotify from any Claude Code session

patterns/adapter

181
from majiayu000/claude-skill-registry

Adapter (Wrapper) Pattern pattern for C development

ActiveRecord Query Patterns

181
from majiayu000/claude-skill-registry

Complete guide to ActiveRecord query optimization, associations, scopes, and PostgreSQL-specific patterns. Use this skill when writing database queries, designing model associations, creating migrations, optimizing query performance, or debugging N+1 queries and grouping errors.

Action Cable & WebSocket Patterns

181
from majiayu000/claude-skill-registry

Real-time WebSocket features with Action Cable in Rails. Use when: (1) Building real-time chat, (2) Live notifications/presence, (3) Broadcasting model updates, (4) WebSocket authorization. Trigger keywords: Action Cable, WebSocket, real-time, channels, broadcasting, stream, subscriptions, presence, cable

accessibility-patterns

181
from majiayu000/claude-skill-registry

Build inclusive web experiences following WCAG guidelines. Covers semantic HTML, ARIA, keyboard navigation, color contrast, and testing strategies. Triggers on accessibility, a11y, WCAG, screen readers, or inclusive design requests.

access-control-patterns

181
from majiayu000/claude-skill-registry

[STUB - Not implemented] Access control auditing with IDOR detection, RBAC/ABAC patterns, and privilege escalation prevention. PROACTIVELY activate for: [TODO: Define on implementation]. Triggers: [TODO: Define on implementation]

acc-testing-knowledge

181
from majiayu000/claude-skill-registry

Testing knowledge base for PHP 8.5 projects. Provides testing pyramid, AAA pattern, naming conventions, isolation principles, DDD testing guidelines, and PHPUnit patterns.

acc-solid-knowledge

181
from majiayu000/claude-skill-registry

SOLID principles knowledge base for PHP 8.5 projects. Provides quick reference for SRP, OCP, LSP, ISP, DIP with detection patterns, PHP examples, and antipattern identification. Use for architecture audits and code quality reviews.