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
使用備援輪詢機制,偵測失敗的傳遞並確保不會錯過重要更新。
sequenceDiagram
box Services
participant OS as Order Service
participant PS as Payment Service
end
participant PSP as External PSP (Stripe...)
OS -->> PS: process
PS -->> PSP: call me back at http://example.webhook.com
PS -->> PS: Timeout: 7 sec
PS -->> PSP: Haven't heard back from you yet
2. Secure with Secrets and Tokens
驗證每個呼叫的簽名,確保是真正的使用者而非冒充者。
- 使用 HMAC 簽名驗證
- 檢查時間戳防止重放攻擊
- 使用 HTTPS 傳輸
3. Make Webhooks Idempotent
結果資料應包含唯一識別碼,確保重複處理不會產生副作用。
{
"event_id": "evt_123456789",
"type": "payment.completed",
"data": { ... }
}4. Handle Webhook Overload
使用佇列處理大量 webhook 請求,避免系統過載。
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...)
participant Qs as Queues
EcomW -->> Gate: Request
Gate -->> OS: process
OS -->> PS: process
PS -->> PSP: call me back at http://example.webhook.com
PSP -->> Qs: Result (Secured Message)
PSP -->> Qs: Result (Secured Message)
PSP -->> Qs: Result (Secured Message)
Qs -->> Gate: data
Qs -->> Gate: data
Comparison Summary
| 特性 | Short Polling | Long Polling | Webhooks |
|---|---|---|---|
| 即時性 | 低 | 中 | 高 |
| 伺服器負載 | 高 | 中 | 低 |
| 實作複雜度 | 低 | 中 | 高 |
| 適用場景 | 低頻更新 | 中頻更新 | 即時通知 |