Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 62 ยท Caching, Performance and Testing

HTTP Caching

Make Symfony responses cacheable: Cache-Control, expiration versus validation, ETag and Last-Modified, reverse proxies, with runnable cache stand-ins.

The fastest request is the one your PHP code never sees. HTTP has a built-in caching system: a response can carry headers that tell browsers, CDNs and reverse proxies how long they may reuse it, and how to check cheaply whether it is still fresh. Symfony's Response object exposes all of this as simple methods. Used well, caching turns a page that costs 80 ms of PHP and three SQL queries into one that is served from memory in a millisecond, or never requested at all.

This lesson explains the two caching models, expiration and validation, shows how to set the headers from a controller, and then rebuilds both models in plain PHP so you can watch the decisions being made. It assumes you know the Response object and the request lifecycle.

Two models: expiration and validation

flowchart TB
    Q["Client wants a page"] --> F{"Fresh copy in cache?"}
    F -->|"yes (expiration)"| U["Use it, no request at all"]
    F -->|no| V["Send request with If-None-Match<br/>or If-Modified-Since (validation)"]
    V --> S{"Still the same?"}
    S -->|"yes"| N["304 Not Modified, empty body<br/>cache reuses its copy"]
    S -->|"no"| G["200 with the new content"]

Expiration avoids the request; validation avoids the body.

  • Expiration says: "This response is good for the next 10 minutes." Within that window, a cache answers without contacting your server at all. Headers: Cache-Control: max-age=... (browsers and shared caches) and s-maxage=... (shared caches such as CDNs only).
  • Validation says: "Keep it, but ask me before reusing it." The server attaches a validator: an ETag (an opaque fingerprint of the content) or a Last-Modified date. Next time, the client sends the validator back in If-None-Match or If-Modified-Since. If nothing changed, the server replies 304 Not Modified with no body, saving the transfer and, if you check cheaply, the work of rendering.

You can combine them: serve fresh copies for a minute, then validate.

Cache-Control from a controller

Symfony's Response has methods for the common directives:

PHP
// src/Controller/ArticleController.php (real Symfony, read-only)
use Symfony\Component\HttpFoundation\Response;

public function show(Article $article): Response
{
    $response = $this->render('article/show.html.twig', ['article' => $article]);

    $response->setPublic();        // shared caches may store it
    $response->setMaxAge(600);     // browsers: fresh for 10 minutes
    $response->setSharedMaxAge(3600); // CDNs and proxies: 1 hour

    return $response;
}

There is also a controller attribute that does the same declaratively:

PHP
// real Symfony, read-only
use Symfony\Component\HttpKernel\Attribute\Cache;

#[Cache(public: true, maxage: 600, smaxage: 3600)]
public function show(Article $article): Response
{
    // ...
}

Know the main directives:

  • public: any cache may store it. private: only the user's browser (use it for anything personalised).
  • max-age and s-maxage: freshness lifetime in seconds.
  • no-cache: caches may store it but must revalidate before every reuse.
  • no-store: never store it at all (account pages, tokens).
  • must-revalidate: once stale, never serve it without checking.
  • stale-while-revalidate: serve the stale copy while fetching a fresh one in the background.

Never mark a response public if it depends on who is logged in. A shared cache would happily hand one user's dashboard to the next visitor. By default, Symfony makes responses with an active session private and no-store-like, which is a safety net, not a design.

Validation with ETag and Last-Modified

For dynamic content that changes unpredictably, set a validator and let Symfony compare it with the request:

PHP
// real Symfony, read-only
public function show(Request $request, Article $article): Response
{
    $response = new Response();
    $response->setEtag(md5($article->getUpdatedAt()->format('c').$article->getId()));
    $response->setLastModified($article->getUpdatedAt());
    $response->setPublic();

    if ($response->isNotModified($request)) {
        return $response; // 304: no template rendering, no body
    }

    return $this->render('article/show.html.twig', ['article' => $article], $response);
}

isNotModified() compares the request's If-None-Match and If-Modified-Since with the response's validators. If they match, it converts the response to 304 Not Modified and drops the body. The important detail is the order: you build the cheap validator first, and only render the expensive template when the check fails.

A good ETag changes whenever the representation changes and not otherwise. Hashing the updated-at time plus id is cheap. Hashing the rendered body also works but saves no rendering time, only bandwidth.

Varying responses

If the same URL returns different content by language or format, tell caches with the Vary header: $response->setVary(['Accept-Language']). The cache then stores one copy per distinct value of that request header. Use it sparingly: Vary: Cookie makes shared caching close to useless.

Reverse proxies and CDNs

Browsers cache for one person. A reverse proxy sits in front of your application and caches for everyone, so the second visitor never reaches PHP. Symfony ships a PHP-based one (HttpCache, enabled with framework.http_cache) that is fine for small sites and development. In production, people usually put Varnish, Nginx caching or a CDN such as Cloudflare in front. All of them obey the same headers you just learned, which is why s-maxage exists: it lets you cache longer in the proxy than in the browser, because you can purge the proxy but not your visitors' browsers.

For fragments of a page, Symfony supports ESI (Edge Side Includes) and the render_esi() Twig function: a mostly static page can embed a small personalised block that is cached separately. It needs a proxy that understands ESI, such as Symfony's HttpCache or Varnish.

Expiration, seen in code

The stand-in below is a tiny shared cache keyed by URL. It stores a response with a max-age and decides on each request whether to serve it, based on an artificial clock so the output is deterministic.

PHP Expiration: a tiny shared cache (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Seven requests, and the origin rendered only four times. Inside the 60-second window the cache answers without asking, and once the entry expires it goes back to the origin for a new copy.

Validation, seen in code

This stand-in shows the other model: the server computes a cheap ETag first, compares it with If-None-Match, and skips the expensive rendering when they match.

PHP Validation: ETag and 304 Not Modified (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

After the first visit, every unchanged reload costs the server only a string comparison and returns a 304 with an empty body. The edit changes the ETag, so the next reload gets a fresh 200. Expiration and validation fit together: when the max-age runs out, the browser revalidates instead of downloading everything again.

Practical rules

  • Start with public and a short s-maxage on pages that are the same for everyone (articles, product lists) and private on anything personalised.
  • Fingerprint your static assets (AssetMapper and Webpack Encore do) and give them max-age of a year; a changed file gets a new URL.
  • Prefer validation for content that changes unpredictably, expiration for content where "a little stale" is fine.
  • Test your headers with curl -I https://example.com/page and look at Cache-Control, ETag, Age and Vary. Browser dev tools show the same, and "disable cache" must be off to see real behaviour.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main difference between expiration and validation?

    Expiration uses max-age to skip the request entirely. Validation uses ETag or Last-Modified so the server can answer 304 with no body.
  2. 2. Which header should you use on a page that shows a logged-in user's private data?

    Shared caches must not store personalised pages. private or no-store keeps them out of CDNs and proxies.
  3. 3. What does a 304 Not Modified response contain?

    304 means the client's copy is still valid, so the server sends no body.
  4. 4. Why does s-maxage exist alongside max-age?

    You cannot purge visitors' browsers, so you keep browser lifetimes short and let the shared cache hold the page longer.

Summary

  • HTTP caching lets browsers, CDNs and proxies reuse responses; you control it with headers.
  • Expiration (max-age, s-maxage) skips the request; validation (ETag, Last-Modified, 304) skips the body and the rendering work.
  • In Symfony use setPublic(), setMaxAge(), setSharedMaxAge(), setEtag(), isNotModified() or the #[Cache] attribute.
  • Personalised responses must be private or no-store; use Vary carefully.
  • A reverse proxy (Symfony's HttpCache, Varnish or a CDN) caches for all visitors; ESI caches page fragments.
  • The runnable examples are plain-PHP stand-ins; the Symfony snippets are real and read-only here.

Next up: The Cache Component.