feat: add stale-on-error Redis recovery - #121
Draft
lan17 wants to merge 2 commits into
Draft
Conversation
36 tasks
lan17
added a commit
that referenced
this pull request
Aug 7, 2026
## Summary Replace read-side Lua with native Redis commands and decode DialCache's frame in TypeScript: - untracked reads use `GET` - tracked reads use one atomic, primary-routed `MGET` for the value and watermark - write and invalidation remain Lua-backed; a watermark-fenced tracked write now atomically unlinks the stale value it rejects - node-redis registers only the three mutation scripts, and GLIDE owns only the three mutation script handles - custom adapters can reuse the public `decodeRedisFrame` and `decodeTrackedRedisFrame` helpers This removes the Redis-to-Lua payload materialization and `string.sub` copy on every hit while preserving the semantic `DialCacheRedisClient.read()` boundary. ## Read architecture | Adapter / mode | Untracked | Tracked | Primary guarantee | | --- | --- | --- | --- | | node-redis standalone | `GET` | `MGET` | standalone connection | | node-redis Cluster | `GET` | raw `MGET` | `sendCommand(..., false, ...)` routes to the slot primary | | GLIDE standalone | `GET` | one-command `Batch(false).mget(...)` | standalone batches execute on the primary even with replica reads configured; `MGET` itself is atomic | | GLIDE Cluster | `GET` | custom-command `MGET` | explicit `primarySlotKey` route | The shared decoder: - validates the frame version and minimum length - preserves missing/short/unsupported frames as clean misses - parses integer and fractional legacy watermarks with the same accepted grammar as Lua - rejects values whose Redis-created timestamp is at or before the watermark - preserves unsupported payload encodings as `DialCacheRedisPayloadEncodingError` - returns binary payloads through a zero-copy `Buffer.subarray()` view Tracked value and watermark reads retain one atomic snapshot, with both values returned by a single `MGET`. Their existing shared Cluster hash tag remains required; mismatched tags still fail with `CROSSSLOT`. ## Breaking change - `READ_CACHE_SCRIPT` and `READ_TRACKED_CACHE_SCRIPT` are removed from `dialcache/redis-protocol`. - `dialcacheRedisScripts.dialcacheRead` and `dialcacheRedisScripts.dialcacheReadTracked` are removed from `dialcache/node-redis`. - Custom node-redis wrappers must expose native `get` / `sendCommand`; `legacyMode` clients are unsupported because neither their callback surface nor `.v4` view exposes the complete native-command-plus-custom-script contract. - The GLIDE helper requires GLIDE 2.x, a direct official `GlideClient` or `GlideClusterClient`, and the same module namespace that created it. Forwarding wrappers should implement `DialCacheRedisClient` directly because their topology cannot be inferred safely. - Official node-redis clients and direct GLIDE 2.x clients passed through the documented helpers keep the same application-facing call shape, so those consumers can bump the package without code changes. - Redis keys, frame format, and invalidation behavior are unchanged. A tracked write rejected by an active future watermark still returns `false`, but now also unlinks the stale value key. No data migration or cache flush is required. - The fenced-write cleanup requires `UNLINK` (Redis 4.0+ or compatible Valkey) and permission for scripts to invoke it. With a command-restricted ACL that denies `UNLINK`, the write fails open as `cache_write` and leaves the stale value for a later cleanup or expiry. `BREAKING CHANGE:` the four deprecated read-Lua exports and registrations above are removed; node-redis adapters require the promise-mode native-command surface; the GLIDE helper requires a direct GLIDE 2.x client from the supplied runtime; and the fenced-write cleanup requires Redis `UNLINK` support plus ACL permission. Under the repository's release configuration, this change should release as `v1.0.0`. ## Adapter behavior changes - The node-redis factory now requires native `get` and `sendCommand` methods in addition to the three registered mutation methods. - The GLIDE factory declares an optional `@valkey/valkey-glide ^2.0.0` peer, validates `Batch` support eagerly, and classifies standalone versus cluster behavior from the supplied runtime's client identities before allocating scripts. Its standalone non-atomic primary batch avoids consuming caller-owned `WATCH` state. - Redis `MGET` returns `null` for wrong-type members. A tracked wrong-type value is therefore a clean miss and may be repaired with a valid DialCache frame after fallback succeeds, while a wrong-type watermark prevents the tracked write from succeeding. An untracked `GET` still surfaces `WRONGTYPE`. Real-engine tests cover both repair and repeated fail-open behavior, including metrics. - The public read contract now specifies frame decoding, miss and watermark rules, atomic authoritative snapshots, and returned-buffer ownership. Shared decoders validate leaf reply types; adapters retain only client-specific envelope validation. ## Benchmark The benchmark harness and JSON results were intentionally kept outside the repository. Methodology: - Redis 6.2.22 and Valkey 8.1.8 - Node 22.22.0, node-redis 4.7.1, GLIDE 2.4.2 - binary payloads of 100 B, 1 KiB, 10 KiB, 100 KiB, and 1 MiB - fresh untracked hit, fresh tracked hit, and invalidated tracked miss - three alternating rounds, one command in flight, loopback Docker - median throughput, latency, Redis `INFO commandstats` execution time, and network bytes At 1 MiB, native fresh-hit throughput improved 15-45% across the two engines and adapters. Server-reported command execution time per logical read fell 95-98%. Small 100 B / 1 KiB end-to-end results were mostly flat/noisy while reported command time still fell about 80-90%; the notable small-case regression was Redis/node-redis's 100 B tracked hit at about -10% throughput. These loopback, one-in-flight results are directional rather than production-capacity measurements. Representative Redis 6.2 + node-redis medians: | 1 MiB scenario | Lua ops/s | Native ops/s | Lua server us/read | Native server us/read | Lua -> native p50 | | --- | ---: | ---: | ---: | ---: | ---: | | untracked hit | 230 | 269 | 719.8 | 32.6 | 3.718 ms -> 2.955 ms | | tracked hit | 217 | 259 | 713.7 | 31.2 | 3.630 ms -> 3.016 ms | | invalidated tracked miss | 1,762 | 284 | 361.6 | 31.0 | 0.566 ms -> 2.949 ms | The invalidated-miss row is the main tradeoff: Lua returns only a null reply, while native `MGET` transfers the stale frame before TypeScript rejects it. At 1 MiB this changes roughly 3-5 response bytes into about 1.05 MB. Across both engines and adapters, invalidated-miss throughput fell 77-84% at 1 MiB (46-58% at 100 KiB), even though server-reported command time still fell 91-94%. The benchmark intentionally measured the read itself and therefore includes that full transfer. In the application path, the first completed fallback that reaches a still-fenced tracked write now atomically unlinks the stale value, bounding subsequent transfers for that entry. This is only a partial mitigation: a read failure or timeout never reaches the write-side cleanup, so the stale payload can continue to transfer or time out until another completed read cleans it up or its TTL expires. ## Scope This branch is updated onto the current `v0.15.0` read contract, including the untracked-cache shadowing changes from #122. It deliberately does not include the server-time / maximum-age behavior proposed in #121. That work can be evaluated separately against this read path and its benchmark tradeoffs. ## Validation - `corepack pnpm typecheck` - `corepack pnpm test` - 424 tests, coverage thresholds passed - `corepack pnpm build` - `corepack pnpm test:package` - including real node-redis and GLIDE standalone and Cluster consumer types, plus packed ESM/CommonJS absence checks for all four removed APIs - `corepack pnpm test:integration` - 113 tests across Redis 6.2, Valkey 8, and Redis Cluster - tracked wrong-type value repair and repeated wrong-type watermark fail-open behavior exercised end to end across both adapters and both standalone engines - stale tracked frames exercise the real decoder and record a remote miss, request/get/fallback timing, and no read error across both adapters and both standalone engines - fenced tracked writes prove stale-value unlinking while preserving the exact watermark and its TTL trajectory - cluster `SCRIPT FLUSH` recovery proves mutation scripts repopulate every master and a subsequent identical read is a cache hit - GLIDE package tests compile against the supported 2.0.0 floor and exercise separate module instances plus packed ESM/CommonJS error identity - focused GLIDE primary/replica probe and three-node Cluster probe - `git diff --check`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Add opt-in stale-on-error recovery from physically retained Redis values.
F = ttlSec[CacheLayer.REMOTE]remains the logical freshness age.M = staleOnErrorMaxAgeSecis the absolute maximum recovery age.age < F.age < M.Closes #117
Contract and flow
All source rejections qualify in v1, including synchronous throws, arbitrary rejection values, and
FallbackTimeoutError. A recovery read gets its own effectiveremoteReadTimeoutMsbudget. Existing single-flight behavior means one leader performs the source attempt and at most one recovery read; process/request followers share the same result. A recovered value may be memoized only inside an already-enabled request-local scope.Configuration
0: explicitly disables an inherited policy.0 < F < M <= 31,536,000seconds.Mdisables only stale recovery for that invocation, preserves valid fresh Redis caching, and records existing configuration-error telemetry.DialCacheKeyConfig.disabled()explicitly sets the field to0.The invocation's once-resolved
F/Msnapshot governs the whole flight. Lowering a boundary takes effect immediately. RaisingMcannot resurrect or extend a key written with a shorter physical TTL; only a later successful write receives the longer retention.Redis protocol and adapters
RedisReadRequest.maxAgeMsis now required. Both read Lua scripts:TIME;age >= maxAgeMs;created_at > watermark.Writes keep the existing key/frame and use physical
PX Fwhen recovery is off orPX Mwhen it is on. Tracked watermark retention continues to derive from the physical value retention, so an opted-in write keeps the watermark for approximatelyM + 60s.Bundled node-redis and Valkey GLIDE adapters pass the age bound atomically. Custom semantic clients must now declare
enforcesMaxAge: true; DialCache checks the marker at construction so an old compiled JavaScript adapter cannot silently ignore logical age. Packed TypeScript, ESM, and CommonJS negative fixtures cover this migration guard.Failure, invalidation, and shadow safety
F; a successful clean-miss shadow fill uses physicalMso future serving reads have the configured reservoir.Observability
Add one bounded optional observer:
Outcomes are
served,miss,read_error,read_timeout, anddeserialization_error. Prometheus exposesdialcache_stale_recovery_counter; Datadog exposesdialcache.stale_recovery.count. Existing fallback errors and duration remain truthful even when stale data ultimately reaches the caller. Observer throws/rejections remain isolated.Rollout and rollback
The current v1 key/frame is intentionally reused, so rollout must be readers-first:
0;Monly for selected use cases;An old reader would treat retained
F..Mdata as fresh. Setting the policy back to0stops new extended-retention writes but does not delete prior ones, so an old binary cannot be restored safely until the largest previously enabledMhas elapsed since the finalPX Mwrite, or affected keys are isolated/removed. Fleets that require mixed-version or immediate rollback safety must use a new key/frame version instead.Performance and resource evidence
The checked-in no-threshold harness reports final-script CPU, outage traffic, coalescing, memory, expiration, watermark residency, and opt-in eviction pressure. The following loopback Docker runs used node-redis, 2,000 sequential iterations,
F=60s,M=300s, and 100-way coalescing:The logical-stale miss still performs a full
GET, but does not return the payload, so it was cheaper than a fresh hit in these sequential runs. The design issue contains the direct old-script versus timestamp-aware comparison: roughly+0.6–0.7 usfixed Redis CPU per present read in that separate synthetic setup. Treat all figures as directional rather than production capacity promises.Every 100-way coalescing run produced one source rejection, two Redis reads, and one stale-recovery metric. Tracked probes observed value
PTTL ~= Mand watermarkPTTL ~= M + 60s; a 1-second tracked value expired while its watermark remained. On isolated Redis 6.2 with4 MiB maxmemory,allkeys-lru, and 500 benchmark-owned 16 KiB pressure keys, the pressure-local counter recorded 348 evictions and the retained stale read became a safe miss. The harness changes no Redis configuration, cleans only its random namespace, gives all owned keys finite TTLs, and has a hard watchdog plus bounded cleanup.Validation
Added regression coverage for retained-key opt-outs, dark-ramp safety, successful source refreshes, exact-
Mexpiry during source failure, per-flight policy snapshots, runtimeFchanges, and complete served-recovery telemetry.corepack pnpm checkcorepack pnpm test:integrationpnpm benchmark:stale-on-errorDIALCACHE_BENCH_ITERATIONS=1000 DIALCACHE_BENCH_FANOUT=100 pnpm benchmark:request-localgit diff --checkIndependent final core and benchmark reviews: clean