← Integrations without dramaIntegrations without drama · #1

An API call on every visit: do you really need it?

A very common pattern that slows sites down and overloads servers, and how a CDN cache fixes it without scaling infrastructure.

It's a very common pattern: a JavaScript snippet that, when the page loads, runs a fetch to get the data the user needs.

With little traffic it works perfectly. But as visits grow, every user is one more request hitting the server. And the classic symptom shows up: everything gets slower.

The key question

Before scaling the server, ask yourself: does this data change on every visit, or only once in a while?

If it changes, say, once a day, you're asking the server thousands of times for the same answer. Each of those requests costs the user time and the server resources.

The fix: a CDN cache

A CDN has nodes all over the world. If you let it keep a copy of the response, the flow changes completely:

  • The first request reaches the server.
  • The following ones get a copy from the node closest to the user.
  • When the data changes, the copy is refreshed.

Usually all it takes is the right headers on the API response:

Cache-Control: public, max-age=60, s-maxage=86400, stale-while-revalidate=3600
  • max-age=60: the browser reuses the response for one minute.
  • s-maxage=86400: the CDN keeps it for up to 24 hours.
  • stale-while-revalidate=3600: if the copy has expired, the CDN keeps serving it while fetching a fresh one in the background. The user never waits.

The hard part: deciding when to refresh

Caching is easy. What you really need to think about is when the copy stops being valid, and what happens if someone sees a version from a few hours ago. There are three common strategies:

  • Expiry (TTL): the copy expires on its own after a set time. Ideal when the data changes at a known pace, like once a day.
  • Purge on update: when the data changes, call the CDN's API to drop the copy. Always fresh, but it has to be wired into whatever updates the data.
  • Versioned URLs: add a version or date to the URL (/data?v=2026-11-21). Each version is a separate copy and they never mix.
Careful: if the response depends on the user (session, permissions, personal data), it can't go in a shared cache. Mark that data as private or split it from the shared part.

Checklist before scaling the server

  • How many requests get exactly the same response?
  • How often does that data really change?
  • Is it acceptable for someone to see a version that's minutes or hours old?
  • Does the response contain anything personal or session-dependent?
  • How will the copy be refreshed when the data changes?

Often the cheapest performance win isn't a bigger server. It's not asking for what you already know.

This article is part of Integrations without drama: a new pattern every week.