Node.js › Caching
How would you implement a write-behind (write-back) caching strategy, and what durability risk does it introduce?
AdvancedAnswer
Write-behind caching writes changes to the cache immediately and defers the actual write to the durable database to a later batched operation, improving write throughput significantly, but introducing a durability risk: if the process crashes before the deferred write happens, that data is permanently lost, so this pattern is only appropriate when losing a small, recent window of writes is genuinely acceptable.
const writeBuffer = new Map();
function recordPageView(pageId) {
writeBuffer.set(pageId, (writeBuffer.get(pageId) || 0) + 1);
}
setInterval(async () => {
for (const [pageId, count] of writeBuffer) {
await db.pageViews.increment(pageId, count);
}
writeBuffer.clear();
}, 30000);Real-world example An analytics system tracking page-view counts buffers increments in memory and flushes them to the database every 30 seconds, accepting a small window of possible data loss on crash since exact real-time counts aren't business-critical.