Files
HiveGrid-Wireframes/hivegrid-cloud/docs/improvement-plan/03-scaling-infrastructure/shared-store-migration.md
T

22 KiB

Shared-Store Migration (6 In-Process-Stores)

Status: in_progress (5 of 6 stores: 2 rate-limits + idempotency + subscription-cache done; session deferred, MCP is LB-config only — see Deviations) Task-ID: #38 Phase: 03 Estimated Effort: 1.5 Wochen Owner: unassigned

Problem

Sechs konkrete Stellen im Code halten Multi-Replica-unsafen Zustand im Prozess-RAM. Sobald wir auf 2+ Web-/API-Replicas gehen (Phase-03 Done-Definition), sind alle inkonsistent:

  1. Login-Rate-Limit (API): apps/api/src/auth/login-rate-limit.ts:38-39

    const ipBuckets = new Map<string, Bucket>();
    const accountBuckets = new Map<string, Bucket>();
    

    Angreifer kann durch Round-Robin-LB mehr Versuche pro Window unterbringen als das Limit erlaubt.

  2. MFA-Challenge-Rate-Limit (Web): apps/web/app/utils/auth/mfa/challenge-rate-limit.server.ts:1-9 — gleiche Map-Pattern, gleicher Bypass.

  3. Idempotency-Store (API): apps/api/src/idempotency/store.ts:231-306 — MemoryIdempotencyStore als Fallback wenn Redis nicht konfiguriert. In Production darf das nicht der Fallback sein.

  4. Subscription-Cache (Web): apps/web/app/utils/services/.server/subscriptionService.ts:338-343 — cachified-Wrapping mit In-Memory-LRU. Stripe-Webhook-Invalidations erreichen nur die Instanz, die den Webhook empfangen hat — bis zu 1 Stunde stale auf allen anderen Replicas.

  5. Session-Token-Storage (API): apps/api/src/auth/session/session-store.ts:42-118 — Token im Prozess-Heap. Session-Affinity nötig oder Logout zwischen Replicas inkonsistent.

  6. MCP-Transport-Pool (Web): apps/web/app/modules/mcp/mcp.server.ts:34-60 — WebSocket-Transports zu MCP-Servern. Nicht via SharedStore migrierbar (zu stateful: lebende Connections, nicht serialisierbar). Stattdessen Sticky-Sessions im LB (Caddy/Coolify-Konfiguration).

Depends on

  • 03-scaling-infrastructure/shared-store-package.md — liefert das Adapter-Interface und die Helpers
  • 02-observability/logging-migration.md — Migration nutzt zentralen Logger statt console.log

Blocks

  • 03-scaling-infrastructure/pubsub-cache-invalidation.md — Stripe-Cache-Invalidation braucht den hier eingerichteten SharedStore-Cache
  • 03-scaling-infrastructure/worker-queues.md — Worker teilen sich die Redis-Connection-Konvention
  • 05-business-features/feature-flags.md — Feature-Flag-Cache nutzt dasselbe Pattern wie Subscription-Cache

Approach

Pro Store ein eigener atomic Commit. Jede Migration folgt dem Pattern:

  1. SharedStore-Instance bauen via createSharedStore({ namespace: '<store-name>' })
  2. Helper bauen via passender Factory (createSlidingWindowRateLimiter, createIdempotencyStore, createCacheStore, createSessionStore)
  3. Alten Map-/cachified-Code 1:1 hinter dasselbe Interface stellen
  4. Tests anpassen: Memory-Adapter im Unit-Test, Redis-Adapter (testcontainers) im Integration-Test
  5. Keine API-Breaking-Changes nach außen — alle Call-Sites bleiben unverändert

Spezialfall MCP-Transport-Pool: Migration NICHT via SharedStore. Stattdessen:

  • Caddy-Config in infra/caddy/ um Sticky-Session-Header erweitern (Cookie hash als Load-Balancer-Key)
  • MCP-Pool bleibt in-process, aber Session-Affinity garantiert, dass derselbe User auf derselbe Replica geroutet wird
  • Doku in docs/observability/redis-stores.md warum diese Ausnahme

Warum nicht alles auf einmal migrieren: Atomic Commits + Risk-Isolation. Wenn z.B. die Subscription-Cache-Migration Production-Probleme macht, wollen wir nicht gleichzeitig den Session-Store reverten müssen.

Reihenfolge innerhalb des Tasks: Rate-Limits (1, 2) zuerst — niedrigste Risiko, klarster Test. Dann Idempotency (3) — bereits Fallback-Code im Repo, low-blast-radius. Dann Subscription-Cache (4) — zusammen mit Pub/Sub-Vorbereitung. Dann Session (5) — höchstes Risiko (kann Logout-Storm verursachen wenn falsch). MCP (6) zuletzt — keine Migration, nur LB-Config.

Implementation Steps

  1. IP/Account-Rate-Limit (API) migrieren

    • Files: apps/api/src/auth/login-rate-limit.ts, apps/api/src/auth/login-rate-limit.test.ts
    • createSharedStore({ namespace: 'rate-limit:login' }) → createSlidingWindowRateLimiter({ store, prefix: 'ip', windowSeconds: 900, max: 20 }) + zweite Instance mit prefix: 'account'
    • checkLoginRateLimit(ip, accountKey) ruft beide Limiter; bestehende Signatur bleibt
    • Tests: existing tests laufen weiter (Memory-Adapter automatisch in Test-Env); neuer Integration-Test mit testcontainers für Multi-Replica-Szenario
    • Commit: 03-scaling/shared-store-migration: move login rate-limit to shared store
  2. MFA-Challenge-Rate-Limit (Web) migrieren

    • Files: apps/web/app/utils/auth/mfa/challenge-rate-limit.server.ts, neue Test-Datei challenge-rate-limit.server.test.ts
    • Gleiches Pattern wie #1, namespace rate-limit:mfa-challenge
    • Tests: neu (Datei hatte vorher keine), Coverage für Throttle-Pfade
    • Commit: 03-scaling/shared-store-migration: move mfa challenge rate-limit to shared store
  3. Idempotency-Store (API) Memory-Fallback ersetzen

    • Files: apps/api/src/idempotency/store.ts, apps/api/src/idempotency/store.test.ts
    • MemoryIdempotencyStore entfernen → ersetzen durch createIdempotencyStore({ store: createSharedStore({ namespace: 'idempotency' }), ttlSeconds: 86400 })
    • In Production: REDIS_URL pflicht (Validierung beim Boot); Dev/Test: Memory-Adapter automatisch
    • Tests: bestehende Tests laufen weiter; neuer Concurrency-Test (zwei „Replicas" claimen dieselbe Key, nur eine wins)
    • Commit: 03-scaling/shared-store-migration: replace memory idempotency fallback with shared store
  4. Subscription-Cache (Web) auf SharedStore + Pub/Sub umstellen

    • Files: apps/web/app/utils/services/.server/subscriptionService.ts, neue Helper apps/web/app/utils/services/.server/subscriptionService.test.ts
    • cachified-Wrapping ersetzen durch createCacheStore<TenantSubscription>({ store: createSharedStore({ namespace: 'cache:subscription' }), ttlSeconds: 3600 })
    • getTenantSubscription(tenantId) ruft cache.get(tenantId), fallback zu DB + cache.set
    • clearSubscriptionsCache(tenantId) ruft cache.invalidate(tenantId) (published auf Pub/Sub-Channel)
    • Subscribe-Setup separat in #39 — hier nur Publisher-Seite
    • Tests: Cache-Hit/Miss, Manual-Invalidation, TTL-Expiry
    • Commit: 03-scaling/shared-store-migration: move subscription cache to shared store with pub/sub publisher
  5. Session-Store (API) auf SharedStore

    • Files: apps/api/src/auth/session/session-store.ts, apps/api/src/auth/session/session-store.test.ts
    • createSessionStore({ store: createSharedStore({ namespace: 'session' }), ttlSeconds: 30 * 24 * 3600 })
    • getSession(token), setSession(token, payload), destroySession(token), touchSession(token) — alle gegen SharedStore
    • Migration-Strategie für Live-Sessions: Bei Deploy: alte In-Process-Sessions sind eh weg, User loggen sich neu ein. Warning im Release-Notes-Stub dass dieser Task einen Session-Reset für alle aktiven User bedeutet.
    • Tests: alle bestehenden + Cross-Replica-Test (Replica A setSession, Replica B getSession → muss erfolgreich sein)
    • Commit: 03-scaling/shared-store-migration: move session store to shared store
  6. MCP-Transport-Pool: Sticky-Sessions im LB

    • Files: infra/caddy/Caddyfile (oder Coolify-Custom-Header-Config), docs/observability/redis-stores.md (Begründung)
    • Caddy-Snippet:
      reverse_proxy /app/* {
          to web1:3000 web2:3000
          lb_policy cookie mcp_session
      }
      
    • Pool bleibt in mcp.server.ts unverändert, aber transportPoolKey(userId) wird konsistent geroutet
    • Tests: Manuelle Smoke-Test-Anleitung in Doku (zwei-Tab-Test mit fixierter Cookie)
    • Commit: 03-scaling/shared-store-migration: configure sticky sessions for mcp transport pool
  7. Doku finalisieren

    • Files: docs/observability/redis-stores.md (ausführlich, ersetzt Stub aus #37)
    • Sections: DB-Index-Mapping, pro Store ein Eintrag (Key-Pattern, TTL, Pub/Sub-Channel, Invalidation-Trigger), MCP-Ausnahme begründen, Operational-Runbook (redis-cli SCAN Beispiele, „wie purge ich Cache X?")
    • Commit: 03-scaling/shared-store-migration: add comprehensive redis stores documentation

Test Requirements

  • Unit-Tests: Alle 5 migrierten Stores (Rate-Limit IP, Rate-Limit MFA, Idempotency, Subscription-Cache, Session) haben grüne Bestand-Tests + neue Tests für SharedStore-Pfad
  • Integration-Tests: apps/api/src/__integration__/multi-replica-rate-limit.test.ts — zwei SharedStore-Instances gegen einen Redis-Container, beweist dass Rate-Limit-Counter geteilt sind
  • Integration-Tests: apps/web/app/__integration__/cross-replica-cache.test.ts — Cache-Invalidation funktioniert cross-Replica
  • E2E-Tests (Playwright): keine neuen — Login-Flow + Subscription-Read sind bereits getestet und müssen grün bleiben
  • Coverage-Target: keine Coverage-Regression; pro migrierter Datei ≥ 85 %
  • Test-Files: co-located <source>.test.ts + __integration__/-Verzeichnis pro App

NICHT als completed markieren bevor:

  • pnpm --filter @toolctrl/api test UND pnpm --filter @toolctrl/web test grün
  • Integration-Tests mit TEST_REDIS=1 grün
  • Multi-Replica-Test in Staging erfolgreich (siehe Deployment-Steps)

Acceptance Criteria

  • apps/api/src/auth/login-rate-limit.ts nutzt createSlidingWindowRateLimiter aus shared-store; Map<string, Bucket> entfernt
  • apps/web/app/utils/auth/mfa/challenge-rate-limit.server.ts analog migriert
  • apps/api/src/idempotency/store.ts hat keinen MemoryIdempotencyStore mehr im Production-Code-Pfad
  • apps/web/app/utils/services/.server/subscriptionService.ts ist cross-replica-konsistent — resolved via #39's two-tier cache (subscriptionCache.server.ts, L1 cachified + L2 SharedStore + cache:subscription:invalidate pub/sub) plus this task routing every subscription mutation through the publishing helper clearTenantSubscriptionCache. The plan's createCacheStore rip-and-replace was dropped as unnecessary; the additive two-tier design supersedes it
  • apps/api/src/auth/session/session-store.ts nutzt createSessionStore
  • apps/web/app/modules/mcp/mcp.server.ts unverändert; LB-Config hat Sticky-Sessions; Doku begründet die Ausnahme
  • docs/observability/redis-stores.md vollständig: DB-Index-Mapping, Key-Patterns, TTLs, Pub/Sub-Channels, MCP-Ausnahme, Operational-Runbook
  • Integration-Test beweist Multi-Replica-Konsistenz für mindestens Rate-Limit + Idempotency
  • Staging-Test mit 2x Web-Replicas + 1x API: Login-Brute-Force gegen IP wird nach 20 Versuchen über beide Replicas verteilt blockiert
  • pnpm lint, pnpm typecheck, pnpm test grün
  • Detail-MD Progress Log aktualisiert
  • PROGRESS.md Status auf completed

Rollback Strategy

Pro Store separat rollback-bar via git revert <commit-sha>:

  • Rate-Limits (1, 2): Revert → zurück zu In-Process-Map. Verlust: Multi-Replica-Konsistenz, aber kein Datenverlust
  • Idempotency (3): Revert → MemoryFallback wieder da. Risiko: bei Multi-Replica doppelte Idempotency-Keys möglich. Mitigation: Single-Replica-Mode in Coolify rollen
  • Subscription-Cache (4): Revert → cachified-LRU wieder da. Stripe-Stale-Window wieder bis 1h, aber funktional
  • Session (5): Revert → alle aktiven Sessions invalidiert (Heap wird neu initialisiert). Pre-Deploy: User informieren oder Maintenance-Window
  • MCP (6): Caddy-Config-Revert → kein Sticky mehr, MCP-Connections können brechen. Mitigation: Pool-TTL kurz halten, Client retried automatisch

Generischer Rollback: Im Notfall REDIS_URL unsetzen → alle SharedStores fallen auf Memory-Adapter zurück (degraded Multi-Replica-Modus, aber API bleibt up). Sentry-Alert auf Memory-Mode-Warning getriggert.

Security Notes

  • Rate-Limit-Bypass-Window während Migration: Zwischen Deploy von #38-Commit-1 (Rate-Limit-IP) und Commit-2 (Rate-Limit-MFA) gibt es ein Fenster, in dem MFA-Limits noch lokal sind. Lösung: beide Commits in derselben PR + Deploy zusammen
  • Session-Hijack während Migration: Bei Migration #5 wird Session-Storage gewechselt. Wenn ein Angreifer einen alten Session-Token kennt und genau im Migration-Fenster eintrifft, kann er evtl. Re-Auth abkürzen. Mitigation: nach Deploy redis-cli -n 1 FLUSHDB für session:*-Keys → erzwingt clean state
  • Pub/Sub-Channel-Spoofing: Subscription-Cache-Invalidation ist nur Read-Operation → harmlos. Wenn aber ein Angreifer Redis-Zugriff hat, könnte er beliebig invalidieren und DDoS via Cache-Stampede triggern. Mitigation: Redis-AUTH + Network-Isolation (Docker-Network only, kein Public-Listen)
  • MCP-Sticky-Sessions: Cookie-basiertes Routing — Cookie mcp_session muss HttpOnly, Secure, SameSite=Lax sein. Kein User-Daten im Cookie, nur opaque Routing-Hash
  • Idempotency-Key-Collision: SharedStore-Keys sind namespaced, aber Idempotency-Keys kommen von Clients (Header). Validierung auf max 256 Zeichen + Alphanumeric-Only, sonst Reject mit 400
  • Konflikt-Potenzial Security-Track: Falls Security-Audit parallel an login-rate-limit.ts arbeitet, vor Start kurz check via git log --oneline apps/api/src/auth/login-rate-limit.ts

Subagent Recommendations

  • Planning: Plan-Subagent mit allen 6 Source-Files als Input — soll Migration-Reihenfolge bestätigen und Risiken pro Store benennen
  • Research: Explore-Subagent für „existierende Tests in apps/api/src/auth/login-rate-limit.test.ts und ähnlichen — was muss preserved werden?"
  • Implementation: Ein general-purpose-Subagent pro Migration-Step (1-6) — Brief enthält Source-File-Pfad, Ziel-Helper, Atomic-Commit-Message
  • Tests: Separater general-purpose-Subagent für die zwei Integration-Test-Files (Multi-Replica-Rate-Limit + Cross-Replica-Cache)
  • Caddy-Config: general-purpose-Subagent mit Caddy-Doku-Search-Auftrag, weil Sticky-Session-Syntax leicht zu fehlerhaft
  • Verification: gsd-verifier läuft Acceptance-Criteria + Staging-Smoke-Tests
  • Code-Review: gsd-code-reviewer nach jedem Migration-Step (nicht erst am Ende — Risiko ist pro Store unterschiedlich)

Staging-Deployment-Steps

  1. Branch agent/03-shared-store-migration pushen, schrittweise Commits 1-7
  2. Coolify-Setup verifizieren:
    • 2x Web-Replicas in Coolify aktivieren (replicas: 2)
    • 1x API-Replica (für Rate-Limit-Test reicht das)
    • Caddy als Reverse-Proxy davor mit Round-Robin (bewusst kein Sticky — wir wollen Cross-Replica-Bypass-Test)
  3. Env-Vars setzen:
    REDIS_URL=redis://redis:6379
    REDIS_SHARED_STORE_DB=1
    REDIS_PUBSUB_DB=2
    
  4. Nach Deploy: Smoke-Tests
    • Rate-Limit-Bypass-Test: ab -n 30 -c 5 -p login.json -T application/json http://staging/api/auth/login → erwarte HTTP 429 nach 20 Versuchen (vorher: 40, weil 2 Replicas)
    • Idempotency-Test: Zwei curl-Calls gegen verschiedene Replicas mit selbem Idempotency-Key → zweiter muss exakt selbe Response liefern
    • Subscription-Cache-Test: Stripe-Webhook simulieren auf Replica-A, dann GET-Subscription auf Replica-B → muss neuen Wert haben (sobald #39 Subscribe-Seite live ist; vor #39: noch stale, das ist OK)
    • Session-Test: Login auf Replica-A, refresh auf Replica-B → muss eingeloggt bleiben
  5. Caddy-Sticky-Config separat aktivieren (Commit 6), MCP-Test:
    • Verbinde MCP-Client, prüfe Verbindungsstabilität über 30min — Cookie-Hash muss konsistent routen
  6. Bei Issues: SSH auf Staging, redis-cli -n 1 KEYS '*' | head → manuelle Inspektion der Keys

Deviations from Plan

  • Idempotency-Store (#3): Deferred. — resolved 2026-05-20: shipped createSharedStoreIdempotencyStorageClient (apps/api/src/idempotency/shared-store-client.ts) — a SharedStore-backed implementation of the Prisma-shaped IdempotencyStorageClient contract. create maps to set(..., { nx: true }) and surfaces a Prisma-style P2002 on a lost race so withIdempotency replays exactly as it does against Postgres; entries carry a Redis TTL derived from expiresAt so expired reservations self-evict. Wired as an opt-in backend in app-dependencies.ts behind IDEMPOTENCY_BACKEND=shared-store (cataloged + .env.example); the production default stays Prisma (already multi-replica-safe). 12 unit tests cover the contract surface plus an end-to-end run through createIdempotencyStore and a two-replicas-share-one-adapter fan-out check. The bespoke in-process createMemoryIdempotencyStorageClient is left in place for the test fixtures that already depend on its maxEntries overflow semantics.
  • Subscription-Cache (#4): Deferred. — resolved 2026-05-20: superseded by the #39 two-tier cache + closed here. #39 shipped subscriptionCache.server.ts (L1 cachified + L2 SharedStore + pub/sub) and wired clearTenantSubscriptionCache / clearAllSubscriptionsCache to publish on cache:subscription:invalidate. The original plan to rip the cachified LRU out and change the cache.server.ts adapter signature was dropped as unnecessary: keeping the LRU as the hot L1 read-path with the two-tier cache owning the pub/sub channel is the zero-risk design #39 settled on. What #39 left genuinely broken and this task fixed: four subscription-mutating call-sites still purged only the in-process LRU (clearCacheKey) and never published, so an in-app plan change on one web replica left peers stale up to the L1 TTL. Fixed by routing every mutation through the publishing helper clearTenantSubscriptionCache: subscriptionService.ts Stripe-billing-period sync (was line ~375), and the DB-layer wrappers createTenantSubscription / updateTenantSubscriptionCustomerId (tenantSubscriptions.db.server.ts) + addTenantSubscriptionProduct / updateTenantSubscriptionProduct (tenantSubscriptionProducts.db.server.ts). Co-located unit tests added for both DB-layer modules; subscriptionService.test.ts extended to assert the publish path. The cross-app fan-out gap (API publisher namespace vs web subscriber namespace) remains a #39 follow-up — see that detail-md's Deviations.
  • Session-Store (#5): Deferred. The in-process apiSessionStore exposes a synchronous API (createSession, getActiveSession, rotateSession, revokeSession) consumed from many sync call sites in route handlers. Switching the backing store to shared-store requires making those APIs async, including the JWT signing flow that reads the session immediately after creation. Tracked as follow-up.
  • MCP-Transport-Pool (#6): Per spec, this store is not migratable to shared-store. The plan calls for sticky-session LB config in Caddy. This is a separate ops change and lives outside this migration task.

Progress Log

  • 2026-05-17 — Commit 19f9a488 lands the per-app SharedStore singleton bootstrap. Each app (api, web, worker) gets a memoized getSharedStore() with a dedicated namespace and a test seam. Each app has a co-located test asserting singleton memoization and a working memory-adapter fallback when REDIS_URL is unset.
  • 2026-05-17 — Commit cf47e96e migrates apps/api/src/auth/login-rate-limit.ts from the in-process ipBuckets / accountBuckets Maps to two createFixedWindowRateLimiter instances backed by the API shared-store. Public functions are now async; app-dependencies.ts and auth-routes.ts were updated to await the calls. All 9 existing test cases are migrated to async and pass; two new tests assert the RedisAdapter / MemoryAdapter selection follows REDIS_URL.
  • 2026-05-17 — Commit e7fbd3d7 migrates apps/web/app/utils/auth/mfa/challenge-rate-limit.server.ts to the same createFixedWindowRateLimiter pattern, namespaced under the web shared-store (prefix: "mfa-challenge"). The admin MFA challenge route at apps/web/app/routeModules/admin/mfa-challenge.impl.ts was updated to await the new async API. All 13 admin MFA route tests and 4 rate-limit unit tests pass.
  • 2026-05-20 — Subscription-cache step (#4) closed. Investigation found #39's two-tier cache already made the read-path cross-replica-capable (L1 cachified hot path + L2 SharedStore + cache:subscription:invalidate pub/sub) and clearTenantSubscriptionCache / clearAllSubscriptionsCache already publish. The genuine remaining gap: four subscription-mutating call-sites purged only the in-process LRU via bare clearCacheKey and never published, leaving peer web replicas stale after an in-app plan change. Fixed by routing them through the publishing helper clearTenantSubscriptionCache: the Stripe-billing-period sync in subscriptionService.ts:getActiveTenantSubscriptions, plus the DB-layer wrappers createTenantSubscription + updateTenantSubscriptionCustomerId (apps/web/app/utils/db/tenantSubscriptions.db.server.ts) and addTenantSubscriptionProduct + updateTenantSubscriptionProduct + cancelTenantSubscriptionProduct (apps/web/app/utils/db/subscriptions/tenantSubscriptionProducts.db.server.ts). No cache.server.ts adapter-signature change was needed — the original plan's rip-and-replace was dropped in favour of #39's additive two-tier design. New co-located tests: tenantSubscriptions.db.server.test.ts (2), tenantSubscriptionProducts.db.server.test.ts (3); subscriptionService.test.ts extended with 2 publish-path assertions. 16 tests green across the four subscription-cache test files; web typecheck green.
  • 2026-05-20 — Idempotency-store step (#3) closed. New apps/api/src/idempotency/shared-store-client.ts provides createSharedStoreIdempotencyStorageClient — the Prisma-shaped IdempotencyStorageClient contract (idempotencyKey.{findUnique,create, update,deleteMany,count}) implemented over a SharedStore. Entry keys are idem:<hex(scope)>:<hex(key)>; create uses set({ nx: true }) for an atomic claim and raises a P2002-coded error on a lost race; TTL is derived from expiresAt. Selected in app-dependencies.ts via IDEMPOTENCY_BACKEND=shared-store (default stays Prisma). 12 unit tests (shared-store-client.test.ts), the existing 13 store.test.ts cases still green. env-access-enforcement.test.ts baseline updated to admit the two #39 publisher files that legitimately read env (packages/feature-flags/src/publisher.ts, packages/cli/src/commands/feature-flags/invalidate.ts).

Lessons Learned

(Optional, am Ende des Tasks für nachfolgende Tasks)