Folded paper texture

Compress Your HTML Responses

There are multiple aspects to the performance of typical Rails applications: database queries, view render time, fragment caching, and more. There are also considerations for the front-end: image compression, Javascript, and CSS size.

We often use CDNs, compression, and minification for the assets (images, CSS, and JS) our applications use. However, many hosts (including Heroku) do not compress the HTML that is generated by our applications by default.

Ensure…

you compress the HTML output being sent from your app with gzip using Rack::Deflater.

config/application.rb

# ...
module DreamCoverage
  class Application < Rails::Application
    # ...
    config.middleware.use Rack::Deflater
    # ...
  end
end

Why?

Compressing ‘text-based’ resources (i.e. the HTML or JSON your views generate) is one of Google‘s standard performance recommendations.

In most cases, text-based responses compress really well. I’ve seen compression of 20x on some of our more “HTML-repetative” #index actions at work, but 4x is typical on smaller pages. It makes an even bigger difference to performance on mobile, where network is more of a bottleneck.

You might find spectacular savings if you’re using something like TailwindCSS, Bootstrap, or another framework that results in repetitive class names in the HTML.

This (sadly!) doesn’t absolve you of other performance work. These compression savings only occur after the page has rendered, so if your database queries are slow, or your views take a long time to generate, you’ll still need to address those issues.

Why not?

It is entirely possible you already serve your application from behind a CDN, like Fastly or Cloudflare, that automatically compresses your HTML and JSON responses. You won’t need Rack::Deflater in these cases.

There will be a small increase in processing time for your users’ devices as they decompress the response, but this is vastly outweighed by the time savings made from sending the compressed response over the Internet.


last updated on 30 Aug 2021 by @andycroll

photo by
JJ Ying

Don’t miss my next post, sign up to the One Ruby Thing email and get my next post in your inbox.

Don’t miss my next post, sign up to the One Ruby Thing email and get my next post in your inbox.