Hi everyone!
We tested a shared response cache in front of Supabase's PostgREST API using SupaFuse and Valkey. SupaFuse wraps the supabase-js fetch path, so application queries keep the usual .from(...).select(...) syntax while multiple backend processes can share cached responses.
With our local workload, SupaFuse hot reads averaged 0.208 ms, compared with 0.531 ms for uncached SDK calls, and made no PostgREST requests. A cold read plus cache fill took 2.415 ms. We also tested invalidation, expiry, request deduplication, and shared rate limiting against real services.
| Component | Configuration |
|---|---|
| Host | Apple M4 Pro, 12 logical CPUs, 48 GiB RAM; macOS arm64 + OrbStack Docker |
| Cache | Official Valkey 9.1.3, one primary and one asynchronous replica; RDB/AOF disabled |
| Supabase | PostgreSQL 17.6, PostgREST 16.1, Kong 2.8.1, Auth 2.195.0, Realtime 2.124.4 |
| Client | Node.js 26.13.0, , , unmodified |
Shuen conducted tests on a shared response cache using SupaFuse and Valkey in front of Supabase's PostgREST API. The tests focused on performance metrics such as cache hit times and invalidation behavior. The thread includes detailed test setups, results, and observations on latency and cache costs. Shuen seeks feedback on the benchmark methodology and additional test cases.
supabase-js@2.112.3ioredis@6.0.0supafuse@1.0.1| Comparison | @supabase-cache-helpers/postgrest-server@0.4.0, using only its Redis store |
Application cache reads and writes went to the primary. The replica was used to check that data, TTLs, and deletions replicated. This was a local primary/replica test; it did not exercise Cluster, Sentinel, or failover.
Node.js workers / SupaFuse
├─ cached reads ────────────► Valkey primary ──► replica
├─ cache misses / writes ──► local Supabase / PostgREST ──► PostgreSQL
└─ cache invalidation ◄───── Supabase Realtime ◄─────────── SQL changes
This example checks cold read → cache hit → write invalidation → refetch → TTL expiry → refetch with one client and a fixed anonymous identity. It uses a 3-second TTL to keep the run short. The cross-process, Realtime, and rate-limit results in the next section come from the broader test suite.
Start your own local Supabase instance first. You need a working Data API, a valid legacy role=anon JWT, and a PostgreSQL connection that can create/drop test tables and grant permissions. The script creates a randomly named table and cache prefix, gives anon access only to its test row, and removes its fixtures when it finishes. All three endpoints must use 127.0.0.1 or localhost.
Create an empty working directory and save the following three files there.
services:
primary:
image: valkey/valkey:9.1.3-alpine@sha256:bf09d58e96d6b4524a15396b65b242bbe18beebbcc15a04d8ee75ddac62fae0b
command: ["valkey-server", "--save", "", "--appendonly", "no"]
ports: ["127.0.0.1:16479:6379"]
labels:
codex.test: valkey-supabase-validation
replica:
image: valkey/valkey:9.1.3-alpine@sha256:bf09d58e96d6b4524a15396b65b242bbe18beebbcc15a04d8ee75ddac62fae0b
command: ["valkey-server", "--save", "", "--appendonly", "no", "--replicaof", "primary", "6379", "--replica-read-only", "yes"]
ports: ["127.0.0.1:16480:6379"]
depends_on: [primary]
labels:
codex.test: valkey-supabase-validation
Save .secrets.env with your local credentials:
SUPABASE_URL=http://127.0.0.1:54321
SUPABASE_ANON_KEY=<your-legacy-anon-JWT>
DATABASE_URL=postgresql://postgres:<your-local-password>@127.0.0.1:54322/postgres
VALKEY_URL=redis://127.0.0.1:16479
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { setTimeout as sleep } from 'node:timers/promises';
import Redis from 'ioredis';
import pg from 'pg';
import { createClient } from '@supabase/supabase-js';
import { createGuardedClient, RedisCacheAdapter } from 'supafuse';
const env = process.env;
for (const key of ['SUPABASE_URL', 'DATABASE_URL', 'VALKEY_URL']) {
assert.ok(env[key], `Missing ${key}`);
assert.ok(['127.0.0.1', 'localhost'].includes(new URL(env[key]).hostname), 'Use local test services');
}
assert.ok(env.SUPABASE_ANON_KEY, 'Missing SUPABASE_ANON_KEY');
const claims = JSON.parse(Buffer.from(env.SUPABASE_ANON_KEY.split('.')[1], 'base64url'));
assert.equal(claims.role, 'anon');
const id = randomUUID().replaceAll('-', '');
const table = `sf_demo_${id}`, prefix = `sf:demo:${id}`, ttl = 3;
const auth = { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false };
const db = new pg.Client({ connectionString: env.DATABASE_URL, connectionTimeoutMillis: 5000 });
const redis = new Redis(env.VALKEY_URL, { lazyConnect: true, enableOfflineQueue: false,
retryStrategy: () => null, maxRetriesPerRequest: 0, connectTimeout: 5000 });
redis.on('error', () => {});
let client, created = false, gets = 0, result;
try {
await db.connect();
await redis.connect();
await db.query(`CREATE TABLE public.${table} (id int PRIMARY KEY, value text NOT NULL)`);
created = true;
await db.query(`INSERT INTO public.${table} VALUES (1, 'v1');
ALTER TABLE public.${table} ENABLE ROW LEVEL SECURITY;
GRANT SELECT, UPDATE ON public.${table} TO anon;
CREATE POLICY read_one ON public.${table} FOR SELECT TO anon USING (id = 1);
CREATE POLICY update_one ON public.${table} FOR UPDATE TO anon USING (id = 1) WITH CHECK (id = 1);
NOTIFY pgrst, 'reload schema'`);
// Wait for the new table to enter PostgREST's schema cache before counting reads.
const raw = createClient(env.SUPABASE_URL, env.SUPABASE_ANON_KEY, { auth });
for (let attempt = 0; ; attempt++) {
const probe = await raw.from(table).select('id').eq('id', 1);
if (!probe.error) break;
if (attempt >= 49) throw probe.error;
await sleep(100);
}
client = createGuardedClient(env.SUPABASE_URL, env.SUPABASE_ANON_KEY, {
auth, dedupe: false,
global: { fetch: async (input, init) => {
if ((init?.method ?? 'GET') === 'GET') gets++;
return fetch(input, { ...init, signal: AbortSignal.timeout(10000) });
} },
cache: { adapter: new RedisCacheAdapter(redis, { prefix }), ttl,
staleWhileRevalidate: 0, cacheAuthenticated: false, strict: true, includeTables: [table] },
});
const read = async () => {
const { data, error } = await client.from(table).select('id,value').eq('id', 1);
assert.equal(error, null);
assert.equal(data.length, 1);
return data[0].value;
};
assert.equal(await read(), 'v1'); // Cold read and cache fill.
assert.equal(await read(), 'v1'); // Cache hit.
assert.equal(gets, 1);
const oldKeys = await redis.keys(`${prefix}:*`); // Only this run's random prefix.
assert.equal(oldKeys.length, 7);
const ttls = await Promise.all(oldKeys.map(key => redis.ttl(key)));
assert.ok(ttls.every(value => value > 0 && value <= ttl));
const write = await client.from(table).update({ value: 'v2' }).eq('id', 1);
assert.equal(write.error, null);
assert.equal((await db.query(`SELECT value FROM public.${table} WHERE id = 1`)).rows[0].value, 'v2');
assert.equal(await redis.exists(...oldKeys), 0); // Same-client write invalidates old keys.
assert.equal(await read(), 'v2');
assert.equal(gets, 2);
const newKeys = await redis.keys(`${prefix}:*`);
assert.equal(newKeys.length, 7);
const deadline = Date.now() + 10000;
while (await redis.exists(...newKeys)) {
assert.ok(Date.now() < deadline, 'Cache keys did not expire');
await sleep(100);
}
assert.equal(await read(), 'v2'); // Expiry causes another origin read.
assert.equal(gets, 3);
result = { runId: id, status: 'pass', ttlSeconds: ttl, keysAfterFill: oldKeys.length,
observedTtls: ttls, getsAfterTwoReads: 1, oldKeysAfterWrite: 0,
valueAfterWrite: 'v2', getsAfterWrite: 2, expiredKeysRemaining: 0, getsAfterExpiry: gets };
} finally {
await client?.guard.disconnect();
if (redis.status === 'ready') {
for (const key of await redis.keys(`${prefix}:*`)) await redis.del(key);
await redis.quit();
} else redis.disconnect();
if (created) await db.query(`DROP TABLE public.${table}`);
await db.end();
}
console.log(JSON.stringify(result, null, 2));
Install the pinned top-level packages and run the script:
npm init -y
npm install --save-exact supafuse@1.0.1 @supabase/supabase-js@2.112.3 ioredis@6.0.0 pg@8.16.3
chmod 600 .secrets.env
docker compose -p supafuse-valkey-repro up -d
node --env-file=.secrets.env reproduce-cache.mjs
# Remove this example's Valkey containers and temporary volumes after the run.
docker compose -p supafuse-valkey-repro down -v
The script counts GETs made by the guarded client after the schema-readiness probe. Our run passed all assertions:
| Step | Value returned | Cumulative PostgREST GETs |
|---|---|---|
| First read | v1 | 1 |
| Repeat the same read | v1 | 1 |
| Update through SupaFuse, then read | v2 | 2 |
| Wait for TTL expiry, then read | v2 | 3 |
The initial fill created one response entry and six tag sets, each with a 3-second TTL. The write removed all seven old keys before the next read. The script also checked that all keys from the next fill expired before the final read. These checks run against the primary; replica behavior was tested separately in the full suite.
The full suite completed 17 passing cases and one confirmed management limitation across 18 cases. It used two independent Node.js worker processes where shared state was being tested.
| Area | Observation |
|---|---|
| Shared cache | Worker A read v1; worker B repeated the query. Together they made one PostgREST GET. The entry and six tag sets had a 30-second TTL on the primary and replica. |
| Writes and expiry | A guarded update cleared all seven old keys on both nodes before refill. The next read returned v2. A separate 3-second TTL case verified natural expiry and refetch. |
| Shared limits | Two workers shared a two-request quota and returned 200 / 200 / 429. Request and byte budgets were also shared through Valkey. The concurrent-request cap remained per client instance. |
| Realtime | After confirming event delivery, direct SQL updates caused cache deletion; the next read fetched the new value. Three observations were 410, 508, and 518 ms, measured with 100 ms polling. |
| Deduplication | With all calls held at a cold-miss barrier, SupaFuse made one GET for 8 or 10 concurrent calls on one client. postgrest-server@0.4.0 made 8 or 10. With two processes missing together, both libraries made two GETs. |
| SWR and hooks | The SWR case returned stale data, triggered one background refresh, then served the new value. A separate one-in-flight plus nine-overlap case produced one GET and nine dedupe hooks. |
| Manual management | Table/tag invalidation worked. With RedisCacheAdapter, guard.inspect().entries returned [] and guard.clearCache() left remote keys untouched. |
| Error handling | After explicitly disconnecting ioredis, strict: false fell back to PostgREST. strict: true returned SDK status: 0 after roughly 7 seconds of read retries. This did not test network blackholes or reconnect delays. |
| RLS check | An anon query for a known hidden row returned []. This checks that case only; it does not establish isolation between arbitrary user sessions. |
SupaFuse can invalidate after a write made through the guarded client. A separate raw SDK writer needs explicit invalidation, such as reader.guard.invalidateTable(table), or an independently configured and ready Realtime subscription. Enabling the SupaFuse subscription does not add a table to the database publication or create its access policies.
The benchmark query returned 20 rows: 4,109 bytes of HTTP response body, with a 300-second cache TTL and the same anonymous identity in all modes. Each mode ran three rounds of 300 serial calls. SupaFuse dedupe, SWR, Realtime, and rate limiting were disabled during timing. MONITOR was disconnected first; cold-read iterations removed only the response value outside the timer and kept existing tag/index keys.
| Mode | Mean (ms) | P95 (ms) | PostgREST GETs / 900 calls |
|---|---|---|---|
| Native SDK | 0.531 | 0.938 | 900 |
| SupaFuse, cache and dedupe off | 0.651 | 1.437 | 900 |
| SupaFuse, cold read and fill | 2.415 | 3.013 | 900 |
| SupaFuse, hot hit | 0.208 | 0.250 | 0 |
| postgrest-server, cold read and fill | 0.822 | 1.095 | 900 |
| postgrest-server, hot hit | 0.138 | 0.171 | 0 |
SupaFuse hot reads reduced mean call time by 60.7% in this setup. Its cold path averaged 1.884 ms more than the native SDK and includes fingerprinting, response serialization, and 14 sequential cache writes.
A command probe recorded 15 commands for a SupaFuse cold read: one GET, one SET, seven EXPIREs, and six SADDs. postgrest-server issued four commands: GET, pipelined SET ... PXAT and ZADD, plus ZREMRANGEBYSCORE. Both hot paths issued one GET.
Adding delay only to the cache connection showed why network placement matters. Each delayed profile used three rounds of 60 calls per mode:
| Cache-link profile | Measured PING | Native SDK mean | SupaFuse cold / hot | postgrest-server cold / hot |
|---|---|---|---|---|
| Direct loopback | 0.166 ms | 0.531 ms | 2.415 / 0.208 ms | 0.822 / 0.138 ms |
| +1 ms each way | 2.688 ms | 0.774 ms | 62.171 / 4.166 ms | 11.810 / 4.078 ms |
| +3 ms each way | 9.258 ms | 1.653 ms | 137.473 / 9.848 ms | 25.322 / 8.770 ms |
This was a TCP delay proxy on a shared development machine, not a measurement of a cloud network. The uncached baseline also varied between profiles. In both delayed profiles, even cache hits took longer than the local uncached query.
Two other measurements help put the latency figures in context:
MEMORY USAGE ... SAMPLES 0 totaled 9,200 bytes across seven keys for SupaFuse and 6,288 bytes across two keys for postgrest-server. This counts primary cache keys only, excluding the replica and process overhead.When we dynamically added a new table to supabase_realtime, the WebSocket channel could report that it had joined before our SQL updates produced cache invalidation. Two preflight runs needed about 14 and 42 seconds before we observed delivery. We therefore confirmed a real change event before timing the three 410–518 ms invalidation observations. Those values include polling error and exclude initialization time.
The cached SELECTs used a fixed anon identity and a single table. Multi-user JWT/claim isolation, embedded relations, and Cluster cross-slot tag deletion need separate tests. The successful SWR case also does not rule out a refresh race under other timing conditions.
For dynamically added publication tables, is there a supported readiness signal before relying on postgres_changes for cache invalidation? We'd also welcome feedback on the benchmark methodology and additional cases worth testing.