Skip to content

RFC: pluggable codec and opt-in projection for @wolfstar/plugin-cache's Redis store #137

Closed

Description

@RedStar071

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

Context

createRedisCache always serializes values as JSON, then optionally compresses them with gzip or brotli. The serializer is private, so there is no way to plug in another format. For large bots most of the Redis memory goes into members, users and messages, and the raw API JSON is verbose: snowflakes as 17–20 character strings, ISO timestamps, repeated key names, and nested user objects inside members.

WolfStar ran its own Redis cache before switching to @wolfstar/plugin-cache (projects/shared/src/lib/cache). It stored every structure in a hand-written binary format (Writer/Reader: bigint snowflakes as 8 bytes, timestamps as numbers, booleans as 1 byte, per-structure field order), in one Redis hash per guild. The format was compact, but it had two problems that make it unsuitable as is:

  • It was lossy: each structure kept only the fields the bot used, so the data could not go back to the API shape. plugin-cache stores full raw API data on purpose, since the managers rebuild structures, toJSON() returns the original fields, and partial payloads merge into the cached entry.
  • The per-structure schemas had to be maintained by hand and updated whenever the Discord API changed.

We are removing that project. This RFC proposes keeping what was useful, a smaller cache footprint, in a way that fits plugin-cache's design.

Desired solution

1. Pluggable codec (lossless)

Add a codec option to createRedisCache:

export interface CacheCodec {
  readonly name: string; // stored in the value tag, so changing codec never breaks existing values
  encode(value: unknown): Buffer | string;
  decode(data: Buffer | string): unknown;
}

createRedisCache({ redis, codec: msgpackCodec(), compression: "none" });
  • The default stays jsonCodec(), with the current behavior.
  • Values are tagged with the codec name, the same way compressed values are tagged today, so switching codecs or mixing them during a migration keeps reading old entries. Compression keeps applying after encoding.
  • Ship a msgpack codec, either built in on msgpackr as an optional peer dependency, or as a documented recipe. Msgpack handles bigint and binary natively, is lossless for raw API data, and is typically smaller than JSON for small entries such as members and roles, where compression has little room to work (to be confirmed by the benchmark below).
  • Snowflake packing as an opt-in codec transform: encode values of known snowflake keys (id, *_id, roles[], …) as 8-byte integers and restore them as strings on decode. This is what made WolfStar's Writer format compact, and it is still lossless.
  • Writing an entry now needs one EntityCache#set, so the codec can be benchmarked per entity. The RFC PR could add a small benchmark (JSON, JSON+gzip, msgpack, msgpack + snowflake packing) on real payloads: GUILD_MEMBER with user, MESSAGE_CREATE, GUILD_CREATE.

2. Per-entity projection (opt-in, explicitly lossy)

For bots that never need some fields, allow trimming what gets stored:

createRedisCache({
  redis,
  project: {
    members: (member) => ({ ...member, user: { id: member.user.id } }), // users are cached separately anyway
    messages: ({ id, channel_id, guild_id, author, content, timestamp, edited_timestamp }) => ({
      id, channel_id, guild_id, author, content, timestamp, edited_timestamp,
    }),
  },
});
  • Applied on write, after the merge with the cached entry, so partial payloads still merge.
  • Documented as lossy: toJSON() and structure getters see only the projected fields, and fetch({ force: true }) is the way back to the full data.
  • Disabled by default, so the "raw API data only" guarantee holds unless a bot opts out of it.

3. Same codec interface for the in-memory cache (optional)

The in-memory cache stores objects directly, so it needs no codec for correctness. But the same projection option would reduce its heap usage too, so createInMemoryCache could accept project as well.

Alternatives considered

  • Upstream WolfStar's Writer/Reader and structures as is. Rejected: lossy, and hand-maintained schemas break on API changes. It could still back a generic self-describing binary codec, but msgpack already provides one with maintained implementations.
  • Compression only (status quo). gzip/brotli help large values such as GUILD_CREATE, but the threshold (compressionThreshold, 1024 bytes by default) skips most members, roles and users, which make up most of the entries. Their cost is mostly per-entry overhead, which a denser encoding reduces and compression does not.
  • A Redis hash per guild (the layout of WolfStar's HashScopedCache). Already covered by indexGuilds, which gives GUILD_DELETE the per-guild key set without scanning, so it is not proposed here.

Additional context

Activity

  1. pullfrog commented on Sep 27, 2026

    @pullfrog
    Contributor

    Assessment

    This RFC is actionable, and grounded in the actual RedisEntityCache implementation (packages/plugin-cache/src/lib/redis.ts). It bundles three independent features; splitting them into separate PRs matches how this repo tends to ship RFCs (e.g. #121). Below is a plan for each, plus a couple of design questions the RFC doesn't fully settle that are worth resolving before writing code.

    Design questions to settle first

    1. Byte-level tag layering. Today serialize/deserialize (redis.ts:344-369) produce <compressionMarker><base64> or bare JSON, and the marker check (value.startsWith("gz:")) relies on JSON never starting with gz:/br:. A codec tag needs to compose with that scheme without breaking reads of data written by 0.2.0. Proposed format: keep the default jsonCodec() untagged (today's exact bytes, so nothing written before this ships needs a migration), and prefix only non-default codecs with <codec.name>: before compression is applied — i.e. compression wraps <codecTag><codecPayload> the same way it wraps JSON today. deserialize then checks the compression marker first (as now), and — after decompressing — checks for a codec tag before falling back to JSON.parse.
    2. String-only storage may erase most of msgpack's size win. RedisClientLike.set/get (redis.ts:20-33) are typed string, so a codec returning a Buffer still has to go through toString("base64") (~1.33x overhead) when compression is off. That eats a large chunk of msgpack's advantage over JSON for small entries (members, roles) that never cross compressionThreshold. Worth deciding up front whether to (a) accept the base64 tax and keep the interface as-is (simpler, smaller diff), or (b) widen RedisClientLike/RedisTransactionLike to also accept/return Buffer so raw bytes can be stored directly (bigger interface change, real memory win, needs an ioredis compatibility check for Buffer mget results). Recommend (a) for the first PR and reassess with the benchmark's actual numbers.
    3. Snowflake packing's key heuristic is riskier than it looks. Matching id/*_id/roles[] by name will mis-happily convert numeric-looking-string fields that are not snowflakes, and outright break real Discord fields that merely have an _id-shaped name — e.g. custom_id on message components is an arbitrary user-supplied string, not a snowflake. A safe implementation needs either an explicit per-entity allowlist of snowflake-typed field paths (verified against CacheEntityTypes in types.ts), or a runtime check that only packs values that parse as a valid Discord snowflake (an integer-parseable string, typically in a plausible ID range) and falls back to storing the original string with a per-value marker otherwise. Pure name-matching is not safe as described.
    4. Where projection hooks in is already clear from the code, no open question: applyCacheOperations (operations.ts:779-816) reads the existing stored value, shallow-merges the new raw payload via mergeValues, then calls store.set(key, mergedValue). So projection can live entirely inside RedisEntityCache.set / MemoryEntityCache.set (applied to the value right before it's written), with zero changes to operations.ts — exactly matching the RFC's "applied on write, after the merge" requirement.

    Proposed PR breakdown

    PR 1 — CacheCodec interface + default jsonCodec(), no behavior change

    • Add CacheCodec (name, encode, decode) to redis.ts (or a new codec.ts), plus jsonCodec(): CacheCodec reproducing today's JSON.stringify/JSON.parse.
    • Add codec?: CacheCodec to RedisEntityCacheOptions/RedisCacheOptions, threaded through createRedisCache the same way compression is today.
    • Rework serialize/deserialize to route through the codec using the tagging scheme from question 1, with the default codec producing byte-identical output to today (verified by a regression test reading fixtures written by the current code).
    • Extend tests/redis.test.ts for: a custom codec round-trip, codec+compression combined, and old-format (untagged JSON, gz:/br: prefixed) values still decoding under the new code path.

    PR 2 — msgpack codec, as a documented recipe rather than a bundled dependency

    • Given plugin-cache currently has no runtime dependency on any serialization/Redis library (ioredis is a devDependency only, used solely for tests against the duck-typed RedisClientLike), adding msgpackr as even an optional peer dependency breaks that pattern. Prefer a msgpackCodec({ pack, unpack }) factory that takes msgpackr's pack/unpack (or Packr/Unpackr instances) supplied by the consumer, documented in the README with an msgpackr install snippet — consistent with the RFC's own "documented recipe" alternative.
    • Add the benchmark script proposed in the RFC (JSON, JSON+gzip, msgpack, msgpack+snowflake-packing) over GUILD_MEMBER+user, MESSAGE_CREATE, GUILD_CREATE fixtures, to produce real numbers instead of assumed ones — this should also settle question 2 above.

    PR 3 — snowflake-packing codec transform

    • A snowflakePacking(codec) wrapper that recursively walks the encoded value tree before codec.encode/after codec.decode, using the safer scheme from question 3 (explicit field list or parse-validated packing, not blind name matching).
    • Needs its own focused test suite: round-trip on every CacheEntityTypes shape that contains snowflake fields, plus an explicit case for a non-snowflake _id-suffixed field (e.g. component custom_id) proving it is left untouched.

    PR 4 — project option for createRedisCache and createInMemoryCache

    • Add project?: Partial<Record<CacheEntityName, (value: Raw) => Raw>> to both option types, applied inside RedisEntityCache.set/MemoryEntityCache.set per the analysis in question 4 above (no operations.ts changes needed).
    • Document clearly (per the RFC) that this is opt-in and lossy: toJSON()/structure getters only see projected fields, fetch({ force: true }) is the way back to full data.
    • Test that merge-then-project still lets a later dispatch's fields "come back" (projection only drops what the projector drops, it doesn't prevent future full fields from being written once the projector is removed/changed).

    Not in scope for this repo yet

    Suggested sequencing

    PR 1 is the prerequisite for everything else and is low-risk (behavior-preserving default). PR 4 (projection) is independent of the codec work and could ship in parallel/first if preferred — it's the simplest change and delivers real memory savings for bots that opt in, with the least design risk. PRs 2 and 3 depend on PR 1's tagging scheme and should follow it, with PR 2's benchmark informing whether PR 3 (and question 2's Buffer-storage option) are worth the added complexity at all.

    Each PR needs a changeset (this is an unreleased-feature addition, minor per the repo's changeset convention) and should update the RedisCache/InMemoryCache sections of packages/plugin-cache/README.md.

    Pullfrog  | Implement plan ➔ | View workflow run | via Pullfrog | Using Claude Sonnet | 𝕏

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

    featurepackages:plugin-cache

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions