BFF Sessions and Token Storage in Redis
On this page
Why memory isn't enough
So far the lab kept sessions in a Map inside the BFF process. That breaks as soon as you run a second instance behind a load balancer: a user signs in on instance A, their next request lands on instance B, and B has never heard of them. A deploy or crash also signs everyone out.
The fix is a shared, fast store that every instance can read. Redis is the usual choice. Valkey, the open-source fork of Redis, works the same way.
A small session store
You don't need a framework for this. A session store is four functions:
// src/sessions.ts
import { Redis } from 'ioredis';
import { randomBytes } from 'node:crypto';
const IDLE_SECONDS = 30 * 60; // signed out after 30 minutes without activity
const ABSOLUTE_SECONDS = 12 * 60 * 60; // must sign in again after 12 hours, however active
export type SessionData = {
user: { sub: string; name?: string; email?: string };
tokens: { accessToken: string; refreshToken?: string; idToken?: string; expiresAt: number };
createdAt: number;
};
export function createSessionStore(redis: Redis) {
const key = (id: string) => `sess:${id}`;
return {
async create(data: SessionData) {
const id = randomBytes(32).toString('base64url');
await redis.set(key(id), JSON.stringify(data), 'EX', IDLE_SECONDS);
return id;
},
async get(id: string) {
const raw = await redis.get(key(id));
if (!raw) return null;
const data = JSON.parse(raw) as SessionData;
if (Date.now() - data.createdAt > ABSOLUTE_SECONDS * 1000) {
await redis.del(key(id));
return null;
}
await redis.expire(key(id), IDLE_SECONDS); // slide the idle timeout
return data;
},
async update(id: string, data: SessionData) {
await redis.set(key(id), JSON.stringify(data), 'EX', IDLE_SECONDS);
},
async destroy(id: string) {
await redis.del(key(id));
},
};
}Two timeouts work together:
- The idle timeout uses Redis's own key expiry. Every read pushes it 30 minutes into the future, so active users stay signed in and abandoned sessions disappear by themselves.
- The absolute timeout caps a session's total life, however active it is. That limits how long a stolen session cookie stays useful.
RFC 10017 adds a useful rule: match the session's maximum lifetime to the refresh token's, and end the session when the refresh token stops working. A session that outlives its tokens can only fail.
Proof that instances share sessions
Two BFF instances on different ports, one Redis. Sign in on the first, read on both:
set-cookie: __Host-Http-sid=<random>; Path=/; HttpOnly; Secure; SameSite=Lax
{ instance: 4920, user: 'Ada' }
{ instance: 4921, user: 'Ada' }
ttl seconds: 1800
after destroy: { instance: 4921, user: null }
13-hour-old session: null key exists after: 0The second instance knew Ada without any shared memory, logout on one instance signed her out everywhere, and a session older than the absolute limit was rejected and deleted. BFF instances are now stateless: you can add, remove and restart them freely.
Encrypt tokens at rest
The Redis values contain access and refresh tokens. Anyone who can read Redis, through a leaked backup, a debugging session or a misconfigured network rule, could use them. Two layers help.
First, lock Redis down: require authentication, use TLS, keep it on a private network, and don't share it with unrelated apps.
Second, encrypt the token fields before storing them, with a key that lives elsewhere, in a secret manager. AES-256-GCM from Node's built-in crypto module both encrypts and detects tampering:
// src/seal.ts
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
const KEY = Buffer.from(process.env.TOKEN_KEY!, 'base64'); // 32 random bytes
export function seal(plain: string): string {
const iv = randomBytes(12); // never reuse an IV with the same key
const cipher = createCipheriv('aes-256-gcm', KEY, iv);
const data = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
return [iv, cipher.getAuthTag(), data].map((b) => b.toString('base64url')).join('.');
}
export function open(sealed: string): string {
const [iv, tag, data] = sealed.split('.').map((s) => Buffer.from(s, 'base64url'));
const decipher = createDecipheriv('aes-256-gcm', KEY, iv);
decipher.setAuthTag(tag);
return Buffer.concat([decipher.update(data), decipher.final()]).toString('utf8');
}Call seal on the refresh and access tokens before store.create, and open after store.get. In a test, flipping a single bit in the stored value made open throw Unsupported state or unable to authenticate data instead of returning garbage.
Keep sessions small
Store what the BFF needs on every request: the user's id and display name, the tokens and timestamps. Don't copy whole user profiles or permission lists into the session, since they go stale. Fetch those from the service that owns them, and cache them briefly if needed (Day 10).
Let users see and end their sessions
Because sessions live on the server, you can offer things browser-held tokens can't: a "signed-in devices" list, and "sign out everywhere". Keep a Redis set per user, user-sessions:<sub>, add each session id to it on login, and destroy every id in it when the user asks. The same mechanism lets support staff end a compromised account's sessions immediately.
Check yourself
Each instance keeps its own memory, so a session created on instance A doesn't exist on instance B, and the load balancer can send the user's next request to either. Restarts and deploys also wipe in-memory sessions and sign everyone out. A shared store like Redis makes instances stateless.
The idle timeout ends a session after a period without activity and resets on each use. The absolute timeout ends it a fixed time after sign-in, however active the user is.
Defense in depth. Backups, snapshots, debugging sessions or one misconfigured network rule can expose Redis data, and plain tokens in it could be used immediately. Encrypting token fields with AES-256-GCM, using a key kept in a secret manager, makes a stolen copy useless and detects tampering.
The instances use different encryption keys, for example because each generated a random key at startup, so one can't decrypt sessions written by the other. The combined project hit exactly this bug. Load one TOKEN_KEY from your secret store on every instance, and refuse to start without it.
RFC 10017 suggests tying it to the refresh token: the session shouldn't outlive the refresh token, and should end when refreshing stops working. Combine that with an idle timeout, such as 30 minutes, and an absolute cap, such as 12 hours, so a stolen cookie stops working on its own.