grpc_graphql_gateway 1.2.4

A Rust implementation of gRPC-GraphQL gateway - generates GraphQL execution code from gRPC services
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
# Smart TTL Management

This guide explains how to use Smart TTL Management to intelligently optimize cache durations based on query patterns and data volatility, maximizing cache hit rates and reducing infrastructure costs.

## Overview

Instead of using a single TTL for all cached responses, Smart TTL Management dynamically adjusts cache durations based on:

- **Query Type**: Different TTLs for user profiles, static content, real-time data, etc.
- **Data Volatility**: Automatically learns how often data changes
- **Mutation Patterns**: Tracks which mutations affect which queries
- **Cache Control Hints**: Respects `@cacheControl` directives from your schema

## Key Benefits

- **Higher Cache Hit Rates**: Increase from 75% to 90%+ by optimizing TTLs
- **Reduced Database Load**: 15% additional reduction in database queries
- **Automatic Optimization**: ML-based volatility detection learns optimal TTLs
- **Cost Savings**: $100-200/month in reduced database costs

## Configuration

```rust
use grpc_graphql_gateway::{SmartTtlConfig, SmartTtlManager};
use std::time::Duration;
use std::collections::HashMap;

let mut custom_patterns = HashMap::new();
custom_patterns.insert("specialQuery".to_string(), Duration::from_secs(7200));

let config = SmartTtlConfig {
    default_ttl: Duration::from_secs(300),              // 5 minutes
    user_profile_ttl: Duration::from_secs(900),         // 15 minutes
    static_content_ttl: Duration::from_secs(86400),     // 24 hours
    real_time_data_ttl: Duration::from_secs(5),         // 5 seconds
    aggregated_data_ttl: Duration::from_secs(1800),     // 30 minutes
    list_query_ttl: Duration::from_secs(600),           // 10 minutes
    item_query_ttl: Duration::from_secs(300),           // 5 minutes
    auto_detect_volatility: true,                       // Enable ML-based learning
    min_observations: 10,                               // Learn after 10 executions
    max_adjustment_factor: 2.0,                         // Can double or halve TTL
    custom_patterns,                                    // Custom query patterns
    respect_cache_hints: true,                          // Honor @cacheControl
};

let ttl_manager = SmartTtlManager::new(config);
```

## Basic Usage

### Calculate Optimal TTL

```rust
use grpc_graphql_gateway::SmartTtlManager;

let query = r#"
    query {
        categories {
            id
            name
        }
    }
"#;

// Calculate TTL
let ttl_result = ttl_manager.calculate_ttl(
    query,
    "categories",
    None, // No cache hint
).await;

println!("TTL: {:?}", ttl_result.ttl);
println!("Strategy: {:?}", ttl_result.strategy);
println!("Confidence: {}", ttl_result.confidence);
```

## Query Type Detection

Smart TTL automatically detects query types and applies appropriate TTLs:

### Real-Time Data (5 seconds)

```graphql
query {
  liveScores { team score }      # Contains "live"
  currentPrice { symbol price }  # Contains "current"
  realtimeData { value }         # Contains "realtime"
}
```

### Static Content (24 hours)

```graphql
query {
  categories { id name }         # Contains "categories"
  tags { name }                  # Contains "tags"
  settings { key value }         # Contains "settings"
  appConfig { version }          # Contains "config"
}
```

### User Profiles (15 minutes)

```graphql
query {
  profile { name email }         # Contains "profile"
  user(id: 1) { name }          # Contains "user"
  me { id name }                # Contains "me"
  account { settings }          # Contains "account"
}
```

### Aggregated Data (30 minutes)

```graphql
query {
  statistics { count average }   # Contains "statistics"
  analytics { views clicks }     # Contains "analytics"
  aggregateData { sum }         # Contains "aggregate"
}
```

### List Queries (10 minutes)

```graphql
query {
  listUsers(limit: 10) { id }   # Contains "list"
  posts(page: 1) { title }      # Contains "page"
  itemsWithOffset(offset: 20) { id } # Contains "offset"
}
```

### Single Item Queries (5 minutes)

```graphql
query {
  getUserById(id: 1) { name }   # Contains "byid"
  getPost(id: 123) { title }    # Contains "get"
  findProduct(id: 42) { name }  # Contains "find"
}
```

## Volatility-Based Learning

Smart TTL learns from query execution patterns:

```rust
// Record query results to track changes
let query = "query { user(id: 1) { name } }";
let result_hash = calculate_hash(&result); // Your hash function

ttl_manager.record_query_result(query, result_hash).await;

// After 10+ executions, TTL will auto-adjust based on volatility
let ttl_result = ttl_manager.calculate_ttl(query, "user", None).await;

match ttl_result.strategy {
    TtlStrategy::VolatilityBased { base_ttl, volatility_score } => {
        println!("Base TTL: {:?}", base_ttl);
        println!("Volatility: {:.2}%", volatility_score * 100.0);
        println!("Adjusted TTL: {:?}", ttl_result.ttl);
    }
    _ => {}
}
```

### Volatility Adjustment

| Volatility Score | Data Behavior | TTL Adjustment |
|-----------------|---------------|----------------|
| **> 0.7** | Changes 70%+ of time | **0.5x** (halve TTL) |
| **0.3 - 0.7** | Moderate changes | **0.75x** |
| **0.1 - 0.3** | Stable | **1.5x** |
| **< 0.1** | Very stable (< 10%) | **2.0x** (double TTL) |

## Cache Control Hints

Respect `@cacheControl` directives from your GraphQL schema:

```graphql
type Query {
  # Cache for 1 hour
  products: [Product!]! @cacheControl(maxAge: 3600)
  
  # Don't cache
  liveData: LiveData! @cacheControl(maxAge: 0)
}
```

```rust
// Parse cache hint from schema metadata
use grpc_graphql_gateway::parse_cache_hint;

let schema_meta = "@cacheControl(maxAge: 3600)";
let hint = parse_cache_hint(schema_meta);

let ttl_result = ttl_manager.calculate_ttl(
    query,
    "products",
    hint, // Will use 3600 seconds
).await;
```

## Mutation Tracking

Track which mutations affect which queries to invalidate caches intelligently:

```rust
// When a mutation occurs
let mutation_type = "updateUser";
let affected_queries = vec![
    "user(id: 1)".to_string(),
    "me".to_string(),
    "userProfile".to_string(),
];

ttl_manager.record_mutation(mutation_type, affected_queries).await;

// Affected queries will have shorter TTLs based on mutation frequency
```

## Custom Pattern Matching

Define custom TTLs for specific query patterns:

```rust
let mut custom_patterns = HashMap::new();

// VIP queries get longer cache
custom_patterns.insert("premiumData".to_string(), Duration::from_secs(7200));

// Expensive queries get aggressive caching
custom_patterns.insert("complexReport".to_string(), Duration::from_secs(3600));

// Frequently updated data gets short cache
custom_patterns.insert("inventory".to_string(), Duration::from_secs(30));

let config = SmartTtlConfig {
    custom_patterns,
    ..Default::default()
};
```

## Integration with Response Cache

Integrate with the existing response cache:

```rust
use grpc_graphql_gateway::{Gateway, CacheConfig, SmartTtlManager};
use std::sync::Arc;

// Create TTL manager
let ttl_manager = Arc::new(SmartTtlManager::new(SmartTtlConfig::default()));

// Modify cache lookup to use smart TTL
async fn cache_with_smart_ttl(
    cache: &ResponseCache,
    ttl_manager: &SmartTtlManager,
    query: &str,
    query_type: &str,
) -> Option<CachedResponse> {
    // Get optimal TTL
    let ttl_result = ttl_manager.calculate_ttl(query, query_type, None).await;
    
    // Check cache
    if let Some(cached) = cache.get(query).await {
        // Use smart TTL for freshness check
        if cached.age() < ttl_result.ttl {
            return Some(cached);
        }
    }
    
    None
}
```

## TTL Analytics

Monitor TTL effectiveness:

```rust
let analytics = ttl_manager.get_analytics().await;

println!("Total query patterns tracked: {}", analytics.total_queries);
println!("Average volatility: {:.2}%", analytics.avg_volatility_score * 100.0);
println!("Average recommended TTL: {:?}", analytics.avg_recommended_ttl);
println!("Highly volatile queries: {}", analytics.highly_volatile_queries);
println!("Stable queries: {}", analytics.stable_queries);
```

## Periodic Cleanup

Clean up old statistics to prevent memory growth:

```rust
use tokio::time::{interval, Duration};

// Run cleanup every hour
let mut cleanup_interval = interval(Duration::from_secs(3600));

tokio::spawn({
    let ttl_manager = Arc::clone(&ttl_manager);
    async move {
        loop {
            cleanup_interval.tick().await;
            
            // Keep stats for last 24 hours
            ttl_manager.cleanup_old_stats(Duration::from_secs(86400)).await;
        }
    }
});
```

## Cost Impact

### Before Smart TTL (Single 5-minute TTL)

| Metric | Value |
|--------|-------|
| Cache hit rate | 75% |
| Database queries (100k req/s) | 25k/s |
| Database instance | db.t3.medium ($72/mo) |

### After Smart TTL (Intelligent TTLs)

| Metric | Value |
|--------|-------|
| Cache hit rate | **90%** |
| Database queries (100k req/s) | **10k/s** |
| Database instance | **db.t3.small ($36/mo)** |
| **Monthly savings** | **$36-100/mo** |

## Best Practices

### 1. Start with Conservative Defaults

```rust
SmartTtlConfig {
    default_ttl: Duration::from_secs(300),  // 5 minutes
    auto_detect_volatility: false,          // Disable learning initially
    ..Default::default()
}
```

### 2. Enable Learning After Understanding Patterns

```rust
SmartTtlConfig {
    auto_detect_volatility: true,
    min_observations: 20,  // More observations = better learning
    ..Default::default()
}
```

### 3. Monitor Analytics Regularly

```rust
// Log analytics daily
let analytics = ttl_manager.get_analytics().await;
info!("Smart TTL Analytics: {:#?}", analytics);
```

### 4. Combine with Static Patterns

```rust
// Use both automatic learning AND manual patterns
let mut custom_patterns = HashMap::new();
custom_patterns.insert("criticalData".to_string(), Duration::from_secs(30));

SmartTtlConfig {
    custom_patterns,
    auto_detect_volatility: true,
    ..Default::default()
}
```

### 5. Respect Cache Hints in Production

```rust
SmartTtlConfig {
    respect_cache_hints: true,  // Always honor developer intent
    ..Default::default()
}
```

## Example: Multi-Tier TTL Strategy

```rust
use grpc_graphql_gateway::{SmartTtlConfig, SmartTtlManager};
use std::time::Duration;

let config = SmartTtlConfig {
    // Core content (balance freshness vs load)
    default_ttl: Duration::from_secs(300),
    
    // User data (moderate freshness)
    user_profile_ttl: Duration::from_secs(900),
    
    // Reference data (cache aggressively)
    static_content_ttl: Duration::from_secs(86400),
    
    // Live data (very short cache)
    real_time_data_ttl: Duration::from_secs(5),
    
    // Reports (expensive to compute, cache longer)
    aggregated_data_ttl: Duration::from_secs(1800),
    
    // Lists (ok to be slightly stale)
    list_query_ttl: Duration::from_secs(600),
    
    // Details (fresher data)
    item_query_ttl: Duration::from_secs(300),
    
    // Learn and optimize
    auto_detect_volatility: true,
    min_observations: 15,
    max_adjustment_factor: 2.0,
    
    // Honor developer hints
    respect_cache_hints: true,
    
    // Custom overrides
    custom_patterns: {
        let mut patterns = HashMap::new();
        patterns.insert("dashboard".to_string(), Duration::from_secs(60));
        patterns.insert("search".to_string(), Duration::from_secs(300));
        patterns
    },
};

let ttl_manager = SmartTtlManager::new(config);
```

## Monitoring

Export TTL metrics to Prometheus:

```rust
// Export analytics as metrics
let analytics = ttl_manager.get_analytics().await;

gauge!("smart_ttl_avg_volatility", analytics.avg_volatility_score);
gauge!("smart_ttl_avg_ttl_seconds", analytics.avg_recommended_ttl.as_secs() as f64);
gauge!("smart_ttl_volatile_queries", analytics.highly_volatile_queries as f64);
gauge!("smart_ttl_stable_queries", analytics.stable_queries as f64);
```

## Related Documentation

- [Response Caching]../performance/caching.md
- [Cost Optimization]../production/cost-optimization-strategies.md
- [Performance Monitoring]../advanced/metrics.md