跳到正文
cccskills
免费在 GitHub 公开

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.

中文简介正在准备中。当前显示原文说明。

集成工具Redis
查看安装方法

包含的文件(1)

  • SKILL.md18.5 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

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
FixeddelaySimple cases, known recovery time
Lineardelay * attemptGradual increase
Exponentialdelay * 2^(attempt-1)Unknown recovery, default choice
Exponential + Jitterexponential ± randomHigh 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

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

Master backend architectures, REST API design, microservices, and server-side development across multiple languages. Use this as a central index to access specialized sub-skills.

中文简介正在准备中。当前显示原文说明。

MikeCheng1208/BattleTree22026年7月22日 更新

在每次回复中使用固定前缀并列出本次实际参考的指令/文件,便于校验是否遵循上下文与规则。

中文简介正在准备中。当前显示原文说明。

MikeCheng1208/BattleTree22026年7月22日 更新

Automate 21risk tasks via Rube MCP (Composio). Always search tools first for current schemas.

中文简介正在准备中。当前显示原文说明。

MikeCheng1208/BattleTree22026年7月22日 更新

Automate 2chat tasks via Rube MCP (Composio). Always search tools first for current schemas.

中文简介正在准备中。当前显示原文说明。

MikeCheng1208/BattleTree22026年7月22日 更新

Arquitecto de Soluciones Principal y Consultor Tecnológico de Andru.ia. Diagnostica y traza la hoja de ruta óptima para proyectos de IA en español.

中文简介正在准备中。当前显示原文说明。

MikeCheng1208/BattleTree22026年7月22日 更新

[00] META. Orchestrate skills into dynamic chains for complex tasks. Analyzes the task, discovers available skills, builds an optimal chain, explains why each skill is needed, and executes step-by-step with user confirmation. Use for any complex task requiring multiple thinking/research/analysis steps. Triggers on "plan this", "how to approach", "what's the strategy", "build a plan", or any multi-step problem requiring skill orchestration.

中文简介正在准备中。当前显示原文说明。

MikeCheng1208/BattleTree22026年7月22日 更新

查看 MikeCheng1208 的全部技能

报告此技能的问题