Skip to content

Commit dc79e38

Browse files
feat(service-cache)!: a declared multi-node deployment on the redis cluster driver shares one Redis cache, so cache-backed limits hold across replicas (#31624)
<!-- claude-projects-attribution: {"github_login":"os-zhuang"} --> _Requested by **Sam** · [project thread](https://claude.ai/code/project/chan_01GsBogozeZG5sdpAARrN7HP?thread=cmsg_01GsBogozeZG5sdpAARrN7HP7y9t5c78P1x2XisqWTYqrR)_ Closes #31553 Clause-②: yes (narrowing) — new exports and options widen the public surface, and one configuration that used to boot is now refused: `CacheServicePlugin({ adapter: 'memory' })` in a deployment that declares multi-node (`OS_EXPECT_MULTI_NODE=true` / `OS_CLUSTER_REPLICAS` > 1) over the `redis` cluster driver. Metadata-protocol: none Skills-docs: updated here — the service-cache README, `content/docs/kernel/contracts/cache-service.mdx`, `content/docs/kernel/cluster.mdx`, `content/docs/plugins/packages.mdx` and `docs/HARDENING.md`; `skills/**` teaches no cache adapter choice (an operator setting, nothing a metadata author writes). ## 维护者速读 - **改了什么**:缓存服务有了真正能用的 Redis 适配器。部署声明多副本、并且集群驱动是 Redis 时,缓存自动改用驱动连着的那台 Redis(复用驱动的连接设置,不另配一套),所有副本共用一个缓存。 - **为什么改**:登录限流、入站 API 预算、短信每日配额、通知节点按地址的邮件限额,计数都存在缓存里。以前每个副本各数各的,N 个副本就是 N 倍上限,攻击者轮换副本就能绕过(ADR-0069 D2 点名的洞)。这些计数器本身不用改代码,缓存换成共享的就自动共用;其中登录限流、短信配额、通知限额各有一个两副本测试。 - **风险与回滚**:单节点路径不变,启动日志逐字钉在测试里;只有"声明多副本 + Redis 驱动"才走新路径。唯一会被拒绝启动的配置,是在这种部署里显式写 `adapter: 'memory'`。Redis 宕机时登录接口会报错(better-auth 不吞错),入站限流放行。回滚 = revert 本 PR。 - **先看**:① `packages/services/service-cache/src/cache-service-plugin.ts` 的 `planCacheAdapter` 决策表和 `init`;② `packages/services/service-cache/src/redis-cache-adapter.ts` 的 `clear`/`stats` 命名空间限定与失败直接抛出;③ `packages/services/service-cluster-redis/src/index.ts` 里驱动交出连接的那一处调用。 - **两分钟验证**:`pnpm --filter @objectstack/plugin-auth exec vitest run --maxWorkers=2 src/rate-limit-storage.shared-redis.test.ts`,预期 3 passed:两个副本合计只放行 5 次(上限 5),未声明多副本的对照组放行 10 次;本机有 `redis-server` 时还会跑两个真进程连真 Redis 的一腿。 - **需要你做的**:无,席位落地。 ## What changes **`@objectstack/service-cache` — the adapter is chosen by topology.** With `adapter` unset (the default, and how `os serve` and the cloud control plane mount it), `CacheServicePlugin.init` decides through a pure function, `planCacheAdapter`: | Deployment | Cache | |:---|:---| | Single node (no multi-node declaration) | `MemoryCacheAdapter`. The cluster service is not read; the boot, including its one info line, is byte-identical. | | Multi-node declared over the `redis` cluster driver | `RedisCacheAdapter`, on `duplicate()` of the driver's ioredis client (same Redis, same key prefix, its own connection), closed at `kernel:shutdown`. | | The same, with `adapter: 'memory'`, or with a redis driver that offers no connection | `init` throws, naming the fix (the card's "refuse boot loudly"). | | Multi-node declared over any other driver, or with no cluster service | `MemoryCacheAdapter`, plus one `warn` that cache-backed limits multiply by the replica count. | `adapter: 'redis'` now works (over `redis.client`, else the driver's connection, else `init` throws). The plugin declares `com.objectstack.service.cluster` an optional dependency, so it reads the driver after the driver started, in either registration order (pinned with the cache plugin registered first). **`RedisCacheAdapter` is implemented.** Entries live at `PREFIX` + `cache:` + `KEY` (default prefix `os:`, the driver's). Values are JSON (a `Date` reads back as its ISO string; `undefined`, functions and `bigint` are refused with a `TypeError`). Redis expires entries itself (`SET … PX`; `ttl` in seconds, `0` = no expiry). A Redis failure is thrown, never answered as a miss, because an outage read as "not found" would silently reset every counter. `clear()` and `stats().keyCount` touch only the cache namespace, never the driver's `kv:` / `ctr:` / lock keys under the same prefix; SCAN uses a widened pattern plus an exact prefix filter, so a prefix containing glob characters is still matched literally. `hits` / `misses` stay per process. The adapter takes no Redis library dependency: the client is a structural `RedisCacheClient`. **`@objectstack/service-cluster` — the connection seam.** `offerClusterDriverConnection(cluster, { driver, client, keyPrefix })` and `readClusterDriverConnection(cluster, driver)`. It is a framework-internal handshake between a driver package and the cache package: nothing is added to the spec `IClusterService` contract, and `packages/spec` is untouched. Two design choices, both pinned in `driver-connection.test.ts`: - **Non-enumerable**, so the offer never shows up in `Object.keys`, a spread, a log line or `JSON.stringify` of the cluster facade (it holds a live client), and it is written once: a second offer throws. - **Under a `Symbol.for` key**, so two copies of `@objectstack/service-cluster` in one process (the ESM and CJS builds, or two resolved versions) read the same offer: the driver may offer through one copy and the cache read through the other. A module-local `Symbol()` or a `WeakMap` would make the offer invisible across copies and the cache would silently stay per-process. The key's spelling is pinned in the test, because renaming it would break every already-published driver. **`@objectstack/service-cluster-redis`** makes one call, offering its client and key prefix. Its own behaviour is unchanged. **Every cache-backed counter shares the same store, with no change of its own.** The sign-in limits, the inbound API budget, the OTP send budget, the daily SMS quota (`service-sms`, `SmsDailyQuota`) and the `notify` node's per-address email-field limit (`service-automation`) all count through `createLazyCounterStore` / `createLazyCacheRateLimitStorage` over `resolveKernelCache`, i.e. in whatever the `cache` slot holds. So the topology choice above makes each of them one counter across replicas; none of them needed a production change, and each now has a two-replica test (below). **Red line held.** The counters reach the cache only through better-auth `rateLimit.customStorage` (`createLazyCacheRateLimitStorage`); `secondaryStorage` is not enabled, so sessions stay in `sys_session` and revocation is untouched. **Docs.** The README, the cache contract page, the cluster page, the packages page and `docs/HARDENING.md` stop calling the adapter a skeleton and state which cache a deployment gets. ## Tests - `service-cache/src/redis-cache-adapter.test.ts`: the same contract battery runs against `MemoryCacheAdapter` and `RedisCacheAdapter` (get/set, objects, delete, has, TTL, `defaultTtl` and `ttl` 0, clear, stats, the counter string envelope). Redis-only cases: two clients share one cache; keys land under `os:cache:` with `PX`; `clear`/`stats` leave the driver's keys alone; a glob-character prefix matches literally; JSON semantics; a foreign non-JSON value reads as a miss; failures are thrown; metric labels; `close()` ownership; the constructor refuses a URL-only option set. - `service-cache/src/cache-service-plugin.topology.test.ts`: the decision table on `planCacheAdapter`; `init` against a context double (the single-node info line pinned verbatim, no warn, no cluster read; the optional-dependency pin; multi-node redis registers Redis and closes it at shutdown; `OS_EXPECT_MULTI_NODE` equals `OS_CLUSTER_REPLICAS>1`; `adapter: 'memory'` throws; the memory driver warns); and real `ObjectKernel` boots with the cluster plugin and the redis driver on `ioredis-mock` (two multi-node kernels share one cache even with the cache plugin registered first; a single-node kernel stays memory; multi-node with `adapter: 'memory'` refuses to boot). - `service-cluster/src/driver-connection.test.ts` (4) and two cases in `service-cluster-redis/src/redis.contract.test.ts`: the offer reads back for its driver only, never throws on non-objects, is invisible to enumeration and serialisation, cannot be replaced, and lives under the pinned `Symbol.for` key; the redis driver offers its client and its prefix (`os:` by default). - `plugin-auth/src/rate-limit-storage.shared-redis.test.ts`: one sign-in key, rule `{ window: 60, max: 5 }`, 10 alternating attempts through `createLazyCacheRateLimitStorage({ resolveCache: () => resolveKernelCache(ctx) })`, the seam `AuthPlugin` wires into better-auth. - Leg 1 (runs everywhere): two kernels on separate mock clients. Declared multi-node: both caches are `RedisCacheAdapter`, 5 admitted in total. Control without the declaration: `MemoryCacheAdapter`, 10 admitted. - Leg 2 (skipped when `redis-server` is not on PATH; the replica process is `src/__fixtures__/rate-limit-storage.shared-redis.replica.ts`): a real `redis-server` on a free port and four forked replica processes, two declared and two not. Declared: `['redis','redis']`, 5 admitted in total. Undeclared: `['memory','memory']`, 10 admitted. Separate processes on purpose: inside one process `serializePerKey` orders every limiter's read-modify-write through one module-level queue, so in-process "nodes" cannot interleave the way replicas do. - `service-sms/src/sms-daily-quota.shared-redis.test.ts`: two kernels, each with the cluster plugin on the redis driver (separate mock clients, one keyspace), `CacheServicePlugin`, a settings host serving `daily_quota: 3`, and the real `SmsServicePlugin`. 8 alternating sends: declared multi-node admits 3 in total; the undeclared control admits 6 (3 per replica). - `service-automation/src/builtin/notify-email-field.shared-redis.integration.test.ts`: the same two-kernel composition with the real `notify` node and an email-field recipient. 12 alternating runs to one address: declared multi-node sends 5 in total (`EMAIL_FIELD_SENDS_PER_WINDOW`); the undeclared control sends 10. ## Acceptance notes - **The seam absent, or the memory driver: resolution as today, with one stated exception.** Single node, any driver: memory, no cluster read, the same info line (`init — the single-node default is unchanged › registers a MemoryCacheAdapter, logs the one line it always logged, warns nothing, reads no cluster`; `planCacheAdapter › single node over the redis driver stays memory`). Multi-node over the memory driver (only reachable past the split-brain guard's override) or with no cluster service: memory, as today, plus one new `warn` line (`planCacheAdapter › multi-node over the memory driver …`, `› multi-node with no cluster service at all …`, `init › over the memory driver: registers memory and warns once, after the unchanged info line`). The exception: multi-node over a driver named `redis` that offers no connection (an older or third-party redis driver) is **refused**, not memory, because that is the card's "multi-replica declared and no shared cache" case (`planCacheAdapter › multi-node over a redis driver that offers no connection: refused, naming the version to install`). - **A Redis outage fails sign-in requests.** better-auth calls `customStorage` with no catch, so a thrown Redis error fails the auth request; the inbound limiter catches and lets the request through. Kept as is: under rule R2 Redis is a hard requirement of multi-replica, and answering a miss would reset the counter. The status code an outage produces at the auth endpoint is NOT MEASURED. - **The boundary race stays.** `ICacheService` has no atomic increment, so two nodes counting one key in the same instant can both be admitted at the limit's boundary: the bounded over-admit ADR-0069 D2 accepts, never a per-node limit. - **The inbound limiter** reads the same `cache` slot and stores JSON strings, so it is shared under the same declaration; it has no test of its own in this PR. - **The refusal lives in `CacheServicePlugin`.** A composition that mounts no cache plugin gets the kernel's in-process fallback, which plugin-auth already ignores as degraded. `os serve` always mounts the plugin, without options; so does the cloud control plane. - **The daily SMS quota and the notify per-address limit** were added to this card's scope by the dispatching seat. Both already lived in the framework and already counted in the kernel `cache`, so the change for them is tests only: `service-sms/src/sms-daily-quota.shared-redis.test.ts` and `service-automation/src/builtin/notify-email-field.shared-redis.integration.test.ts`. - **Leg 2 of the two-process test is NOT MEASURED in CI** unless the runner has `redis-server` on PATH; it ran locally (Redis 7.0.15) and passed. ## Verification Local, on head `820d1fb9` unless a line says otherwise. Every exit code below was captured before any pipe. <details><summary>Package tests and typechecks — all exit 0</summary> | Package | `vitest run` | `typecheck` | |:---|:---|:---| | `@objectstack/service-cache` | 5 files, 74 passed | exit 0 (`tsc` covers all 5 test files) | | `@objectstack/service-cluster` | 8 files, 115 passed | exit 0, test-typecheck ledger 0 errors | | `@objectstack/service-cluster-redis` | 3 files, 39 passed | exit 0 | | `@objectstack/plugin-auth` | 242 files, 4318 passed, 10 skipped; `rate-limit-storage.shared-redis.test.ts` alone: 3 passed, 0 skipped (the two-process leg ran, `redis-server` 7.0.15 on PATH) | exit 0 (`tsc`, examples, test-typecheck ledger unchanged) | | `@objectstack/service-sms` | 10 files, 121 passed (on `3523290e`) | exit 0, ledger unchanged | | `@objectstack/service-automation` | 265 files, 3433 passed (on `3523290e`, under the verify lock, VERDICT command-exit 0) | exit 0, ledger 0 errors | `3523290e` → `820d1fb9` adds one row to `scripts/engine-double-contract.pinned.json` and nothing else. </details> <details><summary>Derived gates — 121 of 121 exit 0</summary> `node scripts/pm/dispatch-gates.mjs --commands` derived 114 families on `3523290e`; all 114 ran there and exited 0 after one real finding was fixed: `check:undeclared-dep-imports` read the replica fixture as published source (it imports devDependencies), so it moved to `src/__fixtures__/`. Three first-run exit-3 readings were prerequisites, not findings (`check:dual-build-cjs-loads` and `spec check:skill-examples` need built output; `check-plugin-teardown-shape --self-test` needs a commit a shallow clone lacks); each exited 0 once the dogfood closure was built and the commit fetched. `check:engine-double-contract` asked for the ledger row the new notify test's double needs, written with `--write` in `820d1fb9`. That commit's `scripts/` path adds 7 families (`agent-test-spelling`, `bash32-floor`, `cli-command-ids`, `entry-guard`, `parse-guard`, `pnpm-filter-targets`, `scripts-symbol-anchors`); they and 8 re-runs (`engine-double-contract`, `test-source-alias`, `type-check-debt`, `cross-package-test-inputs`, `undeclared-dep-imports`, `startup-registry-verdict`, `check-empty-changeset`, `check-adr-0087-registration`) exited 0 on `820d1fb9`. `--ran` with every exit code recorded: `121 derived famil(ies) accounted for — 121 run, 0 NOT-MEASURED (a DERIVED zero)`. `check-adr-0087-registration`: `1 declared-breaking changeset(s), each carrying an ADR-0087 disposition` — `[BREAKING+bang+clause-②-narrowing] not-required (no-migration-prescription)`. </details> <details><summary>Full dogfood (owed by the narrowing arm) — green</summary> On `3523290e` (the later head differs by one ledger row the battery does not read): dependency closure built (`pnpm --filter '@objectstack/dogfood^...' build`, VERDICT command-exit 0), then `pnpm --filter @objectstack/dogfood test` under the verify lock: `VERDICT command-exit 0`, Test Files 440 passed, 3 skipped (443); Tests 3633 passed, 41 skipped (3674). No failure. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QUs3BtX26kRDtX1TcPPLn1)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 8784ccb commit dc79e38

30 files changed

Lines changed: 2125 additions & 84 deletions
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
---
2+
'@objectstack/service-cache': patch
3+
'@objectstack/service-cluster': patch
4+
'@objectstack/service-cluster-redis': patch
5+
---
6+
7+
feat(service-cache)!: a multi-node deployment on the redis cluster driver shares one Redis cache, so cache-backed limits hold across replicas; a per-process cache there refuses to boot
8+
9+
Clause-②: yes (narrowing) — new exports and options widen the public surface, and one configuration that used to boot is now refused: `CacheServicePlugin({ adapter: 'memory' })` in a deployment that declares multi-node (`OS_EXPECT_MULTI_NODE=true` / `OS_CLUSTER_REPLICAS` > 1) over the `redis` cluster driver.
10+
Metadata-protocol: none
11+
12+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no stored row changes shape: what moves is which cache adapter a plugin option set selects at boot, and the one refusal is a boot-time error that names its own remedy. Nothing at rest records the choice, so there is nothing for a migration to rewrite. -->
13+
14+
**BREAKING** for one configuration only: a host that passes `adapter: 'memory'` explicitly AND declares multi-node over the redis cluster driver. Single-node boots, and every boot that leaves `adapter` unset, are unaffected.
15+
16+
- **Before.** `CacheServicePlugin` registered an in-process `MemoryCacheAdapter` on every node. `RedisCacheAdapter` threw `not yet implemented` from every method, and `adapter: 'redis'` threw at `init`. On N replicas every counter kept in the cache counted per process: better-auth's sign-in limits (through `rateLimit.customStorage`), the inbound API budget, the OTP send budget, the daily SMS quota and the `notify` node's per-address email limit each admitted N times the declared limit, and nothing at boot said so.
17+
- **Now (`@objectstack/service-cache`).** With `adapter` unset, the deployment's topology decides at `init`:
18+
- single node (no multi-node declaration): `MemoryCacheAdapter`, the same boot as before; the cluster service is not read;
19+
- multi-node declared over the `redis` cluster driver: `RedisCacheAdapter`, on a connection duplicated from the driver's (same Redis, same key prefix), closed at `kernel:shutdown`. Boot logs `registered redis cache adapter — one cache for every node on this Redis`;
20+
- multi-node declared over that driver with no shared cache possible (`adapter: 'memory'`, or a driver build that offers no connection): `init` throws, naming the fix;
21+
- multi-node declared over any other driver, or with no cluster service: `MemoryCacheAdapter` plus one `warn` that cache-backed limits multiply by the replica count.
22+
23+
`adapter: 'redis'` now works: over `redis.client` (a host-owned ioredis client, never closed by the plugin), else the redis cluster driver's connection, else `init` throws. The plugin declares `com.objectstack.service.cluster` as an optional dependency, so it reads the driver after the driver started, in either registration order.
24+
- **`RedisCacheAdapter`** is implemented. It takes a `client` (constructing none from a URL; `url` is deprecated and refused with a prescription when it is the only thing passed), stores entries at `<keyPrefix>cache:<key>` (default prefix `os:`, the driver's), JSON-encodes values (a `Date` reads back as its ISO string; `undefined`, functions and `bigint` are refused with a `TypeError`), lets Redis expire them (`SET … PX`; `ttl` in seconds, `0` = no expiry), throws Redis failures instead of answering a miss, and confines `clear()` and `stats().keyCount` to its own namespace, so the driver's `kv:` / `ctr:` / lock keys under the same prefix are never touched. `hits` / `misses` stay per process. Counters remain read-modify-write (the contract has no atomic increment): two nodes counting one key in the same instant can both be admitted at a limit's boundary, the bounded imprecision ADR-0069 D2 accepts.
25+
- **New in `@objectstack/service-cache`:** the `redis` option (`CacheServicePluginRedisOptions`: `client`, `keyPrefix`, `defaultTtl`) and the `RedisCacheClient` type. `redisUrl` is deprecated (never read).
26+
- **New in `@objectstack/service-cluster`:** `offerClusterDriverConnection(cluster, { driver, client, keyPrefix })` and `readClusterDriverConnection(cluster, driver)`, the seam a driver offers its connection through. The offer is a non-enumerable property under a `Symbol.for` key, so it never serialises and a second copy of the package reads it too.
27+
- **`@objectstack/service-cluster-redis`** offers its ioredis client and key prefix through that seam. Its own behaviour is unchanged.
28+
29+
Better-auth's `secondaryStorage` stays off: sessions remain in `sys_session`, and the shared cache only carries the rate-limit counters.
30+
31+
**The remedy** for the refused configuration: drop `adapter` (or pass `adapter: 'redis'`) so the cache shares the cluster driver's Redis. A host that deliberately wants per-process caches must also drop the multi-node declaration.

‎content/docs/kernel/cluster.mdx‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -86,10 +86,12 @@ These four are the minimum sufficient set. Higher-level facilities
8686
the primitives instead — today it ships memory and DB adapters only and does
8787
not consume the cluster service.
8888
- **No native cache primitive.** Caches are `KV + PubSub` (read the value,
89-
subscribe to the invalidation channel). `service-cache` is expected to build
90-
on the primitives instead — today it ships a memory adapter plus a Redis
91-
adapter skeleton that throws `RedisCacheAdapter not yet implemented`, and it
92-
does not consume the cluster service either.
89+
subscribe to the invalidation channel). `service-cache` does not build on the
90+
primitives: it ships a memory adapter and a Redis adapter, and in a declared
91+
multi-node deployment over the `redis` driver it runs the Redis adapter on a
92+
connection duplicated from the driver's — the only thing it takes from the
93+
cluster service. Over any other driver it stays per-process and says so at
94+
boot.
9395
- **No native stream/Kafka primitive.** Streaming is intentionally out of
9496
scope for v1. It can be added as a fifth primitive later without changing
9597
the four above.

‎content/docs/kernel/contracts/cache-service.mdx‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -179,5 +179,24 @@ Two adapters ship in `@objectstack/service-cache`, both implementing `ICacheServ
179179

180180
- **`MemoryCacheAdapter`** — Map-backed in-process store with TTL expiry and optional LRU-style
181181
eviction (`maxSize`). Suitable for development, testing, and single-process deployments.
182-
- **`RedisCacheAdapter`** — a skeleton placeholder for future Redis integration; its methods
183-
currently throw `RedisCacheAdapter not yet implemented`.
182+
- **`RedisCacheAdapter`** — one cache for every node of a multi-node deployment, on the Redis
183+
the `redis` cluster driver already connects to (`@objectstack/service-cluster-redis`).
184+
Entries live at `<keyPrefix>cache:<key>` (default prefix `os:`), values are JSON, Redis
185+
expires them, and a Redis failure is thrown rather than answered as a miss.
186+
187+
`CacheServicePlugin` picks between them from the deployment's topology when `adapter` is
188+
left unset:
189+
190+
| Deployment | Cache |
191+
|:---|:---|
192+
| Single node (no multi-node declaration) | memory — unchanged |
193+
| Multi-node declared (`OS_EXPECT_MULTI_NODE=true` / `OS_CLUSTER_REPLICAS` > 1) over the `redis` cluster driver | Redis, on a connection duplicated from the driver's |
194+
| The same, but `adapter: 'memory'` or a driver that offers no connection | boot refused |
195+
| Multi-node declared over another driver | memory, with a `warn` |
196+
197+
A counter kept in the cache — better-auth's sign-in rate limits through
198+
`rateLimit.customStorage`, the inbound API budget, the daily SMS quota, the `notify` node's
199+
per-address email limit — is one counter per cache, so on a
200+
per-process cache N replicas admit N times the declared limit. The Redis adapter makes it
201+
one counter. It never becomes better-auth's `secondaryStorage`: sessions stay in
202+
`sys_session` (see the top of this page).

‎content/docs/plugins/packages.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -229,9 +229,9 @@ All services implement contracts from `@objectstack/spec/contracts` and are kern
229229

230230
### @objectstack/service-cache
231231

232-
**Cache Service** — In-memory caching behind the [`ICacheService` contract](/docs/kernel/contracts/cache-service).
232+
**Cache Service** — Caching behind the [`ICacheService` contract](/docs/kernel/contracts/cache-service), in memory on one node and on a shared Redis across replicas.
233233

234-
- **Adapters**: Memory (the only working adapter). `RedisCacheAdapter` is a **skeleton** — every method throws `not yet implemented`, and `CacheServicePlugin({ adapter: 'redis' })` refuses to start. For a real distributed cache, register your own `ICacheService` via `ctx.registerService('cache', impl)`.
234+
- **Adapters**: Memory (the default) and Redis. A deployment that declares multi-node (`OS_EXPECT_MULTI_NODE=true` / `OS_CLUSTER_REPLICAS` > 1) over the `redis` cluster driver gets `RedisCacheAdapter` on the driver's Redis, so cache-backed limits hold across replicas; a per-process cache there refuses to boot. For any other store, register your own `ICacheService` via `ctx.registerService('cache', impl)`.
235235
- **Features**: `get` / `set` / `delete` / `has` / `clear` / `stats`, per-entry TTL, `maxSize` eviction, lookup & write metrics
236236
- **When to use**: Performance optimization, reduce database load
237237
- **README**: [View README](https://github.com/objectstack-ai/objectstack/blob/main/packages/services/service-cache/README.md)

‎docs/HARDENING.md‎

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -144,23 +144,30 @@ too (`trustProxy` option); `objectstack serve` does that for you.
144144
The buckets live in the kernel `cache` service, resolved when the first
145145
request is metered, so a cache plugin that registers late is still found.
146146
Under `objectstack serve` the `cache` service is always on and is served by
147-
`@objectstack/service-cache`, whose only working adapter is **in-memory** —
148-
per process. On one node that is exact. On N nodes each counts on its own,
149-
so the effective limit is the budget **multiplied by N**, and nothing about
150-
the deployment looks wrong.
151-
152-
For one limit across nodes, register a `cache` service backed by a store
153-
every node shares (Redis, Memcached, …) that implements the
147+
`@objectstack/service-cache`. On one node it is **in-memory** — per process,
148+
and exact. On N nodes a per-process cache would make each node count on its
149+
own, so the effective limit would be the budget **multiplied by N** with
150+
nothing about the deployment looking wrong.
151+
152+
So `@objectstack/service-cache` picks the store from the deployment's
153+
declaration. Declare multi-node (`OS_EXPECT_MULTI_NODE=true` or
154+
`OS_CLUSTER_REPLICAS` > 1) and run the `redis` cluster driver
155+
(`OS_CLUSTER_DRIVER=redis` + `OS_REDIS_URL`), and the cache is Redis — one
156+
store for every node, on a connection duplicated from the driver's. Boot logs
157+
`registered redis cache adapter — one cache for every node on this Redis`.
158+
Declared multi-node over the redis driver, a per-process cache is refused:
159+
`adapter: 'memory'` stops the boot. Declared multi-node over any other driver,
160+
the cache stays per-process and boot warns that limits multiply by the
161+
replica count; to share it there, register a `cache` service backed by a
162+
store every node reaches that implements the
154163
[`ICacheService` contract](../content/docs/kernel/contracts/cache-service.mdx)
155164
— see [Registering Services](../content/docs/kernel/services.mdx#registering-services).
156-
`CacheServicePlugin({ adapter: 'redis' })` is not that: its Redis adapter is a
157-
skeleton and the plugin refuses to start with it. Boot logs which store the
158-
limiter bound to: `inbound rate-limit buckets bound to the kernel cache
159-
service — enforced against ONE store across nodes iff the cache is shared`,
160-
or, with no `cache` service at all, a warning that it fell back to a
161-
per-process store. Counting is read-modify-write, so two nodes can both admit
162-
the last request at a window boundary — a slight over-admit, never a
163-
per-node limit.
165+
The limiter logs which store it bound to: `inbound rate-limit buckets bound
166+
to the kernel cache service — enforced against ONE store across nodes iff the
167+
cache is shared`, or, with no `cache` service at all, a warning that it fell
168+
back to a per-process store. Counting is read-modify-write, so two nodes can
169+
both admit the last request at a window boundary — a slight over-admit, never
170+
a per-node limit.
164171

165172
### Per-class budgets
166173

‎packages/plugins/plugin-auth/package.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,13 @@
6868
"@objectstack/objectql": "workspace:*",
6969
"@objectstack/plugin-hono-server": "workspace:*",
7070
"@objectstack/plugin-security": "workspace:*",
71+
"@objectstack/service-cache": "workspace:*",
72+
"@objectstack/service-cluster": "workspace:*",
73+
"@objectstack/service-cluster-redis": "workspace:*",
7174
"@objectstack/service-settings": "workspace:*",
7275
"@types/node": "^26.6.5",
7376
"hono": "^4.13.9",
77+
"ioredis-mock": "^8.13.1",
7478
"tsx": "^4.23.15",
7579
"typescript": "^6.0.3",
7680
"vitest": "^4.1.11"
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* ONE replica, as its own OS process, for `../rate-limit-storage.shared-redis.test.ts`.
5+
* Under `__fixtures__/` because it is test code that imports devDependencies.
6+
*
7+
* Boots the composition a replica's sign-in limit really runs on — the redis
8+
* cluster driver against the Redis URL in `argv[2]`, then
9+
* `CacheServicePlugin`, which picks its adapter from this process's
10+
* `OS_CLUSTER_REPLICAS` — and counts through the same seam `AuthPlugin` wires
11+
* into better-auth: `rateLimit.customStorage` =
12+
* `createLazyCacheRateLimitStorage({ resolveCache: () => resolveKernelCache(ctx) })`.
13+
*
14+
* It is a separate process on purpose: inside one process `serializePerKey`
15+
* orders every limiter's read-modify-write on a key through one module-level
16+
* queue, so two in-process "nodes" can never interleave the way two replicas
17+
* do. Started by the test with `tsx`, so this file and the limiter it imports
18+
* are this checkout's source; the framework packages it imports are their
19+
* built `dist/`.
20+
*
21+
* IPC protocol (parent ⇄ this process):
22+
* → { type: 'consume', id, key, window, max } ← { type: 'decision', id, allowed }
23+
* → { type: 'exit' } (shuts the kernel down, exits 0)
24+
* ← { type: 'ready', cache } ('redis' | 'memory' | 'other' — the `cache` adapter)
25+
* ← { type: 'failed', message } (boot failed; exits 1)
26+
*/
27+
28+
import { ObjectKernel } from '@objectstack/core';
29+
import { CacheServicePlugin, MemoryCacheAdapter, RedisCacheAdapter } from '@objectstack/service-cache';
30+
import { ClusterServicePlugin } from '@objectstack/service-cluster';
31+
// Registers the `redis` cluster driver with `defineCluster()`.
32+
import '@objectstack/service-cluster-redis';
33+
34+
import { resolveKernelCache } from '../kernel-cache.js';
35+
import { createLazyCacheRateLimitStorage } from '../rate-limit-storage.js';
36+
37+
type Inbound =
38+
| { type: 'consume'; id: number; key: string; window: number; max: number }
39+
| { type: 'exit' };
40+
41+
async function main(): Promise<void> {
42+
const redisUrl = process.argv[2];
43+
const nodeId = process.argv[3] ?? `replica-${process.pid}`;
44+
if (!redisUrl || typeof process.send !== 'function') {
45+
throw new Error('usage: fork(<this file>, [<redis url>, <node id>]) with an IPC channel');
46+
}
47+
48+
const kernel = new ObjectKernel({ logger: { level: 'silent' }, skipSystemValidation: true } as never);
49+
await kernel.use(new ClusterServicePlugin({ config: { driver: 'redis', url: redisUrl, nodeId } }));
50+
await kernel.use(new CacheServicePlugin());
51+
await kernel.bootstrap();
52+
53+
const ctx = {
54+
getKernel: () => kernel,
55+
getService: <T>(name: string): T => kernel.getService<T>(name),
56+
} as unknown as Parameters<typeof resolveKernelCache>[0];
57+
const storage = createLazyCacheRateLimitStorage({ resolveCache: () => resolveKernelCache(ctx) });
58+
59+
process.on('message', (raw: Inbound) => {
60+
if (raw.type === 'exit') {
61+
void kernel.shutdown().finally(() => process.exit(0));
62+
return;
63+
}
64+
void storage
65+
.consume(raw.key, { window: raw.window, max: raw.max })
66+
.then((d) => process.send!({ type: 'decision', id: raw.id, allowed: d.allowed }))
67+
.catch((err: unknown) => process.send!({ type: 'decision', id: raw.id, error: String(err) }));
68+
});
69+
70+
// By `instanceof`, not `constructor.name`: the bundled `dist/` renames classes.
71+
const cache = kernel.getService<object>('cache');
72+
const adapter = cache instanceof RedisCacheAdapter ? 'redis' : cache instanceof MemoryCacheAdapter ? 'memory' : 'other';
73+
process.send({ type: 'ready', cache: adapter });
74+
}
75+
76+
main().catch((err: unknown) => {
77+
process.send?.({ type: 'failed', message: err instanceof Error ? err.message : String(err) });
78+
process.exitCode = 1;
79+
setTimeout(() => process.exit(1), 50);
80+
});

0 commit comments

Comments
 (0)