Memory Cache Functions ($.cache)
High-performance in-memory caching with automatic SEC_MEM_ prefixing for all cache keys.
Overview
The $.cache namespace provides methods to store and retrieve data in memory, improving performance by reducing database queries and expensive computations.
Key Features
- ✅ Automatic Prefixing: All keys automatically prefixed with
SEC_MEM_ - ✅ Time-based Expiry: Set custom expiration times (default: 5 minutes)
- ✅ JSON Serialization: Objects are automatically serialized
- ✅ Audit Logging: All operations logged with user context
- ✅ Thread-Safe: Built on
IMemoryCachefor reliability
$.cache.set()
Store a value in cache with optional expiry time.
Syntax
$.cache.set(key, value, expirySeconds)
Parameters
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
key | string | Yes | - | Cache key (automatically prefixed with SEC_MEM_) |
value | any | Yes | - | Value to cache (objects are JSON serialized) |
expirySeconds | number | No | 300 | Expiration time in seconds (5 minutes default) |
Returns
No return value (void).
Examples
Basic String Caching
// Cache for 5 minutes (default)
$.cache.set('user_token', context.authToken);
// Cache for 1 hour
$.cache.set('user_profile', context.userProfile, 3600);
Cache Complex Objects
var loanData = {
loanAmount: 50000,
interestRate: 12.5,
term: 24,
customer: {
name: 'John Doe',
id: 'CUST001'
}
};
// Cache for 10 minutes
$.cache.set('loan_application_' + context.applicationId, loanData, 600);
Cache API Response
var apiResponse = doCmd('GetExistingLoanSchedules', {
accountNumber: context.accountNumber
});
// Cache schedule data for 5 minutes
$.cache.set('schedules_' + context.accountNumber, apiResponse, 300);
Short-Lived Cache
// Cache for 30 seconds (useful for rapid repeated access)
$.cache.set('temp_calculation_' + context.sessionId, calculationResult, 30);
Notes
- Keys are case-sensitive
- Actual cache key stored:
SEC_MEM_+ your key - Values are serialized to JSON automatically
- Old entries are automatically removed when expired
$.cache.get()
Retrieve a value from cache.
Syntax
$.cache.get(key)
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Cache key (without SEC_MEM_ prefix) |
Returns
Returns the cached value, or null if not found or expired.
Examples
Basic Retrieval
var token = $.cache.get('user_token');
if (token) {
console.log('Using cached token');
} else {
console.log('Token not in cache or expired');
}
Retrieve and Use
var profile = $.cache.get('user_profile');
if (profile) {
return {
name: profile.name,
email: profile.email,
fromCache: true
};
} else {
// Load from database
var freshProfile = doCmd('GetUserProfile', { userId: context.userId });
$.cache.set('user_profile', freshProfile, 3600);
return {
...freshProfile,
fromCache: false
};
}
Check Before Use
var schedules = $.cache.get('schedules_' + context.accountNumber);
if (schedules === null) {
// Not in cache, load fresh data
schedules = doCmd('GetExistingLoanSchedules', {
accountNumber: context.accountNumber
});
$.cache.set('schedules_' + context.accountNumber, schedules, 300);
}
return schedules;
$.cache.remove()
Delete a cache entry.
Syntax
$.cache.remove(key)
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Cache key to remove |
Returns
No return value (void).
Examples
Invalidate Cache After Update
// Update account
var result = doCmd('UpdateDepositAccount', {
accountNumber: context.accountNumber,
newBalance: context.newBalance
});
// Remove cached balance
$.cache.remove('balance_' + context.accountNumber);
return result;
Clear Multiple Related Caches
// Clear all related caches after loan disbursement
$.cache.remove('loan_schedules_' + context.loanId);
$.cache.remove('loan_details_' + context.loanId);
$.cache.remove('customer_loans_' + context.customerId);
var result = doCmd('DisburseLoan', {
accountNumber: context.accountNumber
});
return result;
Conditional Cache Clear
if (context.forceRefresh) {
$.cache.remove('user_dashboard_' + context.userId);
console.log('Cache cleared, loading fresh data');
}
var dashboard = $.cache.get('user_dashboard_' + context.userId);
// ... rest of logic
$.cache.exists()
Check if a cache key exists without retrieving its value.
Syntax
$.cache.exists(key)
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Cache key to check |
Returns
Returns true if the key exists and is not expired, false otherwise.
Examples
Check Before Loading
if ($.cache.exists('expensive_report_' + context.reportId)) {
console.log('Report is cached');
return $.cache.get('expensive_report_' + context.reportId);
} else {
console.log('Generating report...');
var report = generateExpensiveReport(context.reportId);
$.cache.set('expensive_report_' + context.reportId, report, 1800); // 30 min
return report;
}
Conditional Processing
var cacheKey = 'processing_' + context.transactionId;
if ($.cache.exists(cacheKey)) {
return {
status: 'in_progress',
message: 'Transaction is already being processed'
};
}
// Mark as processing
$.cache.set(cacheKey, { startTime: new Date() }, 120); // 2 min lock
// Process transaction
var result = processTransaction(context.transactionId);
// Remove lock
$.cache.remove(cacheKey);
return result;
$.cache.getOrSet()
Get a cached value, or create and cache it using a factory function if it doesn't exist.
Syntax
$.cache.getOrSet(key, factoryFunction, expirySeconds)
Parameters
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
key | string | Yes | - | Cache key |
factoryFunction | function | Yes | - | Function that creates the value if not cached |
expirySeconds | number | No | 300 | Expiration time in seconds |
Returns
Returns the cached value or the result of the factory function.
Examples
Basic Pattern
var balance = $.cache.getOrSet('balance_' + context.accountNumber, function() {
// This function only runs if value is not cached
return doCmd('GetDepositAccountBalance', {
accountNumber: context.accountNumber
});
}, 60); // Cache for 1 minute
return balance;
Complex Object Creation
var customerSummary = $.cache.getOrSet('customer_summary_' + context.customerId, function() {
// Expensive multi-step operation
var accounts = doCmd('GetCustomerAccounts', { customerId: context.customerId });
var loans = doCmd('GetCustomerLoans', { customerId: context.customerId });
var profile = doCmd('GetCustomerProfile', { customerId: context.customerId });
return {
profile: profile,
totalAccounts: accounts.length,
totalLoans: loans.length,
totalBalance: accounts.reduce(function(sum, acc) { return sum + acc.balance; }, 0),
lastUpdated: new Date()
};
}, 600); // Cache for 10 minutes
return customerSummary;
With Error Handling
var schedules = $.cache.getOrSet('loan_schedules_' + context.loanId, function() {
try {
return doCmd('GetExistingLoanSchedules', {
loanId: context.loanId
});
} catch (error) {
console.error('Failed to load schedules: ' + error.message);
return null;
}
}, 300);
if (!schedules) {
return { error: 'Unable to load loan schedules' };
}
return schedules;
Common Patterns
1. Cache Aside Pattern
function getAccountBalance(accountNumber) {
var cacheKey = 'balance_' + accountNumber;
// Try cache first
var balance = $.cache.get(cacheKey);
if (balance === null) {
// Cache miss - load from source
var result = doCmd('GetDepositAccountBalance', {
accountNumber: accountNumber
});
balance = result.balance;
// Store in cache
$.cache.set(cacheKey, balance, 60);
}
return balance;
}
2. Write-Through Pattern
function updateAccountBalance(accountNumber, newBalance) {
// Update database
var result = doCmd('UpdateDepositAccountBalance', {
accountNumber: accountNumber,
balance: newBalance
});
// Update cache
$.cache.set('balance_' + accountNumber, newBalance, 60);
return result;
}
3. Time-based Invalidation
var cacheKey = 'daily_report_' + context.reportDate;
var report = $.cache.getOrSet(cacheKey, function() {
return generateDailyReport(context.reportDate);
}, 86400); // Cache for 24 hours
return report;
4. User-Scoped Caching
var userId = context.userId;
var cacheKey = 'user_' + userId + '_dashboard';
var dashboard = $.cache.getOrSet(cacheKey, function() {
return {
accounts: doCmd('GetUserAccounts', { userId: userId }),
loans: doCmd('GetUserLoans', { userId: userId }),
recentTransactions: doCmd('GetRecentTransactions', { userId: userId, limit: 10 })
};
}, 300);
return dashboard;
5. Cache Warming
// Proactively cache commonly accessed data
function warmCache() {
var popularAccountNumbers = ['ACC001', 'ACC002', 'ACC003'];
popularAccountNumbers.forEach(function(accountNo) {
var cacheKey = 'balance_' + accountNo;
if (!$.cache.exists(cacheKey)) {
var balance = doCmd('GetDepositAccountBalance', {
accountNumber: accountNo
});
$.cache.set(cacheKey, balance.balance, 120);
}
});
return { warmed: popularAccountNumbers.length };
}
Best Practices
✅ Do
-
Use descriptive keys that include identifiers
$.cache.set('loan_schedules_' + loanId, data, 300); -
Set appropriate expiry times based on data volatility
$.cache.set('static_config', config, 3600); // 1 hour for static data
$.cache.set('account_balance', balance, 60); // 1 minute for volatile data -
Invalidate cache after updates
doCmd('UpdateAccount', data);
$.cache.remove('account_' + accountId); -
Use getOrSet for cleaner code
var data = $.cache.getOrSet(key, function() {
return expensiveOperation();
}, 300); -
Handle null returns gracefully
var cached = $.cache.get(key);
if (cached === null) {
// Load fresh data
}
❌ Don't
-
Don't cache sensitive data long-term
// Bad: Caching passwords
$.cache.set('user_password', password, 3600); // DON'T DO THIS -
Don't use overly generic keys
// Bad: Ambiguous key
$.cache.set('data', someData, 300);
// Good: Descriptive key
$.cache.set('customer_accounts_' + customerId, someData, 300); -
Don't cache excessively large objects
// Be mindful of memory usage with large datasets -
Don't forget to remove cache when data changes
// Always invalidate after updates
doCmd('UpdateLoan', loanData);
$.cache.remove('loan_' + loanId); // Important!
Performance Tips
- Cache expensive operations: Database queries, API calls, complex calculations
- Use shorter expiry for frequently changing data: Account balances, transaction counts
- Use longer expiry for static data: Configuration, product catalogs
- Monitor cache hit rates: Add logging to track cache effectiveness
- Clear related caches together: When updating entities, clear all related cache entries
Troubleshooting
Cache Not Working
// Verify cache is storing values
$.cache.set('test_key', 'test_value', 60);
var retrieved = $.cache.get('test_key');
console.log('Cache test: ' + retrieved); // Should print: Cache test: test_value
Cache Expiring Too Quickly
// Increase expiry time
$.cache.set('my_key', myValue, 1800); // 30 minutes instead of default 5
Cache Not Updating
// Ensure you're removing old cache after updates
doCmd('UpdateData', newData);
$.cache.remove('data_key'); // Clear old cache