Next.js Discord

Discord Forum

Issue about Cache Handler with Loadbalancer

Unanswered
Short-tailed Hawk posted this in #help-forum
Open in Discord
Short-tailed HawkOP
My website works on 2 ec2s instances, a load balancer and a EFS shared cache, i have a test page that returns me an color inside an array of 10 colors, and a button to revalidate the cache. When consistly refreshing the page, the cache data remains the same for 120 seconds which is correct, since my website runs in 2 ec2s.
The problem is that when i click in the button to revalidate. So lets say that the page starts with the color blue, then i click the button, it goes to red, but if i refresh the page, it goes back to the color blue

This is the Cache Handler Code:
const fs = require('fs').promises;
const path = require('path');

const CACHE_DIR = '/mnt/efs/cache';

class CacheHandler {
  constructor(options) {
    this.options = options;
  }

  async get(key) {
    try {
      const data = await fs.readFile(path.join(CACHE_DIR, key), 'utf8');
      return JSON.parse(data);
    } catch (error) {
      console.log("Error reading cache file:", error);
      // If file doesn't exist or there's an error reading it, return null
      return null;
    }
  }

  async set(key, data, ctx) {
    try {
      await fs.mkdir(CACHE_DIR, { recursive: true });
      await fs.writeFile(path.join(CACHE_DIR, key), JSON.stringify({
        value: data,
        lastModified: Date.now(),
        tags: ctx.tags,
      }));
    } catch (error) {
      console.error('Error writing to cache:', error);
    }
  }

  async revalidateTag(tags) {
    tags = Array.isArray(tags) ? tags : [tags];
    try {
      const files = await fs.readdir(CACHE_DIR);
      for (const file of files) {
        const filePath = path.join(CACHE_DIR, file);
        const data = JSON.parse(await fs.readFile(filePath, 'utf8'));
        if (data.tags && data.tags.some(tag => tags.includes(tag))) {
          await fs.unlink(filePath);
        }
      }
    } catch (error) {
      console.error('Error revalidating tags:', error);
    }
  }
}

module.exports = CacheHandler;

0 Replies