Develop a rate-limited webhook delivery service layering exponential backoff, dead…
- User
Develop a rate-limited webhook delivery service layering exponential backoff, dead letter queues, and observability.
Assistant
Develop a rate-limited webhook delivery service layering exponential backoff, dead letter queues, and observability.
The user wants a design and implementation for a rate-limited webhook delivery service. Key features required:
1. High-Level Architecture:
I need to define the components and the data flow.
429 (Too Many Requests), 5xx server errors, and timeouts using exponential backoff.2. Detailed Component Design:
Data Structure (The Webhook Task):
id: UUIDurl: Target URLpayload: JSON bodyheaders: Auth headers, etc.attempts: Count of retries.next_attempt_at: Timestamp for scheduled retry (if using a delayed queue).Rate Limiting Strategy:
example.com).Exponential Backoff Strategy:
min(cap, base * 2 ^ attempt). Jitter is crucial to prevent thundering herds.Dead Letter Queue (DLQ):
attempts > max_retries (e.g., 5), move to DLQ.3. Technology Stack Selection:
golang.org/x/time/rate (Limiter).net/http with timeouts.4. Implementation Structure (Go):
Webhook, Service.5. Refining the Observability:
webhooks_sent_total{status="success|failed|retry"}webhooks_latency_secondswebhooks_rate_limit_hits6. Drafting the Code (Mental Draft & Refinement):
time.Sleep in a goroutine is bad for production (process restart loses data). A "Visibility Timeout" or "Delayed Queue" is better. For this prompt, I will implement a simplified version where the worker calculates the delay and pushes it to a "Delayed Queue" abstraction, or if running locally, sleeps (but note the caveat). Better approach: Use a sorted set (ZSET) in Redis where the score is the execution timestamp. Let's write a mock queue interface to keep the code dependency-light but conceptually correct.7. Step-by-Step Implementation Plan:
x/time/rate or Redis logic.8. Writing the Code (Iterative refinement):
Self-Correction during drafting: A pure in-memory implementation is dangerous because if the app crashes, pending webhooks are lost. I must emphasize that the Queue should be persistent (Redis/RabbitMQ/DB). I will implement a "System Design" section first, then the Go code for the worker logic.
Backoff Math: delay = base * 2^attempt. Add rand for jitter.
Rate Limiting: Use a map[string]*rate.Limiter for per-host limits to avoid blasting a specific target.
9. Final Review of Requirements:
Let's structure the output:
(Self-Correction): The user asked for a "Service". I should provide a robust main loop structure.
Let's write the actual Go code blocks.
Config struct.Webhook struct.Worker struct.Process function.Backoff Implementation detail:
Need to handle the "Delay". In a real queue like RabbitMQ, you publish with an expiration/headers. In a DB, you set process_at. I will simulate the "Delay" logic conceptually to keep the code runnable/understandable without needing a running Redis instance, but I will add comments on where the external dependency goes.
Refining the Code Structure: I will create a modular structure:
limiter.go: Rate limiting logic.queue.go: Interface for Queue/DLQ.worker.go: The main logic.main.go: Wiring it together.This provides a complete "service" view.
(Observability): I'll use standard log/slog and a metrics placeholder interface to represent Prometheus/OpenTelemetry.
(DLQ): Just a specialized Queue implementation.
Let's generate the response. This design outlines a robust, production-grade webhook delivery service in Go. This architecture is designed to decouple the ingestion of webhooks from their delivery, ensuring high reliability and system stability.
The service relies on Asynchronous Queuing to handle backpressure and Exponential Backoff to handle destination failures.
[Producer]
|
v
[Ingestion API] ---> [Primary Queue (Redis/NATS/SQS)]
|
v
[Dispatcher Service]
|
+-----------------+------------------+
| (Rate Limit Check) | (Circuit Breaker)
v v
[HTTP Client POST] --(Success)--> [Observer/Metrics]
|
| (Failure)
v
[Calculate Delay] ---> [Delayed Queue / Scheduler]
|
v
(Re-queue after delay or DLQ if retries exhausted)
stripe.com) to prevent overwhelming the receiver or getting banned.This implementation uses generic interfaces for the Queue and Cache so it can be adapted to Redis, SQL, or in-memory stores.
package main
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"math/rand"
"net/http"
"time"
)
// WebhookPayload represents the data to be sent
type WebhookPayload struct {
EventID string `json:"event_id"`
EventType string `json:"event_type"`
Data interface{} `json:"data"`
}
// Job represents a unit of work in the queue
type Job struct {
ID string `json:"id"`
TargetURL string `json:"target_url"`
Payload WebhookPayload `json:"payload"`
Attempts int `json:"attempts"`
MaxRetry int `json:"max_retry"`
NextRetry time.Time `json:"next_retry"`
CreatedAt time.Time `json:"created_at"`
}
// Config settings
var (
MaxRetries = 5
InitialBackoff = 1 * time.Second
MaxBackoff = 1 * time.Minute
RateLimitPerHost = 50 // 50 requests per second per host
)
We use "Full Jitter" (adding randomness) to prevent the Thundering Herd problem, where many retries hit the server simultaneously.
func calculateNextRetry(attempts int) time.Time {
// Exponential calculation: min(cap, base * 2^n)
backoff := InitialBackoff << uint(attempts)
if backoff > MaxBackoff {
backoff = MaxBackoff
}
// Add Jitter (randomness) to synchronize collisions
jitter := time.Duration(rand.Int63n(int64(backoff)))
return time.Now().Add(backoff + jitter)
}
This is the core engine. It pulls jobs, checks rate limits, executes the request, and handles failures.
type Worker struct {
Queue QueueInterface
DLQ DLQInterface
RateLimiter RateLimiterInterface
Client *http.Client
Logger *slog.Logger
}
func (w *Worker) Run(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
default:
// 1. Fetch Job (Blocking or Polling)
job, err := w.Queue.Pop(ctx)
if err != nil {
// Log error or sleep briefly
time.Sleep(1 * time.Second)
continue
}
// 2. Check Rate Limit (Per Host)
if !w.RateLimiter.Allow(job.TargetURL) {
// If rate limited, re-queue with a small delay or push to a "waiting" pile
w.Logger.Warn("rate limit exceeded", "url", job.TargetURL)
w.Queue.Requeue(job, time.Now().Add(1*time.Second))
continue
}
// 3. Process Job
if err := w.processJob(ctx, job); err != nil {
w.handleFailure(job, err)
} else {
w.handleSuccess(job)
}
}
}
}
func (w *Worker) processJob(ctx context.Context, job *Job) error {
w.Logger.Info("attempting delivery", "job_id", job.ID, "attempt", job.Attempts)
// Marshal payload
body, _ := json.Marshal(job.Payload)
req, err := http.NewRequest("POST", job.TargetURL, bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Event-ID", job.Payload.EventID)
resp, err := w.Client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// Consider 5xx and 429 as retryable errors
if resp.StatusCode >= 500 || resp.StatusCode == 429 {
return fmt.Errorf("server returned status: %d", resp.StatusCode)
}
// 4xx (except 429) are usually client errors, no point retrying
if resp.StatusCode >= 400 {
return fmt.Errorf("permanent client error: %d", resp.StatusCode)
}
return nil
}
func (w *Worker) handleSuccess(job *Job) {
// Metrics: Increment success counter
w.Logger.Info("webhook delivered", "job_id", job.ID)
// Acknowledge/Remove from queue
w.Queue.Ack(job.ID)
}
func (w *Worker) handleFailure(job *Job, err error) {
w.Logger.Error("webhook failed", "job_id", job.ID, "error", err)
job.Attempts++
// Check if max retries exceeded OR if error is permanent (4xx)
if job.Attempts >= job.MaxRetry || isPermanentError(err) {
w.Logger.Warn("moving to dead letter queue", "job_id", job.ID)
w.DLQ.Push(job, err)
w.Queue.Ack(job.ID) // Remove from active queue
return
}
// Requeue with Backoff
retryTime := calculateNextRetry(job.Attempts)
w.Logger.Info("scheduling retry", "job_id", job.ID, "retry_at", retryTime)
w.Queue.Requeue(job, retryTime)
}
func isPermanentError(err error) bool {
// Logic to determine if error is 4xx
return false
}
These interfaces abstract the underlying technology (Redis, SQL, etc.).
type QueueInterface interface {
Pop(ctx context.Context) (*Job, error)
Requeue(job *Job, executeAt time.Time) error
Ack(jobID string) error
}
type DLQInterface interface {
Push(job *Job, err error) error
}
// RateLimiterInterface uses a Token Bucket or Sliding Window algorithm
type RateLimiterInterface interface {
Allow(targetHost string) bool
}
Observability is split into three pillars:
Structured Logging:
slog (or Zap/Logrus).job_id, target_url, attempt_number, status_code, and latency_ms.Metrics (Prometheus):
webhooks_sent_total{status="success|failed|retry"}.webhooks_latency_seconds (Distribution of time taken to send).webhooks_queue_depth (Current size of the pending queue).webhooks_dlq_total (Number of messages moved to Dead Letter Queue).Tracing (OpenTelemetry):
Pop from the queue.job.id, target.url).Error.The code above uses an interface. In a real production scenario, you would implement the Token Bucket algorithm using Redis for distributed rate limiting.
ratelimit:{target_host}redis.ttl(key) < 0 (doesn't exist), create it with value RateLimitPerHost and expiry 1s.redis.get(key) > 0, decrement and return True (Allowed).False (Denied).EventID or X-Event-ID header) to handle duplicate deliveries gracefully.