Claude-skill-registry 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.

install
source · Clone the upstream repo
git clone https://github.com/majiayu000/claude-skill-registry
Claude Code · Install into ~/.claude/skills/
T=$(mktemp -d) && git clone --depth=1 https://github.com/majiayu000/claude-skill-registry "$T" && mkdir -p ~/.claude/skills && cp -r "$T/skills/data/acc-stability-patterns-knowledge" ~/.claude/skills/majiayu000-claude-skill-registry-acc-stability-patterns-knowledge && rm -rf "$T"
manifest: skills/data/acc-stability-patterns-knowledge/SKILL.md
source content

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

StateBehaviorTransitions To
ClosedRequests pass through, failures countedOpen (on threshold)
OpenRequests fail fast, no calls to serviceHalf-Open (after timeout)
Half-OpenLimited requests allowed for testingClosed (on success) / Open (on failure)

Retry Backoff Strategies

StrategyFormulaUse 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

AlgorithmPrecisionMemoryBurst Handling
Token BucketMediumLowAllows bursts
Sliding WindowHighMediumSmooth limiting
Fixed WindowLowLowEdge bursts
Leaky BucketHighLowNo bursts

Bulkhead Types

TypeIsolationUse Case
SemaphoreThread/request countSingle-process apps
Thread PoolDedicated threadsCPU-bound work
Queue-basedRequest queueAsync processing
DistributedRedis/shared stateMulti-instance apps

PHP Implementation Patterns

Circuit Breaker with PSR Clock

<?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

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

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

ViolationWhere to LookSeverity
No timeout on external callsHTTP clients, DB queriesCritical
Retry without backoffRetry implementationsWarning
No circuit breaker on external servicesAPI clients, adaptersCritical
Unbounded connection poolsDatabase, HTTP poolsWarning
No fallback strategyCircuit breaker usageWarning
Retry non-idempotent operationsCommand handlersCritical
Rate limiting only in-memoryMulti-instance appsWarning
No jitter in retryHigh-concurrency systemsWarning

Detection Patterns

# 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 TypeFailure ThresholdOpen TimeoutSuccess Threshold
Critical API3-530-60s3-5
Background Job5-1060-120s2-3
Internal Service3-515-30s2-3
Database2-310-20s1-2

Retry Configuration

Operation TypeMax AttemptsBase DelayMax Delay
HTTP API Call3100ms10s
Database Query350ms5s
Message Queue51s60s
File Operation210ms100ms

Rate Limiter Settings

Endpoint TypeRateWindowBurst
Public API100/min1 min20
Authenticated API1000/min1 min100
Admin API10000/min1 min1000
Webhook60/min1 min10

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