Some backend adverts we read, especially from fintechs and remote payment teams, listed Redis, MongoDB or "NoSQL" next to PostgreSQL or MySQL. You do not need these for your first project, which is why this lesson is optional. But knowing what they are for helps you understand adverts and answer interview questions sensibly.
What caching is
A cache is a quick place to keep an answer you have already worked out, so you do not have to work it out again. Imagine Issahaku's bus booking app in Tamale. Every time someone opens it, the app asks the database for today's routes and prices. The answer only changes a few times a day, yet the database repeats the same work thousands of times. Caching the answer for a few minutes removes most of that load.
async function getRoutes() {
const hit = await cache.get("routes");
if (hit) return JSON.parse(hit);
const routes = await db.getRoutes();
await cache.set("routes",
JSON.stringify(routes), { EX: 300 });
return routes;
}EX: 300 means the cached copy expires after 300 seconds, so prices never get more than five minutes out of date.
The hard part: staleness
A cache can serve old data. If a price changes, either wait for the copy to expire or delete it when you update the price. Never cache things that must always be exact at that moment, such as a wallet balance before a payment.