Repository navigation
Description
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-cachestores 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
msgpackras an optional peer dependency, or as a documented recipe. Msgpack handlesbigintand 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'sWriterformat 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_MEMBERwithuser,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, andfetch({ 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/Readerand 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 byindexGuilds, which givesGUILD_DELETEthe per-guild key set without scanning, so it is not proposed here.
Additional context
- Code being retired: WolfStar
projects/shared/src/lib/cache(structures,HashScopedCache) andprojects/shared/src/lib/data/Writer.ts/Reader.ts. - Related: RFC: plugin-gateway follow-ups from replacing a dedicated gateway process (register entrypoint, member requests, session resume, …) #121, and RFC:
@wolfstar/plugin-broker— distribute gateway events across processes over Redis Streams #136 (@wolfstar/plugin-broker), which needs the sameCodecinterface. Sharing it (for example exporting it fromplugin-cache) would keep one encoding and compression implementation across both packages.
Activity
pullfrog commentedon Sep 27, 2026
Assessment
This RFC is actionable, and grounded in the actual
RedisEntityCacheimplementation (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
serialize/deserialize(redis.ts:344-369) produce<compressionMarker><base64>or bare JSON, and the marker check (value.startsWith("gz:")) relies on JSON never starting withgz:/br:. A codec tag needs to compose with that scheme without breaking reads of data written by 0.2.0. Proposed format: keep the defaultjsonCodec()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.deserializethen checks the compression marker first (as now), and — after decompressing — checks for a codec tag before falling back toJSON.parse.RedisClientLike.set/get(redis.ts:20-33) are typedstring, so a codec returning aBufferstill has to go throughtoString("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 crosscompressionThreshold. Worth deciding up front whether to (a) accept the base64 tax and keep the interface as-is (simpler, smaller diff), or (b) widenRedisClientLike/RedisTransactionLiketo also accept/returnBufferso raw bytes can be stored directly (bigger interface change, real memory win, needs aniorediscompatibility check forBuffermget results). Recommend (a) for the first PR and reassess with the benchmark's actual numbers.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_idon 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 againstCacheEntityTypesintypes.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.applyCacheOperations(operations.ts:779-816) reads the existing stored value, shallow-merges the new raw payload viamergeValues, then callsstore.set(key, mergedValue). So projection can live entirely insideRedisEntityCache.set/MemoryEntityCache.set(applied to the value right before it's written), with zero changes tooperations.ts— exactly matching the RFC's "applied on write, after the merge" requirement.Proposed PR breakdown
PR 1 —
CacheCodecinterface + defaultjsonCodec(), no behavior changeCacheCodec(name,encode,decode) toredis.ts(or a newcodec.ts), plusjsonCodec(): CacheCodecreproducing today'sJSON.stringify/JSON.parse.codec?: CacheCodectoRedisEntityCacheOptions/RedisCacheOptions, threaded throughcreateRedisCachethe same waycompressionis today.serialize/deserializeto 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).tests/redis.test.tsfor: 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
plugin-cachecurrently has no runtime dependency on any serialization/Redis library (ioredisis a devDependency only, used solely for tests against the duck-typedRedisClientLike), addingmsgpackras even an optional peer dependency breaks that pattern. Prefer amsgpackCodec({ pack, unpack })factory that takes msgpackr'spack/unpack(orPackr/Unpackrinstances) supplied by the consumer, documented in the README with anmsgpackrinstall snippet — consistent with the RFC's own "documented recipe" alternative.GUILD_MEMBER+user,MESSAGE_CREATE,GUILD_CREATEfixtures, to produce real numbers instead of assumed ones — this should also settle question 2 above.PR 3 — snowflake-packing codec transform
snowflakePacking(codec)wrapper that recursively walks the encoded value tree beforecodec.encode/aftercodec.decode, using the safer scheme from question 3 (explicit field list or parse-validated packing, not blind name matching).CacheEntityTypesshape that contains snowflake fields, plus an explicit case for a non-snowflake_id-suffixed field (e.g. componentcustom_id) proving it is left untouched.PR 4 —
projectoption forcreateRedisCacheandcreateInMemoryCacheproject?: Partial<Record<CacheEntityName, (value: Raw) => Raw>>to both option types, applied insideRedisEntityCache.set/MemoryEntityCache.setper the analysis in question 4 above (nooperations.tschanges needed).toJSON()/structure getters only see projected fields,fetch({ force: true })is the way back to full data.Not in scope for this repo yet
Codecinterface with@wolfstar/plugin-broker(RFC:@wolfstar/plugin-broker— distribute gateway events across processes over Redis Streams #136) can't be done today since that package doesn't exist. Recommend designingCacheCodecgenerically enough (notplugin-cache-specific in its typing) that it can be extracted/re-exported later, but don't add cross-package wiring until RFC:@wolfstar/plugin-broker— distribute gateway events across processes over Redis Streams #136 has a PR.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,
minorper the repo's changeset convention) and should update theRedisCache/InMemoryCachesections ofpackages/plugin-cache/README.md.Claude Sonnet| 𝕏