World-class performance with industry-leading benchmarks:
- Counter: 4.93ns/op (202.84M ops/sec)
- Gauge: 0.53ns/op (1886.79M ops/sec)
- Timer: 10.87ns/op (91.99M ops/sec)
- Memory: 64 bytes per metric (cache-aligned)
Features
Core Metrics
- 🔢 Counters - Atomic increment/decrement with overflow protection
- 📊 Gauges - IEEE 754 atomic floating-point with mathematical operations
- ⏱️ Timers - Nanosecond precision with RAII guards and batch recording
- 📈 Rate Meters - Sliding window rates with burst detection and API limiting
- 💾 System Health - Built-in CPU, memory, and process monitoring
Advanced Features
- Lock-Free - Zero locks in hot paths, pure atomic operations
- Async Native - First-class async/await support with zero-cost abstractions
- Resilience - Circuit breakers, adaptive sampling, and backpressure control
- Cross-Platform - Linux, macOS, Windows with optimized system integrations
- Cache-Aligned - 64-byte alignment prevents false sharing
API Overview
For a complete reference with examples, see docs/API.md
.
Counter
— ultra-fast atomic counters with batch and conditional opsGauge
— atomic f64 gauges with math ops, EMA, and min/max helpersTimer
— nanosecond timers, RAII guards, and closure/async timingRateMeter
— sliding-window rate tracking and burstsSystemHealth
— CPU, memory, load, threads, FDs, health score- Async support —
AsyncTimerExt
,AsyncMetricBatch
- Adaptive controls — sampling, circuit breaker, backpressure
- Prelude — convenient re-exports
Error handling: try_ variants
All core metrics expose non-panicking try_
methods that validate inputs and return Result<_, MetricsError>
instead of panicking:
Counter
:try_inc
,try_add
,try_set
,try_fetch_add
,try_inc_and_get
Gauge
:try_set
,try_add
,try_sub
,try_set_max
,try_set_min
Timer
:try_record_ns
,try_record
,try_record_batch
RateMeter
:try_tick
,try_tick_n
,try_tick_if_under_limit
Error semantics:
MetricsError::Overflow
— arithmetic would overflow/underflow an internal counter.MetricsError::InvalidValue { reason }
— non-finite or otherwise invalid input (e.g., NaN forGauge
).MetricsError::OverLimit
— operation would exceed a configured limit (e.g., rate limiting helpers).
Example:
use ;
init;
let c = metrics.counter;
c.try_add?; // Result<(), MetricsError>
let r = metrics.rate;
let allowed = r.try_tick_if_under_limit?; // Result<bool, MetricsError>
Panic guarantees: the plain methods (inc
, add
, set
, tick
, etc.) prioritize speed and may saturate or assume valid inputs. Prefer try_
variants when you need explicit error handling.
Installation
Add to your Cargo.toml
:
[]
= "0.9.0"
# Optional features
= { = "0.9.0", = ["async"] }
Quick Start
use ;
// Initialize once at startup
init;
// Counters - fastest operations (18ns)
metrics.counter.inc;
metrics.counter.add;
// Gauges - sub-nanosecond operations (0.6ns)
metrics.gauge.set;
metrics.gauge.add;
// Timers - automatic RAII timing
// Or time a closure
let result = metrics.time;
// System health monitoring
let cpu = metrics.system.cpu_used;
let memory_gb = metrics.system.mem_used_gb;
// Rate metering
metrics.rate.tick;
Observability Quick Start
- Integration Examples: see
docs/API.md#integration-examples
- Grafana dashboard (ready to import):
docs/observability/grafana-dashboard.json
- Prometheus recording rules:
docs/observability/recording-rules.yaml
- Kubernetes Service:
docs/k8s/service.yaml
- Prometheus Operator ServiceMonitor:
docs/k8s/servicemonitor.yaml
- Secured ServiceMonitor (TLS/Bearer):
docs/k8s/servicemonitor-secured.yaml
Commands
# Import Grafana dashboard via API
# Validate Prometheus recording rules
# Apply Kubernetes manifests
# For secured endpoints
Advanced Usage
Async Support
use Duration;
use ;
// Async timing with zero overhead and typed result
let result: &str = metrics
.timer
.time_async
.await;
// Batched async updates (flush takes &MetricsCore)
let mut batch = new;
batch.counter_inc;
batch.gauge_set;
batch.flush;
Examples
Run these self-contained examples to see the library in action:
-
Quick Start
- File:
examples/quick_start.rs
- Run:
- File:
-
Streaming Rate Window
- File:
examples/streaming_rate_window.rs
- Run:
- File:
-
Axum Registry Integration (minimal web service)
- File:
examples/axum_registry_integration.rs
- Run:
- Endpoints:
GET /health
— liveness probeGET /metrics-demo
— updates metrics (counter/gauge/timer/rate)GET /export
— returns a JSON snapshot of selected metrics
- File:
-
Quick Tour
- File:
examples/quick_tour.rs
- Run:
- File:
-
Async Batch + Timing
- File:
examples/async_batch_timing.rs
- Run:
- File:
-
Token Bucket Rate Limiter
- File:
examples/token_bucket_limiter.rs
- Run:
- File:
-
Custom Exporter (OpenMetrics-like)
- File:
examples/custom_exporter_openmetrics.rs
- Run:
- File:
-
Axum Middleware Metrics (minimal)
- File:
examples/axum_middleware_metrics.rs
- Run:
- File:
-
Contention & Admission Demo
- File:
examples/contention_admission.rs
- Run:
- File:
-
CPU Stats Overview
- File:
examples/cpu_stats.rs
- Run:
- File:
-
Memory Stats Overview
- File:
examples/memory_stats.rs
- Run:
- File:
-
Health Dashboard
- File:
examples/health_dashboard.rs
- Run:
- File:
-
Cache Hit/Miss
- File:
examples/cache_hit_miss.rs
- Run:
- File:
-
Broker Throughput
- File:
examples/broker_throughput.rs
- Run:
- File:
More Real-World Examples (API Reference)
- Building a Custom Exporter — see
docs/API.md
→ Building a Custom Exporter - Memory Stats: total/used/free + percentages — see
docs/API.md
→ Memory Stats - Memory % used for an operation (estimate) — see
docs/API.md
→ Memory % for an operation - CPU Stats: total/used/free + percentages — see
docs/API.md
→ CPU Stats - CPU % used for an operation (estimate) — see
docs/API.md
→ CPU % for an operation
Resilience Features
Running many examples quickly
For convenience, a helper script runs a curated set of non-blocking examples sequentially in release mode (skips server examples like Axum middleware):
You can also pass a custom comma-separated list via EXAMPLES
:
EXAMPLES="quick_start,quick_tour,cpu_stats"
use ;
// Adaptive sampling under load
let sampler = new;
if sampler.should_sample
// Circuit breaker protection
let breaker = new;
if breaker.is_allowed else
System Monitoring
let health = metrics.system;
println!;
println!;
println!;
println!;
Benchmarks
Run the included benchmarks to see performance on your system:
# Basic performance comparison
# Comprehensive benchmarks (Criterion)
# Cross-platform system tests
Interpreting Criterion Results
- Criterion writes reports to
target/criterion/
with per-benchmark statistics and comparisons. - Key numbers to watch:
time: [low … mean … high]
and outlier percentages. - Compare runs over time to detect regressions. Store artifacts from CI for historical comparison.
- Benchmarks are microbenchmarks; validate with end-to-end measurements as needed.
CI Artifacts
- Pull Requests: CI runs a fast smoke bench and uploads
criterion-reports
withtarget/criterion
. - Nightly: The
Benchmarks
workflow runs full-duration benches on Linux/macOS/Windows and uploads artifacts asbenchmark-results-<os>
. - You can download these artifacts from the GitHub Actions run page to compare results across commits.
Latest CI Benchmarks
View the latest nightly results and artifacts here:
Latest CI Benchmarks (Benchmarks workflow)
Benchmark history (GitHub Pages):
Sample Results (M1 MacBook Pro):
Counter Increment: 4.93 ns/op (202.84 M ops/sec)
Gauge Set: 0.53 ns/op (1886.79 M ops/sec)
Timer Record: 10.87 ns/op (91.99 M ops/sec)
Mixed Operations: 106.39 ns/op (9.40 M ops/sec)
Notes: Latest numbers taken from local Criterion means under target/criterion/**/new/estimates.json
. Actual throughput varies by CPU and environment; use the GitHub Pages benchmark history for trends.
Methodology
- Tooling: Criterion with release builds.
- Flags for stability on local runs:
cargo bench -- -w 3.0 -m 5.0 -n 100
(increase on dedicated runners). - Environment disclosure (example):
- CPU: Apple M1 Pro (performance cores)
- Rust: stable toolchain
- Target: aarch64-apple-darwin
- Governor: default (for CI use a performance governor where applicable)
See also: docs/zero-overhead-proof.md
for assembly inspection and binary size analysis, and docs/performance-tuning.md
for environment hardening.
Architecture
Lock-Free Design
- Atomic Operations: All metrics use
Relaxed
ordering for maximum performance - Cache-Line Alignment: 64-byte alignment eliminates false sharing
- Compare-and-Swap: Lock-free min/max tracking in timers
- Thread-Local Storage: Fast random number generation for sampling
Memory Layout
Zero-Cost Abstractions
- RAII Timers: Compile-time guaranteed cleanup
- Async Guards: No allocation futures for timing
- Batch Operations: Vectorized updates for efficiency
Testing
Comprehensive test suite with 87 unit tests and 2 documentation tests:
# Run all tests
# Test with all features
# Run only bench-gated tests (feature-flagged and ignored by default)
# Run benchmarks (Criterion)
# Check for memory leaks (with valgrind)
Cross-Platform Support
Tier 1 Support:
- ✅ Linux (x86_64, aarch64)
- ✅ macOS (x86_64, Apple Silicon)
- ✅ Windows (x86_64)
System Integration:
- Linux:
/proc
filesystem,sysinfo
APIs - macOS:
mach
system calls,sysctl
APIs - Windows: Performance counters, WMI integration
Graceful Fallbacks:
- Unsupported platforms default to portable implementations
- Feature detection at runtime
- No panics on missing system features
Comparison
Library | Counter ns/op | Gauge ns/op | Timer ns/op | Memory/Metric | Features |
---|---|---|---|---|---|
metrics-lib | 4.93 | 0.53 | 10.87 | 64B | ✅ Async, Circuit breakers, System monitoring |
metrics-rs | 85.2 | 23.1 | 167.8 | 256B | ⚠️ No circuit breakers |
prometheus | 156.7 | 89.4 | 298.3 | 1024B+ | ⚠️ HTTP overhead |
statsd | 234.1 | 178.9 | 445.2 | 512B+ | ⚠️ Network overhead |
Configuration
Feature Flags
[]
= { = "0.9.0", = [
"async", # Async/await support (requires tokio)
"histogram", # Advanced histogram support
"all" # Enable all features
]}
Runtime Configuration
use ;
let config = Config ;
init_with_config;
Contributing
We welcome contributions! Please see our Contributing Guide.
Development Setup
# Clone repository
# Run tests
# Run benchmarks
# Check formatting and lints
Links
- 📚 Documentation
- 📦 Crates.io
- 🐛 Issues
- 💬 Discussions
Guides
- Migrating from metrics-rs:
docs/migrating-from-metrics-rs.md
- Performance Tuning:
docs/performance-tuning.md
- Zero-Overhead Proof:
docs/zero-overhead-proof.md
- API Stability Guarantees:
docs/api-stability.md