tracing_throttle/lib.rs
1//! # tracing-throttle
2//!
3//! High-performance log deduplication and rate limiting for the `tracing` ecosystem.
4//!
5//! This crate provides a `tracing::Layer` that suppresses repetitive log events based on
6//! configurable policies. Events are deduplicated by their signature (level, target, and message).
7//! Event field **values** are NOT included in signatures by default - use
8//! `.with_event_fields()` to include specific fields.
9//!
10//!
11//! ## Quick Start
12//!
13//! ```rust,no_run
14//! use tracing_throttle::{TracingRateLimitLayer, Policy};
15//! use tracing_subscriber::prelude::*;
16//! use std::time::Duration;
17//!
18//! // Use sensible defaults: 50 burst capacity, 1 token/sec (60/min), 10k signature limit
19//! let rate_limit = TracingRateLimitLayer::new();
20//!
21//! // Or customize for high-volume applications:
22//! let rate_limit = TracingRateLimitLayer::builder()
23//! .with_policy(Policy::token_bucket(100.0, 10.0).unwrap()) // 100 burst, 600/min
24//! .with_max_signatures(50_000) // Custom limit
25//! .with_summary_interval(Duration::from_secs(30))
26//! .build()
27//! .unwrap();
28//!
29//! // Apply the rate limit as a filter to your fmt layer
30//! tracing_subscriber::registry()
31//! .with(tracing_subscriber::fmt::layer().with_filter(rate_limit))
32//! .init();
33//! ```
34//!
35//! ## Features
36//!
37//! ### Rate Limiting Policies
38//! - **Token bucket limiting**: Burst tolerance with smooth recovery (recommended default)
39//! - **Time-window limiting**: Allow K events per time period with natural reset
40//! - **Count-based limiting**: Allow N events, then suppress the rest (no recovery)
41//! - **Exponential backoff**: Emit at exponentially increasing intervals (1st, 2nd, 4th, 8th...)
42//! - **Custom policies**: Implement your own rate limiting logic
43//!
44//! ### Eviction Strategies
45//! - **LRU eviction**: Evict least recently used signatures (default)
46//! - **Priority-based**: Custom priority functions to keep important events (ERROR over INFO)
47//! - **Memory-based**: Enforce byte limits with automatic memory tracking
48//! - **Combined**: Use both priority and memory constraints together
49//!
50//! ### Other Features
51//! - **Per-signature throttling**: Different messages are throttled independently
52//! - **Observability metrics**: Built-in tracking of allowed, suppressed, and evicted events
53//! - **Fail-safe circuit breaker**: Fails open during errors to preserve observability
54//!
55//! ## Event Signatures
56//!
57//! Events are deduplicated based on their **signature**. By default, signatures include:
58//! - Event level (INFO, WARN, ERROR, etc.)
59//! - Target (module path)
60//! - Message text
61//!
62//! **Event field VALUES are NOT included by default.** This means:
63//!
64//! ```rust,no_run
65//! # use tracing::info;
66//! info!(user_id = 1, "Login"); // Signature: (INFO, target, "Login")
67//! info!(user_id = 2, "Login"); // SAME signature - will be rate limited together!
68//! ```
69//!
70//! To rate-limit events per field value, use `.with_event_fields()`:
71//!
72//! ```rust,no_run
73//! # use tracing_throttle::TracingRateLimitLayer;
74//! let layer = TracingRateLimitLayer::builder()
75//! .with_event_fields(vec!["user_id".to_string()]) // Include user_id in signature
76//! .build()
77//! .unwrap();
78//! ```
79//!
80//! Now each user_id gets its own rate limit:
81//!
82//! ```rust,no_run
83//! # use tracing::info;
84//! info!(user_id = 1, "Login"); // Signature: (INFO, target, "Login", user_id=1)
85//! info!(user_id = 2, "Login"); // Signature: (INFO, target, "Login", user_id=2)
86//! ```
87//!
88//! **See `tests/event_fields.rs` for complete examples.**
89//!
90//! ## Observability
91//!
92//! Monitor rate limiting behavior with built-in metrics:
93//!
94//! ```rust,no_run
95//! # use tracing_throttle::{TracingRateLimitLayer, Policy};
96//! # let rate_limit = TracingRateLimitLayer::builder()
97//! # .with_policy(Policy::count_based(100).unwrap())
98//! # .build()
99//! # .unwrap();
100//! // Get current metrics
101//! let metrics = rate_limit.metrics();
102//! println!("Events allowed: {}", metrics.events_allowed());
103//! println!("Events suppressed: {}", metrics.events_suppressed());
104//! println!("Signatures evicted: {}", metrics.signatures_evicted());
105//!
106//! // Get snapshot for calculations
107//! let snapshot = metrics.snapshot();
108//! println!("Suppression rate: {:.2}%", snapshot.suppression_rate() * 100.0);
109//! ```
110//!
111//! ## Eviction Strategies
112//!
113//! Control which event signatures are kept when storage limits are reached:
114//!
115//! ### LRU (Default)
116//!
117//! ```rust,no_run
118//! # use tracing_throttle::TracingRateLimitLayer;
119//! let layer = TracingRateLimitLayer::builder()
120//! .with_max_signatures(10_000) // Uses LRU eviction by default
121//! .build()
122//! .unwrap();
123//! ```
124//!
125//! ### Priority-Based
126//!
127//! Keep important events (ERROR) over less important ones (INFO):
128//!
129//! ```rust,no_run
130//! # use tracing_throttle::{TracingRateLimitLayer, EvictionStrategy};
131//! # use std::sync::Arc;
132//! let layer = TracingRateLimitLayer::builder()
133//! .with_max_signatures(5_000)
134//! .with_eviction_strategy(EvictionStrategy::Priority(Arc::new(|_sig, state| {
135//! match state.metadata.as_ref().map(|m| m.level.as_str()) {
136//! Some("ERROR") => 100,
137//! Some("WARN") => 50,
138//! Some("INFO") => 10,
139//! _ => 5,
140//! }
141//! })))
142//! .build()
143//! .unwrap();
144//! ```
145//!
146//! ### Memory-Based
147//!
148//! Enforce memory limits with automatic tracking:
149//!
150//! ```rust,no_run
151//! # use tracing_throttle::{TracingRateLimitLayer, EvictionStrategy};
152//! let layer = TracingRateLimitLayer::builder()
153//! .with_eviction_strategy(EvictionStrategy::Memory {
154//! max_bytes: 5 * 1024 * 1024, // 5MB limit
155//! })
156//! .build()
157//! .unwrap();
158//! ```
159//!
160//! ### Combined
161//!
162//! Use both priority and memory constraints:
163//!
164//! ```rust,no_run
165//! # use tracing_throttle::{TracingRateLimitLayer, EvictionStrategy};
166//! # use std::sync::Arc;
167//! let layer = TracingRateLimitLayer::builder()
168//! .with_eviction_strategy(EvictionStrategy::PriorityWithMemory {
169//! priority_fn: Arc::new(|_sig, state| {
170//! match state.metadata.as_ref().map(|m| m.level.as_str()) {
171//! Some("ERROR") => 100,
172//! _ => 10,
173//! }
174//! }),
175//! max_bytes: 10 * 1024 * 1024,
176//! })
177//! .build()
178//! .unwrap();
179//! ```
180//!
181//! See `examples/eviction.rs` for complete working examples.
182//!
183//! ## Fail-Safe Operation
184//!
185//! The library uses a circuit breaker to fail open during errors, preserving
186//! observability over strict rate limiting:
187//!
188//! ```rust,no_run
189//! # use tracing_throttle::{TracingRateLimitLayer, CircuitState};
190//! # let rate_limit = TracingRateLimitLayer::new();
191//! // Check circuit breaker state
192//! let cb = rate_limit.circuit_breaker();
193//! match cb.state() {
194//! CircuitState::Closed => println!("Normal operation"),
195//! CircuitState::Open => println!("Failing open - allowing all events"),
196//! CircuitState::HalfOpen => println!("Testing recovery"),
197//! }
198//! ```
199//!
200//! ## Memory Management
201//!
202//! By default, tracks up to 10,000 unique event signatures with LRU eviction.
203//! Each signature uses approximately 200-400 bytes (includes event metadata for summaries).
204//!
205//! **Typical memory usage:**
206//! - 10,000 signatures (default): ~2-4 MB
207//! - 50,000 signatures: ~10-20 MB
208//! - 100,000 signatures: ~20-40 MB
209//!
210//! **Configuration:**
211//! ```rust,no_run
212//! # use tracing_throttle::TracingRateLimitLayer;
213//! // Increase limit for high-cardinality applications
214//! let rate_limit = TracingRateLimitLayer::builder()
215//! .with_max_signatures(50_000)
216//! .build()
217//! .unwrap();
218//!
219//! // Monitor usage
220//! let sig_count = rate_limit.signature_count();
221//! let evictions = rate_limit.metrics().signatures_evicted();
222//! ```
223//!
224//! ### Memory Usage Breakdown
225//!
226//! Each tracked signature consumes memory for:
227//!
228//! ```text
229//! Per-Signature Memory:
230//! ├─ EventSignature (hash key) ~32 bytes (u64 hash)
231//! ├─ EventState (value) ~170-370 bytes
232//! │ ├─ Policy state ~40-80 bytes (depends on policy type)
233//! │ ├─ SuppressionCounter ~40 bytes (atomic counters + timestamp)
234//! │ ├─ EventMetadata (Optional) ~50-200 bytes (level, message, target, fields)
235//! │ │ ├─ Level string ~8 bytes
236//! │ │ ├─ Message string ~20-100 bytes (depends on message length)
237//! │ │ ├─ Target string ~20-50 bytes (module path)
238//! │ │ └─ Fields (BTreeMap) ~0-50 bytes (depends on field count)
239//! │ └─ Metadata overhead ~40 bytes (DashMap internals)
240//! └─ Total per signature ~200-400 bytes (varies with policy & message length)
241//! ```
242//!
243//! **Estimated memory usage at different signature limits:**
244//!
245//! | Signatures | Memory (typical) | Memory (worst case) | Use Case |
246//! |------------|------------------|---------------------|----------|
247//! | 1,000 | ~200 KB | ~400 KB | Small apps, few event types |
248//! | 10,000 (default) | ~2 MB | ~4 MB | Most applications |
249//! | 50,000 | ~10 MB | ~20 MB | High-cardinality apps |
250//! | 100,000 | ~20 MB | ~40 MB | Very large systems |
251//!
252//! **Additional overhead:**
253//! - Metrics: ~100 bytes (atomic counters)
254//! - Circuit breaker: ~200 bytes (state tracking)
255//! - Layer structure: ~500 bytes
256//! - **Total fixed overhead: ~800 bytes**
257//!
258//! ### Signature Cardinality Analysis
259//!
260//! **What affects signature cardinality?**
261//!
262//! By default, signatures are computed from `(level, target, message)` only.
263//! Field values are NOT included unless configured with `.with_event_fields()`.
264//!
265//! ```rust,no_run
266//! # use tracing::info;
267//! // Low cardinality (good) - same signature for all occurrences
268//! info!("User login successful"); // Always same signature
269//! info!(user_id = 123, "User login"); // SAME signature (user_id not included by default)
270//!
271//! // Medium cardinality - if you configure .with_event_fields(vec!["user_id".to_string()])
272//! # let id = 123;
273//! info!(user_id = %id, "User login"); // One signature per unique user_id
274//!
275//! // High cardinality (danger) - if you configure .with_event_fields(vec!["request_id".to_string()])
276//! # let uuid = "abc";
277//! info!(request_id = %uuid, "Processing"); // New signature every time!
278//! ```
279//!
280//! **Cardinality examples:**
281//!
282//! | Pattern | Config | Unique Signatures | Memory Impact |
283//! |---------|--------|-------------------|---------------|
284//! | Static messages only | Default | ~10-100 | Minimal (~10 KB) |
285//! | Messages with fields | Default (fields ignored) | ~10-100 | Minimal (~10 KB) |
286//! | `.with_event_fields(["user_id"])` | Stable IDs | ~1,000-10,000 | Low (1-2 MB) |
287//! | `.with_event_fields(["session_id"])` | Session IDs | ~10,000-100,000 | Medium (10-25 MB) |
288//! | `.with_event_fields(["request_id"])` | UUIDs | Unbounded | **High risk** |
289//!
290//! **How to estimate your cardinality:**
291//!
292//! 1. **Count unique log templates** in your codebase
293//! 2. **Multiply by field cardinality** (unique values per field)
294//! 3. **Example calculation:**
295//! - 50 unique log messages
296//! - 10 severity levels used
297//! - Average 20 unique user IDs per message
298//! - **Estimated: 50 × 20 = 1,000 signatures** (✓ well below default)
299//!
300//! ### Configuration Guidelines
301//!
302//! **When to use the default (10k signatures):**
303//! - ✅ Most applications with structured logging
304//! - ✅ Log messages use stable identifiers (user_id, tenant_id, service_name)
305//! - ✅ You're unsure about cardinality
306//! - ✅ Memory is not severely constrained
307//!
308//! **When to increase the limit:**
309//!
310//! ```rust,no_run
311//! # use tracing_throttle::TracingRateLimitLayer;
312//! let rate_limit = TracingRateLimitLayer::builder()
313//! .with_max_signatures(50_000) // 5-10 MB overhead
314//! .build()
315//! .expect("valid config");
316//! ```
317//!
318//! - ✅ High log volume with many unique event types (>10k)
319//! - ✅ Large distributed system with many services/endpoints
320//! - ✅ You've measured cardinality and need more capacity
321//! - ✅ Memory is available (10+ MB is acceptable)
322//!
323//! **When to use unlimited signatures:**
324//!
325//! ```rust,no_run
326//! # use tracing_throttle::TracingRateLimitLayer;
327//! let rate_limit = TracingRateLimitLayer::builder()
328//! .with_unlimited_signatures() // ⚠️ Unbounded memory growth
329//! .build()
330//! .expect("valid config");
331//! ```
332//!
333//! - ⚠️ **Use with extreme caution** - can cause unbounded memory growth
334//! - ✅ Controlled environments (short-lived processes, tests)
335//! - ✅ Known bounded cardinality with monitoring in place
336//! - ✅ Memory constraints are not a concern
337//! - ❌ **Never use** if logging includes UUIDs, timestamps, or other high-cardinality data
338//!
339//! ### Monitoring Memory Usage
340//!
341//! **Check signature count in production:**
342//!
343//! ```rust,no_run
344//! # use tracing_throttle::TracingRateLimitLayer;
345//! # use tracing::warn;
346//! # let rate_limit = TracingRateLimitLayer::new();
347//! // In a periodic health check or metrics reporter:
348//! let sig_count = rate_limit.signature_count();
349//! let evictions = rate_limit.metrics().signatures_evicted();
350//!
351//! if sig_count > 8000 {
352//! warn!("Approaching signature limit: {}/10000", sig_count);
353//! }
354//!
355//! if evictions > 1000 {
356//! warn!("High eviction rate: {} signatures evicted", evictions);
357//! }
358//! ```
359//!
360//! **Integrate with memory profilers:**
361//!
362//! ```bash
363//! # Use Valgrind Massif for heap profiling
364//! valgrind --tool=massif --massif-out-file=massif.out ./your-app
365//!
366//! # Analyze with ms_print
367//! ms_print massif.out
368//!
369//! # Look for DashMap and EventState allocations
370//! ```
371//!
372//! **Signs you need to adjust signature limits:**
373//!
374//! | Symptom | Likely Cause | Action |
375//! |---------|--------------|--------|
376//! | High eviction rate (>1000/min) | Cardinality > limit | Increase `max_signatures` |
377//! | Memory growth over time | Unbounded cardinality | Fix logging (remove UUIDs), add limit |
378//! | Low signature count (<100) | Over-provisioned | Can reduce limit safely |
379//! | Frequent evictions + suppression | Limit too low | Increase limit or reduce cardinality |
380
381// Domain layer - pure business logic
382pub mod domain;
383
384// Application layer - orchestration
385pub mod application;
386
387// Infrastructure layer - external adapters
388pub mod infrastructure;
389
390// Re-export commonly used types for convenience
391pub use domain::{
392 policy::{
393 CountBasedPolicy, ExponentialBackoffPolicy, Policy, PolicyDecision, PolicyError,
394 RateLimitPolicy, TimeWindowPolicy, TokenBucketPolicy,
395 },
396 signature::EventSignature,
397 summary::{SuppressionCounter, SuppressionSummary},
398};
399
400pub use application::{
401 circuit_breaker::{CircuitBreaker, CircuitBreakerConfig, CircuitState},
402 emitter::EmitterConfigError,
403 limiter::RateLimiter,
404 metrics::{Metrics, MetricsSnapshot},
405 ports::{Clock, Storage},
406 registry::SuppressionRegistry,
407};
408
409#[cfg(feature = "async")]
410pub use application::emitter::{EmitterHandle, ShutdownError};
411
412pub use infrastructure::{
413 clock::SystemClock,
414 eviction::{EvictionStrategy, PriorityFn},
415 layer::{BuildError, TracingRateLimitLayer, TracingRateLimitLayerBuilder},
416 storage::ShardedStorage,
417};
418
419#[cfg(feature = "async")]
420pub use infrastructure::layer::SummaryFormatter;
421
422#[cfg(feature = "redis-storage")]
423pub use infrastructure::redis_storage::{RedisStorage, RedisStorageConfig};