Site not working if redis cache stopped/crashed
Hello! I use "nuxt-multi-cache": "^3.2.0", "nuxt": "^3.11.0",
I use redisDriver like storage. I also use the useDataCache() to stack the data cache; If it happens that the redis server becomes unavailable, then all pages of the site stop working. How can this be fixed? I would like the site to continue working if the connection to redis is lost.
multiCache.serverOptions.ts
import { defineMultiCacheOptions } from 'nuxt-multi-cache/dist/runtime/serverOptions';
import redisDriver, { RedisOptions } from 'unstorage/drivers/redis';
import { H3Event, getHeader } from 'h3';
import { serverLog } from '@/shared/lib/server-log.ts';
const redisHost = process.env.REDIS_HOST;
const redisPort = process.env.REDIS_PORT;
const redisOptions: RedisOptions = {
base: 'route:',
host: redisHost,
// tls: true as any,
port: Number(redisPort),
// password: 'REDIS_PASSWORD'
};
export default defineMultiCacheOptions({
data: {
storage: {
driver: redisHost
? redisDriver({
...redisOptions,
base: 'data:',
})
: undefined,
},
},
enabledForRequest(event) {
return Promise.resolve(!event.path.includes('payload.json'));
},
route: {
storage: {
driver: redisHost
? redisDriver({
...redisOptions,
})
: undefined,
},
buildCacheKey: (event: H3Event): string => {
const cookies = getHeader(event, 'cookie') || '';
const city = getCookie(cookies, 'city') || '';
let [url, params] = String(event.path).split('?');
const cleanParams = params ? String(params) : 'params';
const theme = process.env.NUXT_THEME;
const releaseVersion = process.env.NUXT_RELEASE || 1;
if (url === '/') {
url = 'home';
}
url = String(url).replace(/\//g, '-');
return `release:${releaseVersion}:theme:${theme}:url:${url}:${cleanParams}:${city}`;
},
},
});
const cacheKey = `regionCityList-${theme}`;
const { value, addToCache } = await useDataCache<Array<Region>>(
cacheKey,
useRequestEvent(),
);
const regions = []; // fake regions
await addToCache(regions, [cacheKey], 7200);
Please help me!
Thank you for reporting this! I agree that it's weird that the error "propagates" to the useDataCache composable. However, there are valid reasons why somebody would want to have an error there: If your app heavily depends on caching, for example due to high traffic, you may actually want to handle this in your app. Imagine if your cache backend goes down and your frontend app suddenly issues a ton of requests to your backend, which it is not able to process. In such a case, you could quickly crash both the backend and frontend. So "knowing" that the cache backend is down would definitely help prevent this, as you could return an error in the frontend when this happens.
But this is actually not consistently handled by the module currently (for example, it catches an error in the route cache but does not in data cache). I think it would be reasonable to add an option in the module to define what the behaviour should be if the storage driver throws an error. I will implement that.