Menu

Next.js use cache, cacheLife and cacheTag: How One View Counter Rebuilt Every Page
πŸ“°

Next.js use cache, cacheLife and cacheTag: How One View Counter Rebuilt Every Page

DEV Community: nextjsΒ·Mohsen FallahnejadΒ·1 day ago
#Hc6SLxJH
#devtonextjs#devto#dev#cache#next
Reading 0:00
15s threshold

Vercel's usage page told me this blog had used 2 h 32 min of function CPU in 30 days: 80% of everything on my account. It's a blog. The posts only change when I deploy.

The cause was one line near the top of my pages:

const stats = await getPostStats ( ) ; // read + comment counts, cached for 5 minutes

Enter fullscreen mode

Exit fullscreen mode

The counts were cached for 5 minutes. But the 5-minute timer didn't stay on the counts. Every page that showed them took it on, so every post, tag and series page went stale every 5 minutes and was rebuilt on the server the next time a reader or a crawler came by.

The mental model: a shared fridge

Think of the server cache as one fridge that every visitor shares .

"use cache" puts a result in the fridge. The next caller takes it out instead of cooking it again.

cacheLife is the best-before sticker. After that date, the next visitor still gets the old dish while a fresh one cooks in the background.

cacheTag is the name on the lid.…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.