Data Caching with Redis

Cache database query results in Node.js and manage cache updates and consistency with MySQL.

🎯 Introduction

By the end of this article, you will be able to cache public user profiles from MySQL, verify cache hits on repeated queries, and delete old copies after updating profiles.


🧱 Cache Reads and the Cache-Aside Pattern

Cache-aside lets the application decide when to read the cache, query the data source, and update cached copies. Redis does not automatically synchronize data from MySQL; application code controls the order of reads and writes across them.

A cache hit means finding a usable cached copy. Fetching from the source means querying the authoritative data source when the copy is missing.

Use cases: frequently queried data that can tolerate briefly returning an old value, such as public user profiles. We will observe the workflow through query functions.

To query a user profile, follow this sequence:

  1. Look for the user's cached profile in Redis.
  2. If present, return it directly without querying MySQL.
  3. If absent, query MySQL.
  4. If the user exists, store the profile in Redis with an expiration and return it. Otherwise, return an empty result.

This article implements the basic workflow while Redis is available. The next article adds negative caching and failure protection.


🛠 Cache Database Query Results from Node.js

Use Node.js 22.9.0, redis 5.9.0, mysql2 3.11.5, and Redis 7.4.2. Complete MySQL integration with Node.js first. Prepare its .env, db.mjs, and blog_demo.user table, retaining the practice user with ID 1.

Install the database driver in the current Redis practice directory and copy those two configuration files. db.mjs exports pool for database connection reuse:

npm install --save-exact mysql2@3.11.5

SQL and connection pool usage follow the MySQL course; here we only add caching. Create user-repository.mjs to count actual source reads:

user-repository.mjs
import { pool } from './db.mjs';

export const metrics = { sourceReads: 0 };

export async function findUser(id) {
    metrics.sourceReads += 1;
    const [rows] = await pool.execute('SELECT id, username AS name FROM user WHERE id = ?', [id]);
    return rows[0] ?? null;
}

This returns the public ID and name, or null when no user is found. sourceReads is only for local observation; use monitoring in a deployed service.

Centralize key definitions in user-cache.mjs:

user-cache.mjs
import { redis } from './redis.mjs';
import { findUser } from './user-repository.mjs';

export const userKey = id => `course:cache:user:v1:${id}`;

First, query the database and save a copy:

user-cache.mjs
async function loadUser(id) {
    const user = await findUser(id);
    if (user !== null) {
        await redis.set(userKey(id), JSON.stringify(user), { EX: 60 });
    }
    return user;
}

Only users actually found are cached. The 60-second lifetime is for practice; choose a production value based on how long stale data is acceptable.

Connect cache reads to database reads:

user-cache.mjs
export async function getUser(id) {
    const raw = await redis.get(userKey(id));
    return raw === null ? loadUser(id) : JSON.parse(raw);
}

A cache hit does not call findUser. For now, assume this program wrote valid JSON. The next article handles corrupt contents.

Create cache-demo.mjs to test with an empty cache:

cache-demo.mjs
import { redis } from './redis.mjs';
import { pool } from './db.mjs';
import { getUser, userKey } from './user-cache.mjs';
import { metrics } from './user-repository.mjs';

await redis.connect();
await redis.del(userKey(1));

Read twice consecutively:

cache-demo.mjs
console.log(await getUser(1));
console.log(await getUser(1));
console.log('Database reads:', metrics.sourceReads);

Both calls return the same profile, and the read count is 1. Observing fewer database reads confirms that this exercise hit the cache.

Finish the script and run it:

cache-demo.mjs
await redis.close();
await pool.end();
node --env-file=.env cache-demo.mjs

Configure DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, and DB_NAME in .env as in the MySQL course. Do not commit real credentials.


🪤 Cache Updates and Consistency with MySQL

Cache consistency concerns whether the Redis copy matches the authoritative database record. Updating the database does not automatically change the old copy; reading it still returns the old value.

Use cases: after updating a cached user profile, subsequent queries need to retrieve fresh data. A common order is commit the MySQL update first, then delete the Redis copy. Create update-user.mjs and prepare its dependencies:

update-user.mjs
import { pool } from './db.mjs';
import { redis } from './redis.mjs';
import { userKey } from './user-cache.mjs';

After modifying the data, handle cache deletion separately:

update-user.mjs
export async function updateUser(id, name) {
    await pool.execute('UPDATE user SET username = ? WHERE id = ?', [name, id]);
    try {
        await redis.del(userKey(id));
        return { cacheInvalidated: true };
    } catch (error) {
        console.error('Profile updated, but cache invalidation failed:', error.message);
        return { cacheInvalidated: false };
    }
}

This example updates an existing user. A single UPDATE uses autocommit; for a multi-statement database transaction, delete the cache only after commit succeeds. Do not report a failed deletion as a failed MySQL update. A real endpoint can keep invalidation status in server logs.

Only user details are cached here. If the same record also appears in cached lists or other results, handle those related copies when updating it.

Create update-demo.mjs to observe a cached copy, its removal after an update, and a subsequent read of the new value:

update-demo.mjs
import { redis } from './redis.mjs';
import { pool } from './db.mjs';
import { getUser, userKey } from './user-cache.mjs';
import { updateUser } from './update-user.mjs';

await redis.connect();
await getUser(1);

Update the profile and check invalidation:

update-demo.mjs
console.log(await updateUser(1, 'Lin'));
console.log(await redis.exists(userKey(1)));
console.log(await getUser(1));

With Redis available, you should see cacheInvalidated: true, then 0, then a profile with the name Lin.

update-demo.mjs
await redis.close();
await pool.end();
node --env-file=.env update-demo.mjs

This order still does not guarantee that all concurrent requests immediately see the new value. A reader may fetch old data, an updater may then commit and delete the cache, and the earlier reader may finally write the old data back. Strong consistency requires reads to reflect completed updates; ordinary cache-aside does not guarantee this.

When brief staleness is acceptable, combine TTLs, failure alerts, and reliable retries. Stricter requirements need data versioning or read/write coordination. A delayed second deletion is not a consistency guarantee.


❓ Questions and Answers

Q1: Can I query MySQL first and write Redis every time?

That saves a copy, but it does not reduce database queries and therefore does not achieve this article's caching goal.

Q2: Can I immediately revert MySQL if cache deletion fails?

That is not a general solution. Other requests may already have used or updated the database record. Keep the committed result and handle cache invalidation.

Q3: Is it easier to cache every database field?

Cache only fields the endpoint is allowed to expose and actually needs. Keep internal information such as password hashes out of public profile copies.


🧪 Exercise

Cache user 1, update the name, and read again. Record cache existence and database read counts, and explain each change.

// Write your code here

🎉 You now understand the basic workflow for caching database queries and invalidating copies after updates!