Skip to main content

@strutvane/redis: Cache, Locks, Sessions and Rate Limits That Work Across Every Server

Redis and Valkey for Strutvane apps, with per-app and per-tenant key prefixes, fail-fast behaviour and safe production defaults.

Updated 7 min readMarkdown

Your app runs happily on one server. Then traffic grows, and you add a second one behind a load balancer.

Suddenly, strange things happen:

  • A user signs in on server A, and server B has never heard of them.
  • Your "5 exports per hour" limit is really 10, because each server counts on its own.
  • The nightly report job runs twice, because both servers thought it was their turn.
  • The cache on server A says one thing, and the cache on server B says another.

The fix is well known: put the shared state in one fast place that every server can reach. Usually that's Redis. The tricky part is doing it safely: keys that don't collide, locks that release correctly, and an app that behaves sensibly when Redis is down.

That's @strutvane/redis.


What it is

@strutvane/redis brings Redis and Valkey (fast, in-memory data stores) to apps built on Strutvane, an open-source (MIT) TypeScript framework for business (B2B) apps. It gives you:

  • a cache store,
  • atomic locks,
  • a session store,
  • rate limiting,
  • an idempotency store (so a retried request isn't processed twice),
  • and an experimental queue driver, ready for when framework queues arrive.

Every key lives under your app's prefix, and can be scoped to a tenant (one customer company in a multi-tenant app).

Why it exists

The framework ships with in-memory and file-based stores, which are perfect for one server and for development. As soon as you have more than one process, you need shared state. Rather than make every app wire up a Redis client and invent its own key naming, this package plugs Redis into the framework's existing extension points. Your code keeps using the framework's Cache facade and middleware; only the storage underneath changes.

It's also opinionated about safety, because shared infrastructure is where small mistakes become big ones. One app flushing another app's keys, a lock released by the wrong process, a password sent in plain text across a network: this package is designed so those don't happen by default.

What you get

Cache

  • A cache store that implements the framework's cache contract, with atomic add and increment.
  • Extras like remember, many, putMany, forever, and flexible, which is stale-while-revalidate: serve the slightly old value instantly, refresh it in the background.
  • forTenant(id) to give each tenant its own cache space.
  • With CACHE_STORE=redis, the framework's throttle middleware counts in Redis, so a rate limit like throttle:api holds across every server.

Locks

  • Owner tokens, so only the process that took a lock can release it.
  • Safe release and extend (done in one atomic step on the server).
  • Locks expire on their own if the holder crashes.
  • block() waits for a lock up to a time limit, then fails with a clear lock_timeout error.

Rate limiting

  • Fixed and sliding windows, computed atomically on the Redis server's clock (so servers with slightly different clocks still agree).

Sessions and idempotency

  • A Redis session store, switched on with SESSION_DRIVER=redis.
  • Session ids and idempotency keys are stored as SHA-256 hashes, never in plain form.

Keys and tenants

  • Every key is <prefix><area>:<key>. The default prefix is your app name plus environment, like my_blog:production:, so two apps (or staging and production) sharing one Redis never collide.
  • Tenant ids may only contain letters, digits, _ and -, so one tenant can't reach into another's key space.
  • Flushes match your prefix literally and never run FLUSHDB (which would wipe everyone's keys on a shared server).

When things go wrong

This is the part I'm proudest of, because it's where most integrations get sloppy:

  • Redis is down: commands fail fast with a clear 503 redis_unavailable problem instead of piling up in memory. After a failed connect, new attempts wait a second (a "circuit breaker"), and the log says why, never including the password.
  • Wrong password or missing permission: also redis_unavailable. It fails closed.
  • Shutdown: the connection closes gracefully, waiting a bounded time for pending replies.
  • Production, Redis on another machine: the app refuses to boot unless you've made an explicit choice about TLS (encryption in transit) and set a password. You can opt out on purpose (for example, when the network is protected another way), and the app still logs a warning at boot. TLS always verifies the server's certificate; there's no switch to turn that off.
  • Bad settings: the app stops at boot with invalid_redis_config and tells you which value is wrong. Passwords and connection URLs are refused in config files, because config gets cached and is easy to dump. They belong in .env only.

How it fits into Strutvane

@strutvane/redis is an add-on. It depends only on the published @strutvane/framework (as a peer dependency, so your app has exactly one copy) and plugs in through container tokens. Its provider binds:

  • the shared Redis connection (with a health() check you can use for readiness probes);
  • the key space, locks and rate limiter;
  • the framework's cache manager, extended with redis stores;
  • the session store, when SESSION_DRIVER=redis;
  • the idempotency store, when your default cache store is Redis.

Its installer is idempotent: it writes config/redis.ts, adds the REDIS_* keys to .env and .env.example (secrets left empty, existing values never overwritten), and registers the provider. It does not switch your app to Redis; you choose that in .env when your server is ready. node strut remove redis reverses it.

A quick look

npm install @strutvane/redis
node strut add redis

Then, when you're ready, in .env:

CACHE_STORE=redis
SESSION_DRIVER=redis
REDIS_URL=rediss://app:secret@cache.example.com:6380/0

And in your code:

import { Cache } from '@strutvane/framework/facades'
import { RedisLocksToken, RedisRateLimiterToken } from '@strutvane/redis'

// Cache
await Cache.store('redis').put('stats', { posts: 3 }, 60)

// Atomic locks: owner tokens, safe release, expiry if the holder crashes
await app.make(RedisLocksToken).create('reports:build', 120).block(10, () => buildReports())

// Rate limits in your own code (fixed or sliding window)
const limit = await app.make(RedisRateLimiterToken).hit(`export:${user.id}`, {
  max: 5,
  windowSeconds: 3600,
  algorithm: 'sliding',
})

Requirements: Node 24.3+, Redis 6.2+ or Valkey 7.2+. It uses the official @redis/client (MIT).

⚠️ This is a 0.2 preview. The APIs may still change before 1.0, planned for January 2027. The queue driver is experimental until framework queues land in 0.3.

Built to be trusted

  • 80 unit tests, plus 154 integration tests against a real Redis server (started in a throwaway container with ACL users and a TLS port), not a mock. The same suite can run against Valkey.
  • CI on Linux, Windows and macOS, on Node 24 and Node 26.
  • Security-reviewed and secure by default: verified TLS, hashed session ids, no FLUSHDB, refusal to boot with risky production settings.
  • Every release is staged by CI and approved by a human with two-factor authentication, and published with npm provenance.

What's next

From the README:

  • The queue driver gets wired in once the framework defines queues (0.3).
  • Sentinel and cluster support (they plug in behind the same driver seam).
  • Broadcasting (pub/sub) for realtime features.

Try it, and tell me what you think

Next in the series: @strutvane/health, so you know your app is sick before your users do. Follow along! ⚡

— Vishwajit VM


Part of the Strutvane series. Strutvane™ is open source under the MIT licence.

About the author

  • Hi, I'm Vishwajit VM, a backend & AI engineer from New Delhi. For 5+ years I've built the parts of apps you don't see: APIs, databases, queues and AI agents, for teams in hiring, real estate, finance, retail and civic tech. My rule is simple: a system should keep working when something goes wrong. Right now I'm a backend developer at SPNX, building an EU VAT-registration platform that runs in production. After hours I'm building Strutvane, an open-source TypeScript framework for business apps (I'm writing about it as a series on my blog, vishwajitvm.hashnode.dev), plus my own products such as DevFlow-AI (self-hosted AI code review) and Hopline (encrypted peer-to-peer file transfer). Day to day I work with Python, FastAPI, Node.js, TypeScript, NestJS, PostgreSQL, Redis, Docker, LangGraph and RAG, and I've shipped plenty of Laravel/PHP and React along the way. Outside work, I'm a part-time photographer. See my work at https://vishwajit-labs-web.vercel.app/

No comments yet. Be the first to comment.