Webhooks
Webhooks はサーバーが能動的 に通知 をプッシュする仕組 み。ポーリング(Polling)と比較 して、イベント更新 を即時 に受信 できる。
Polling vs Webhooks

Short Polling
クライアントが定期的 にサーバーにリクエストを送信 し、更新 を確認 。
sequenceDiagram
box Services
participant OS as ...Service
participant PS as Payment Service
end
participant PSP as External PSP (Stripe...)
OS -->> PS: process
PS -->> PSP: Payment ready?
PSP -->> PS: not ready
PS -->> PSP: Payment ready?
PSP -->> PS: Yes!
欠点 :
過剰 リクエスト: 頻繁 な周期的 リクエストが不要 なサーバー負荷 とネットワークトラフィックを発生
**遅延 **: 更新 はポーリング間隔 でのみ受信
Long Polling
クライアントがリクエスト送信後 、サーバーは新 しいデータがあるかタイムアウトまで接続 を維持 。
sequenceDiagram
box Services
participant OS as ...Service
participant PS as Payment Service
end
participant PSP as External PSP (Stripe...)
OS -->> PS: process
PS -->>+ PSP: Payment ready?
PSP -> PSP: Connection Open - timeout: 10 sec
PSP -->>- PS: Yes
欠点 :
**リソース集約的 **: 長期 接続 の維持 がサーバーリソースを消費
**接続 中断 遅延 **: 接続 が切 れた場合 、再接続 に遅延 が発生
Webhooks
サーバーがイベント発生時 に能動的 にクライアントに通知 。
sequenceDiagram
participant EcomW as Ecommerce Website
participant Gate as API Gateway
box Services
participant OS as Order Service
participant PS as Payment Service
end
participant PSP as External PSP (Stripe...)
EcomW -->> Gate: Request
Gate -->> OS: process
OS -->> PS: process
PS -->> PSP: call me back at http://example.webhook.com
PSP -->> Gate: Result
Webhooks ベストプラクティス
1. Fallback Polling Mechanism
失敗 した配信 を検出 し、重要 な更新 を見逃 さないようにバックアップポーリングを使用 。
2. Secure with Secrets and Tokens
各 呼 び出 しの署名 を検証 し、本物 のユーザーであることを確認 。
3. Make Webhooks Idempotent
結果 データには一意 の識別子 を含 め、重複 処理 で副作用 が発生 しないようにする。
4. Handle Webhook Overload
キューを使用 して大量 の webhook リクエストを処理 し、システム過負荷 を回避 。
Comparison Summary
| 特性 | Short Polling | Long Polling | Webhooks |
|---|---|---|---|
| 即時性 | 低 | 中 | 高 |
| サーバー負荷 | 高 | 中 | 低 |
| 実装 複雑度 | 低 | 中 | 高 |
| 適用 シナリオ | 低頻度 更新 | 中頻度 更新 | 即時 通知 |