Images Styles in Drupal 7 with Varnish
We experimented an issue with Images Style in one of our Drupal sites that we have with Varnish as a frontend cache, here the story and how to solve it.
About Image Style
As you may know, image style is a module provided in the core of Drupal 7 to create thumbnails of the uploaded images. What this module does is provide an url for the preset based in the url of the real image.
The first time, the thumbnail does not exists in the server file system so Drupal will handle the request, he knows that is a request for image style module and invoke the handler to create the thumbnail. The handler work with the input parameter and the configuration for the style and creates a thumbnail and will save it into the public folder.
In the next call, the Web Server will serve the generated file directly, no Drupal work is involved.
The problem
Sometimes when we have a high load traffic and a lot of simultaneous request to the same file happens that If two request are sent all most in the same time Drupal asumes that there is no thumbnail and tries to generate the thumbnail for both request, what happens is that one of the request throws an error because can not generate the image, it sends an HTTP 500 error with a nice message “Error generating image” as response.
If you have varnish in the front, varnish will cache this response and will always server this 500 error, the result is that you user won’t see the wanted.
The Solution
You might think that is an issue with image cache, but no, is an issue that can be easily fixed in Varnish.
In order to solve this we added this code snippet in varnish to NOT cache any 500 error produced in the image resources.
You can add this snippet in the vcl_fetch.
if (req.url ~ "(?i)\.(png|gif|jpeg|jpg|ico)(\?.*)?$") { if (beresp.status == 503 || beresp.status == 500) { set beresp.http.cache-control = "no-cache"; set beresp.ttl = 0s; return (hit_for_pass); } }
Note: Sample for Varnish 3.