Configuration Cache
Cache configuration that rarely changes to avoid repeated fetches.
Basic Pattern
import { MemoryCache } from '@humanspeak/memory-cache'
interface Config {
features: Record<string, boolean>
settings: Record<string, string>
version: string
}
const configCache = new MemoryCache<Config>({
maxSize: 100,
ttl: 5 * 60 * 1000 // 5 minutes
})
async function getConfig(environment: string): Promise<Config> {
const cached = configCache.get(environment)
if (cached) {
return cached
}
// Fetch from remote config service
const config = await fetchConfigFromRemote(environment)
configCache.set(environment, config)
return config
}
// Force refresh config
function refreshConfig(environment: string): void {
configCache.delete(environment)
}
// Refresh all environments
function refreshAllConfigs(): void {
configCache.clear()
}import { MemoryCache } from '@humanspeak/memory-cache'
interface Config {
features: Record<string, boolean>
settings: Record<string, string>
version: string
}
const configCache = new MemoryCache<Config>({
maxSize: 100,
ttl: 5 * 60 * 1000 // 5 minutes
})
async function getConfig(environment: string): Promise<Config> {
const cached = configCache.get(environment)
if (cached) {
return cached
}
// Fetch from remote config service
const config = await fetchConfigFromRemote(environment)
configCache.set(environment, config)
return config
}
// Force refresh config
function refreshConfig(environment: string): void {
configCache.delete(environment)
}
// Refresh all environments
function refreshAllConfigs(): void {
configCache.clear()
}With Change Detection
import { MemoryCache } from '@humanspeak/memory-cache'
const configCache = new MemoryCache<Config>({
maxSize: 100,
ttl: 5 * 60 * 1000,
hooks: {
onSet: ({ key, value, isUpdate }) => {
if (isUpdate) {
console.log(`Config updated for ${key}:`, value.version)
// Notify dependent services
eventBus.emit('config:updated', { environment: key, config: value })
}
},
onExpire: ({ key }) => {
console.log(`Config expired for ${key}, will refresh on next access`)
}
}
})import { MemoryCache } from '@humanspeak/memory-cache'
const configCache = new MemoryCache<Config>({
maxSize: 100,
ttl: 5 * 60 * 1000,
hooks: {
onSet: ({ key, value, isUpdate }) => {
if (isUpdate) {
console.log(`Config updated for ${key}:`, value.version)
// Notify dependent services
eventBus.emit('config:updated', { environment: key, config: value })
}
},
onExpire: ({ key }) => {
console.log(`Config expired for ${key}, will refresh on next access`)
}
}
})Key Considerations
- TTL: 5-10 minutes balances freshness and performance
- Force Refresh: Provide a way to manually invalidate
- Versioning: Include version in config for change detection