banner
innei

innei

写代码是因为爱,写到世界充满爱!
github
telegram
twitter

Cache Headers and Utilize Edge Network for Accelerated Access

This article uses Cloudflare + Vercel as an example.

Understanding Cache Headers#

In production, we usually use Redis to cache API data. For frontend applications, we generally use Content Delivery Networks (CDNs) to cache pages and other static resources.

We know that the HTTP header cache-control can be used for caching resources.

For example, cache-control: max-age=60 means that the resource will not expire within 60 seconds, and the browser can use the local cache directly if it does not force a refresh (for example, if the request header contains cache-control: max-age=0).

In edge networks or CDNs, relevant headers are usually cached.

For example, the value of s-maxage.

Note

s-maxage

The s-maxage response directive indicates how long the response remains fresh in a shared cache. The s-maxage directive is ignored by private caches, and overrides the value specified by the max-age directive or the Expires header for shared caches, if they are present.

Cache-Control: s-maxage=604800

Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#s-maxage

And this value is generally used by CDNs or edge networks to control the caching time.

In Vercel. In the Cache section, it tells us that we can use this value to control the caching time of an API response. It also provides Vercel's private HTTP headers, such as Vercel-CDN-Cache-Control.

In Cloudflare, the example in When to use CDN-Cache-Control can better help understand the caching control of resources on various ends.

Headers:

Cache-Control: max-age=14400, s-maxage=84000
Cloudflare-CDN-Cache-Control: max-age=24400
CDN-Cache-Control: max-age=18000

Cache behavior:

CachesCache TTL (seconds)
Origin Server Cache14400
Network Shared Cache84000
Cloudflare Edge24400
Other CDNs18000
Browser Cache14400

In the above table, Cloudflare can consume the cache-control: s-maxage and Cloudflare-CDN-Cache-Control in the response header to control the caching of resources in the Cloudflare distribution network and edge network.

By using cache headers, we can make resources accessible to users more quickly and reduce the load on servers.

Taking Next.js deployed on Vercel as an example, let's optimize it to reduce the real requests to the server under short-term concurrency.

Caching Next.js API Routes#

This is a simple Next.js API Route.

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export const GET = async (req: NextRequest) => {
  return NextResponse.json({})
}

Now we can add cache headers.

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export const GET = async (req: NextRequest) => {
  return NextResponse.json(
    {},
    {
      headers: {
        'Cache-Control': 'max-age=60, s-maxage=86400',
        'CDN-Cache-Control': 'max-age=86400',
      },
    },
  )
}

Now let's proxy the API using Cloudflare.

After the first request, in the next request, we can see that Cloudflare has hit the cache.

Cf-Cache-Status: HIT

Using vercel.json to Configure Headers Globally#

In individual APIs, it is very cumbersome to add cache headers every time, and we cannot control routes other than API Routes. We can use vercel.json to configure headers globally.

Create a vercel.json file in the root directory of the project with the following content:

The following routes refer to the project Shiro and can be configured as needed.

{
  "headers": [
    {
      "source": "/",
      "headers": [
        {
          "key": "Cache-Control",
          "value": "s-maxage=300, stale-while-revalidate=59"
        },
        {
          "key": "CDN-Cache-Control",
          "value": "max-age=300"
        },
        {
          "key": "Vercel-CDN-Cache-Control",
          "value": "max-age=300"
        }
      ]
    },
    {
      "source": "/og",
      "headers": [
        {
          "key": "Cache-Control",
          "value": "s-maxage=3600, stale-while-revalidate=30"
        },
        {
          "key": "CDN-Cache-Control",
          "value": "max-age=3600"
        },
        {
          "key": "Vercel-CDN-Cache-Control",
          "value": "max-age=3600"
        }
      ]
    },
    {
      "source": "/api/(.*)",
      "headers": [
        {
          "key": "Cache-Control",
          "value": "s-maxage=60, stale-while-revalidate=30"
        },
        {
          "key": "CDN-Cache-Control",
          "value": "max-age=60"
        },
        {
          "key": "Vercel-CDN-Cache-Control",
          "value": "max-age=60"
        }
      ]
    },
    {
      "source": "/feed",
      "headers": [
        {
          "key": "Cache-Control",
          "value": "s-maxage=86400, stale-while-revalidate=3600"
        },
        {
          "key": "CDN-Cache-Control",
          "value": "max-age=86400"
        },
        {
          "key": "Vercel-CDN-Cache-Control",
          "value": "max-age=86400"
        }
      ]
    }
  ]
}

Using the configuration provided by Vercel, we can configure cache headers for each route. After the configuration, Vercel will automatically add cache headers when responding to these requests, then Cloudflare will read the cache headers and cache them in the Cloudflare network. When the next request arrives, it will be directly read from the Cloudflare cache.

The value of stale-while-revalidate= controls how long a resource can still use expired resources after expiration, and then updates the resource asynchronously in the background. So even in the case of expiration, users can quickly access the resources and speed up page loading.

[!IMPORTANT]

Route matching is from bottom to top, which means that the first item can be defined as a global fallback, which matches /(.*)

Reference: https://vercel.com/docs/projects/project-configuration#headers

Vercel Edge Network Cache#

You may have noticed the header Vercel-CDN-Cache-Control. This header is Vercel's private header used to control the caching of resources in the Vercel edge network. Since Vercel also provides caching, why use Cloudflare?

I think there are probably the following reasons:

  1. Cloudflare is generally used as a DNS provider and has faster response times.
  2. Vercel's cache hit rate is strange, sometimes it hits, sometimes it doesn't, which puzzles me; while Cloudflare's cache hit rate is in line with the documentation and within expectations.

This article is synchronized and updated to xLog by Mix Space
The original link is https://innei.in/posts/tech/vercel-cloudflare-http-header-about-cache


Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.