Search code examples
phpcachingsymfonyhttp-caching

Should I check if 'is not modified' for most responses?


I'm intrigued by this snippet:

public function indexAction()
{
    $response = $this->render('MyBundle:Main:index.html.twig');
    $response->setETag(md5($response->getContent()));
    $response->isNotModified($this->getRequest());

    return $response;
}

Should I do this whenever possible? I'm thinking that most pages in my websites could save bandwidth this way (though not CPU).


Solution

  • Doing this blindly just to save Bandwidth is in my opinion a waste of time and an unnecessary code complexification.

    Your cache strategy is very important and must be implemented wisely on your whole application, using various cache techniques depending on what your controllers do.

    • For static pages, I would recommend to use cache expiration without Etag but more with Expires Header or Cache-control Header

    • For dynamic pages, I would recommend here a use of cache with more validation and then the use of Last-modified of Etag

    • Lastly, for many cases (in my case, static pages with heavy shared caching but a topbar on top with personal info about logged user that I cannot cache), I'll recommend the use of ESI to cache separately the different blocks of your page (in my case, topbar never cached, and the rest of the page cached with validation and ETag)

    This way, with a little bit more reflexion and global strategy, you define on top of your application a reliable and efficient caching that saves both your bandwith and your CPU