Performance Guide
Ecosistema completo para organización y gestión de contenido con interfaces espaciales
⚡ Performance Optimization Guide
Complete guide to achieving maximum performance with the GoGrab Storage System.
🎯 Performance Targets
Default Performance (Out of the Box)
- Cache Hits: 0.3ms (instant access)
- Average Operations: 2-5ms
- 95th Percentile: < 10ms
- Storage Capacity: 20GB+ with OPFS
Optimized Performance (With Tuning)
- Cache Hits: 0.1-0.2ms (memory only)
- Hot Keys: < 1ms
- Bulk Operations: Batched for efficiency
- Cache Hit Rate: > 90%
🚀 Quick Wins
1. Enable Performance Monitoring
provideGgStorage({
namespace: 'my-app',
cache: { maxItems: 2000, ttlMs: 600000 },
performance: {
monitoring: true, // ✅ Enable performance tracking
microCacheBudget: 150 * 1024 // 150KB micro-cache
}
})
2. Use Pre-warming
Pre-load frequently accessed keys on startup:
// app.config.ts
{
provide: APP_INITIALIZER,
useFactory: (storage: StorageService) => {
return async () => {
// Pre-warm critical keys
await storage.prewarm([
'user-profile',
'user-settings',
'app-config',
'navigation-state'
]);
};
},
deps: [StorageService],
multi: true
}
Result: Instant access to these keys (< 0.3ms)
3. Optimize Cache Size
provideGgStorage({
namespace: 'my-app',
cache: {
maxItems: 5000, // ⬆️ Increase cache size
ttlMs: 900000 // 15 minutes (longer retention)
}
})
When to increase:
- High read frequency
- Limited unique keys (< 10,000)
- Memory is available
When to keep default:
- Many unique keys (> 100,000)
- Limited memory
- Infrequent access patterns
💾 Micro-Cache Optimization
Understanding Micro-Cache
The micro-cache is a fast localStorage-based cache (< 0.3ms access) that sits between RAM cache and primary storage.
┌─────────────────┐
│ RAM Cache │ ← 0.1ms
├─────────────────┤
│ Micro-Cache │ ← 0.3ms (localStorage)
├─────────────────┤
│ Primary Store │ ← 2-5ms (OPFS/Dexie)
└─────────────────┘
Tuning Micro-Cache Budget
performance: {
microCacheBudget: 200 * 1024 // 200KB (from default 100KB)
}
Budget Guidelines:
- 50KB: Minimal (10-20 small keys)
- 100KB: Default (30-50 keys)
- 200KB: Aggressive (80-100 keys)
- 500KB: Maximum (200+ keys) - use with caution
Monitoring Micro-Cache
const stats = storage.getMicroCacheStats();
console.log({
size: stats.size, // Current cache size
budget: stats.budget, // Total budget
utilization: stats.size / stats.budget, // 0-1
hitRate: stats.hitRate, // 0-1
evictions: stats.evictions // Total evictions
});
// If evictions are high, increase budget:
if (stats.evictions > 1000 && stats.hitRate < 0.8) {
console.warn('⚠️ Consider increasing micro-cache budget');
}
🎯 Strategy Optimization
Speed Strategy
Best For: Real-time apps, games, dashboards
storage.setStrategy('speed');
Features:
- Queued writes (non-blocking)
- Aggressive micro-cache
- Minimal redundancy
- Maximum throughput
Trade-off: Slightly reduced durability
Balanced Strategy (Default)
Best For: Most applications
storage.setStrategy('balanced');
Features:
- Instant writes to primary
- Smart redundancy for critical data
- Balanced cache usage
- Optimal for general use
Durable Strategy
Best For: Financial, medical, critical data
storage.setStrategy('durable');
Features:
- Triple redundancy
- Synchronous writes
- Maximum data safety
- Lower throughput
📊 Adaptive Strategy
Enable intelligent automatic strategy switching:
performance: {
adaptiveStrategy: true, // ✅ Enable intelligent switching
monitoring: true
}
How It Works:
- System monitors operation patterns
- Automatically selects optimal adapter per key
- Applies redundancy based on key patterns
- Adjusts cache priorities dynamically
Key Pattern Recognition:
// Automatically recognized patterns:
'user/*' → Redundant storage (important)
'auth/*' → Triple redundancy (critical)
'cache/*' → Speed optimized
'temp/*' → Single adapter (fast)
'critical/*' → Maximum redundancy
🔄 Batch Operations
Manual Batching
Group operations for better performance:
// ❌ Slow: Individual operations
for (const item of items) {
await storage.put(`items/${item.id}`, item);
}
// ✅ Fast: Batched operations
await Promise.all(
items.map(item => storage.put(`items/${item.id}`, item))
);
Result: 3-5x faster for bulk operations
Automatic Batching
Enable automatic operation batching:
performance: {
batchProcessing: true, // ✅ Enable auto-batching
batchSize: 50, // Operations per batch
batchDelay: 10 // Wait 10ms to accumulate
}
Best For:
- High-frequency writes
- Analytics/logging
- Bulk data imports
💨 Flash Persistence Optimization
Debounce Configuration
Control write frequency:
const settings = autoFlashState('settings', defaultValue, {
debounceMs: 500 // Wait 500ms before saving (default: 300)
});
Guidelines:
- 100ms: Very frequent updates (typing, dragging)
- 300ms: Default (good balance)
- 500ms: Less critical updates
- 1000ms: Infrequent updates
Priority-Based Sync
Control MongoDB sync intervals:
// Critical: Immediate sync
const authToken = autoFlashState({
key: 'auth-token',
defaultValue: null,
priority: 'critical' // < 1 second
});
// High: Every 5 minutes
const preferences = autoFlashState({
key: 'preferences',
defaultValue: {},
priority: 'high' // 5 minutes
});
// Normal: Every 30 minutes
const appData = autoFlashState({
key: 'app-data',
defaultValue: {},
priority: 'normal' // 30 minutes
});
// Low: Manual sync only
const analytics = autoFlashState({
key: 'analytics',
defaultValue: [],
priority: 'low' // Manual
});
🔍 Performance Monitoring
Real-Time Monitoring
@Component({})
export class PerformanceMonitorComponent {
private storage = inject(StorageService);
readonly stats = computed(() => {
const perf = this.storage.getPerformanceStats();
const cache = this.storage.getMicroCacheStats();
return {
cacheHitRate: perf?.cacheHitRate || 0,
avgDuration: perf?.avgDuration || 0,
totalOps: perf?.totalOperations || 0,
microCacheSize: cache.size,
microCacheBudget: cache.budget,
microCacheHitRate: cache.hitRate
};
});
}
Performance Report
// Get detailed performance report
const report = storage.getPerformanceReport();
console.log(report);
// Output:
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Storage Performance Report
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Cache Hit Rate: 92.5%
// Avg Operation Time: 1.8ms
// Total Operations: 15,423
// Adapter Usage:
// - OPFS: 45%
// - Dexie: 35%
// - localStorage: 20%
// Micro-Cache:
// - Size: 85KB / 100KB (85%)
// - Hit Rate: 88%
// - Evictions: 234
🎯 Common Performance Issues
Issue 1: Low Cache Hit Rate (< 60%)
Symptoms:
const stats = storage.getPerformanceStats();
console.log(stats.cacheHitRate); // 0.45 (45%)
Solutions:
Increase cache size:
cache: { maxItems: 5000, ttlMs: 900000 }Increase micro-cache budget:
performance: { microCacheBudget: 200 * 1024 }Use pre-warming:
await storage.prewarm(frequentKeys);
Issue 2: High Average Operation Time (> 10ms)
Symptoms:
const stats = storage.getPerformanceStats();
console.log(stats.avgDuration); // 15ms
Solutions:
Check adapter usage:
console.log(stats.adapterUsage);Enable adaptive strategy:
performance: { adaptiveStrategy: true }Switch to speed strategy:
storage.setStrategy('speed');
Issue 3: Frequent Micro-Cache Evictions
Symptoms:
const stats = storage.getMicroCacheStats();
console.log(stats.evictions); // 5000+
Solutions:
Increase budget:
performance: { microCacheBudget: 200 * 1024 }Reduce debounce time:
autoFlashState(key, value, { debounceMs: 100 })
📈 Performance Benchmarks
Standard Configuration
provideGgStorage({
namespace: 'app',
cache: { maxItems: 1000, ttlMs: 300000 },
strategy: 'balanced'
})
Results:
- Cache hits: 0.3ms
- Average: 3.5ms
- 95th percentile: 8ms
- Cache hit rate: 85%
Optimized Configuration
provideGgStorage({
namespace: 'app',
cache: { maxItems: 5000, ttlMs: 900000 },
strategy: 'speed',
performance: {
monitoring: true,
adaptiveStrategy: true,
microCacheBudget: 200 * 1024,
batchProcessing: true
}
})
Results:
- Cache hits: 0.2ms
- Average: 1.8ms
- 95th percentile: 5ms
- Cache hit rate: 92%
Improvement: ~50% faster, 7% higher cache hit rate
🎓 Best Practices Summary
- ✅ Enable Performance Monitoring: Always enable in development
- ✅ Use Pre-warming: Pre-load critical keys on startup
- ✅ Tune Cache Size: Based on unique key count
- ✅ Optimize Micro-Cache: Increase budget if evictions are high
- ✅ Choose Right Strategy: Speed for real-time, Durable for critical
- ✅ Enable Adaptive Strategy: Let system optimize automatically
- ✅ Batch Operations: Group related operations
- ✅ Monitor Regularly: Check stats weekly
- ✅ Use Flash Persistence: Automatic optimization built-in
- ✅ Optimize Debounce: Match update frequency to needs
🔗 Related Documentation
- Core Concepts - Understanding the architecture
- API Reference - Complete API documentation
- Integration Guide - Setup and configuration
- Flash Persistence - Auto-persistent signals
With these optimizations, you can achieve world-class performance! ⚡