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)

Optimized Performance (With Tuning)


🚀 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:

When to keep default:


💾 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:

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:

Trade-off: Slightly reduced durability

Balanced Strategy (Default)

Best For: Most applications

storage.setStrategy('balanced');

Features:

Durable Strategy

Best For: Financial, medical, critical data

storage.setStrategy('durable');

Features:


📊 Adaptive Strategy

Enable intelligent automatic strategy switching:

performance: {
  adaptiveStrategy: true,  // ✅ Enable intelligent switching
  monitoring: true
}

How It Works:

  1. System monitors operation patterns
  2. Automatically selects optimal adapter per key
  3. Applies redundancy based on key patterns
  4. 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:


💨 Flash Persistence Optimization

Debounce Configuration

Control write frequency:

const settings = autoFlashState('settings', defaultValue, {
  debounceMs: 500  // Wait 500ms before saving (default: 300)
});

Guidelines:

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:

  1. Increase cache size:

    cache: { maxItems: 5000, ttlMs: 900000 }
    
  2. Increase micro-cache budget:

    performance: { microCacheBudget: 200 * 1024 }
    
  3. 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:

  1. Check adapter usage:

    console.log(stats.adapterUsage);
    
  2. Enable adaptive strategy:

    performance: { adaptiveStrategy: true }
    
  3. Switch to speed strategy:

    storage.setStrategy('speed');
    

Issue 3: Frequent Micro-Cache Evictions

Symptoms:

const stats = storage.getMicroCacheStats();
console.log(stats.evictions);  // 5000+

Solutions:

  1. Increase budget:

    performance: { microCacheBudget: 200 * 1024 }
    
  2. Reduce debounce time:

    autoFlashState(key, value, { debounceMs: 100 })
    

📈 Performance Benchmarks

Standard Configuration

provideGgStorage({
  namespace: 'app',
  cache: { maxItems: 1000, ttlMs: 300000 },
  strategy: 'balanced'
})

Results:

Optimized Configuration

provideGgStorage({
  namespace: 'app',
  cache: { maxItems: 5000, ttlMs: 900000 },
  strategy: 'speed',
  performance: {
    monitoring: true,
    adaptiveStrategy: true,
    microCacheBudget: 200 * 1024,
    batchProcessing: true
  }
})

Results:

Improvement: ~50% faster, 7% higher cache hit rate


🎓 Best Practices Summary

  1. ✅ Enable Performance Monitoring: Always enable in development
  2. ✅ Use Pre-warming: Pre-load critical keys on startup
  3. ✅ Tune Cache Size: Based on unique key count
  4. ✅ Optimize Micro-Cache: Increase budget if evictions are high
  5. ✅ Choose Right Strategy: Speed for real-time, Durable for critical
  6. ✅ Enable Adaptive Strategy: Let system optimize automatically
  7. ✅ Batch Operations: Group related operations
  8. ✅ Monitor Regularly: Check stats weekly
  9. ✅ Use Flash Persistence: Automatic optimization built-in
  10. ✅ Optimize Debounce: Match update frequency to needs

🔗 Related Documentation


With these optimizations, you can achieve world-class performance! ⚡