Full answer
Read path
- GET key from the cache. If found, return it (hit).
- If not found (miss), query the database.
- Store the value with SET key value EX ttl, then return it.
Write path
- Update the database first, then DELETE the cache key. Deleting is simpler and safer than writing the new value, because concurrent writers could leave the cache with the older value if their cache writes arrive out of order.
- A short window of stale data is still possible (a reader loaded the old row just before the update and writes it after the delete). A TTL bounds this.
Details
- Choose the TTL from how stale data may be: seconds for prices or stock, minutes or hours for reference data. Add random jitter so many keys do not expire together.
- Negative caching: also cache "not found" for a short time so repeated lookups of missing ids do not hit the database.
- Key design: include a prefix, entity and version, for example student:v1:42.
- The application must work when the cache is down (fall back to the database, with protection against overload).
- Serialise values (JSON). Keep values small. Never cache per-user private data under a shared key.
javascript
const Redis = require('ioredis');
const redis = new Redis(process.env.REDIS_URL);
const db = { 42: { id: 42, name: 'Asha' } }; // a stand-in for the database
let dbReads = 0;
const loadFromDb = async (id) => { dbReads++; return db[id] ?? null; };
async function getStudent(id) {
const key = `bk15:student:${id}`;
const cached = await redis.get(key);
if (cached !== null) return { source: 'cache', value: JSON.parse(cached) };
const value = await loadFromDb(id);
// a missing row is cached for a short time, found rows for longer
await redis.set(key, JSON.stringify(value), 'EX', value ? 60 : 5);
return { source: 'database', value };
}
async function updateStudent(id, changes) {
db[id] = { ...db[id], ...changes }; // 1. write the database
await redis.del(`bk15:student:${id}`); // 2. then delete the cache key
}
(async () => {
await redis.del('bk15:student:42', 'bk15:student:99');
const show = (label, r) => console.log(label.padEnd(26), r.source.padEnd(9), JSON.stringify(r.value));
show('first read', await getStudent(42));
show('second read', await getStudent(42));
console.log('TTL on the key (seconds) :', await redis.ttl('bk15:student:42'));
await updateStudent(42, { name: 'Asha Rao' });
show('after update', await getStudent(42));
show('missing id', await getStudent(99));
show('missing id again', await getStudent(99));
console.log('database reads in total :', dbReads);
await redis.del('bk15:student:42', 'bk15:student:99');
redis.disconnect();
})();Runs against the local Redis server. The 'database' is a plain object with a read counter, so the effect of the cache can be counted. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): first read database {"id":42,"name":"Asha"} second read cache {"id":42,"name":"Asha"} TTL on the key (seconds) : 60 after update database {"id":42,"name":"Asha Rao"} missing id database null missing id again cache null database reads in total : 3
Key points
- Check the cache, on a miss read the database and fill the cache.
- On updates, write the database and delete the key.
- TTL limits staleness and memory.
- Cache missing results briefly (negative caching).
- The system must still work when the cache is unavailable.
Common mistakes
- Updating the cache value instead of deleting it, with racing writers.
- No TTL, so stale or unused data stays forever.
- Caching null results forever.
- Using one global key for per-user data.
- Letting a cache outage take down the whole service.
Follow-ups
- What is read-through compared with cache-aside?
- Why delete the key instead of setting it on update?
- How do you choose a TTL?
Tips
- Describe read path and write path separately.
- Say 'delete, not update'.
- Mention TTL and negative caching.