To add Redis caching to a multi-tenant SaaS app, authorize each request, include tenant scope in every key, and cache database reads with expiration. Reliable multi-tenant Redis caching keeps the database as the source of truth.
A cache hit can bypass database protections, so tenant isolation must extend beyond your queries. Start with one read-and-update path, then test its security and failure behavior before expanding.
Key takeaways
- Establish trusted tenant context before reading or writing cached data.
- Combine tenant-scoped keys with authorization, bounded expiration, and post-commit invalidation.
- Reuse Redis connections, limit memory, and test cross-tenant access alongside outages.
1. Establish trusted tenant context
Authorize the selected workspace
A workspace slug, request header, or organization picker identifies the requested tenant. It doesn’t prove membership.
Authenticate the caller, resolve the workspace to an internal tenant ID, and validate active membership and permissions. Pass that verified context explicitly into your cache and database functions.
If required membership lookup or policy evaluation fails, deny the operation. Never substitute a default tenant or permissive role.
Run permission checks before cache access
Authorize every request, including requests that return cached records. Otherwise, a revoked member could keep receiving data until expiration.
A cache hit skips the database, so database row-level security cannot protect the response returned by Redis.
Avoid mutable global tenant variables. Concurrent requests and workers could inherit another customer’s context. Background jobs need explicit tenant scope, and user-delegated jobs must reevaluate access when they execute.
2. Design tenant-aware Redis keys
Define a consistent namespace
Use a predictable structure such as saas:prod:v1:t:<tenantId>:document:<documentId>.
The application and environment prefixes separate workloads. The version identifies the cached representation, while the tenant and document IDs identify ownership and the resource.
Centralize key construction rather than assembling strings throughout your routes. Encode variable components so delimiters inside identifiers cannot create ambiguous keys.

Include every input that changes the result
For search results, include normalized filters, pagination, and sorting. If a response varies by user permissions, cache a tenant-scoped base record and apply authorization and response filtering afterward.
Prefixes prevent collisions but don’t enforce access. Redis ACL permissions can restrict commands and key patterns. However, a shared application credential with broad access still relies on your backend to enforce tenant boundaries.
3. Create one reusable Redis client
This example uses Node.js ES modules, the redis package, and PostgreSQL queries through an existing pg pool. Install the client with npm install redis.
Following the official node-redis guide, initialize one client per application process:
import { createClient } from "redis";
const cache = createClient({
url: process.env.REDIS_URL,
socket: { connectTimeout: 500 },
disableOfflineQueue: true
});
cache.on("error", () => console.warn("Redis connection error"));
cache.connect().catch(() => console.warn("Redis startup failed"));
function documentKey(ctx, id) {
if (!ctx?.tenantId) throw new Error("Tenant context required");
return `saas:prod:v1:t:${encodeURIComponent(ctx.tenantId)}:document:${encodeURIComponent(id)}`;
}
Here, connectTimeout limits each connection attempt to 500 milliseconds. Disabling the offline queue prevents cache commands from accumulating during disconnection. The read path below bypasses Redis while the client isn’t ready.
Supply credentials through secret management. Keep Redis on private networking and use TLS for production connections.
4. Implement tenant-scoped cache-aside reads
Redis’s cache-aside pattern reads the cache first, loads misses from the database, and stores successful results with expiration.
Call this function only after membership and document-read authorization succeed. Here, db is your PostgreSQL pool, and ctx contains the verified tenant:
async function getDocument(db, ctx, id) {
const key = documentKey(ctx, id);
if (cache.isReady) {
try {
const raw = await cache.get(key);
if (raw !== null) return JSON.parse(raw);
} catch {
console.warn("Cache read failed");
}
}
const { rows } = await db.query(
"SELECT id, title FROM documents WHERE tenant_id=$1 AND id=$2",
[ctx.tenantId, id]
);
const document = rows[0] ?? null;
if (document && cache.isReady) {
try {
await cache.set(key, JSON.stringify(document), {
EX: 60 + Math.floor(Math.random() * 16)
});
} catch {
console.warn("Cache population failed");
}
}
return document;
}
Both paths use the same tenant context. The database lookup includes tenant and resource IDs, while Redis receives a tenant-scoped key.
The selected fields also limit cached content. Don’t serialize an entire ORM object containing credentials or internal fields.
This example doesn’t cache missing records. Negative caching needs separate invalidation when a record appears. Cache failures fall back to PostgreSQL; database or authorization failures must still propagate.
5. Set TTLs and invalidate after writes
Choose expiration by acceptable staleness
The example uses a TTL between 60 and 75 seconds. That’s an illustrative setting for document titles, not a universal recommendation. EX specifies seconds, and setting the value and expiration together avoids accidentally creating persistent entries.
The random variation, called TTL jitter, reduces synchronized expiration. However, it doesn’t prevent concurrent misses for one popular key. For expensive reads, add per-key request coalescing so concurrent callers share one database fetch.

Delete affected entries after commit
After update authorization succeeds, commit the database change before invalidating its cache entry. This single-statement example assumes PostgreSQL autocommit:
const result = await db.query(
"UPDATE documents SET title=$3 WHERE tenant_id=$1 AND id=$2 RETURNING id",
[ctx.tenantId, id, title]
);
if (result.rowCount > 0) {
try {
await cache.del(documentKey(ctx, id));
} catch {
console.warn("Cache invalidation failed");
}
}
Also invalidate affected listings and aggregate caches. For multi-statement transactions, delete only after COMMIT.
Expiration limits an entry’s lifetime but doesn’t guarantee consistency. A concurrent reader can fetch an old value and populate Redis after deletion. For stricter requirements, coordinate version-checked fills with writes or bypass caching. Durable outbox-based invalidation retries help recover failed deletions but don’t eliminate that race.
6. Bound connection use and cache memory
Keep connections separate from tenant identity
Ordinary cache reads can reuse the shared client. Don’t open a new connection per request or tenant.
Use an explicit bounded pool when your workload needs dedicated connections. Budget across all application replicas and workers. Set command deadlines as well as connection timeouts, because an established connection can still stall.
If PostgreSQL uses row-level security, keep its tenant context transaction-local. A Redis key prefix doesn’t repair database context left on a reused connection.
Configure memory for disposable data
Redis applies its configured key eviction policy when memory reaches maxmemory. Eviction can remove entries before their TTL expires, so every read must tolerate misses.
For a cache-only workload, allkeys-lfu is one option for retaining frequently accessed keys. Select policy and capacity from workload measurements.
Keep disposable cache data separate from queues or correctness-critical records. Also cap cached payload sizes and prevent one tenant’s unbounded search combinations from consuming disproportionate memory.
7. Test isolation and monitor failure paths
Test tenant boundaries through the application
Create two isolated test tenants with distinct records. Include one user who belongs to both but has different permissions.
Run these cases through HTTP so authentication, routing, cache access, and database behavior all participate:
| Test | Required result |
|---|---|
| Request another tenant’s known document ID | No record or metadata is disclosed. |
| Override tenant headers or body fields | Verified context remains unchanged. |
| Warm tenant A’s cache, then request as tenant B | No cached data crosses tenants. |
| Remove membership after warming the cache | Subsequent access is denied. |
| Deny an update | Neither the database nor cache changes. |
For denied operations, assert the absence of side effects, including queued jobs. Also test missing context, malformed cached JSON, Redis disconnection, expiration, and simultaneous reads during updates.
Test background execution after membership revocation and database connection reuse across tenants.
Measure customer impact, not only hit rate
Track cache hits, misses, Redis command latency, timeouts, invalidation failures, memory usage, evictions, and connection counts. Measure database load and endpoint latency alongside them.
Redis’s global hit ratio covers every workload sharing that server. Application metrics should distinguish document reads from other cache uses.
For diagnostics, record trusted tenant context and correlation IDs without credentials or payloads. Avoid raw tenant IDs as unbounded metric labels.
Load-test a Redis outage too. Successful fallback can still overwhelm PostgreSQL when every request becomes a database read.
Frequently asked questions
Should authorization decisions use the same cache keys?
No. Authorization decisions depend on the tenant, principal, action, and relevant resource context. They also require a revocation strategy.
A cached document must never imply permission to read it. For an initial implementation, keep required membership and policy checks outside the resource cache so their failures deny access.
Does Redis make database updates and invalidation atomic?
No. A Redis transaction cannot atomically commit a separate PostgreSQL transaction.
Post-commit deletion with expiration suits data that tolerates temporary staleness. Where that isn’t acceptable, use coordinated consistency controls or leave the affected read uncached. Permission revocation must not depend on a document’s TTL.
Build one safe cached path first
Reliable multi-tenant Redis caching depends on trusted tenant context throughout authorization, key construction, database access, and background work. Expiration and invalidation control stale data, while bounded connections and memory keep the cache manageable.
Start with one endpoint and its cross-tenant regression tests. Expand only after cache hits, misses, updates, and outages preserve the same access rules.