DragonFire Developer Portal

DragonFire Cache Component

Beta
v1.3.2

The DragonFire Cache component is an essential part of the Core SDK, providing high-performance distributed caching with millisecond-level synchronization. Based on fractal memory organization principles, it offers significant performance improvements for applications that need rapid data access and consistency.

Note: For more comprehensive information about the DragonFire Cache system, please see the DragonFire Cache documentation.

Key Features

  • Fractal Distribution: Data is distributed across nodes using fractal patterns for optimal access
  • Millisecond Synchronization: Ultra-fast synchronization across distributed cache nodes
  • Phi-optimized Memory Layout: Golden ratio based memory organization for optimal access patterns
  • Automatic Memory Management: Smart memory allocation and garbage collection
  • Tiered Caching: Multiple cache tiers with different persistence and performance characteristics
  • Intelligent Predictive Caching: Anticipates data access patterns and pre-caches data

Usage in Core SDK

The Cache component is included in the Core SDK and can be accessed through the core instance:

import { DragonFireCore } from '@dragonfire/core-sdk';

// Initialize the Core SDK
const core = new DragonFireCore({
  apiKey: 'YOUR_API_KEY',
  region: 'us-west',
});

// Access the Cache component
const cache = core.components.cache;

// Basic cache operations
await cache.set('user:profile:123', { name: 'Alice', role: 'Admin' });
const userData = await cache.get('user:profile:123');

// Batch operations
await cache.setBatch({
  'user:settings:123': { theme: 'dark', notifications: true },
  'user:preferences:123': { language: 'en', timezone: 'UTC-8' }
});

// Use cache patterns
const userCache = cache.pattern('user:*:123');
const allUserData = await userCache.getAll();

// Subscribe to cache changes
cache.subscribe('user:profile:*', (key, newValue, oldValue) => {
  console.log(`Profile updated: ${key}`);
  console.log('New value:', newValue);
});

Configuration

The Cache component can be configured with various options to optimize performance for specific use cases:

// Configure the cache component
core.components.cache.configure({
  // Memory constraints
  maxMemory: '256MB',
  evictionPolicy: 'LRU',
  
  // Distribution configuration
  distributionFactor: 0.8,
  replicationNodes: 3,
  
  // Performance tuning
  compressionLevel: 'medium',
  fractionalIndexing: true,
  
  // Synchronization settings
  syncInterval: 50, // milliseconds
  syncPriority: 'high',
  
  // Tiered caching
  tiers: [
    { name: 'memory', size: '128MB', ttl: 300 },
    { name: 'local-disk', size: '1GB', ttl: 3600 },
    { name: 'distributed', size: '10GB', ttl: 86400 }
  ]
});

Advanced Features

Fractal Distribution

The DragonFire Cache uses fractal distribution patterns to optimize data storage and retrieval across nodes:

// Configure fractal distribution
cache.setDistributionPattern({
  type: 'fractal',
  baseFactor: 'phi', // Golden ratio
  dimensions: 3,
  nodeMapping: 'balanced'
});

// View distribution visualization
const distMap = await cache.getDistributionMap();
console.log(`Distribution efficiency: ${distMap.efficiency.toFixed(2)}`);
console.log(`Node balance: ${distMap.nodeBalance.toFixed(2)}`);
Cache Fractal Distribution

Time-based Operations

The Cache component supports sophisticated time-based operations for data that changes over time:

// Set data with time-to-live (TTL)
await cache.set('session:token:123', 'abc123', { ttl: 3600 }); // 1 hour

// Set data with versioning
await cache.setVersioned('document:123', documentData, { version: 5 });

// Get only if newer than timestamp
const doc = await cache.getIfNewer('document:123', lastSyncTimestamp);

// Set with automatic expiration based on access patterns
await cache.setWithAccessPattern('resource:123', resourceData, {
  initialTTL: 3600,
  extendOnAccess: true,
  accessFactorMultiplier: 1.5,
  maxTTL: 86400 // 1 day
});

Cache Patterns and Wildcards

Work with groups of cache keys using pattern matching:

// Create a pattern object for user data
const userDataCache = cache.pattern('user:*:123');

// Get all matching keys
const keys = await userDataCache.keys();

// Delete all user data
await userDataCache.deleteAll();

// Set time-to-live for all matching entries
await userDataCache.expireAll(7200); // 2 hours

// Count matching entries
const count = await userDataCache.count();

// Get all values as a map
const values = await userDataCache.getValueMap();

Cache Synchronization

Control how cache data synchronizes across distributed nodes:

// Configure synchronization
cache.setSyncOptions({
  priority: 'high',
  interval: 25, // milliseconds
  batchSize: 50,
  retryStrategy: 'exponential',
  maxRetries: 5
});

// Force synchronization
await cache.forceSyncNow();

// Check sync status
const syncStatus = await cache.getSyncStatus();
console.log(`Sync lag: ${syncStatus.lagMs}ms`);
console.log(`Sync queue size: ${syncStatus.queueSize}`);

// Temporary pause synchronization
await cache.pauseSync();

// Resume synchronization
await cache.resumeSync();

Integration with Other Components

The Cache component integrates seamlessly with other Core SDK components:

GeoCode

Uses GeoCode's geometric structures to optimize data distribution patterns.

// Use GeoCode for cache optimization
const cacheLayout = core.components.geoCode.createPhiOptimizedLayout(3, 5);
cache.setGeometricDistribution(cacheLayout);

DragonHeart

Leverages DragonHeart's harmonic processing for predictive caching.

// Enable predictive caching
cache.enablePredictiveCache({
  engine: 'dragonheart',
  analysisInterval: 60000, // 1 minute
  confidenceThreshold: 0.75
});

DragonCube

Uses DragonCube's high-performance computing for complex cache operations.

// Accelerate complex cache operations
cache.setComputeAcceleration('dragoncube');

// Perform accelerated batch operation
await cache.acceleratedMapReduce(keys, mapFunction, reduceFunction);

Performance Optimization

The DragonFire Cache component includes several performance optimization features:

Memory Optimization

// Configure memory optimization
cache.setMemoryOptimization({
  compressionLevel: 'high',
  deduplication: true,
  structuralSharing: true,
  lazyDeserialization: true
});

// Monitor memory usage
const memStats = await cache.getMemoryStats();
console.log(`Memory usage: ${memStats.usedMB}MB / ${memStats.totalMB}MB`);
console.log(`Items: ${memStats.items}, Avg size: ${memStats.avgItemSizeKB}KB`);

Batching Operations

// Start a cache transaction
const transaction = cache.transaction();

// Add operations to transaction
transaction.set('key1', value1);
transaction.set('key2', value2);
transaction.delete('key3');
transaction.expire('key4', 3600);

// Execute all operations atomically
await transaction.commit();

Prefetching

// Define a prefetch strategy
cache.setPrefetchStrategy({
  patterns: ['user:*:recent', 'content:popular:*'],
  anticipation: 'accessPattern', // or 'timePattern', 'relationPattern'
  aggressiveness: 0.7 // 0-1 scale
});

// Manually trigger prefetch
await cache.prefetch('user:profile:*', {
  depth: 2,
  relations: ['settings', 'preferences']
});

API Reference

For a complete API reference of the Cache component, please refer to the DragonFire Cache API Reference.

Key Methods

Method Description
get(key, options) Gets a value from cache
set(key, value, options) Sets a value in cache with optional TTL and other parameters
delete(key) Deletes a value from cache
has(key) Checks if a key exists in cache
getBatch(keys, options) Gets multiple values in a single operation
setBatch(entries, options) Sets multiple values in a single operation
pattern(pattern) Creates a pattern object for working with key patterns
subscribe(pattern, callback) Subscribes to cache changes matching a pattern
configure(options) Configures cache behavior and performance options
transaction() Creates a new cache transaction for atomic operations

Next Steps