NextJS and caching of pages

clock icon

asked 8 months ago

Message

1Answers

Eye

9Views

we are running a nextJS server as a service on a Kubernetes cluster, with a minimum of two replicas. So in a normal situation, we have these:

our-nextjs-server-prod-bd7c6dc4c-2dlqg               1/1     Running     0          18h
our-nextjs-server-prod-bd7c6dc4c-7dkbp               1/1     Running     0          18h

When the first server is hit for a page it hasn't cached yet, it will work on it, store it in the host node's volume, and will serve it from there in subsequent calls. Now, if the second server is hit for the same page, but is hosted on a different node, it will have to, as I understand it, re-generate the page as it doesn't exist on its node's volume.

Is there a way to have multiple nextJS pods from different nodes utilize a common resource to cache pages? a common volume, an external resource like Redis perhaps? Is there a best practice around that requirement?

For a moment: Let's disregard the CDN in front of the nextJS service caching the results for a certain TTL. We need those nextJS pods hit frequently so that they can ping the application server for changed properties that'll trigger a re-build of the page.

1 Answers

You can use react cache to cache your API.

import { cache } from 'react' . . .

const getLatest = cache(async () => {. . .})

Other alternatives

Redis: Suitable for distributed environments, offers advanced features like TTL, and can be managed independently of the Next.js application

Shared Volume: Simpler setup within Kubernetes but can have limitations depending on your storage backend and scalability requirements.

 

Write your answer here

Top Questions