AgentSkillsCN

acc-create-rate-limiter

为 PHP 8.5 生成限流器模式。通过令牌桶、滑动窗口与固定窗口算法,实现请求限流,并附带单元测试。

SKILL.md
--- frontmatter
name: acc-create-rate-limiter
description: Generates Rate Limiter pattern for PHP 8.5. Creates request throttling with token bucket, sliding window, and fixed window algorithms. Includes unit tests.

Rate Limiter Generator

Creates Rate Limiter pattern infrastructure for request throttling and API protection.

When to Use

ScenarioExample
API protectionPrevent abuse
Resource throttlingDatabase connection limits
Fair usagePer-user request limits
Burst protectionSpike handling

Component Characteristics

RateLimiterInterface

  • Common interface for all algorithms
  • Check and consume methods
  • Remaining capacity queries

Algorithms

  • Token Bucket: Smooth rate limiting with burst capacity
  • Sliding Window: Time-based with sliding window log
  • Fixed Window: Simple time-based counter

RateLimitResult

  • Contains allowed/denied status
  • Provides retry-after information
  • Generates HTTP headers

Generation Process

Step 1: Generate Core Components

Path: src/Infrastructure/Resilience/RateLimiter/

  1. RateLimiterInterface.php — Common interface
  2. RateLimitResult.php — Result value object with headers
  3. RateLimitExceededException.php — Exception with retry info
  4. StorageInterface.php — Storage abstraction

Step 2: Choose and Generate Algorithm

Choose based on use case:

  1. TokenBucketRateLimiter.php — For APIs with burst allowance
  2. SlidingWindowRateLimiter.php — For strict per-time limits
  3. FixedWindowRateLimiter.php — For simple rate limiting

Step 3: Generate Storage

  1. RedisStorage.php — Production storage with TTL

Step 4: Generate Tests

  1. {Algorithm}RateLimiterTest.php — Algorithm tests
  2. RateLimitResultTest.php — Result value object tests

File Placement

ComponentPath
All Classessrc/Infrastructure/Resilience/RateLimiter/
Unit Teststests/Unit/Infrastructure/Resilience/RateLimiter/

Naming Conventions

ComponentPatternExample
InterfaceRateLimiterInterfaceRateLimiterInterface
Token BucketTokenBucketRateLimiterTokenBucketRateLimiter
Sliding WindowSlidingWindowRateLimiterSlidingWindowRateLimiter
Fixed WindowFixedWindowRateLimiterFixedWindowRateLimiter
ResultRateLimitResultRateLimitResult
ExceptionRateLimitExceededExceptionRateLimitExceededException
Test{ClassName}TestTokenBucketRateLimiterTest

Quick Template Reference

RateLimiterInterface

php
interface RateLimiterInterface
{
    public function attempt(string $key, int $tokens = 1): RateLimitResult;
    public function getRemainingTokens(string $key): int;
    public function getRetryAfter(string $key): ?int;
    public function reset(string $key): void;
}

RateLimitResult

php
final readonly class RateLimitResult
{
    public static function allowed(int $remaining, int $limit, \DateTimeImmutable $resetsAt): self;
    public static function denied(int $limit, int $retryAfter, \DateTimeImmutable $resetsAt): self;
    public function isAllowed(): bool;
    public function isDenied(): bool;
    public function toHeaders(): array; // X-RateLimit-* headers
}

Usage Example

php
// Create limiter
$limiter = new TokenBucketRateLimiter(
    capacity: 100,
    refillRate: 10.0, // 10 tokens per second
    clock: $clock,
    storage: new RedisStorage($redis)
);

// Check limit
$result = $limiter->attempt('user:123');

if ($result->isDenied()) {
    throw new RateLimitExceededException(
        key: 'user:123',
        limit: $result->limit,
        retryAfterSeconds: $result->retryAfterSeconds
    );
}

// Add headers to response
foreach ($result->toHeaders() as $name => $value) {
    $response = $response->withHeader($name, (string) $value);
}

Algorithm Comparison

AlgorithmBurst HandlingMemoryPrecisionUse Case
Token BucketGood (configurable)LowMediumAPIs with burst allowance
Sliding WindowLimitedHighHighStrict per-time limits
Fixed WindowPoor (boundary issues)LowLowSimple rate limiting

Anti-patterns to Avoid

Anti-patternProblemSolution
No Redis/Shared StoragePer-instance limitsUse shared storage
Missing HeadersClient can't adaptReturn X-RateLimit-* headers
Single AlgorithmDoesn't fit all casesChoose per use case
No Retry-AfterClient spamsAlways return retry timing
Synchronous BlockingThread blockingUse non-blocking check

References

For complete PHP templates and examples, see:

  • references/templates.md — All algorithm implementations
  • references/examples.md — Middleware example and tests