In-memory caching stores data temporarily inside your app's memory. It helps your app get data faster without asking a database every time.
In-memory caching patterns in Node.js
const cache = new Map(); // Save data cache.set(key, value); // Get data const value = cache.get(key); // Check if key exists const hasKey = cache.has(key); // Remove data cache.delete(key); // Clear all cache cache.clear();
Map is a built-in JavaScript object good for simple in-memory caching.
You can use any string or object as a key in Map.
cache.set('user_1', { name: 'Alice', age: 25 }); const user = cache.get('user_1');
if (cache.has('settings')) { console.log('Settings found in cache'); }
cache.delete('temp_data');cache.clear();
This Node.js server caches the current time when you visit /time. The first request stores the time, and later requests return the cached time quickly. Visiting /clear clears the cache.
import http from 'node:http'; const cache = new Map(); const server = http.createServer((req, res) => { const url = req.url || ''; if (url === '/time') { if (cache.has('time')) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(`Cached time: ${cache.get('time')}`); } else { const now = new Date().toISOString(); cache.set('time', now); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(`New time cached: ${now}`); } } else if (url === '/clear') { cache.clear(); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Cache cleared'); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Not found'); } }); server.listen(3000, () => { console.log('Server running at http://localhost:3000'); });
In-memory cache is fast but resets when the app restarts.
Use cache carefully to avoid stale data by adding expiration if needed.
For bigger apps, consider dedicated caching tools like Redis.
In-memory caching stores data inside your app for quick reuse.
Use JavaScript's Map for simple cache storage and retrieval.
Remember cache clears on app restart and may need expiration logic.
Practice
Solution
Step 1: Understand caching purpose
In-memory caching stores data temporarily inside the app to avoid repeated slow operations.Step 2: Differentiate from other storage types
Permanent storage is done on disk, not in-memory cache. Network and encryption are unrelated here.Final Answer:
To store data temporarily for faster access during runtime -> Option DQuick Check:
In-memory cache = temporary fast storage [OK]
- Confusing cache with permanent disk storage
- Thinking cache sends data over network
- Assuming cache encrypts data
Solution
Step 1: Recall Map object creation syntax
JavaScript's Map is created with new Map(), capital M and parentheses.Step 2: Check options for syntax correctness
const cache = new Map(); uses correct syntax. const cache = Map(); misses new keyword. const cache = {}; uses object literal, not Map. const cache = new map(); uses lowercase 'map' which is invalid.Final Answer:
const cache = new Map(); -> Option CQuick Check:
Map creation = new Map() [OK]
- Omitting 'new' keyword
- Using lowercase 'map' instead of 'Map'
- Confusing Map with plain object {}
const cache = new Map();
cache.set('user1', {name: 'Alice'});
cache.set('user2', {name: 'Bob'});
console.log(cache.get('user1').name);What will be printed to the console?
Solution
Step 1: Understand cache.set and cache.get usage
cache.set('user1', {name: 'Alice'}) stores an object with name 'Alice' under key 'user1'.Step 2: Retrieve and access property
cache.get('user1') returns the object {name: 'Alice'}, so accessing .name gives 'Alice'.Final Answer:
Alice -> Option AQuick Check:
cache.get('user1').name = Alice [OK]
- Assuming cache.get returns key instead of value
- Forgetting to use .name on the returned object
- Thinking cache.get returns undefined if key exists
const cache = new Map();
function getData(key) {
if (cache.has(key)) {
return cache.get;
}
const data = fetchFromDb(key);
cache.set(key, data);
return data;
}What is the bug causing incorrect cache retrieval?
Solution
Step 1: Analyze cache retrieval line
cache.get is a function, but code returns cache.get without calling it with key.Step 2: Correct method usage
It should be cache.get(key) to retrieve the cached value properly.Final Answer:
cache.get is a function reference, should call cache.get(key) -> Option BQuick Check:
Use cache.get(key) to get value [OK]
- Returning cache.get without parentheses
- Using non-existent cache.exists method
- Confusing cache.set with cache.add
Solution
Step 1: Understand expiration requirement
We want each cache entry to be removed individually after 5 seconds.Step 2: Evaluate options for expiration logic
Use Map and setTimeout to delete the key after 5 seconds when setting cache uses setTimeout per key to delete it after 5 seconds, which fits requirement. Use Map and clear the entire cache every 5 seconds with setInterval clears entire cache, not per key. Use a plain object and rely on garbage collection to remove old keys relies on garbage collection which does not remove keys automatically. Use Map and never delete keys to keep cache forever never deletes keys, so no expiration.Final Answer:
Use Map and setTimeout to delete the key after 5 seconds when setting cache -> Option AQuick Check:
Use setTimeout per key for expiration [OK]
- Clearing whole cache instead of individual keys
- Expecting garbage collection to remove keys automatically
- Not deleting keys causes memory bloat
Ready to prove it?
Pass the test and this pattern moves unknown
