Folded paper texture

image by JJ Ying

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.

RailsConf 2024

I'm co-chairing RailsConf 2024 in Detroit May 7–9. Come and join us 

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.

Brighton Ruby 2024

Still running UK’s friendliest, Ruby event on Friday 28th June. Ice cream + Ruby 


Last updated on August 30th, 2021 by @andycroll

An email newsletter, with one Ruby/Rails technique delivered with a ‘why?’ and a ‘how?’ every two weeks. It’s deliberately brief, focussed & opinionated.