cache-kit 0.9.0

A type-safe, fully generic, production-ready caching framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
---
layout: single
title: Installation
description: "Getting started with cache-kit in your Rust project"
permalink: /installation/
nav_order: 2
date: 2025-12-21
---

---

## Prerequisites

- **Rust:** 1.75 or later
- **Tokio:** 1.41 or later (async runtime)

---

## For AI Agents & Automated Tools

If you're using an AI agent, code generator, or automated tool to integrate cache-kit, see the [Installation for Agents](/installation-agents/) page for structured, machine-readable setup information.

---

## Installation

Add cache-kit to your `Cargo.toml`:

```toml
[dependencies]
cache-kit = { version = "0.9" }
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.41", features = ["rt", "sync", "macros"] }
```

### Feature Flags

cache-kit uses feature flags to enable optional backends:

| Feature     | Description                           | Default     |
| ----------- | ------------------------------------- | ----------- |
| `inmemory`  | In-memory cache backend               | ✅ Enabled  |
| `redis`     | Redis backend with connection pooling | ❌ Optional |
| `memcached` | Memcached backend                     | ❌ Optional |
| `all`       | Enable all backends                   | ❌ Optional |

---

## Choosing Your API: CacheExpander vs CacheService

cache-kit provides two APIs for cache operations. **For most use cases, use `CacheService`.**

### Quick Decision Table

| Scenario                           | Use              | Reason                        |
| ---------------------------------- | ---------------- | ----------------------------- |
| Building web service (Axum, Actix) | **CacheService** | Already Arc'd, clone is cheap |
| Building a library                 | CacheExpander    | Flexibility in Arc wrapping   |
| Uncertain                          | **CacheService** | 90% of use cases              |

> **⚠️ Can't decide? Use CacheService.** It's simpler and covers most cases.

> **📖 For deeper understanding:** See [Core Concepts]/concepts/ for detailed explanations of `CacheExpander` and `CacheService`, including design philosophy, usage patterns, and examples throughout the documentation.

### CacheService (Recommended for Web Applications)

**Use CacheService when:**

- Building web services (Axum, Actix, Rocket)
- Need to share cache across threads
- Want simple, ergonomic API

**Key characteristics:**

- Already wrapped in `Arc` internally
- Implements `Clone` (cheap reference counting)
- Methods: `.execute()`, `.execute_with_config()`
- Perfect for dependency injection

**Example:**

```rust
use cache_kit::{CacheService, backend::RedisBackend};

// Create once at startup
let cache = CacheService::new(backend);

// Share across services (Clone is cheap - just Arc increment)
let user_service = UserService::new(cache.clone());
let product_service = ProductService::new(cache.clone());
let order_service = OrderService::new(cache.clone());
```

### CacheExpander (Low-Level API)

**Use CacheExpander when:**

- Need custom Arc wrapping patterns
- Building cache middleware or custom abstractions
- Want explicit control over ownership

**Key characteristics:**

- No built-in Arc wrapper
- Methods: `.with()`, `.with_config()`
- Requires manual `Arc` wrapping for sharing

**Example:**

```rust
use cache_kit::{CacheExpander, backend::RedisBackend};
use std::sync::Arc;

let expander = CacheExpander::new(backend);

// Must wrap in Arc manually for sharing
let cache = Arc::new(expander);
let user_service = UserService::new(cache.clone());
```

---

### Basic Installation (InMemory Only)

```toml
[dependencies]
cache-kit = { version = "0.9" }
```

This provides the InMemory backend, perfect for:

- Development
- Testing
- Single-instance services

### Redis Backend

```toml
[dependencies]
cache-kit = { version = "0.9", features = ["redis"] }
```

Enables production-grade Redis caching with connection pooling.

### Memcached Backend

```toml
[dependencies]
cache-kit = { version = "0.9", features = ["memcached"] }
```

Enables Memcached backend for high-performance distributed caching.

### All Backends

```toml
[dependencies]
cache-kit = { version = "0.9", features = ["all"] }
```

Enables all available backends. Useful for:

- Testing multiple backends
- Switching backends based on environment
- Benchmarking comparisons

---

## Minimal Configuration

cache-kit requires minimal configuration. Here's a complete working example:

```rust
use cache_kit::{
    CacheEntity, CacheFeed, DataRepository, CacheService,
    backend::InMemoryBackend,
    strategy::CacheStrategy,
};
use serde::{Deserialize, Serialize};

#[derive(Clone, Serialize, Deserialize)]
struct User {
    id: String,
    name: String,
}

impl CacheEntity for User {
    type Key = String;
    fn cache_key(&self) -> Self::Key { self.id.clone() }
    fn cache_prefix() -> &'static str { "user" }
}

struct UserFeeder {
    id: String,
    user: Option<User>,
}

impl CacheFeed<User> for UserFeeder {
    fn entity_id(&mut self) -> String { self.id.clone() }
    fn feed(&mut self, entity: Option<User>) { self.user = entity; }
}

struct UserRepository;

impl DataRepository<User> for UserRepository {
    async fn fetch_by_id(&self, id: &String) -> cache_kit::Result<Option<User>> {
        Ok(Some(User {
            id: id.clone(),
            name: "Alice".to_string(),
        }))
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let backend = InMemoryBackend::new();
    let cache = CacheService::new(backend);
    let repository = UserRepository;

    let mut feeder = UserFeeder {
        id: "user_001".to_string(),
        user: None,
    };

    cache.execute(&mut feeder, &repository, CacheStrategy::Refresh).await?;

    println!("User: {:?}", feeder.user);
    Ok(())
}
```

---

## Backend Configuration

### ⚠️ Production Backend Requirement

**InMemory backend is for development/testing only.** Use Redis or Memcached for production deployments.

---

### InMemory Backend

No configuration required:

```rust
use cache_kit::{CacheService, backend::InMemoryBackend};

let cache = CacheService::new(InMemoryBackend::new());
```

The InMemory backend uses `DashMap` internally, providing:

- Lock-free concurrent HashMap
- Thread-safe operations
- Zero external dependencies

### Redis Backend

```rust
use cache_kit::{CacheService, backend::{RedisBackend, RedisConfig}};
use std::time::Duration;

let config = RedisConfig {
    host: "localhost".to_string(),
    port: 6379,
    username: None,
    password: None,
    database: 0,
    pool_size: 16,
    connection_timeout: Duration::from_secs(5),
};

let backend = RedisBackend::new(config).await?;
let cache = CacheService::new(backend);
```

#### Redis Configuration Options

| Field                | Type             | Default       | Description                       |
| -------------------- | ---------------- | ------------- | --------------------------------- |
| `host`               | `String`         | `"localhost"` | Redis server hostname or IP       |
| `port`               | `u16`            | `6379`        | Redis server port                 |
| `username`           | `Option<String>` | `None`        | Redis username (Redis 6+)         |
| `password`           | `Option<String>` | `None`        | Redis password for authentication |
| `database`           | `u32`            | `0`           | Redis database number (0-15)      |
| `pool_size`          | `u32`            | `16`          | Connection pool size              |
| `connection_timeout` | `Duration`       | `5s`          | Connection timeout                |

#### Configuration Examples

```rust
use std::time::Duration;

// Basic configuration (all defaults)
let config = RedisConfig::default();

// Custom host and port
let config = RedisConfig {
    host: "redis.example.com".to_string(),
    port: 6379,
    ..Default::default()
};

// With authentication
let config = RedisConfig {
    host: "redis.example.com".to_string(),
    port: 6379,
    password: Some("secret".to_string()),
    database: 1,
    ..Default::default()
};

// With custom pool size
let config = RedisConfig {
    host: "localhost".to_string(),
    port: 6379,
    pool_size: 32,
    connection_timeout: Duration::from_secs(10),
    ..Default::default()
};
```

#### Environment-Based Configuration

```rust
use std::env;
use std::time::Duration;

let redis_host = env::var("REDIS_HOST")
    .unwrap_or_else(|_| "localhost".to_string());
let redis_port = env::var("REDIS_PORT")
    .ok()
    .and_then(|p| p.parse().ok())
    .unwrap_or(6379);
let redis_password = env::var("REDIS_PASSWORD").ok();

let config = RedisConfig {
    host: redis_host,
    port: redis_port,
    password: redis_password,
    ..Default::default()
};

let backend = RedisBackend::new(config).await?;
```

### Memcached Backend

```rust
use cache_kit::{CacheService, backend::{MemcachedBackend, MemcachedConfig}};
use std::time::Duration;

let config = MemcachedConfig {
    servers: vec!["localhost:11211".to_string()],
    pool_size: 16,
    connection_timeout: Duration::from_secs(5),
};

let cache = CacheService::new(MemcachedBackend::new(config).await?);
```

#### Memcached Configuration Options

| Field                | Type          | Default  | Description                |
| -------------------- | ------------- | -------- | -------------------------- |
| `servers`            | `Vec<String>` | Required | Memcached server addresses |
| `pool_size`          | `u32`         | `16`     | Connection pool size       |
| `connection_timeout` | `Duration`    | `5s`     | Connection timeout         |

#### Multiple Memcached Servers

```rust
use cache_kit::backend::{MemcachedBackend, MemcachedConfig};
use std::time::Duration;

let config = MemcachedConfig {
    servers: vec![
        "memcached-01:11211".to_string(),
        "memcached-02:11211".to_string(),
        "memcached-03:11211".to_string(),
    ],
    pool_size: 20,
    connection_timeout: Duration::from_secs(10),
};

let backend = MemcachedBackend::new(config).await?;
```

---

## TTL Configuration

Configure time-to-live (TTL) for cached entries:

### Global TTL

```rust
use std::time::Duration;
use cache_kit::{CacheService, observability::TtlPolicy, backend::InMemoryBackend};

let cache = CacheService::new(InMemoryBackend::new());
// Note: TTL configuration via CacheService is set through backend configuration
```

### No TTL (Cache Forever)

```rust
use cache_kit::{CacheService, backend::InMemoryBackend};

// Don't set TTL - cached entries never expire
let cache = CacheService::new(InMemoryBackend::new());
```

**Note:** "Cache forever" is not recommended for production. Always set appropriate TTLs based on your data freshness requirements.

---

## Environment-Based Configuration

Create a configuration module for your application:

```rust
use cache_kit::{CacheService, backend::{InMemoryBackend, RedisBackend, RedisConfig}};
use std::env;
use std::time::Duration;

pub enum Environment {
    Development,
    Production,
}

impl Environment {
    pub fn from_env() -> Self {
        match env::var("ENV").as_deref() {
            Ok("production") => Environment::Production,
            _ => Environment::Development,
        }
    }
}

pub async fn create_cache_service() -> Result<CacheService<impl cache_kit::backend::CacheBackend>, Box<dyn std::error::Error>> {
    match Environment::from_env() {
        Environment::Development => {
            Ok(CacheService::new(InMemoryBackend::new()))
        }
        Environment::Production => {
            let redis_host = env::var("REDIS_HOST")
                .unwrap_or_else(|_| "localhost".to_string());
            let redis_password = env::var("REDIS_PASSWORD").ok();

            let config = RedisConfig {
                host: redis_host,
                password: redis_password,
                pool_size: 20,
                connection_timeout: Duration::from_secs(10),
                ..Default::default()
            };

            let backend = RedisBackend::new(config).await?;
            Ok(CacheService::new(backend))
        }
    }
}
```

Usage:

```rust
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cache = create_cache_service().await?;

    // Your application logic
    Ok(())
}
```

---

## Docker Compose for Development

Use Docker Compose to run Redis and Memcached locally:

```yaml
version: "3.8"

services:
  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"
    volumes:
      - redis_data:/data
    command: redis-server --appendonly yes

  memcached:
    image: memcached:1.6-alpine
    ports:
      - "11211:11211"
    command: memcached -m 64

volumes:
  redis_data:
```

Start services:

```bash
docker-compose up -d
```

Test connections:

```bash
# Redis
redis-cli ping  # Should return: PONG

# Memcached
echo "stats" | nc localhost 11211  # Should return stats
```

---

## Testing Configuration

For unit and integration tests, use the InMemory backend:

```rust
#[cfg(test)]
mod tests {
    use super::*;
    use cache_kit::backend::InMemoryBackend;

    #[tokio::test]
    async fn test_user_caching() {
        // Use InMemory backend for tests (no external dependencies)
        let backend = InMemoryBackend::new();
        let mut expander = CacheExpander::new(backend);

        // Your test logic
    }
}
```

---

## Production Checklist

Before deploying cache-kit to production:

- [ ] **Backend selected:** Redis or Memcached for production
- [ ] **Connection pooling configured:** Set `pool_size` in config (default: 16) or via `REDIS_POOL_SIZE`/`MEMCACHED_POOL_SIZE` environment variables
- [ ] **TTL policies defined:** Set TTLs based on data freshness requirements
- [ ] **Error handling implemented:** Handle cache failures gracefully
- [ ] **Monitoring enabled:** Track cache hit/miss rates
- [ ] **Environment variables set:** `REDIS_HOST`, `REDIS_PORT`, `REDIS_PASSWORD`, `REDIS_POOL_SIZE` (for Redis) or `MEMCACHED_SERVERS`, `MEMCACHED_POOL_SIZE` (for Memcached)
- [ ] **Fallback strategy:** Application works if cache is unavailable
- [ ] **Load tested:** Verify performance under expected load

---

## Common Configuration Patterns

### Pattern 1: Shared Cache Across Services

```rust
use cache_kit::{CacheService, backend::{RedisBackend, RedisConfig}};

let backend = RedisBackend::new(config).await?;
let cache = CacheService::new(backend);

// CacheService is Clone - easily share across services
let user_service = UserService::new(cache.clone());
let product_service = ProductService::new(cache.clone());
```

---

## Next Steps

- Learn about [Database & ORM compatibility]/database-compatibility/
- Explore [Cache backend options]/backends/ in detail
- Review [Serialization formats]/serialization/
- See the [Actix + SQLx example]https://github.com/megamsys/cache-kit.rs/tree/main/examples/actixsqlx