Considering resilience patterns
I need to implement resilience patterns and provide concise code examples, like timeouts, retries with jittered backoff, circuit breakers, and more. I’m thinking of using popular languages like Go, Java, and Node for examples. It's essential to show minimal yet comprehensive snippets, possibly focusing on one ecosystem like Kubernetes with Envoy. The user hasn't specified a language, so I should consider multiple languages, yet choosing a couple, like Go and Node.js, could be best for clarity.Creating resilience snippets
I’m outlining key resilience patterns and need concise code examples. This includes timeouts for server requests, retries with jittered backoff, and circuit breakers using libraries like Resilience4j or Envoy. I also want to cover bulkheads, idempotency keys, hedging, queues, and observability metrics using OpenTelemetry and Prometheus.
I'm considering TypeScript with Express for the HTTP server/client examples, while also providing Go code snippets for various patterns. I'll keep the examples small and focused on reference implementation recipes to maintain clarity.Creating resilience examples in Go
I’m planning to use Go for my examples and include configurations for Envoy and Kubernetes. I aim for short, runnable snippets for various resilience patterns.
I’ll include timeouts for both client and server HTTP requests, retries with jittered exponential backoff, and circuit breakers using sony/gobreaker. For bulkheads, I’ll limit concurrent calls with a semaphore, and for idempotency keys, I’ll show how to handle unique constraints in the database. I’ll also discuss hedging, queues with SQS or Rabbit, and observability through OpenTelemetry. Additionally, I’ll mention guardrails for retries based on idempotency.Drafting Envoy and Go examples
I need to include configuration examples for Envoy, covering request timeouts, retries, circuit breakers, and outlier detection. It might be useful to present both app-level and infra-level patterns since the user asked for implementations.
I’ll provide snippets for hedging and queues separately, include bulkheads for both process (semaphore) and infra (Kubernetes), and aim for concise code.
I'll structure the final answer in Markdown, maintaining clear headings and minimal code examples, ensuring it remains between 700-1000 words. I’ll also focus on observability using OpenTelemetry with Prometheus metrics for counters and histograms, and include utility functions for jitter.Drafting resilience patterns in Go
I’m focusing on creating a shared HTTP client, setting timeouts with http.Client{Timeout: ...} and using context.WithTimeout. For retries, I'll implement a function like DoWithRetry(ctx, fn), while wrapping calls for circuit breakers and limiting concurrency for bulkheads.
The function callDownstream(ctx, req) will acquire a semaphore and handle circuit breaking and retries. I’ll also include snippets for idempotency keys, hedging, queue configurations for SQS, and observability with OpenTelemetry and Prometheus metrics. Additionally, I’ll provide Envoy and Kubernetes configuration examples, keeping everything concise and clear.
Below are “drop-in” resilience recipes (mostly Go), plus a few infra configs (Envoy, SQS). Mix-and-match; don’t blindly enable retries everywhere.
1) Timeouts (client + server + propagation)
Server: enforce request deadline
srv := &http.Server{
Addr: ":8080",
ReadHeaderTimeout: 2 * time.Second,
IdleTimeout: 60 * time.Second,
}
http.HandleFunc("/v1/do", func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 1500*time.Millisecond)
defer cancel()
// pass ctx to all downstream calls; respect ctx.Done()
_ = ctx
w.WriteHeader(http.StatusOK)
})
log.Fatal(srv.ListenAndServe())
Client: hard timeout + per-try timeout
client := &http.Client{ Timeout: 2 * time.Second } // absolute upper bound
ctx, cancel := context.WithTimeout(context.Background(), 1800*time.Millisecond)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
resp, err := client.Do(req)
2) Retries with jittered exponential backoff (only for safe cases)
- Retry only on: connect timeouts, 5xx, 429 (with
Retry-After), etc.
- Only auto-retry idempotent ops (GET/HEAD) unless you use idempotency keys.
func retry(ctx context.Context, attempts int, base, max time.Duration, fn func(context.Context) error) error {
var err error
for i := 0; i < attempts; i++ {
// per-try budget
tryCtx, cancel := context.WithTimeout(ctx, 700*time.Millisecond)
err = fn(tryCtx)
cancel()
if err == nil || ctx.Err() != nil { return err }
// Full jitter: sleep = rand(0, min(max, base*2^i))
cap := base << i
if cap > max { cap = max }
d := time.Duration(rand.Int63n(int64(cap) + 1))
timer := time.NewTimer(d)
select {
case <-ctx.Done(): timer.Stop(); return ctx.Err()
case <-timer.C:
}
}
return err
}
3) Circuit breaker (fail fast when dependency is unhealthy)
import "github.com/sony/gobreaker"
cb := gobreaker.NewCircuitBreaker(gobreaker.Settings{
Name: "payments",
MaxRequests: 10, // in half-open
Interval: 30 * time.Second, // rolling window reset
Timeout: 10 * time.Second, // open -> half-open after
ReadyToTrip: func(c gobreaker.Counts) bool {
return c.Requests >= 50 && float64(c.TotalFailures)/float64(c.Requests) >= 0.5
},
})
call := func(ctx context.Context) error {
_, err := cb.Execute(func() (any, error) {
// real downstream call; must honor ctx
return nil, doHTTP(ctx)
})
return err
}
4) Bulkheads (limit concurrency per dependency)
Semaphore bulkhead
import "golang.org/x/sync/semaphore"
var payBH = semaphore.NewWeighted(20) // max 20 concurrent calls
func callPayments(ctx context.Context) error {
if err := payBH.Acquire(ctx, 1); err != nil { return err }
defer payBH.Release(1)
return doHTTP(ctx)
}
Also consider separate worker pools / queues per dependency so one slow backend doesn’t consume all goroutines/threads.
5) Idempotency keys (safe retries for POST)
HTTP contract
- Client sends:
Idempotency-Key: <uuid> on POST/PUT
- Server stores outcome keyed by
(key, route, auth principal) and replays response.
Postgres schema
CREATE TABLE idempotency (
key TEXT PRIMARY KEY,
route TEXT NOT NULL,
subject TEXT NOT NULL,
status INT NOT NULL,
response JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
Handler sketch (single-flight via unique key)
func handleCreate(w http.ResponseWriter, r *http.Request) {
key := r.Header.Get("Idempotency-Key")
if key == "" { http.Error(w, "missing Idempotency-Key", 400); return }
// 1) check if exists -> return stored response
if found { writeStored(w, stored); return }
// 2) execute business op
status, resp := doCreate()
// 3) insert result; if conflict, read & return existing (race-safe)
// INSERT ... ON CONFLICT (key) DO NOTHING; then SELECT
}
6) Hedging (tail-latency reduction) + cancellation
Send a “backup” request after a delay; keep the first success, cancel the other.
func hedged(ctx context.Context, hedgeAfter time.Duration, primary, backup func(context.Context) (*http.Response, error)) (*http.Response, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
type res struct{ r *http.Response; e error }
ch := make(chan res, 2)
go func() { r, e := primary(ctx); ch <- res{r, e} }()
timer := time.NewTimer(hedgeAfter)
defer timer.Stop()
select {
case out := <-ch:
if out.e == nil { cancel() }
return out.r, out.e
case <-timer.C:
go func() { r, e := backup(ctx); ch <- res{r, e} }()
out := <-ch
if out.e == nil { cancel() }
return out.r, out.e
}
}
Use hedging sparingly (only on read/idempotent calls; ensure backend capacity).
7) Queues (decouple + smooth spikes) + DLQ
AWS SQS redrive (DLQ)
{
"RedrivePolicy": {
"deadLetterTargetArn": "arn:aws:sqs:us-east-1:123:my-dlq",
"maxReceiveCount": "5"
}
}
Consumer pattern
- visibility timeout > max processing time
- retry by letting message reappear (or explicit delay queue)
- emit metrics for queue depth + age-of-oldest
for {
msg := receive()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
err := handle(ctx, msg)
cancel()
if err == nil {
deleteMsg(msg)
} else {
// do not delete => SQS retries; after maxReceiveCount goes to DLQ
// optionally change visibility to add delay/backoff
}
}
8) Observability (metrics, logs, traces) for all the above
OpenTelemetry HTTP server + client
import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
mux := http.NewServeMux()
mux.Handle("/v1/do", otelhttp.NewHandler(http.HandlerFunc(handler), "do"))
client := &http.Client{
Transport: otelhttp.NewTransport(http.DefaultTransport),
Timeout: 2 * time.Second,
}
Key metrics to emit
requests_total{route,code}
dependency_latency_ms{dep} (histogram)
retries_total{dep,reason}, retry_attempts_hist{dep}
circuit_state{dep} (0=closed,1=open,2=half)
bulkhead_inflight{dep}, bulkhead_rejected_total{dep}
queue_depth, queue_oldest_age_seconds, dlq_depth
hedge_total{dep}, hedge_wins_total{dep}
Log fields
trace_id, span_id, idempotency_key, dependency, attempt, circuit_state.
Edge/config option (Envoy): timeouts + retries + circuit breaking
route_config:
virtual_hosts:
- routes:
- match: { prefix: "/payments" }
route:
cluster: payments
timeout: 2s
retry_policy:
retry_on: "5xx,connect-failure,reset,refused-stream"
num_retries: 2
per_try_timeout: 700ms
retry_back_off: { base_interval: 50ms, max_interval: 500ms }
clusters:
- name: payments
circuit_breakers:
thresholds:
- max_connections: 1000
max_pending_requests: 100
max_requests: 200
max_retries: 3
outlier_detection:
consecutive_5xx: 5
interval: 5s
base_ejection_time: 30s
If you tell me your stack (Go/Java/.NET/Node, Kubernetes/service-mesh or not, HTTP vs gRPC), I can rewrite these as idiomatic code using your preferred libraries (Resilience4j/Polly/Envoy/Istio, etc.) and show a single cohesive wrapper you can apply per dependency.