Designing a resilience layer
The user wants help building a resilience layer, likely asking for architectural guidance and sample code. I should ask about the programming language but can start with pseudocode in common stacks like Node.js, Java, Go, or .NET. I’m considering middleware design with specific features like bulkhead isolation for APIs/tenants, adaptive timeouts, and rate limiting. Including components, algorithms, and observability details is key; I might even add sample pseudocode in TypeScript or Java to demonstrate integration.Building a resilience layer
I'm thinking about implementing token buckets, which could be distributed using Redis for multi-instance setups or locally with consistent hashing. I should also provide synthetic fallbacks with cached responses and clear contracts defining fallback providers per endpoint, with necessary schemas and TTLs. It's important to ensure idempotency and include metrics. I’ll outline steps for the resilience process, and given the lack of a specified language, I’ll provide a minimal Go example using concurrency primitives like context and semaphores.Creating resilience client in Go
I'm working on a Go code skeleton for a ResilienceClient, which includes a method called Do(ctx, tenant, upstream, req, fallbackFn) to return a response. I plan to use the rate package for the token bucket and implement a weighted semaphore for bulkhead management. For adaptive timeouts, I'll maintain stats using an exponentially weighted moving average to approximate p95. I’ll include a Redis-based rate limiter suggestion and provide a synthetic fallback in the HTTP response. Finally, I’ll shape this all into a markdown response, covering architecture, design, algorithms, and configuration.
Goal
Wrap all outbound calls to third‑party APIs in a single “resilience layer” that enforces:
- Bulkheads (concurrency isolation) per upstream (and optionally per-tenant).
- Adaptive timeouts (deadline derived from observed latency + error signals).
- Token buckets per tenant (rate limits + burst control, ideally distributed).
- Synthetic fallback responses (safe, schema-valid responses when degraded).
This should be a library/middleware around your HTTP client so every call follows the same pipeline.
Request pipeline (recommended order)
For each outbound request:
-
Identify tenant + route key
tenantId, upstreamName, endpointKey (or full route template).
-
Token bucket (per-tenant, optionally per-upstream)
Reject/queue quickly if tenant exceeds its budget.
-
Bulkhead (per-upstream, optionally per-tenant)
Limit concurrent in-flight requests to isolate failures.
-
Adaptive timeout
Compute deadline from recent latency distribution + clamp bounds.
-
Execute request with deadline
Capture latency + outcome.
-
On failure, generate synthetic fallback
Deterministic, schema-valid, optionally “stale-but-safe”.
-
Record metrics + update adaptive model
Latency, timeouts, errors, fallback rate, queue wait, permits used.
Core design
Keys and scoping
- Bulkhead key:
upstreamName (recommended)
Optional: upstreamName:tenantId if tenants should not impact each other.
- Rate limit key:
tenantId (recommended)
Optional: tenantId:upstreamName if a tenant’s usage should be partitioned by upstream.
- Timeout model key:
upstreamName:endpointKey (more precise than upstream-only)
Adaptive timeout algorithm (practical, lightweight)
Maintain per (upstream, endpoint) rolling stats:
- EWMA of latency mean (
μ)
- EWMA of latency deviation (
σ), e.g., EWMA of absolute deviation
Then compute:
p95_est ≈ μ + 2*σ (rough but stable)
timeout = clamp(minTimeout, maxTimeout, p95_est * factor + fixedBuffer)
Add a penalty when recent timeout/error rate rises:
- If
timeouts_last_1m / total_last_1m > 5%, temporarily increase factor or fixedBuffer slightly (or reduce concurrency with bulkhead—your choice).
This avoids a static timeout that’s either too aggressive (causing self-inflicted timeouts) or too lenient (tying up resources).
Token bucket per tenant (multi-instance)
If you run multiple app instances, local token buckets won’t be consistent. Use one of:
- Redis (Lua script) token bucket / GCRA
- Envoy / API gateway rate limiting
- Consistent hashing tenants to a limiter shard (only if acceptable)
Local-only is fine for single instance or “best-effort” throttling.
Synthetic fallback responses
Define fallback per endpoint with:
- Schema contract (always parseable)
- Safety: never lies about irreversible actions
- Signal: include headers/fields indicating fallback was served
- TTL / freshness: “stale cache” is often best
Common fallback types:
- Last-known-good cache (LKG): return cached response if not too old
- Empty-but-valid: e.g.,
items: [], hasMore: false
- Partial: return subset of fields that are safe
- Degrade feature: return a response that causes UI to hide optional panels
Reference implementation (Go skeleton)
This is a single wrapper around http.Client showing:
- Bulkhead via
semaphore.Weighted
- Token bucket via
rate.Limiter
- Adaptive timeout via EWMA stats
- Synthetic fallback via a callback
Note: for distributed per-tenant buckets, swap the rate.Limiter with Redis/GCRA.
package resilience
import (
"bytes"
"context"
"errors"
"io"
"math"
"net/http"
"sync"
"time"
"golang.org/x/sync/semaphore"
"golang.org/x/time/rate"
)
type Outcome string
const (
OutcomeOK Outcome = "ok"
OutcomeTimeout Outcome = "timeout"
OutcomeError Outcome = "error"
OutcomeFallback Outcome = "fallback"
)
type FallbackFunc func(ctx context.Context, cause error) (*http.Response, error)
type Config struct {
MinTimeout time.Duration
MaxTimeout time.Duration
TimeoutFactor float64 // e.g. 1.3
TimeoutBuffer time.Duration // e.g. 50ms
// Bulkhead concurrency per upstream
BulkheadPermits int64
// Token bucket defaults (per tenant)
TokensPerSecond float64
Burst int
// EWMA smoothing (0..1). Higher = reacts faster.
EWMAAlpha float64
}
type Client struct {
http *http.Client
cfg Config
mu sync.Mutex
bulkheads map[string]*semaphore.Weighted // key: upstream (or upstream:tenant)
limiters map[string]*rate.Limiter // key: tenant (or tenant:upstream)
stats map[string]*latencyStats // key: upstream:endpoint
}
type latencyStats struct {
mu sync.Mutex
meanMs float64
devMs float64 // EWMA of absolute deviation
init bool
}
func New(httpClient *http.Client, cfg Config) *Client {
if httpClient == nil {
httpClient = &http.Client{}
}
return &Client{
http: httpClient,
cfg: cfg,
bulkheads: make(map[string]*semaphore.Weighted),
limiters: make(map[string]*rate.Limiter),
stats: make(map[string]*latencyStats),
}
}
func (c *Client) getBulkhead(key string) *semaphore.Weighted {
c.mu.Lock()
defer c.mu.Unlock()
if b, ok := c.bulkheads[key]; ok {
return b
}
b := semaphore.NewWeighted(c.cfg.BulkheadPermits)
c.bulkheads[key] = b
return b
}
func (c *Client) getLimiter(key string) *rate.Limiter {
c.mu.Lock()
defer c.mu.Unlock()
if l, ok := c.limiters[key]; ok {
return l
}
l := rate.NewLimiter(rate.Limit(c.cfg.TokensPerSecond), c.cfg.Burst)
c.limiters[key] = l
return l
}
func (c *Client) getStats(key string) *latencyStats {
c.mu.Lock()
defer c.mu.Unlock()
if s, ok := c.stats[key]; ok {
return s
}
s := &latencyStats{}
c.stats[key] = s
return s
}
func (s *latencyStats) observe(d time.Duration, alpha float64) {
ms := float64(d.Milliseconds())
s.mu.Lock()
defer s.mu.Unlock()
if !s.init {
s.meanMs, s.devMs, s.init = ms, 0, true
return
}
mean := s.meanMs
s.meanMs = alpha*ms + (1-alpha)*mean
dev := math.Abs(ms - s.meanMs)
s.devMs = alpha*dev + (1-alpha)*s.devMs
}
func (s *latencyStats) timeout(cfg Config) time.Duration {
s.mu.Lock()
defer s.mu.Unlock()
// If no data, start conservative
if !s.init {
return clamp(cfg.MinTimeout, cfg.MaxTimeout, 2*cfg.MinTimeout)
}
p95 := s.meanMs + 2.0*s.devMs
base := time.Duration(p95)*time.Millisecond
t := time.Duration(float64(base)*cfg.TimeoutFactor) + cfg.TimeoutBuffer
return clamp(cfg.MinTimeout, cfg.MaxTimeout, t)
}
func clamp(min, max, v time.Duration) time.Duration {
if v < min { return min }
if v > max { return max }
return v
}
type CallParams struct {
TenantID string
Upstream string
EndpointKey string // e.g. "GET /v1/orders/:id"
}
type Result struct {
Response *http.Response
Outcome Outcome
Latency time.Duration
Err error
}
// Do executes the outbound request with rate limiting, bulkhead, adaptive timeout, and fallback.
func (c *Client) Do(ctx context.Context, p CallParams, req *http.Request, fb FallbackFunc) Result {
// 1) Token bucket
lim := c.getLimiter(p.TenantID)
if err := lim.Wait(ctx); err != nil {
return c.fallback(ctx, fb, err)
}
// 2) Bulkhead
bh := c.getBulkhead(p.Upstream)
if err := bh.Acquire(ctx, 1); err != nil {
return c.fallback(ctx, fb, err)
}
defer bh.Release(1)
// 3) Adaptive timeout
statsKey := p.Upstream + ":" + p.EndpointKey
st := c.getStats(statsKey)
timeout := st.timeout(c.cfg)
ctx2, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// 4) Execute
start := time.Now()
resp, err := c.http.Do(req.WithContext(ctx2))
lat := time.Since(start)
// 5) Observe latency for successful responses (and optionally some failures)
if err == nil && resp != nil {
st.observe(lat, c.cfg.EWMAAlpha)
return Result{Response: resp, Outcome: OutcomeOK, Latency: lat}
}
// classify timeout
if errors.Is(err, context.DeadlineExceeded) || errors.Is(ctx2.Err(), context.DeadlineExceeded) {
// still observe to adapt upward if needed
st.observe(lat, c.cfg.EWMAAlpha)
return c.fallback(ctx, fb, err)
}
return c.fallback(ctx, fb, err)
}
func (c *Client) fallback(ctx context.Context, fb FallbackFunc, cause error) Result {
if fb == nil {
return Result{Outcome: OutcomeError, Err: cause}
}
resp, err := fb(ctx, cause)
if err != nil {
return Result{Outcome: OutcomeError, Err: err}
}
// Mark response as synthetic
resp.Header.Set("X-Resilience-Fallback", "1")
return Result{Response: resp, Outcome: OutcomeFallback, Err: cause}
}
// Helper to build a JSON synthetic response quickly
func JSONFallback(status int, body []byte) *http.Response {
return &http.Response{
StatusCode: status,
Header: make(http.Header),
Body: io.NopCloser(bytes.NewReader(body)),
}
}
Example usage
res := rclient.Do(ctx,
resilience.CallParams{
TenantID: "t-123",
Upstream: "payments",
EndpointKey: "POST /v1/charge",
},
req,
func(ctx context.Context, cause error) (*http.Response, error) {
// safe synthetic response (do not claim charge succeeded)
return resilience.JSONFallback(503, []byte(`{"error":"payments_unavailable","retryable":true}`)), nil
},
)
if res.Outcome == resilience.OutcomeFallback {
// degrade functionality; schedule retry; etc.
}
Operational guidance (what makes this work in production)
- Metrics (per upstream and tenant)
inflight (bulkhead used / max)
rate_limited_total
timeouts_total, errors_total
fallback_total
latency_ms histograms (p50/p95/p99)
- Logging: include
tenantId, upstream, endpointKey, timeoutUsedMs, queueWaitMs
- Config defaults (typical starting point)
MinTimeout: 200–500ms (depends on upstream)
MaxTimeout: 2–10s (depends on UX)
BulkheadPermits: based on upstream’s safe concurrency (start 20–100)
TokensPerSecond/Burst: per tenant contract
EWMAAlpha: 0.1–0.3 (stable but responsive)
- Fallback correctness rules
- Never return “success” for non-idempotent operations (payments, writes)
- Prefer LKG cache for reads
- Always mark fallback responses (header/field) for downstream behavior
If you tell me your stack, I can tailor it
If you share language/runtime (Java/Spring, Node, .NET, Go) and whether you need distributed rate limiting (Redis) and per-endpoint configs, I can provide a drop-in module (filters/interceptors), plus Redis token bucket/GCRA scripts and a config schema.