0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHP 8.2+ で作るレジリエンスパイプライン ─ Aegis v0.0.1 を公開しました

0
Last updated at Posted at 2026-04-30

はじめに

PHPで外部 API や DB を呼び出すコードを書いていると、以下の事象に遭遇する方は多いのではないでしょうか。

  • ネットワークの瞬断で 1 回だけ失敗する → リトライしたい
  • 障害中のサービスを叩き続けて自分まで巻き添えになる → サーキットブレーカーで遮断したい
  • 処理が返ってこなくなる → タイムアウトを設けたい
  • API の呼び出し制限を超える → レートリミッターを入れたい
  • 高負荷時にリソースを使い果たす → 同時実行数を絞りたい

Java エコシステムには Resilience4j、.NET には Polly という成熟したライブラリがあります。しかし PHP には、これらをコンポーザブルなパイプラインとして組み合わせられる同等ライブラリがありませんでした。

そこで作ったのが Aegis です。

Aegis とは

Aegis は PHP 8.2+ 向けのレジリエンスライブラリです。Retry・Circuit Breaker・Adaptive Circuit Breaker・Timeout・Rate Limiter(3 種)・Bulkhead・Fallback・Cache・Hedge の 11 戦略を、ビルダーパターンで自由に組み合わせられます。

$pipeline = ResiliencePipeline::builder()
    ->circuitBreaker('payment-api', failureThreshold: 5)
    ->retry(maxAttempts: 3)
    ->timeout(Duration::seconds(5))
    ->fallback(fn(\Throwable $e) => ['status' => 'unavailable'])
    ->build();

$result = $pipeline->execute(fn() => $httpClient->post('/charge', $payload));

既存ライブラリとの比較

ライブラリ Retry CB Timeout Rate Limiter Bulkhead Fallback 合成可能 PHP 8.2+
ackintosh/ganesha ✗ ✅ ✗ ✗ ✗ ✗ ✗ ✅
cline/retry ✅ ✗ ✗ ✗ ✗ ✗ ✗ ✅
Aegis ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅

インストール

composer require kissmint3395/aegis

要件:

  • PHP 8.2+
  • psr/event-dispatcher ^1.0
  • psr/simple-cache ^3.0(任意。状態の永続化に使用)

30 秒で動かす

まずはリトライだけ。これが Aegis の最小構成です。

use Aegis\ResiliencePipeline;

$pipeline = ResiliencePipeline::builder()
    ->retry(maxAttempts: 3)
    ->build();

// 失敗したら最大 3 回まで自動リトライ
$result = $pipeline->execute(fn() => $api->fetch('/users'));

各戦略の解説

Retry(リトライ)

一時的な障害に対して、バックオフ付きで再試行します。

use Aegis\Backoff\ExponentialBackoff;
use Aegis\Duration;

$pipeline = ResiliencePipeline::builder()
    ->retry(
        maxAttempts: 3,
        // 100ms → 200ms → 400ms とジッター付きで増加
        backoff: ExponentialBackoff::withJitter(
            Duration::milliseconds(100),
            maxDelay: Duration::seconds(5),
        ),
        retryOn: [\RuntimeException::class],
    )
    ->build();

HTTP ステータスコードで条件を絞ることもできます。

->retry(
    retryIf: fn(\Throwable $e) => $e->getCode() >= 500,
)

全リトライが失敗すると RetryExhaustedException がスローされ、getPrevious() で最後の原因を取得できます。


Circuit Breaker(サーキットブレーカー)

連続失敗が閾値を超えたら回路を「開いて」以降の呼び出しを即座にブロック。障害サービスへの連続アクセスを防ぎます。

$pipeline = ResiliencePipeline::builder()
    ->circuitBreaker(
        name: 'inventory-api',
        failureThreshold: 5,           // 5 回連続失敗でオープン
        successThreshold: 2,           // HalfOpen で 2 回成功でクローズ
        resetAfter: Duration::seconds(30),
    )
    ->build();
Closed ──(5回失敗)──► Open ──(30秒経過)──► HalfOpen
  ▲                                                │
  └──────────(2回成功)────────────────────────────┘
                              (1回失敗)──► Open

複数の PHP-FPM ワーカーで状態を共有したい場合は PSR-16 対応のストレージを使います。

use Aegis\Strategy\CircuitBreaker\Storage\Psr16Storage;

->circuitBreaker('api', storage: new Psr16Storage($redisCache))

Adaptive Circuit Breaker(アダプティブ サーキットブレーカー)

連続失敗数ではなく「直近 N 件中の失敗率(%)」でサーキットを制御する方式です。Resilience4j の sliding-window 相当。

$pipeline = ResiliencePipeline::builder()
    ->adaptiveCircuitBreaker(
        name: 'payment-api',
        windowSize: 20,              // 直近 20 件を評価
        failureRateThreshold: 50.0,  // 50% 以上失敗でオープン
        minimumCalls: 5,             // 5 件未満は評価しない(起動直後の誤トリップを防ぐ)
    )
    ->build();

散発的な失敗にも反応できるため、通常の CB より高トラフィック環境に向いています。


Timeout(タイムアウト)

->timeout(Duration::seconds(5))

Unix 環境(pcntl 拡張あり)では SIGALRM によるプリエンプティブ割り込みを行います。Windows や pcntl なし環境では実行後に経過時間をチェックする方式にフォールバックします(Retry の合計時間制限として機能します)。


Rate Limiter(レートリミッター)3 種

Aegis は 3 つのアルゴリズムを提供しています。

方式 特徴 向いているケース
Fixed Window シンプル。ウィンドウ境界でバースト可能性あり 厳密さより実装コストを優先したい場合
Sliding Window タイムスタンプを記録し境界バーストを防ぐ 公平なレート制限が必要な場合
Token Bucket バーストを許容しつつ平均レートを制御 API クォータ管理・突発トラフィックを許容したい場合
// Fixed Window: 60 秒に 100 回まで
->rateLimit('api', limit: 100, window: Duration::seconds(60))

// Sliding Window: 同じ設定でもバースト問題なし
->slidingRateLimit('api', limit: 100, window: Duration::seconds(60))

// Token Bucket: バースト 20 件許容、1 秒ごとに 10 トークン補充
->tokenBucketRateLimit(
    name: 'api',
    capacity: 20,
    refillRate: 10,
    refillPeriod: Duration::seconds(1),
)

Bulkhead(バルクヘッド)

同時実行数を制限してリソース枯渇を防ぎます。艦船の隔壁(bulkhead)が浸水を区画に封じ込めるように、一部の過負荷が全体に波及しないようにします。

$pipeline = ResiliencePipeline::builder()
    ->bulkhead(
        name: 'slow-external-api',
        maxConcurrent: 10,    // 最大 10 並行まで許可
    )
    ->build();

上限を超えた呼び出しは即座に BulkheadFullException を返します(キューイングはしません)。


Fallback(フォールバック)

すべての戦略が失敗したとき、代替値を返す最後の砦です。

$pipeline = ResiliencePipeline::builder()
    ->circuitBreaker('recommendation-api')
    ->retry(maxAttempts: 3)
    ->fallback(fn(\Throwable $e) => $this->getDefaultRecommendations())
    ->build();

フォールバック自体が例外をスローした場合は FallbackNotAvailableException がスローされ、getOriginalException() で元の原因を参照できます。


Cache(キャッシュ)

成功したレスポンスをキャッシュし、TTL 内は $next() の呼び出しをスキップします。staleOnFailure: true を設定すると、ダウンストリームが失敗した際に期限切れのキャッシュを返します。

use Aegis\Strategy\Cache\Storage\CacheInMemoryStorage;

$pipeline = ResiliencePipeline::builder()
    ->cache(
        name: 'product-list',
        ttl: Duration::minutes(5),
        staleOnFailure: true,   // 障害時は古いキャッシュを返す
        storage: new CacheInMemoryStorage(),
    )
    ->build();

Hedge(ヘッジ)— 実験的

「テールレイテンシー」対策です。一定時間内に応答がない場合、別のリクエストを投げて先に成功した方を採用します。

->hedge(
    delay: Duration::milliseconds(200),
    maxHedges: 1,
)

PHP で真のレイテンシーヘッジを実現するには Fiber::suspend() を使う非同期フレームワーク(ReactPHP / Swoole)が必要です。同期 callable の場合、ヘッジは各失敗後に即発火します。

戦略の合成と推奨順序

複数の戦略を組み合わせるとき、外側(先に追加)ほどコストの高い処理をガードするのが基本です。

$pipeline = ResiliencePipeline::builder()
    ->bulkhead('svc', maxConcurrent: 10)            // 1. 同時実行数ゲート(最も外側)
    ->rateLimit('svc', limit: 100)                  // 2. レートゲート
    ->timeout(Duration::seconds(10))                // 3. 全体の時間予算
    ->circuitBreaker('svc', failureThreshold: 5)    // 4. 不健全なら即ブロック
    ->retry(maxAttempts: 3)                         // 5. 一時的失敗をリトライ
    ->fallback(fn() => $defaultValue)               // 6. 最終手段(最も内側)
    ->build();

execute() が呼ばれると、各戦略が Bulkhead → Rate Limiter → Timeout → Circuit Breaker → Retry → Fallback の順に外側から適用されます。

PSR-14 イベント連携

withEventDispatcher() を使うと、パイプライン内部の動作を PSR-14 イベントで観測できます。

use Aegis\Event\RetryAttempted;
use Aegis\Event\CircuitOpened;

$pipeline = ResiliencePipeline::builder()
    ->withEventDispatcher($dispatcher)
    ->circuitBreaker('api')
    ->retry(maxAttempts: 3)
    ->build();

// Monolog への接続例(PSR-14 実装によりリスナー登録 API は異なります)
$dispatcher->listen(RetryAttempted::class, function (RetryAttempted $e) use ($logger): void {
    $logger->warning('Retrying...', [
        'attempt'  => $e->attempt,
        'max'      => $e->maxAttempts,
        'delay_ms' => $e->delayMs,
        'error'    => $e->cause->getMessage(),
    ]);
});

$dispatcher->listen(CircuitOpened::class, function (CircuitOpened $e) use ($logger): void {
    $logger->critical("Circuit opened: {$e->name}");
});

提供イベント一覧:

イベント 発火タイミング
RetryAttempted リトライ待機前
CircuitOpened Closed → Open
CircuitClosed HalfOpen → Closed
CircuitHalfOpened Open → HalfOpen
RateLimitExceeded レート制限に達したとき
BulkheadRejected バルクヘッドが満杯のとき
TokenBucketExhausted トークンバケットが空のとき

品質

  • PHPStan level 8(0〜9 中)でエラーゼロ
  • 63 テスト / 287 アサーション — すべてグリーン
  • GitHub Actions CI で PHP 8.2 / 8.3 / 8.4 のマトリクステスト
strategy:
  matrix:
    php: ["8.2", "8.3", "8.4"]

おわりに

Aegis は MIT ライセンスで公開しています。

今後のロードマップ:

  • PHPStan 2.x 対応
  • 統合 StorageInterface(CB / RateLimiter / Bulkhead のストレージを共通化)
  • OpenTelemetry アダプター

バグ報告・機能提案・PR はいずれも歓迎です。Issue でお気軽にどうぞ。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?