DragonFire Developer Portal

Cache API

Related APIs

Resources

Cache API Reference

Version 3.0.1

The DragonFire Cache API provides zero-friction access to a millisecond-level distributed fractal caching system. This service enables applications to store and retrieve data with geometric-based access patterns for optimized performance.

IMPORTANT: All DragonFire Cache API operations require an active DragonFire service connection. Always initialize the Hexwave connection before using the Cache API.

Overview

The DragonFire Cache service is a distributed, fractal-based caching system that provides high-performance storage and retrieval of data. Unlike traditional caching systems, DragonCache organizes data in fractal patterns for optimal access and distribution.

Key Features

  • Fractal Distribution: Data automatically distributes in phi-resonant fractal patterns across the service
  • Geometric Optimization: Access patterns optimized based on geometric relationships
  • Harmonic Synchronization: Cache nodes synchronize using harmonic mathematical constants
  • Zero-friction Access: Simple, intuitive API with async/await support
  • Automatic Scaling: Cache scales automatically based on usage patterns

Cache Architecture

DragonFire Cache Architecture

Client SDK Requirements

To use the DragonFire Cache API, you'll need the DragonFire Cache Client SDK:

# Using npm
npm install @dragonfire/cache-client

# Using yarn
yarn add @dragonfire/cache-client

Initialization

Before using the DragonFire Cache service, you need to initialize a client instance with a connection to the DragonFire service.

Creating a Cache Client

DragonCacheClient constructor

Creates a new client for interacting with the DragonFire Cache service.

Syntax
constructor(dragonfire: DragonFireClient, options?: CacheClientOptions)
Parameters
Name Type Description
dragonfire DragonFireClient An initialized and connected DragonFire client instance.
options CacheClientOptions Optional. Configuration options for the cache client.
Example
import { DragonFireClient } from '@dragonfire/client';
import { DragonCacheClient } from '@dragonfire/cache-client';

// Initialize DragonFire client
const dragonfire = new DragonFireClient({
  apiKey: 'YOUR_API_KEY',
  region: 'us-west'
});
await dragonfire.connect();

// Initialize cache client
const cache = new DragonCacheClient(dragonfire, {
  dimension: 8,                  // Fractal dimension (6, 8, 10, 12, 14, or 16)
  resonancePattern: 'phi',       // Mathematical pattern for harmonization
  autoScale: true,               // Enable automatic scaling
  compressionEnabled: true,      // Enable compression for large values
  defaultTTL: 3600000            // Default time-to-live (1 hour in ms)
});

Configuration Options

The cache client can be configured with various options:

Option Type Default Description
dimension number 8 Fractal dimension for cache organization. Higher values create more complex distributions.
resonancePattern string 'phi' Mathematical pattern for cache harmonization. Options: 'phi', 'pi', 'sqrt2', 'sqrt3', 'e'.
autoScale boolean true Automatically scale cache capacity based on usage patterns.
defaultTTL number 3600000 Default time-to-live for cache entries in milliseconds (1 hour).
compressionEnabled boolean true Enable compression for large values using Merlin compression.
compressionThreshold number 1024 Size threshold in bytes for when to apply compression.
maxCacheSize number -1 Maximum size of cache in MB. -1 for unlimited (service quotas still apply).
evictionPolicy string 'lru' Cache eviction policy. Options: 'lru', 'lfu', 'phi-weighted'.

Initialization Events

Monitor the initialization process via events:

// Listen for initialization events
cache.on('connecting', () => {
  console.log('Connecting to DragonFire Cache service...');
});

cache.on('connected', (info) => {
  console.log(`Connected to cache node ${info.nodeId} in region ${info.region}`);
  console.log(`Cache dimensions: ${info.dimensions}`);
  console.log(`Available capacity: ${info.availableCapacity} MB`);
});

cache.on('error', (error) => {
  console.error('Cache error:', error);
});

Basic Operations

The DragonCache API provides standard operations for working with cached data.

Setting Values

set()

Stores a value in the cache with an associated key.

Syntax
async set(key: string, value: any, options?: SetOptions): Promise
Parameters
Name Type Description
key string The key under which to store the value. Can include path segments with . separator.
value any The value to store. Can be any JSON-serializable value.
options SetOptions Optional. Additional options for the set operation.
Returns

A Promise that resolves to a boolean indicating whether the operation was successful.

Example
// Store a simple value
await cache.set('user.123.name', 'John Doe');

// Store a complex object with options
await cache.set('user.123.profile', {
  name: 'John Doe',
  email: 'john@example.com',
  preferences: {
    theme: 'dark',
    notifications: true
  }
}, {
  ttl: 86400000,              // 24 hours in milliseconds
  priority: 'high',           // Priority for this cache entry
  compress: true,             // Force compression regardless of size
  tags: ['user', 'profile']   // Tags for easier management
});
Set Options
Option Type Description
ttl number Time-to-live in milliseconds. Overrides the default TTL.
priority string Cache priority ('low', 'normal', 'high'). Affects eviction.
compress boolean Force compression regardless of size threshold.
tags string[] Tags associated with this cache entry for easier management.
consistency string Consistency level ('eventual', 'strong'). Default is 'eventual'.

Getting Values

get()

Retrieves a value from the cache by its key.

Syntax
async get(key: string, options?: GetOptions): Promise
Parameters
Name Type Description
key string The key of the value to retrieve. Can include path segments with . separator.
options GetOptions Optional. Additional options for the get operation.
Returns

A Promise that resolves to the stored value, or null if the key doesn't exist.

Example
// Simple retrieval
const name = await cache.get('user.123.name');
console.log('User name:', name);  // 'John Doe'

// Typed retrieval with options
interface UserProfile {
  name: string;
  email: string;
  preferences: {
    theme: string;
    notifications: boolean;
  };
}

const profile = await cache.get('user.123.profile', {
  defaultValue: {              // Default value if not found
    name: 'Unknown',
    email: '',
    preferences: {
      theme: 'light',
      notifications: false
    }
  },
  consistencyLevel: 'eventual', // Read consistency level
  refreshTTL: true             // Refresh the TTL on read
});

console.log('User profile:', profile);
Get Options
Option Type Description
defaultValue T Default value to return if the key doesn't exist.
consistencyLevel string Read consistency level ('eventual', 'strong').
refreshTTL boolean Whether to refresh the TTL on read.
includeMetadata boolean Whether to include metadata in the result.

Deleting Values

delete()

Removes a value from the cache.

Syntax
async delete(key: string, options?: DeleteOptions): Promise
Parameters
Name Type Description
key string The key of the value to delete. Can include path segments with . separator.
options DeleteOptions Optional. Additional options for the delete operation.
Returns

A Promise that resolves to a boolean indicating whether the key was found and deleted.

Example
// Delete a specific key
const deleted = await cache.delete('user.123.name');
console.log('Deleted:', deleted);  // true if key existed and was deleted

// Delete with cascade
await cache.delete('user.123', {
  cascade: true  // Delete all keys with prefix user.123.*
});

Checking for Existence

exists()

Checks if a key exists in the cache without retrieving its value.

Syntax
async exists(key: string): Promise
Parameters
Name Type Description
key string The key to check for existence.
Returns

A Promise that resolves to a boolean indicating whether the key exists.

Example
// Check if a key exists
const hasProfile = await cache.exists('user.123.profile');
if (hasProfile) {
  console.log('User profile exists in cache');
} else {
  console.log('User profile not found in cache');
}

Advanced Features

The DragonCache API provides several advanced features for more sophisticated cache operations.

Atomic Operations

increment()

Atomically increments a numeric value stored in the cache.

Syntax
async increment(key: string, value: number = 1, options?: SetOptions): Promise
Parameters
Name Type Description
key string The key of the numeric value to increment.
value number The amount to increment by. Default is 1.
options SetOptions Optional. Additional options for the operation.
Returns

A Promise that resolves to the new value after incrementing.

Example
// Increment a counter
let count = await cache.increment('visits.counter');
console.log('Visit count:', count);  // 1 if this is the first increment

// Increment by a specific amount
count = await cache.increment('visits.counter', 5);
console.log('Visit count:', count);  // Previous value + 5

Batch Operations

mget()

Retrieves multiple values from the cache in a single operation.

Syntax
async mget(keys: string[], options?: GetOptions): Promise>
Parameters
Name Type Description
keys string[] Array of keys to retrieve values for.
options GetOptions Optional. Additional options for the get operation.
Returns

A Promise that resolves to a Map of key-value pairs for the requested keys.

Example
// Get multiple values in one call
const values = await cache.mget([
  'user.123.name', 
  'user.123.email', 
  'user.123.preferences.theme'
]);

console.log('User name:', values.get('user.123.name'));
console.log('User email:', values.get('user.123.email'));
console.log('User theme:', values.get('user.123.preferences.theme'));

mset()

Stores multiple key-value pairs in the cache in a single operation.

Syntax
async mset(entries: Map | Record, options?: SetOptions): Promise
Parameters
Name Type Description
entries Map | Record Map or object of key-value pairs to store.
options SetOptions Optional. Additional options for the set operation.
Returns

A Promise that resolves to a boolean indicating whether all operations were successful.

Example
// Set multiple values in one call
await cache.mset({
  'user.123.name': 'John Doe',
  'user.123.email': 'john@example.com',
  'user.123.preferences.theme': 'dark'
}, {
  ttl: 86400000,  // 24 hours
  tags: ['user', 'profile']
});

Cache Patterns

getOrSet()

Gets a value from the cache, or sets it if it doesn't exist.

Syntax
async getOrSet(
  key: string, 
  factory: () => Promise | T, 
  options?: SetOptions
): Promise
Parameters
Name Type Description
key string The key to get or set.
factory () => Promise | T Function that provides the value if key doesn't exist.
options SetOptions Optional. Additional options for the set operation.
Returns

A Promise that resolves to the cached value or the result of the factory function.

Example
// Get cached value or compute if not present
const userProfile = await cache.getOrSet('user.123.profile', async () => {
  // This only runs if the key doesn't exist in cache
  console.log('Cache miss, fetching from database...');
  return await database.getUserProfile('123');
}, {
  ttl: 3600000,  // 1 hour
  tags: ['user']
});

console.log('User profile:', userProfile);

Fractal Storage

DragonCache uses a unique fractal storage system for optimized data distribution and access.

Fractal Dimensions

The cache organizes data in fractal dimensions, with higher dimensions allowing for more complex data relationships:

Dimension Node Count Optimal Use Case
6 64 Simple key-value data with minimal relationships
8 256 General purpose caching (default)
10 1,024 Complex object hierarchies with many relationships
12 4,096 Graph-like data with dynamic connections
14 16,384 Multi-dimensional data with complex access patterns
16 65,536 Highly interconnected data requiring massive parallelism

Resonance Patterns

DragonCache uses mathematical resonance patterns to optimize data synchronization:

Pattern Mathematical Basis Optimal Use Case
phi Golden Ratio (φ = 1.618...) General purpose, balanced performance (default)
pi Pi (π = 3.14159...) Circular/cyclical data patterns
sqrt2 Square Root of 2 (√2 = 1.414...) Binary data, high-throughput operations
sqrt3 Square Root of 3 (√3 = 1.732...) Geometric/spatial data, 3D operations
e Euler's Number (e = 2.718...) Growth patterns, financial calculations

Understanding Fractal Caching

DragonCache's fractal approach offers several advantages over traditional caching systems:

  • Self-similarity: Data is distributed in patterns that repeat at different scales, improving locality of reference.
  • Space-filling: Fractal patterns efficiently utilize available cache space.
  • Natural clustering: Related data naturally clusters together based on key patterns.
  • Emergent optimization: Access patterns automatically optimize over time based on usage.

Path-Based Access

DragonCache uses a path-based key system to align with its fractal architecture:

// Keys can use dot notation to represent paths
await cache.set('users.123.profile.preferences.theme', 'dark');
await cache.set('users.123.profile.preferences.notifications', true);

// Path segments map to fractal dimensions
const theme = await cache.get('users.123.profile.preferences.theme');
console.log(theme);  // 'dark'

// You can retrieve entire subtrees
const preferences = await cache.get('users.123.profile.preferences');
console.log(preferences);  // { theme: 'dark', notifications: true }

Fractal Visualization

You can visualize the current fractal state of your cache for debugging purposes:

// Get a visualization of cache distribution
const visualization = await cache.visualizeFractal({
  dimension: 2,        // Reduce to 2D for visualization
  colorMapping: 'heat' // Color mapping based on access frequency
});

// This would return a URL to a visual representation of your cache
console.log('Cache visualization:', visualization.url);

// Get statistics about fractal distribution
const stats = await cache.getFractalStats();
console.log('Fractal dimension:', stats.fractalDimension);
console.log('Distribution entropy:', stats.entropy);
console.log('Node utilization:', stats.nodeUtilization);

Performance

The DragonCache API provides several methods for monitoring and optimizing cache performance.

Cache Statistics

getStats()

Retrieves statistics about the cache.

Syntax
async getStats(): Promise
Returns

A Promise that resolves to a CacheStats object containing various statistics.

Example
// Get cache statistics
const stats = await cache.getStats();
console.log('Cache size:', stats.size);
console.log('Item count:', stats.itemCount);
console.log('Hit rate:', stats.hitRate);
console.log('Miss rate:', stats.missRate);
console.log('Average access time:', stats.avgAccessTime, 'ms');
console.log('Memory usage:', stats.memoryUsage, 'MB');

Performance Optimization

optimize()

Optimizes the cache for better performance based on current usage patterns.

Syntax
async optimize(options?: OptimizeOptions): Promise
Parameters
Name Type Description
options OptimizeOptions Optional. Additional options for optimization.
Returns

A Promise that resolves to an OptimizationResult object with information about the optimization.

Example
// Optimize cache based on usage patterns
const result = await cache.optimize({
  strategy: 'access-pattern',   // Optimize based on access patterns
  aggressiveness: 0.7,          // Optimization aggressiveness (0-1)
  minImprovementThreshold: 0.1  // Minimum improvement to apply changes
});

console.log('Optimization complete');
console.log('Performance improvement:', result.performanceImprovement);
console.log('Redistribution count:', result.redistributionCount);
console.log('Time taken:', result.timeTaken, 'ms');

Performance Monitoring

You can monitor cache performance in real-time:

// Enable performance monitoring
cache.enablePerformanceMonitoring({
  sampleRate: 0.1,          // Sample 10% of operations
  detailedTracking: true,   // Track detailed metrics
  reportInterval: 60000     // Report every minute
});

// Listen for performance reports
cache.on('performanceReport', (report) => {
  console.log('Performance report:');
  console.log('P50 latency:', report.latencyP50, 'ms');
  console.log('P95 latency:', report.latencyP95, 'ms');
  console.log('P99 latency:', report.latencyP99, 'ms');
  console.log('Operations per second:', report.operationsPerSecond);
  console.log('Hit ratio:', report.hitRatio);
  
  // If latency is high, consider optimizing
  if (report.latencyP95 > 10) {
    cache.optimize();
  }
});

Event Handling

The DragonCache API provides an event system for monitoring cache operations and changes.

Event Types

Event Description Callback Parameters
set Fired when a value is set in the cache (key: string, metadata: object)
get Fired when a value is retrieved from the cache (key: string, hit: boolean)
delete Fired when a value is deleted from the cache (key: string)
expire Fired when a value expires (key: string)
evict Fired when a value is evicted from the cache (key: string, reason: string)
clear Fired when the cache is cleared ()
error Fired when an error occurs (error: Error, operation: string)
performanceReport Fired when a performance report is generated (report: PerformanceReport)

Subscribing to Events

// Listen for cache hits and misses
cache.on('get', (key, hit) => {
  if (hit) {
    console.log(`Cache hit for key: ${key}`);
  } else {
    console.log(`Cache miss for key: ${key}`);
  }
});

// Listen for cache set events
cache.on('set', (key, metadata) => {
  console.log(`Set key: ${key}`);
  console.log(`Size: ${metadata.size} bytes`);
  console.log(`TTL: ${metadata.ttl} ms`);
});

// Listen for eviction events
cache.on('evict', (key, reason) => {
  console.log(`Key ${key} evicted. Reason: ${reason}`);
});

Pattern-Based Event Listening

Listen for events on specific key patterns:

// Listen for changes to user profiles
cache.onKeyPattern('users.*.profile', (key, event, data) => {
  console.log(`User profile changed: ${key}`);
  console.log(`Event: ${event}`);
  console.log(`Data:`, data);
});

// Listen for changes to any user settings
cache.onKeyPattern('users.*.settings.*', (key, event) => {
  console.log(`Setting changed: ${key}`);
  console.log(`Event: ${event}`);
});

Error Handling

The DragonCache API provides structured error handling for managing different types of failures.

Error Types

The cache client defines several error types:

Error Type Description Recovery Strategy
CacheError Base class for all cache errors Depends on specific error
ConnectionError Error connecting to cache service Check DragonFire connection, retry
KeyNotFoundError Key not found in cache Set value, use getOrSet pattern
KeyTooLargeError Key exceeds maximum length Use shorter keys
ValueTooLargeError Value exceeds maximum size Split value, use compression
QuotaExceededError Cache quota exceeded Clear unneeded entries, request quota increase
TimeoutError Operation timed out Retry with increased timeout

Error Handling Examples

// Try-catch error handling
try {
  const value = await cache.get('some.key');
  // Use value...
} catch (error) {
  if (error instanceof KeyNotFoundError) {
    console.log('Key not found, setting default value');
    await cache.set('some.key', defaultValue);
  } else if (error instanceof ConnectionError) {
    console.error('Cache connection error:', error.message);
    fallbackToLocalCache();
  } else {
    console.error('Unexpected cache error:', error);
  }
}

// Event-based error handling
cache.on('error', (error, operation) => {
  console.error(`Cache error during ${operation}:`, error.message);
  
  // Log detail for debugging
  console.error('Error details:', {
    errorType: error.constructor.name,
    code: error.code,
    operation: operation,
    key: error.key,
    retryable: error.isRetryable
  });
});

Fallback Strategies

Implement fallback strategies for cache failures:

// Configure fallback strategies
cache.configureFallback({
  enabled: true,
  localCacheFallback: true,   // Use local memory cache as fallback
  localCacheSize: 1000,       // Max items in local cache
  persistentFallback: true,   // Use persistent storage as fallback
  persistentStoragePath: './cache-fallback',
  maxRetries: 3,              // Retry count for recoverable errors
  retryDelay: 1000            // Base delay between retries
});

// Example using failsafe get operation
try {
  // This will automatically use fallbacks if main cache fails
  const value = await cache.failsafeGet('user.profile', {
    defaultValue: { name: 'Unknown' },
    timeout: 2000
  });
  
  console.log('User profile:', value);
} catch (error) {
  // This will only happen if all fallbacks fail
  console.error('Complete cache failure:', error);
}