Overview
The Playground project implements a sophisticated multi-layer caching strategy to minimize Firebase operations, reduce latency, and improve user experience. The system uses both localStorage for persistence and in-memory Map objects for fast access.Caching Layers
1. LocalStorage Cache (Persistent)
Used for data that needs to survive page reloads and persist across sessions.2. In-Memory Cache (Fast)
Used for frequently accessed data during a single page session.3. Firebase (Source of Truth)
The database serves as the authoritative source, with cache invalidation strategies.LocalStorage Caching
Plantillas (Templates) Cache
Templates are cached in localStorage with a 5-minute validity window:Cache Update Strategy
Background Verification
While using cached data, the system monitors Firebase for changes:User Preferences Cache
User-specific settings are stored per user:Firebase Monitor Data Cache
Monitoring data is persisted to track operations across sessions:In-Memory Caching
Shift Color Cache
Colors for shifts are preloaded once and cached in memory:Shift Quantity Cache
Shift quantities are cached to avoid repeated Firebase queries:All Shifts Data Cache
For complex operations, all shift data is cached:Cache Invalidation
Manual Invalidation
Some operations require explicit cache clearing:Time-based Invalidation
Caches expire after a set time (e.g., 5 minutes for templates):Event-based Invalidation
Real-time listeners detect changes and invalidate cache:Optimization Strategies
1. Preload on Page Load
2. Batch Operations
Instead of querying each item individually, load everything at once:3. Lazy Loading
Only load data when needed:4. Memory Management
Limit cache size to prevent memory issues:Cache Storage Limits
LocalStorage
- Size limit: ~5-10MB depending on browser
- Scope: Per origin (domain)
- Persistence: Until explicitly cleared
Memory (JavaScript)
- Size limit: Available heap memory
- Scope: Per page instance
- Persistence: Until page reload
Best Practices
- Use Map over Object: For frequent lookups, Map has O(1) performance
- Serialize consistently: Use
JSON.stringify()for cache comparison - Handle cache misses: Always provide fallback behavior
- Monitor cache effectiveness: Track hit/miss ratios
- Clear stale data: Implement TTL (Time To Live) for all caches
- Validate cached data: Verify data integrity before use
Performance Impact
Without Cache
- Load time: 2-5 seconds
- Firebase reads: 50-100+ per page load
- User experience: Slow, loading indicators
With Cache
- Load time: 0.1-0.5 seconds
- Firebase reads: 1-5 per page load
- User experience: Instant, responsive
Related Files
source/scriptHorariosStop.js- Shift color and quantity cachingsource/scriptPlantillas.js- Template cachingsource/FirebaseMonitor.js- Monitor data caching
