Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
fix(cache): fail fast when Redis is unreachable
spacesdrive363de985a465
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bf3d28a..12f38bc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -62,6 +62,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).### Fixed+- When Redis was unreachable, every cached request waited about 4 seconds for the cache client's retries; the cache now gives up after one quick retry and skips Redis for 30 seconds after a failure- `GET /api/comparison` returned stored account secrets (Instagram tokens, Reddit cookies) and ranked Instagram and Reddit accounts with YouTube channels; it now ranks YouTube channels only, passed through `safeAccount()`- The frontend test for the Google sign-in nonce failed about one run in 23, because it required at least 40 characters while the nonce length varies around 36 to 43diff --git a/backend/lib/cache.ts b/backend/lib/cache.tsindex 6c63735..ff777e9 100644--- a/backend/lib/cache.ts+++ b/backend/lib/cache.ts@@ -13,36 +13,54 @@ const ANALYTICS_TTL_SECONDS = 6 * 60 * 60;const VIDEOS_CACHE_VERSION = 2;const IG_CACHE_VERSION = 2;+// after a failure this isolate skips redis for a while, so an outage costs one timeout, not one per call+const CACHE_COOLDOWN_MS = 30_000;+type Versioned<T> = T & { version: number };+let cacheDownUntil = 0;++export function resetCacheState(): void {+ cacheDownUntil = 0;+}++function cacheAvailable(redis: Redis | null): redis is Redis {+ return redis !== null && Date.now() >= cacheDownUntil;+}++function markCacheDown(): void {+ cacheDownUntil = Date.now() + CACHE_COOLDOWN_MS;+}+async function readKey<T>(redis: Redis | null, key: string): Promise<T | null> {- if (!redis) return null;+ if (!cacheAvailable(redis)) return null;try {return await redis.get<T>(key);} catch {// a cache miss falls back to the live api+ markCacheDown();return null;}}async function writeKey(redis: Redis | null, key: string, value: unknown): Promise<undefined> {- if (!redis) return undefined;+ if (!cacheAvailable(redis)) return undefined;try {await redis.set(key, value, { ex: ANALYTICS_TTL_SECONDS });} catch {// a failed write only costs a refetch next time- return undefined;+ markCacheDown();}return undefined;}async function deleteKey(redis: Redis | null, key: string): Promise<undefined> {- if (!redis) return undefined;+ if (!cacheAvailable(redis)) return undefined;try {await redis.del(key);} catch {// the entry still expires on its own ttl- return undefined;+ markCacheDown();}return undefined;}diff --git a/backend/lib/redis.ts b/backend/lib/redis.tsindex d13d64c..a7b1b46 100644--- a/backend/lib/redis.ts+++ b/backend/lib/redis.ts@@ -2,6 +2,7 @@ import { Redis } from '@upstash/redis';import type { Env } from '../types/env.ts';const RATE_LIMIT_TIMEOUT_MS = 1000;+const CACHE_TIMEOUT_MS = 3000;function credentials(env: Env): { url: string; token: string } | null {const url = env.UPSTASH_REDIS_REST_URL?.replace(/^\uFEFF/, '').trim();@@ -10,9 +11,15 @@ function credentials(env: Env): { url: string; token: string } | null {return { url, token };}+// one quick retry instead of the default five (about 4 seconds); lib/cache.ts then skips Redis for a whileexport function getRedis(env: Env): Redis | null {const config = credentials(env);- return config ? new Redis(config) : null;+ if (!config) return null;+ return new Redis({+ ...config,+ retry: { retries: 1, backoff: () => 100 },+ signal: () => AbortSignal.timeout(CACHE_TIMEOUT_MS),+ });}// Every request waits on the rate limit check, so it fails fast instead of using thediff --git a/backend/tests/lib/cache.test.ts b/backend/tests/lib/cache.test.tsindex 855ed91..3509de1 100644--- a/backend/tests/lib/cache.test.ts+++ b/backend/tests/lib/cache.test.ts@@ -1,8 +1,8 @@-import { test } from 'node:test';+import { test, beforeEach, mock } from 'node:test';import assert from 'node:assert/strict';import {getVideosCache, setVideosCache, deleteVideosCache,- getIGCache, setIGCache, getRedditCache, setRedditCache,+ getIGCache, setIGCache, getRedditCache, setRedditCache, resetCacheState,} from '../../lib/cache.ts';import type { Redis } from '../../types/app.ts';import type { VideosCacheData, YouTubeVideo } from '../../../shared/types/youtube.ts';@@ -27,6 +27,8 @@ const failingRedis = {del: async () => { throw new Error('down'); },} as unknown as Redis;+beforeEach(() => resetCacheState());+test('every helper is a no-op without redis', async () => {assert.equal(await getVideosCache(null, 'u', 'a'), null);assert.equal(await getIGCache(null, 'u', 'a'), null);@@ -69,3 +71,24 @@ test('delete removes the entry', async () => {assert.equal(await getVideosCache(redis, 'u', 'a'), null);assert.deepEqual(await getIGCache(redis, 'u', 'a'), { media: [], version: 2 });});++test('after a failure redis is skipped for 30 seconds, then tried again', async () => {+ mock.timers.enable({ apis: ['Date'], now: 1_000_000 });+ try {+ let calls = 0;+ const flaky = {+ get: async () => { calls++; throw new Error('down'); },+ } as unknown as Redis;+ const healthy = memoryRedis();+ await setVideosCache(healthy, 'u', 'a', { videos: [] } as unknown as VideosCacheData);++ assert.equal(await getVideosCache(flaky, 'u', 'a'), null);+ assert.equal(await getVideosCache(healthy, 'u', 'a'), null);+ assert.equal(calls, 1);++ mock.timers.tick(30_000);+ assert.deepEqual(await getVideosCache(healthy, 'u', 'a'), { videos: [], version: 2 });+ } finally {+ mock.timers.reset();+ }+});diff --git a/docs/architecture/backend/CACHING.md b/docs/architecture/backend/CACHING.mdindex 44a477c..7dedd88 100644--- a/docs/architecture/backend/CACHING.md+++ b/docs/architecture/backend/CACHING.md@@ -30,6 +30,15 @@ export async function getRedditCache(redis: Redis | null, userId: string, accoun}```+## When Redis Fails++A Redis outage must make the app slower to refresh, never slower to respond:++- **Short timeout.** `getRedis()` in `lib/redis.ts` gives every call a 3 second timeout and one retry after 100 ms, instead of the SDK default of five retries with backoff (about 4 seconds per call).+- **Cooldown.** When a read, write or delete fails, `lib/cache.ts` skips Redis in that isolate for 30 seconds (`CACHE_COOLDOWN_MS`): reads return a miss and writes are dropped. An outage therefore costs one timeout per isolate every 30 seconds, not one per cache call. `resetCacheState()` clears the cooldown in tests.++The rate limiter uses its own client with a 1 second timeout and no retries; see `RATE_LIMITING.md`.+`redis.get<T>()` does not validate what Redis returns; the type is what the matching setter wrote. Bump the cache version (below) when that shape changes.## Cache Keysdiff --git a/docs/philosophy/PERFORMANCE.md b/docs/philosophy/PERFORMANCE.mdindex d6f6eb1..5772d88 100644--- a/docs/philosophy/PERFORMANCE.md+++ b/docs/philosophy/PERFORMANCE.md@@ -42,6 +42,8 @@ await redis.set(key, data, { ex: 3600 }); // expire after 1 hourEach protected request runs two rate limit checks (`ip` before authentication, `user` after it), each one Redis script call, so a request pays two short Upstash round trips. A client already over its limit is answered from the isolate without Redis, and a Redis outage costs at most one 1 second timeout per isolate every 30 seconds. See `docs/architecture/backend/RATE_LIMITING.md`.+The analytics cache follows the same rule: a 3 second timeout, one retry, then 30 seconds without Redis in that isolate after a failure (see `docs/architecture/backend/CACHING.md`).+## Edge DeploymentThe Cloudflare Worker runs at the edge - in a data center close to the user. This means:diff --git a/frontend/src/docs/pages/selfHost/Redis.tsx b/frontend/src/docs/pages/selfHost/Redis.tsxindex dc09613..a674a1c 100644--- a/frontend/src/docs/pages/selfHost/Redis.tsx+++ b/frontend/src/docs/pages/selfHost/Redis.tsx@@ -5,7 +5,7 @@ export default function Redis() {return (<><DocTitle title="Upstash Redis (optional)" lead="A cache that saves YouTube and Instagram quota, makes pages load faster, and makes rate limits exact." />- <P>Twiligent works fully without Redis. Every cache read falls back to a live API call, and Redis errors are ignored. Add it when you have several members or many YouTube channels.</P>+ <P>Twiligent works fully without Redis. Every cache read falls back to a live API call, and Redis errors are ignored. If Redis stops answering, the backend gives up on it within a few seconds and stops trying for half a minute, so pages keep loading at the speed of the live APIs. Add it when you have several members or many YouTube channels.</P><P>The backend also limits how fast each person and each network can call it, so one client cannot use up the shared YouTube quota. With Redis, those limits are counted once across every Cloudflare location. Without it, each Worker instance counts on its own, so the limits are looser but still apply. There is nothing to configure.</P><Steps><Step title="Create a database">