Chunked transfer encoding in Rails (streaming)

7th August 2013

Anyone that has written a little PHP knows what the flush() family of functions do. The ideal usage scenario for using chunked transfer[0] is when we have something costly to render e.g. the first three most recent articles on a blog. Why ? one might ask.

Is rather simple: in a normal request where the server responds with a Content-Length header the browser will wait until the whole page comes down the wire then it goes loading the assets et al.

Using the Transfer-Encoding: chunked header, the server will send chunks of the rendered page back to the browser so in the case of Rails, it starts with the layout and sends out the <head> part including assets like js and css.

It's clear how this helps the rendering of the page on the client side : get the first chunk containing the <head> with assets, immediately start loading the assets while waiting for the rest of the response. Of course, browsers nowadays include lots of micro-optimizations that might already do something similar but still this remains a good practice.

Implementation wise, you just need to add to your controller methods something like :