Skip to content

Client-side cache returns Uint8Array instead of Buffer when the client maps strings to Buffer #3536

Closed

Description

@OmBhandwaldar

Description

I set a client-wide type mapping of BLOB_STRING to Buffer and enabled clientSideCache. Every cached read then comes back as a plain Uint8Array instead of a Buffer, already on the first call, before anything is served from the cache. Buffer.isBuffer() returns false and toString() gives the byte values ("104,101,108,108,111") instead of "hello". TypeScript still types the reply as Buffer. With the cache off, the same client returns a Buffer.

The client-side caching docs recommend exactly this setup if you want caching with a custom type mapping (client-side-caching.md#L149), and the type mapping docs use BLOB_STRING: Buffer as the example of a client-wide mapping (command-options.md#L40-L50).

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

for (const clientSideCache of [undefined, { ttl: 0, maxEntries: 0 }]) {
  const client = await createClient({
    url: process.env.REDIS_URL,
    commandOptions: { typeMapping: { [RESP_TYPES.BLOB_STRING]: Buffer } },
    clientSideCache
  }).connect();
  await client.set("greeting", "hello");

  const label = clientSideCache ? "cache on " : "cache off";
  for (const call of [1, 2]) {
    const value = await client.get("greeting");
    console.log(`${label}, call ${call}: Buffer.isBuffer=${Buffer.isBuffer(value)} toString()=${JSON.stringify(value.toString())}`);
  }
  await client.del("greeting");
  client.destroy();
}

Output is in the Logs section below; I ran it three times and got the same result each time. hGetAll() values and createClientPool() with a cache are affected too, and [email protected] behaves the same.

The cause is in BasicClientSideCache.handleCache(). It returns a structuredClone() of the reply, both for a cache hit and for the miss that fills the cache, and structuredClone() turns a Buffer into a plain Uint8Array:

return structuredClone(cacheEntry.value);

return structuredClone(val);

A possible fix: when the type mapping maps blob or simple strings to Buffer, copy the reply with a small helper that copies Buffers with Buffer.from() and walks arrays, Maps, Sets and plain objects. All other clients keep structuredClone(). A reply can only contain Buffers if the type mapping asks for them, so nothing changes for clients without that mapping. On Node 20, 22 and 24 the helper was faster than structuredClone() for every reply with Buffers that I benchmarked, between 1.4x and 13.8x, from a 16-byte value up to a 1 MB value and a 5000-field hash.

I have this working with tests locally. Would you be open to a PR along these lines?

Node.js Version

v24.16.0

Redis Server Version

8.2.10

Node Redis Version

[email protected], also reproduced on master (6377325)

Platform

macOS

Logs

cache off, call 1: Buffer.isBuffer=true toString()="hello"
cache off, call 2: Buffer.isBuffer=true toString()="hello"
cache on , call 1: Buffer.isBuffer=false toString()="104,101,108,108,111"
cache on , call 2: Buffer.isBuffer=false toString()="104,101,108,108,111"

Activity

  1. DivyaRaval1909 commented on Oct 24, 2026

    @DivyaRaval1909

    Can confirm this behavior. In Node.js, Buffer subclasses Uint8Array, but the structured clone algorithm only preserves standard Uint8Array when copying TypedArrays, stripping Buffer's prototype:

    const buf = Buffer.from("hello");
    const cloned = structuredClone(buf);
    
    Buffer.isBuffer(cloned);      // false
    cloned instanceof Uint8Array; // true
    cloned.toString();            // "104,101,108,108,111" instead of "hello"

    This directly impacts BasicClientSideCache.handleCache() (packages/client/lib/client/cache.ts lines 635 & 694) when following the recommended configuration in docs/client-side-caching.md (commandOptions: { typeMapping: { [RESP_TYPES.BLOB_STRING]: Buffer } }).

    +1 for @OmBhandwaldar's proposal — looking forward to the PR!

  2. suryakant-source commented on Oct 24, 2026

    @suryakant-source

    I can reproduce this: the client-side cache clones replies with structuredClone, which keeps plain Uint8Array but not the Buffer subclass, so a BLOB_STRING -> Buffer type mapping is lost on every cached read (even the first one, since the reply is cloned before caching). I'd like to send a PR that re-applies the configured type mapping after the clone. Will link it here shortly.

  3. OmBhandwaldar commented on Oct 24, 2026

    @OmBhandwaldar
    ContributorAuthor

    Thanks for confirming. I offered a fix above and already have it working with tests, but I held off on a PR until we agree on the approach here.

    About the approach in #3539 (as of dd4d28e): it does a structuredClone() and then walks the reply a second time. That happens on every cached read and for every client, including the ones that don't map anything to Buffer. I timed cache hits through a real client on Node 20, 22 and 24 (macOS). With the default string mapping, a cached hGetAll() of a 1000-field hash goes from about 0.06 ms to 0.10-0.12 ms per read. A single get() doesn't change measurably. With a Buffer mapping, cached hGetAll() and lRange() of 1000 entries take 1.6x to 2.3x as long as today.

    What I proposed only changes the copy for clients with a Buffer mapping, so everyone else stays on structuredClone(). With a Buffer mapping, the same reads came out 1.5x to 2.9x faster than today.

    Either way is fine with me, whichever the maintainers prefer.

  4. PavelPashov commented on Oct 26, 2026

    @PavelPashov
    Contributor

    @OmBhandwaldar Thank you for the detailed report and the benchmarks.

    There are now two proposed approaches: changing the copy only for clients that map strings to Buffer, or re-applying the type mapping after structuredClone() as in #3539. I'll leave the choice between them to @nkaradzhov. Please hold off on a second PR until he weighs in.

  5. nkaradzhov commented on Oct 27, 2026

    @nkaradzhov
    Collaborator

    Thanks for the clear report and the benchmarks, @OmBhandwaldar. Let's go with your approach: keep structuredClone() for clients that don't need anything else, and use a type-aware copy only when the type mapping needs it. Please go ahead and open the PR.

    A few notes, to save a review round:

    • Buffer isn't the only type structuredClone() changes. A VerbatimString comes back as a plain String object without its format. No cacheable command returns a verbatim string today, but nothing stops one in the future, so please cover it too. The copy should keep every type the decoder can produce.
    • Pick the copy from the type mapping. Use the type-aware copy when BLOB_STRING, SIMPLE_STRING or VERBATIM_STRING maps to Buffer, or VERBATIM_STRING maps to VerbatimString. Use structuredClone() otherwise.
    • In the copy: Buffer.from() for a Buffer, new VerbatimString(value.format, String(value)) for a VerbatimString, and walk arrays, Map (keys and values), Set and plain objects. Return primitives as they are, and fall back to structuredClone() for anything else.
    • Use it on both return paths in handleCache(): the cache hit and the miss that fills the cache.
    • Tests:
      • A unit test in cache.spec.ts that copies a nested reply (arrays, Map, Set, objects) holding each of these types, for each mapping above and for no mapping. Check that every value keeps its class, and that changing the copy doesn't change the cached value.
      • A testAll case with BLOB_STRING: Buffer and the cache on, which checks that get() and hGetAll() return a Buffer on the first call and on the second.
    • Benchmark: please add a suite under benchmark/lib/ that runs cached reads with the cache on: get() of a small and a 1 MB value, and hGetAll() of a 1,000-field hash, each with the default mapping and with BLOB_STRING: Buffer. Mostly cache hits, plus one cache-miss case. Run it on master and on your branch, and put both sets of numbers in the PR description. The default mapping should show no change.

    @suryakant-source, thanks for #3539 and for jumping on this. We're going with the approach above, so I'll close #3539. A review of the new PR would be very welcome.

  6. added a commit that references this issue on Oct 27, 2026
    5282e53
  7. added a commit that references this issue on Oct 28, 2026
    835e9f2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions