Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 600
ChocoDeveloper Avatar asked Aug 19 '12 01:08

ChocoDeveloper


People also ask

What is the purpose of if-modified-since?

The If-Modified-Since request HTTP header makes the request conditional: the server sends back the requested resource, with a 200 status, only if it has been last modified after the given date.

What does 304 not modified mean?

The HTTP 304 Not Modified client redirection response code indicates that there is no need to retransmit the requested resources. It is an implicit redirection to a cached resource.

What is the purpose for the if-modified-since header?

The If-Modified-Since HTTP header indicates the time for which a browser first downloaded a resource from the server. This helps determine whether or not the resource has changed since the last time it was accessed.

Is 304 not modified an error?

The HTTP status code 304 means Not Modified – the web page you requested hasn't changed since the last time you accessed it. After that, your browser will retrieve the cached version of the web page in your local storage.


1 Answers

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

like image 109
guillaumepotier Avatar answered Oct 01 '22 09:10

guillaumepotier