Skip to content

Client-side cache returns the previous database's value after select() #3631

Closed

Description

@maxymlyskov

Description

With clientSideCache on, a get() after select(1) returns the value cached from database 0. The server is never asked, so the client keeps serving the other database's value until that key name is written somewhere and the server sends an invalidation.

Expected: a cached read is served only for the database it was read from. After select(1), get('k') returns db 1's value, the same as a client without the cache.

// REDIS_URL=redis://localhost:6379 node repro.mjs
import { createClient } from "redis";

const url = process.env.REDIS_URL;
const db0 = await createClient({ url }).connect();
const db1 = await createClient({ url, database: 1 }).connect();
await db0.set("csc-db", "value in db 0");
await db1.set("csc-db", "value in db 1");

const client = await createClient({ url, RESP: 3, clientSideCache: {} }).connect();
console.log("db 0, get():", await client.get("csc-db"));
await client.select(1);
console.log("db 1, get():", await client.get("csc-db"));
console.log("db 1, raw GET:", await client.sendCommand(["GET", "csc-db"]));
console.log("cache hits:", client.clientSideCache.stats().hitCount);

for (const c of [client, db0, db1]) c.destroy();

The output is under Logs, the same on 3 of 3 runs. Without clientSideCache, the second get() returns value in db 1.

The cache key is built from the command arguments only:

function generateCacheKey(redisArgs: ReadonlyArray<RedisArgument>): string {
const tmp = new Array(redisArgs.length * 2);
for (let i = 0; i < redisArgs.length; i++) {
const arg = redisArgs[i];
if (typeof arg === 'string') {
tmp[i] = arg.length;
tmp[i + redisArgs.length] = arg;
} else {
// Decoding a Buffer as UTF-8 is lossy (invalid bytes all become U+FFFD), so distinct
// binary keys could share a cache entry. latin1 maps every byte to its own character;
// the "b" prefix keeps a Buffer apart from a string with the same characters.
tmp[i] = 'b' + arg.length;
tmp[i + redisArgs.length] = arg.toString('latin1');
}
}
return tmp.join('_');
}

and SELECT updates the client's selected database but does not touch the cache:

async SELECT(db: number): Promise<void> {
await this.sendCommand(['SELECT', db.toString()]);
this._self.#selectedDB = db;
}

Invalidation messages carry only the key name, so nothing invalidates an entry when the database changes.

Proposed change: add the client's selected database to the cache key, read when the command runs, so select(), a SELECT in a pipeline or multi(), reset() and the database option are all covered. Invalidation would stay per key name, so a write to k in any database still drops every cached k. This touches cache.ts and index.ts. Custom ClientSideCacheProvider subclasses would keep working if the database is passed as a trailing optional argument or read from the client. Another option is to reject SELECT while the cache is on, the way the cache already blocks some CLIENT subcommands, but that seems harsher for users. Which do you prefer? I can open a PR with a failing test.

Node.js Version

v22.23.3

Redis Server Version

8.10.2

Node Redis Version

[email protected] (cache.ts and SELECT are the same on master 2f1e7d9)

Platform

Linux

Logs

db 0, get(): value in db 0
db 1, get(): value in db 0
db 1, raw GET: value in db 1
cache hits: 1

Activity

  1. nkaradzhov commented on Nov 18, 2026

    @nkaradzhov
    Collaborator

    Thanks. Confirmed: the cache key has no database, and select() never touches the cache.

    We'd rather not take either proposed option. Rejecting SELECT would break apps that select a database once after connecting. A database in the cache key changes the key format and the provider API for a rare case.

    Instead, empty the cache when the selected database changes:

    • Add a small helper that sets #selectedDB and, if the value changed, calls this.#clientSideCache?.invalidate(null, this._clientId).
    • Use it in the places that set #selectedDB after a successful SELECT: select(), the pipeline path, and the multi() path.
    • In reset(), always empty the cache, even when the database doesn't change. RESET turns client tracking off on the server, so entries cached before it never get invalidated.
    • Leave raw sendCommand(['SELECT', ...]) out of scope.

    For tests, your repro works well as a spec in cache.spec.ts. Please add the same check for SELECT inside a pipeline and inside multi(), plus one for reset().

    A PR along these lines is welcome.

  2. Cdineshreddy12 commented on Nov 19, 2026

    @Cdineshreddy12
    Contributor

    Opened #3641 along the lines @nkaradzhov described — cache emptied on db change in select()/pipeline/multi(), always on reset(), same-db select keeps it, raw sendCommand SELECT out of scope. Includes the repro as a spec plus the pipeline/multi/reset variants.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions