Skip to main content

tower_resilience/
composition.rs

1//! # Composition Guide
2//!
3//! Comprehensive guide to composing resilience patterns together, including layer ordering,
4//! error type integration, and workarounds for complex compositions.
5//!
6//! ## Note on Health Check
7//!
8//! Health Check is **not a Tower layer** and cannot be composed with other patterns in the
9//! layer stack. Instead, it wraps resource instances at a different architectural level:
10//!
11//! ```text
12//! Application Layer:
13//!   HealthCheckWrapper (manages multiple resources)
14//!     ├─ primary_db
15//!     ├─ secondary_db
16//!     └─ tertiary_db
17//!
18//! Tower Layer Stack:
19//!   ServiceBuilder
20//!     ├─ TimeLimiter
21//!     ├─ CircuitBreaker
22//!     ├─ Retry
23//!     └─ Service (selected by HealthCheckWrapper)
24//! ```
25//!
26//! Use Health Check to **select** healthy resources, then apply Tower layers to the
27//! selected resource for request-level resilience.
28
29pub mod selection {
30    //! # Pattern Selection Guide
31    //!
32    //! A comprehensive guide for selecting and composing resilience patterns.
33    //!
34    //! ## The Onion Model
35    //!
36    //! Tower middleware wraps services like layers of an onion. The outermost layer
37    //! processes requests first (and responses last):
38    //!
39    //! ```text
40    //! Request → [Retry] → [CircuitBreaker] → [Timeout] → [RateLimit] → Service
41    //!                                                                     ↓
42    //! Response ← [Retry] ← [CircuitBreaker] ← [Timeout] ← [RateLimit] ← Response
43    //! ```
44    //!
45    //! **Key insight**: Layer order matters. A timeout outside retry limits total time;
46    //! inside retry, each attempt gets the full timeout.
47    //!
48    //! ## Understanding ServiceBuilder Order
49    //!
50    //! `ServiceBuilder` applies layers **outside-in**: the first `.layer()` call
51    //! becomes the outermost wrapper (it sees the request first), and the layer
52    //! closest to `.service(...)` is innermost, closest to the wrapped service.
53    //! ([`tower::ServiceBuilder`'s own docs](https://docs.rs/tower/latest/tower/struct.ServiceBuilder.html#order):
54    //! "Layers that are added first will be called with the request first.")
55    //!
56    //! ```text
57    //! // Execution order: Fallback → Timeout → Retry → Service
58    //! ServiceBuilder::new()
59    //!     .layer(fallback)   // added 1st, outermost, executes 1st
60    //!     .layer(timeout)    // added 2nd, middle
61    //!     .layer(retry)      // added 3rd, innermost, executes last (closest to service)
62    //!     .service(svc)
63    //! ```
64    //!
65    //! ## Client-Side vs Server-Side Patterns
66    //!
67    //! | Context | Goal | Primary Patterns |
68    //! |---------|------|------------------|
69    //! | **Client-side** | Protect self from slow/failing dependencies | Retry, CircuitBreaker, Timeout, Hedge, Fallback |
70    //! | **Server-side** | Protect self from overwhelming traffic | RateLimiter, Bulkhead, Timeout |
71    //!
72    //! Most applications need both: client-side patterns for outgoing calls,
73    //! server-side patterns for incoming requests.
74    //!
75    //! ## Note on Health Check
76    //!
77    //! Health Check is **not a Tower layer** - it's a resource manager that wraps multiple
78    //! backend instances (databases, cache nodes, etc.) and selects healthy ones. Use it
79    //! alongside Tower layers, not as part of the layer stack. See the
80    //! [module-level documentation](super) for details.
81    //!
82    //! ## Pattern Quick Reference
83    //!
84    //! | Pattern | Purpose | Use When | Avoid When |
85    //! |---------|---------|----------|------------|
86    //! | **Retry** | Recover from transient failures | Network blips, 503s, deadlocks | Non-idempotent ops, 4xx errors |
87    //! | **CircuitBreaker** | Fail fast when dependency is down | Cascading failure risk | Single-shot operations |
88    //! | **TimeLimiter** | Bound operation duration | Unbounded external calls | Already-bounded operations |
89    //! | **Bulkhead** | Isolate resource pools | Multi-tenant, mixed criticality | Uniform workloads |
90    //! | **RateLimiter** | Control throughput | API quotas, resource protection | Internal service calls |
91    //! | **Fallback** | Graceful degradation | Cached alternatives exist | No sensible default |
92    //! | **Hedge** | Reduce tail latency | Idempotent reads, P99 matters | Expensive operations |
93    //! | **Cache** | Reduce load, improve latency | High read:write ratio | Frequently changing data |
94    //! | **Adaptive** | Auto-tune concurrency | Unknown optimal limits | Known fixed capacity |
95    //! | **Outlier** | Eject unhealthy instances | Fleet of backends, hard failures | Single backend |
96    //!
97    //! ## Decision Flowchart
98    //!
99    //! Use this flowchart to determine which patterns to apply:
100    //!
101    //! ```text
102    //! START: What are you protecting?
103    //! │
104    //! ├─► Calling external dependency?
105    //! │   │
106    //! │   ├─► Can fail transiently? ────────────► Add Retry
107    //! │   │
108    //! │   ├─► Can hang indefinitely? ───────────► Add TimeLimiter
109    //! │   │
110    //! │   ├─► Can be completely down? ──────────► Add CircuitBreaker
111    //! │   │
112    //! │   ├─► Fleet of backends? ─────────────► Add OutlierDetection
113    //! │   │
114    //! │   ├─► Has rate limits? ─────────────────► Add RateLimiter (client-side)
115    //! │   │
116    //! │   ├─► P99 latency critical? ────────────► Add Hedge (if idempotent)
117    //! │   │
118    //! │   └─► Has fallback data? ───────────────► Add Fallback
119    //! │
120    //! ├─► Receiving incoming requests?
121    //! │   │
122    //! │   ├─► Multi-tenant? ────────────────────► Add Bulkhead (per-tenant)
123    //! │   │
124    //! │   ├─► Need to limit throughput? ────────► Add RateLimiter
125    //! │   │
126    //! │   ├─► Mixed criticality? ───────────────► Add Bulkhead (per-priority)
127    //! │   │
128    //! │   └─► Unknown optimal concurrency? ─────► Add AdaptiveLimiter
129    //! │
130    //! └─► Caching opportunity?
131    //!     │
132    //!     ├─► High read:write ratio? ───────────► Add Cache
133    //!     │
134    //!     └─► Concurrent duplicate requests? ───► Add Coalesce
135    //! ```
136}
137
138pub mod stacks {
139    //! # Progressive Stacks by Service Type
140    //!
141    //! Ready-to-use resilience configurations for common scenarios.
142    //!
143    //! ## External API Clients
144    //!
145    //! For calling third-party APIs (Stripe, Twilio, AWS, etc.):
146    //!
147    //! **Minimal Stack:**
148    //! ```text
149    //! ServiceBuilder::new()
150    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(10)))  // Bound total time
151    //!     .layer(RetryLayer::new(config))                         // Retry transient failures
152    //!     .service(http_client)
153    //! ```
154    //!
155    //! **Standard Stack:**
156    //! ```text
157    //! ServiceBuilder::new()
158    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(30)))  // Outermost: total budget
159    //!     .layer(RetryLayer::builder()                            // Retry within budget
160    //!         .max_attempts(3)
161    //!         .exponential_backoff(Duration::from_millis(100))
162    //!         .build())
163    //!     .layer(CircuitBreakerLayer::builder()                   // Track failures per-attempt
164    //!         .failure_rate_threshold(0.5)
165    //!         .build())
166    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(10)))  // Innermost: per-attempt limit
167    //!     .service(http_client)
168    //! ```
169    //!
170    //! **Full Stack (with fallback):**
171    //! ```text
172    //! ServiceBuilder::new()
173    //!     .layer(FallbackLayer::value(cached_response))           // Outermost: catch all failures
174    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(30)))  // Total budget for all retries
175    //!     .layer(RetryLayer::builder()                            // Retry before CB sees failure
176    //!         .max_attempts(3)
177    //!         .exponential_backoff(Duration::from_millis(100))
178    //!         .build())
179    //!     .layer(CircuitBreakerLayer::builder()                   // Track per-attempt failures
180    //!         .failure_rate_threshold(0.5)
181    //!         .wait_duration_in_open(Duration::from_secs(30))
182    //!         .build())
183    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(10)))  // Innermost: per-attempt limit
184    //!     .service(http_client)
185    //! ```
186    //!
187    //! **With Hedging (for latency-sensitive, idempotent calls):**
188    //! ```text
189    //! ServiceBuilder::new()
190    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(30)))  // Total budget
191    //!     .layer(RetryLayer::builder()                            // Retry failures
192    //!         .max_attempts(3)
193    //!         .exponential_backoff(Duration::from_millis(100))
194    //!         .build())
195    //!     .layer(CircuitBreakerLayer::builder()                   // Track failures
196    //!         .failure_rate_threshold(0.5)
197    //!         .build())
198    //!     .layer(HedgeLayer::builder()                            // Fire backup after P95
199    //!         .delay(Duration::from_millis(50))
200    //!         .max_hedged_attempts(2)
201    //!         .build())
202    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(10)))  // Per-attempt limit
203    //!     .service(api_client)
204    //! ```
205    //!
206    //! ## Database Connections
207    //!
208    //! For database clients (PostgreSQL, MySQL, etc.):
209    //!
210    //! **Standard Stack:**
211    //! ```text
212    //! ServiceBuilder::new()
213    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(5)))   // Bound query time
214    //!     .layer(RetryLayer::builder()                            // Retry transient errors
215    //!         .max_attempts(2)
216    //!         .retry_on(|e| is_transient_db_error(e))
217    //!         .build())
218    //!     .layer(BulkheadLayer::builder()                         // Limit concurrent queries
219    //!         .max_concurrent_calls(20)  // Match connection pool size
220    //!         .build())
221    //!     .service(db_client)
222    //! ```
223    //!
224    //! **With Circuit Breaker (for replicas):**
225    //! ```text
226    //! ServiceBuilder::new()
227    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(5)))   // Bound query time
228    //!     .layer(CircuitBreakerLayer::builder()                   // Fail fast if replica down
229    //!         .failure_rate_threshold(0.5)
230    //!         .minimum_number_of_calls(10)
231    //!         .build())
232    //!     .layer(BulkheadLayer::builder()                         // Limit concurrent queries
233    //!         .max_concurrent_calls(20)
234    //!         .build())
235    //!     .service(db_client)
236    //! ```
237    //!
238    //! ## Internal Microservices
239    //!
240    //! For calling other services you control:
241    //!
242    //! **Standard Stack:**
243    //! ```text
244    //! ServiceBuilder::new()
245    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(5)))   // Bound total time
246    //!     .layer(RetryLayer::builder()                            // Retry transient failures
247    //!         .max_attempts(2)
248    //!         .fixed_backoff(Duration::from_millis(50))
249    //!         .build())
250    //!     .layer(CircuitBreakerLayer::builder()                   // Fail fast if service down
251    //!         .failure_rate_threshold(0.6)
252    //!         .slow_call_rate_threshold(0.8)
253    //!         .slow_call_duration_threshold(Duration::from_secs(2))
254    //!         .build())
255    //!     .service(grpc_client)
256    //! ```
257    //!
258    //! **With Adaptive Concurrency:**
259    //! ```text
260    //! ServiceBuilder::new()
261    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(5)))   // Bound total time
262    //!     .layer(AdaptiveLimiterLayer::new(Vegas::default()))     // Auto-tune concurrency
263    //!     .layer(RetryLayer::builder()                            // Retry transient failures
264    //!         .max_attempts(2)
265    //!         .build())
266    //!     .service(grpc_client)
267    //! ```
268    //!
269    //! ## Latency-Critical Paths
270    //!
271    //! For operations where P99 latency matters (trading, real-time):
272    //!
273    //! **With Hedging:**
274    //! ```text
275    //! ServiceBuilder::new()
276    //!     .layer(TimeLimiterLayer::new(Duration::from_millis(100)))  // Tight deadline
277    //!     .layer(HedgeLayer::builder()                               // Fire hedge after 10ms
278    //!         .delay(Duration::from_millis(10))
279    //!         .max_hedged_attempts(2)
280    //!         .build())
281    //!     .service(cache_client)
282    //! ```
283    //!
284    //! **Parallel Hedging (fire all immediately):**
285    //! ```text
286    //! ServiceBuilder::new()
287    //!     .layer(TimeLimiterLayer::new(Duration::from_millis(50)))   // Very tight deadline
288    //!     .layer(HedgeLayer::builder()                               // Race all regions
289    //!         .no_delay()  // Fire all requests immediately
290    //!         .max_hedged_attempts(3)
291    //!         .build())
292    //!     .service(multi_region_client)
293    //! ```
294    //!
295    //! ## Message Queues
296    //!
297    //! For Kafka, RabbitMQ, SQS, etc.:
298    //!
299    //! **Consumer Stack:**
300    //! ```text
301    //! ServiceBuilder::new()
302    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(30)))  // Bound processing time
303    //!     .layer(RetryLayer::builder()                            // Retry with backoff
304    //!         .max_attempts(5)
305    //!         .backoff(ExponentialBackoff::new(Duration::from_secs(1))
306    //!             .max_interval(Duration::from_secs(60)))
307    //!         .build())
308    //!     .layer(CircuitBreakerLayer::builder()                   // Fail fast if handler broken
309    //!         .failure_rate_threshold(0.5)
310    //!         .wait_duration_in_open(Duration::from_secs(60))
311    //!         .build())
312    //!     .service(message_handler)
313    //! ```
314    //!
315    //! **Producer Stack:**
316    //! ```text
317    //! ServiceBuilder::new()
318    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(5)))   // Bound publish time
319    //!     .layer(RetryLayer::builder()                            // Retry transient failures
320    //!         .max_attempts(3)
321    //!         .exponential_backoff(Duration::from_millis(100))
322    //!         .build())
323    //!     .layer(BulkheadLayer::builder()                         // Limit concurrent publishes
324    //!         .max_concurrent_calls(50)
325    //!         .build())
326    //!     .service(queue_producer)
327    //! ```
328    //!
329    //! ## Caching Layers
330    //!
331    //! For Redis, Memcached, etc.:
332    //!
333    //! **Standard Stack:**
334    //! ```text
335    //! ServiceBuilder::new()
336    //!     .layer(FallbackLayer::value(None))                        // Outermost: cache miss is OK
337    //!     .layer(TimeLimiterLayer::new(Duration::from_millis(50)))  // Fast timeout
338    //!     .layer(CircuitBreakerLayer::builder()                     // Fail fast if cache down
339    //!         .failure_rate_threshold(0.3)                          // Sensitive threshold
340    //!         .build())
341    //!     .service(redis_client)
342    //! ```
343    //!
344    //! **With Request Coalescing:**
345    //! ```text
346    //! ServiceBuilder::new()
347    //!     .layer(TimeLimiterLayer::new(Duration::from_millis(100)))  // Bound lookup time
348    //!     .layer(CoalesceLayer::new())                               // Dedupe concurrent lookups
349    //!     .layer(CircuitBreakerLayer::builder()                      // Fail fast if cache down
350    //!         .failure_rate_threshold(0.3)
351    //!         .build())
352    //!     .service(redis_client)
353    //! ```
354}
355
356pub mod patterns {
357    //! # Composition Patterns
358    //!
359    //! Patterns are designed to be composed together for comprehensive resilience.
360    //!
361    //! ## Inbound (Server-Side)
362    //!
363    //! Protect your service from abusive or overwhelming clients:
364    //!
365    //! ```text
366    //! ┌─────────────┐
367    //! │   Request   │
368    //! └──────┬──────┘
369    //!        │
370    //!        ▼
371    //! ┌─────────────────┐
372    //! │  Rate Limiter   │ ← Reject abusive clients
373    //! └────────┬────────┘
374    //!          │
375    //!          ▼
376    //! ┌─────────────────┐
377    //! │    Bulkhead     │ ← Isolate tenant resources
378    //! └────────┬────────┘
379    //!          │
380    //!          ▼
381    //! ┌─────────────────┐
382    //! │  Time Limiter   │ ← Prevent runaway requests
383    //! └────────┬────────┘
384    //!          │
385    //!          ▼
386    //! ┌─────────────────┐
387    //! │     Handler     │
388    //! └─────────────────┘
389    //! ```
390    //!
391    //! ## Outbound (Client-Side)
392    //!
393    //! Make your clients resilient to downstream failures:
394    //!
395    //! ```text
396    //! ┌─────────────┐
397    //! │   Request   │
398    //! └──────┬──────┘
399    //!        │
400    //!        ▼
401    //! ┌─────────────────┐
402    //! │    Fallback     │ ← Graceful degradation
403    //! └────────┬────────┘
404    //!          │
405    //!          ▼
406    //! ┌─────────────────┐
407    //! │  Time Limiter   │ ← Don't wait forever
408    //! └────────┬────────┘
409    //!          │
410    //!          ▼
411    //! ┌─────────────────┐
412    //! │ Circuit Breaker │ ← Fail fast when down
413    //! └────────┬────────┘
414    //!          │
415    //!          ▼
416    //! ┌─────────────────┐
417    //! │      Retry      │ ← Handle transient errors
418    //! └────────┬────────┘
419    //!          │
420    //!          ▼
421    //! ┌─────────────────┐
422    //! │    Reconnect    │ ← Auto-reconnect on disconnect
423    //! └────────┬────────┘
424    //!          │
425    //!          ▼
426    //! ┌─────────────────┐
427    //! │     Client      │
428    //! └─────────────────┘
429    //! ```
430    //!
431    //! ## Read-Through Cache
432    //!
433    //! Cache expensive operations with resilience:
434    //!
435    //! ```text
436    //! ┌─────────────┐
437    //! │   Request   │
438    //! └──────┬──────┘
439    //!        │
440    //!        ▼
441    //! ┌─────────────────┐
442    //! │      Cache      │ ← Try cache first
443    //! └────────┬────────┘
444    //!          │ (miss)
445    //!          ▼
446    //! ┌─────────────────┐
447    //! │ Circuit Breaker │ ← Protect backend
448    //! └────────┬────────┘
449    //!          │
450    //!          ▼
451    //! ┌─────────────────┐
452    //! │  Time Limiter   │ ← Bound latency
453    //! └────────┬────────┘
454    //!          │
455    //!          ▼
456    //! ┌─────────────────┐
457    //! │    Backend      │
458    //! └─────────────────┘
459    //! ```
460}
461
462pub mod ordering {
463    //! # Layer Ordering
464    //!
465    //! Layer order is critical! Understanding how `ServiceBuilder` applies layers
466    //! is essential for correct composition.
467    //!
468    //! ## ServiceBuilder Order
469    //!
470    //! `ServiceBuilder` applies layers **outside-in**: the first `.layer()` call becomes
471    //! the outermost wrapper (it sees the request first), and the layer closest to
472    //! `.service(...)` is innermost. Per
473    //! [`tower::ServiceBuilder`'s own docs](https://docs.rs/tower/latest/tower/struct.ServiceBuilder.html#order):
474    //! "Layers that are added first will be called with the request first."
475    //!
476    //! ```text
477    //! // Build order vs Execution order:
478    //! ServiceBuilder::new()
479    //!     .layer(A)  // Added 1st → Outermost  → Executes FIRST (sees request first)
480    //!     .layer(B)  // Added 2nd → Middle     → Executes 2nd
481    //!     .layer(C)  // Added 3rd → Innermost  → Executes LAST  (closest to service)
482    //!     .service(svc)
483    //!
484    //! // Execution: Request → A → B → C → Service → C → B → A → Response
485    //! ```
486    //!
487    //! ## Recommended Layer Order
488    //!
489    //! From outermost (first to process request) to innermost:
490    //!
491    //! | Position | Layer | Rationale | If Wrong |
492    //! |----------|-------|-----------|----------|
493    //! | 1 | Fallback | Catch all errors | Users see raw errors |
494    //! | 2 | Total Timeout | Bound entire operation | Can wait forever across retries |
495    //! | 3 | Retry | Retry within timeout budget | Retries exceed total timeout |
496    //! | 4 | Circuit Breaker | Fail fast when down | Wastes retries on dead service |
497    //! | 5 | Bulkhead | Limit concurrency | Slow calls exhaust resources before CB trips |
498    //! | 6 | Per-call Timeout | Bound each attempt | One slow call consumes retry budget |
499    //! | 7 | Rate Limiter | Respect downstream limits | Retry amplifies rate limit violations |
500    //! | 8 | Hedge | Fire parallel requests | Hedges not bounded by per-call timeout |
501    //! | 9 | Service | The actual service | - |
502    //!
503    //! ## Client-Side (Outbound) - Correct Order
504    //!
505    //! In `ServiceBuilder`, add layers from outermost to innermost:
506    //!
507    //! ```text
508    //! ServiceBuilder::new()
509    //!     // Added first → outermost → executes first
510    //!     .layer(fallback)           // Catches all errors, provides degraded response
511    //!     .layer(cache)              // Skips remaining layers on cache hit
512    //!     .layer(total_timeout)      // Bounds entire operation including retries
513    //!     // Middle layers
514    //!     .layer(retry)              // Retries individual failures; sees every circuit-breaker
515    //!                                // rejection too (exclude those via `retry_on` -- see
516    //!                                // "Circuit Breaker with Retry" below)
517    //!     .layer(circuit_breaker)    // Fails fast if service is down
518    //!     // Added last → innermost → executes last (closest to service)
519    //!     .layer(per_call_timeout)   // Bounds each attempt
520    //!     .service(http_client);
521    //! ```
522    //!
523    //! ## Server-Side (Inbound) - Correct Order
524    //!
525    //! ```text
526    //! ServiceBuilder::new()
527    //!     // Added first → outermost → executes first
528    //!     .layer(rate_limiter)       // Reject over-limit requests immediately
529    //!     .layer(bulkhead)           // Isolate resources after rate limiting
530    //!     // Added last → innermost → executes last
531    //!     .layer(timeout)            // Bound handler execution
532    //!     .service(handler);
533    //! ```
534    //!
535    //! ## Common Patterns
536    //!
537    //! **Timeout inside vs outside Retry:**
538    //!
539    //! ```text
540    //! // Total timeout (all retries must complete in 30s)
541    //! ServiceBuilder::new()
542    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(30)))  // Outermost
543    //!     .layer(RetryLayer::new(config))
544    //!     .service(svc)
545    //!
546    //! // Per-attempt timeout (each attempt gets 10s)
547    //! ServiceBuilder::new()
548    //!     .layer(RetryLayer::new(config))
549    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(10)))  // Innermost
550    //!     .service(svc)
551    //!
552    //! // Both (recommended for external APIs)
553    //! ServiceBuilder::new()
554    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(30)))  // Total (outer)
555    //!     .layer(RetryLayer::new(config))
556    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(10)))  // Per-attempt (inner)
557    //!     .service(svc)
558    //! ```
559    //!
560    //! **Circuit Breaker with Retry:**
561    //!
562    //! Both orderings are valid, with different tradeoffs; see [the full
563    //! comparison](https://github.com/joshrotenberg/tower-resilience/blob/main/docs/circuitbreaker-tower-comparison.md#composition-with-retry-budgets)
564    //! for the complete reasoning:
565    //!
566    //! ```text
567    //! // Retry outside CB (recommended default):
568    //! // - Every retry attempt -- including the first -- calls the breaker directly,
569    //! //   so the breaker's sliding window reflects real attempt volume against the
570    //! //   transport, not a smoothed per-request outcome
571    //! // - Pair with `.retry_on(...)` to exclude circuit-open rejections, so a local
572    //! //   rejection doesn't consume a retry-budget token or schedule a backoff sleep
573    //! //   for a call that never left the process
574    //! ServiceBuilder::new()
575    //!     .layer(RetryLayer::new(config))              // Outer
576    //!     .layer(CircuitBreakerLayer::new(cb_config))  // Inner
577    //!     .service(svc)
578    //!
579    //! // CB outside retry:
580    //! // - The breaker only ever sees one call per external request -- Retry's own
581    //! //   internal attempts happen inside `Retry::call`'s future, so the breaker
582    //! //   observes the retry's fully-adjudicated final outcome, not individual
583    //! //   attempts
584    //! // - Appropriate when the retry's entire multi-attempt operation should count
585    //! //   as one unit of health for the breaker, but this does not gate individual
586    //! //   retry attempts on transport health -- choose this deliberately, not by
587    //! //   default
588    //! ServiceBuilder::new()
589    //!     .layer(CircuitBreakerLayer::new(cb_config))  // Outer
590    //!     .layer(RetryLayer::new(config))              // Inner
591    //!     .service(svc)
592    //! ```
593}
594
595pub mod anti_patterns {
596    //! # Common Anti-Patterns
597    //!
598    //! Pitfalls to avoid when composing resilience patterns.
599    //!
600    //! ## 1. Retry Storm
601    //!
602    //! **Problem:** Retrying without backoff overwhelms failing services.
603    //!
604    //! ```text
605    //! // Bad: Immediate retries hammer the service
606    //! RetryLayer::builder()
607    //!     .max_attempts(5)
608    //!     .fixed_backoff(Duration::ZERO)
609    //!     .build()
610    //! ```
611    //!
612    //! ```text
613    //! // Good: Exponential backoff with jitter
614    //! RetryLayer::builder()
615    //!     .max_attempts(3)
616    //!     .exponential_backoff(Duration::from_millis(100))
617    //!     .build()
618    //! ```
619    //!
620    //! ## 2. Timeout Inside Timeout
621    //!
622    //! **Problem:** Inner timeout longer than outer, making outer ineffective.
623    //!
624    //! ```text
625    //! // Bad: Inner timeout (10s) longer than outer (5s) - inner never triggers
626    //! ServiceBuilder::new()
627    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(5)))   // Outer: 5s
628    //!     .layer(RetryLayer::new(config))
629    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(10)))  // Inner: 10s
630    //!     .service(svc)
631    //! ```
632    //!
633    //! ```text
634    //! // Good: Inner timeout shorter than outer
635    //! ServiceBuilder::new()
636    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(30)))  // Total: 30s
637    //!     .layer(RetryLayer::new(config))
638    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(10)))  // Per-attempt: 10s
639    //!     .service(svc)
640    //! ```
641    //!
642    //! ## 3. Circuit Breaker Too Sensitive
643    //!
644    //! **Problem:** Opens on normal traffic variance.
645    //!
646    //! ```text
647    //! // Bad: Opens on 2 failures out of 10
648    //! CircuitBreakerLayer::builder()
649    //!     .failure_rate_threshold(0.1)  // 10% threshold
650    //!     .minimum_number_of_calls(10)
651    //!     .build()
652    //! ```
653    //!
654    //! ```text
655    //! // Good: Requires sustained failure pattern
656    //! CircuitBreakerLayer::builder()
657    //!     .failure_rate_threshold(0.5)   // 50% threshold
658    //!     .minimum_number_of_calls(20)   // Need 20 calls before evaluating
659    //!     .sliding_window_size(100)      // Over last 100 calls
660    //!     .build()
661    //! ```
662    //!
663    //! ## 4. Bulkhead Too Small
664    //!
665    //! **Problem:** Legitimate traffic rejected.
666    //!
667    //! ```text
668    //! // Bad: Only 2 concurrent calls
669    //! BulkheadLayer::builder()
670    //!     .max_concurrent_calls(2)
671    //!     .build()
672    //! ```
673    //!
674    //! ```text
675    //! // Good: Sized for expected concurrency + headroom
676    //! BulkheadLayer::builder()
677    //!     .max_concurrent_calls(50)  // Based on load testing
678    //!     .max_wait_duration(Duration::from_secs(1))
679    //!     .build()
680    //! ```
681    //!
682    //! ## 5. Retrying Non-Idempotent Operations
683    //!
684    //! **Problem:** Duplicate side effects (double charges, duplicate messages).
685    //!
686    //! ```text
687    //! // Bad: Retry POST without idempotency
688    //! RetryLayer::builder()
689    //!     .retry_on(|_| true)  // Retries everything
690    //!     .build()
691    //! ```
692    //!
693    //! ```text
694    //! // Good: Only retry safe operations
695    //! RetryLayer::builder()
696    //!     .retry_on(|e| {
697    //!         e.is_transient() && request.method().is_idempotent()
698    //!     })
699    //!     .build()
700    //! ```
701    //!
702    //! ## 6. Missing Fallback for User-Facing Services
703    //!
704    //! **Problem:** Users see raw errors.
705    //!
706    //! ```text
707    //! // Bad: Error propagates to user
708    //! ServiceBuilder::new()
709    //!     .layer(CircuitBreakerLayer::new(config))
710    //!     .service(product_catalog)
711    //! ```
712    //!
713    //! ```text
714    //! // Good: Graceful degradation
715    //! ServiceBuilder::new()
716    //!     .layer(FallbackLayer::value(cached_catalog))
717    //!     .layer(CircuitBreakerLayer::new(config))
718    //!     .service(product_catalog)
719    //! ```
720    //!
721    //! ## 7. Hedging Non-Idempotent Operations
722    //!
723    //! **Problem:** Duplicate writes or side effects.
724    //!
725    //! ```text
726    //! // Bad: Hedging a write operation
727    //! ServiceBuilder::new()
728    //!     .layer(HedgeLayer::builder()
729    //!         .delay(Duration::from_millis(50))
730    //!         .build())
731    //!     .service(create_order)  // Could create duplicate orders!
732    //! ```
733    //!
734    //! ```text
735    //! // Good: Only hedge reads or idempotent operations
736    //! ServiceBuilder::new()
737    //!     .layer(HedgeLayer::builder()
738    //!         .delay(Duration::from_millis(50))
739    //!         .build())
740    //!     .service(get_product)  // Safe to duplicate
741    //! ```
742    //!
743    //! ## 8. Retry Without Timeout
744    //!
745    //! **Problem:** Each attempt can hang forever, exhausting resources.
746    //!
747    //! ```text
748    //! // Bad: No timeout, retries can hang indefinitely
749    //! ServiceBuilder::new()
750    //!     .layer(RetryLayer::builder()
751    //!         .max_attempts(3)
752    //!         .build())
753    //!     .service(http_client)
754    //! ```
755    //!
756    //! ```text
757    //! // Good: Timeout bounds each attempt
758    //! ServiceBuilder::new()
759    //!     .layer(RetryLayer::builder()
760    //!         .max_attempts(3)
761    //!         .build())
762    //!     .layer(TimeLimiterLayer::new(Duration::from_secs(10)))
763    //!     .service(http_client)
764    //! ```
765}
766
767pub mod error_types {
768    //! # Error Type Integration
769    //!
770    //! When composing multiple resilience layers, all layers must agree on error types.
771    //! Tower-resilience provides three approaches, from simplest to most flexible.
772    //!
773    //! ## 1. `ResilienceError<E>` (Recommended - Zero Boilerplate)
774    //!
775    //! Use the provided [`ResilienceError<E>`](tower_resilience_core::ResilienceError) type
776    //! to eliminate manual `From` implementations:
777    //!
778    //! ```rust,no_run
779    //! # #[cfg(all(feature = "bulkhead", feature = "ratelimiter"))]
780    //! # {
781    //! use tower::ServiceBuilder;
782    //! use tower_resilience_core::ResilienceError;
783    //! use tower_resilience_bulkhead::BulkheadLayer;
784    //! use tower_resilience::ratelimiter::RateLimiterLayer;
785    //! use std::time::Duration;
786    //!
787    //! // Your application error
788    //! #[derive(Debug, Clone)]
789    //! enum AppError {
790    //!     DatabaseDown,
791    //!     InvalidRequest,
792    //! }
793    //!
794    //! impl std::fmt::Display for AppError {
795    //!     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
796    //!         match self {
797    //!             AppError::DatabaseDown => write!(f, "Database down"),
798    //!             AppError::InvalidRequest => write!(f, "Invalid"),
799    //!         }
800    //!     }
801    //! }
802    //!
803    //! impl std::error::Error for AppError {}
804    //!
805    //! // That's it! Zero From implementations needed
806    //! type ServiceError = ResilienceError<AppError>;
807    //!
808    //! // All resilience layer errors automatically convert to ResilienceError
809    //! // let service = ServiceBuilder::new()
810    //! //     .layer(bulkhead)
811    //! //     .layer(rate_limiter)
812    //! //     .service(my_service);
813    //! # }
814    //! ```
815    //!
816    //! **Benefits:**
817    //! - Zero boilerplate - no manual `From` implementations
818    //! - Works with any number of layers
819    //! - Rich error context (layer names, counts, durations)
820    //! - Convenient helpers: `is_timeout()`, `is_rate_limited()`, etc.
821    //! - Application errors wrapped in `Application` variant
822    //!
823    //! **Use when:**
824    //! - Building new services
825    //! - You want to move fast with minimal code
826    //! - Standard error categorization is sufficient
827    //!
828    //! ## 2. Custom Error Type with Manual From
829    //!
830    //! Define your own error type and implement `From` for each layer:
831    //!
832    //! ```rust,no_run
833    //! # use std::time::Duration;
834    //! # #[cfg(all(feature = "retry", feature = "circuitbreaker"))]
835    //! # {
836    //! use tower_resilience::retry::RetryLayer;
837    //! use tower_resilience::circuitbreaker::CircuitBreakerLayer;
838    //!
839    //! #[derive(Debug, Clone)]
840    //! enum ServiceError {
841    //!     Network(String),
842    //!     Timeout,
843    //!     CircuitOpen,
844    //!     RateLimit,
845    //! }
846    //!
847    //! // Manual From implementations give you full control
848    //! // impl From<BulkheadError> for ServiceError { /* ... */ }
849    //! // impl From<CircuitBreakerError> for ServiceError { /* ... */ }
850    //!
851    //! let retry = RetryLayer::<(), (), ServiceError>::builder()
852    //!     .max_attempts(3)
853    //!     .retry_on(|err| matches!(err, ServiceError::Network(_)))
854    //!     .build();
855    //! # }
856    //! ```
857    //!
858    //! **Use when:**
859    //! - You need very specific error semantics
860    //! - Different recovery strategies per layer
861    //! - Integrating with legacy error types
862    //! - Custom error logging requirements
863    //!
864    //! ## 3. Error Mapping Layer
865    //!
866    //! Use `tower::util::MapErr` to convert between error types:
867    //!
868    //! ```rust,no_run
869    //! # #[cfg(feature = "retry")]
870    //! # {
871    //! use tower::{ServiceBuilder, ServiceExt};
872    //! use tower_resilience::retry::RetryLayer;
873    //! use std::time::Duration;
874    //!
875    //! # #[derive(Debug)]
876    //! # struct DatabaseError;
877    //! # #[derive(Debug, Clone)]
878    //! # struct AppError;
879    //! # impl From<DatabaseError> for AppError {
880    //! #     fn from(_: DatabaseError) -> Self { AppError }
881    //! # }
882    //! # async fn example() {
883    //! # let db_service = tower::service_fn(|_req: ()| async { Ok::<_, DatabaseError>(()) });
884    //! let service = ServiceBuilder::new()
885    //!     .layer(RetryLayer::<(), (), AppError>::builder()
886    //!         .max_attempts(3)
887    //!         .build())
888    //!     .map_err(|err: DatabaseError| AppError::from(err))
889    //!     .service(db_service);
890    //! # }
891    //! # }
892    //! ```
893}
894
895pub mod advanced {
896    //! # Advanced Composition
897    //!
898    //! ## Overview
899    //!
900    //! Tower-resilience patterns are designed to compose together using Tower's `ServiceBuilder`.
901    //! However, composing 3+ layers can encounter Rust trait bound limitations. This guide
902    //! explains successful patterns and workarounds.
903    //!
904    //! ## Basic Composition (2 Layers)
905    //!
906    //! Two-layer composition works reliably with `ServiceBuilder`:
907    //!
908    //! ```rust,no_run
909    //! # #[cfg(all(feature = "retry", feature = "timelimiter"))]
910    //! # {
911    //! use tower::ServiceBuilder;
912    //! use tower_resilience::retry::RetryLayer;
913    //! use tower_resilience::timelimiter::TimeLimiterLayer;
914    //! use std::time::Duration;
915    //!
916    //! # #[derive(Debug, Clone)]
917    //! # struct MyError;
918    //! # async fn example() {
919    //! # let service = tower::service_fn(|_req: ()| async { Ok::<_, MyError>(()) });
920    //! let composed = ServiceBuilder::new()
921    //!     .layer(TimeLimiterLayer::builder()
922    //!         .timeout_duration(Duration::from_secs(5))
923    //!         .build())
924    //!     .layer(RetryLayer::<(), (), MyError>::builder()
925    //!         .max_attempts(3)
926    //!         .exponential_backoff(Duration::from_millis(100))
927    //!         .build())
928    //!     .service(service);
929    //! # }
930    //! # }
931    //! ```
932    //!
933    //! ## Limitations with 3+ Layers
934    //!
935    //! **Problem**: Composing 3+ resilience layers using `ServiceBuilder` often hits Rust
936    //! trait bound limitations. This is a known issue with complex Tower layer stacks.
937    //!
938    //! **Why it happens**:
939    //! - Each layer wraps the service in a new type
940    //! - Trait bounds become deeply nested
941    //! - Rust's type inference struggles with complex layer stacks
942    //! - Some combinations trigger "overflow evaluating the requirement" errors
943    //!
944    //! **Example that may fail**:
945    //!
946    //! ```rust,ignore
947    //! // This may encounter trait bound errors
948    //! ServiceBuilder::new()
949    //!     .layer(cache_layer)
950    //!     .layer(circuit_breaker)
951    //!     .layer(retry_layer)
952    //!     .layer(timeout_layer)
953    //!     .service(base_service);  // Error: trait bounds not satisfied
954    //! ```
955    //!
956    //! ## Workarounds
957    //!
958    //! ### 1. Manual Layer Composition
959    //!
960    //! Apply layers one at a time manually (most reliable):
961    //!
962    //! ```rust,no_run
963    //! # #[cfg(all(feature = "retry", feature = "circuitbreaker", feature = "cache"))]
964    //! # {
965    //! use tower::Layer;
966    //! use tower_resilience::retry::RetryLayer;
967    //! use tower_resilience::circuitbreaker::CircuitBreakerLayer;
968    //! use tower_resilience_cache::CacheLayer;
969    //! use std::time::Duration;
970    //!
971    //! # #[derive(Debug, Clone)]
972    //! # struct MyError;
973    //! # #[derive(Clone)]
974    //! # struct Request { id: u64 }
975    //! # async fn example() {
976    //! # let base_service = tower::service_fn(|req: Request| async { Ok::<_, MyError>(req) });
977    //! // Build layers inside-out manually
978    //! let with_retry = RetryLayer::<Request, Request, MyError>::builder()
979    //!     .max_attempts(3)
980    //!     .build()
981    //!     .layer(base_service);
982    //!
983    //! let with_circuit_breaker = CircuitBreakerLayer::builder()
984    //!     .failure_rate_threshold(0.5)
985    //!     .build()
986    //!     .unwrap()
987    //!     .layer(with_retry);
988    //!
989    //! let service = CacheLayer::builder()
990    //!     .max_size(1000)
991    //!     .ttl(Duration::from_secs(300))
992    //!     .key_extractor(|req: &Request| req.id)
993    //!     .build()
994    //!     .unwrap()
995    //!     .layer(with_circuit_breaker);
996    //! # }
997    //! # }
998    //! ```
999    //!
1000    //! ### 2. Limit ServiceBuilder Stack Depth
1001    //!
1002    //! Keep ServiceBuilder stacks to 2-3 layers max, compose manually beyond that:
1003    //!
1004    //! ```rust,no_run
1005    //! # #[cfg(all(feature = "retry", feature = "timelimiter", feature = "cache"))]
1006    //! # {
1007    //! use tower::{ServiceBuilder, Layer};
1008    //! use tower_resilience::retry::RetryLayer;
1009    //! use tower_resilience::timelimiter::TimeLimiterLayer;
1010    //! use tower_resilience_cache::CacheLayer;
1011    //! use std::time::Duration;
1012    //!
1013    //! # #[derive(Debug, Clone)]
1014    //! # struct MyError;
1015    //! # #[derive(Clone)]
1016    //! # struct Request { id: u64 }
1017    //! # async fn example() {
1018    //! # let base_service = tower::service_fn(|req: Request| async { Ok::<_, MyError>(req) });
1019    //! // First 2 layers via ServiceBuilder
1020    //! let inner = ServiceBuilder::new()
1021    //!     .layer(TimeLimiterLayer::builder()
1022    //!         .timeout_duration(Duration::from_secs(5))
1023    //!         .build())
1024    //!     .layer(RetryLayer::<Request, Request, MyError>::builder()
1025    //!         .max_attempts(3)
1026    //!         .build())
1027    //!     .service(base_service);
1028    //!
1029    //! // Additional layers manually
1030    //! let service = CacheLayer::builder()
1031    //!     .max_size(1000)
1032    //!     .ttl(Duration::from_secs(300))
1033    //!     .key_extractor(|req: &Request| req.id)
1034    //!     .build()
1035    //!     .unwrap()
1036    //!     .layer(inner);
1037    //! # }
1038    //! # }
1039    //! ```
1040    //!
1041    //! ### 3. Split Complex Compositions
1042    //!
1043    //! For very complex stacks, split into logical groups and compose separately:
1044    //!
1045    //! ```rust,no_run
1046    //! # #[cfg(all(feature = "retry", feature = "timelimiter"))]
1047    //! # {
1048    //! use tower::{ServiceBuilder, Layer};
1049    //! use tower_resilience::retry::RetryLayer;
1050    //! use tower_resilience::timelimiter::TimeLimiterLayer;
1051    //! use std::time::Duration;
1052    //!
1053    //! # #[derive(Debug, Clone)]
1054    //! # struct MyError;
1055    //! # async fn example() {
1056    //! # let base_service = tower::service_fn(|_req: ()| async { Ok::<_, MyError>(()) });
1057    //! // Build retry layer first
1058    //! let retry_layer = RetryLayer::<(), (), MyError>::builder()
1059    //!     .max_attempts(3)
1060    //!     .build();
1061    //!
1062    //! // Apply retry manually
1063    //! let with_retry = retry_layer.layer(base_service);
1064    //!
1065    //! // Then use ServiceBuilder for remaining layers
1066    //! let service = ServiceBuilder::new()
1067    //!     .layer(TimeLimiterLayer::builder()
1068    //!         .timeout_duration(Duration::from_secs(5))
1069    //!         .build())
1070    //!     .service(with_retry);
1071    //! # }
1072    //! # }
1073    //! ```
1074    //!
1075    //! ## Working Examples
1076    //!
1077    //! See the repository examples for complete, working compositions:
1078    //!
1079    //! - [`examples/composition_outbound.rs`] - Client-side resilience stack
1080    //! - [`examples/server_api.rs`] - Server-side protection
1081    //!
1082    //! [`examples/composition_outbound.rs`]: https://github.com/joshrotenberg/tower-resilience/blob/main/examples/composition_outbound.rs
1083    //! [`examples/server_api.rs`]: https://github.com/joshrotenberg/tower-resilience/blob/main/examples/server_api.rs
1084}
1085
1086pub mod references {
1087    //! # References
1088    //!
1089    //! ## Books
1090    //!
1091    //! - **"Release It!" by Michael Nygard** - Foundational text on stability patterns
1092    //!
1093    //! ## Papers
1094    //!
1095    //! - **"The Tail at Scale" (Dean & Barroso, Google 2013)** - Essential reading on
1096    //!   tail latency and hedging.
1097    //!   [CACM Link](https://cacm.acm.org/research/the-tail-at-scale/)
1098    //!
1099    //! ## Prior Art
1100    //!
1101    //! - **Resilience4j** (Java) - Primary inspiration for this library.
1102    //!   [Docs](https://resilience4j.readme.io/)
1103    //! - **Polly** (.NET) - Excellent PolicyWrap ordering guide.
1104    //!   [Wiki](https://github.com/App-vNext/Polly/wiki/PolicyWrap)
1105    //! - **Netflix Hystrix** (maintenance mode) - Pioneered many patterns.
1106    //!   [GitHub](https://github.com/Netflix/Hystrix)
1107    //! - **Failsafe** (Java) - Clean API design inspiration.
1108    //!   [Docs](https://failsafe.dev/)
1109    //!
1110    //! ## Tower Ecosystem
1111    //!
1112    //! - **tower** - [docs.rs/tower](https://docs.rs/tower)
1113    //! - **tower-http** - [docs.rs/tower-http](https://docs.rs/tower-http)
1114    //!
1115    //! ## Pattern Documentation
1116    //!
1117    //! - [Circuit Breaker Pattern (Martin Fowler)](https://martinfowler.com/bliki/CircuitBreaker.html)
1118    //! - [Bulkhead Pattern (Azure Architecture)](https://docs.microsoft.com/en-us/azure/architecture/patterns/bulkhead)
1119    //! - [Retry Pattern (Azure Architecture)](https://docs.microsoft.com/en-us/azure/architecture/patterns/retry)
1120}