Speeding lights through a tunnel.

10 Website Speed Optimization Tactics for Drupal 8 & 9

Our comprehensive guide to getting the best performance out of a Drupal site.

Photo by Mathew Schwartz on Unsplash

Many of the common website speed problems in Drupal 7 are now a distant memory with Drupal 8 and Drupal 9. Features like Drupal’s built-in Dynamic Page Cache help bring great performance benefits to the two most recent versions. This article will highlight other tactics to assist with getting the best performance out of your Drupal site.

Before we take a look at some of the approaches we can use for optimizing Drupal, let's cover how we can actually test our performance.

One of the most comprehensive and easy to use tools is Google’s PageSpeed Insights tool. This tool can very quickly and clearly highlight potential performance improvements that apply for your site.

Chromatic PageSpeed Insights.

While PageSpeed Insights is a great tool to get started, a solid performance improvement strategy includes continuous performance monitoring. For this, we recommend an automated service such as Calibre or SpeedCurve.

Chromatic Calibre performance monitoring.

These services build upon existing technology, such as WebPageTest and Google Chrome Lighthouse by allowing you to schedule regular tests and easily visualizing metrics over time.

With that covered, we can jump into our recommendations for getting the best performance out of your Drupal site.

Caching

Caching is one of the most impactful ways to reduce load time. Drupal 8 comes with caching enabled by default, however, additional or alternative caching implementations may work best for your specific site.

Page Cache

Page Caching allows repeated requests for a specific page to be served quickly and efficiently by storing the resulting HTML after the first time they are requested and serving that cached version of the page going forward. This reduces page load times and prevents unnecessary heavy lifting by the web and database servers.

For smaller sites with mostly anonymous traffic, Drupal Core’s Internal Page Cache module should be configured. For sites of this size, it may provide all of the performance gains necessary for your site. Drupal’s Dynamic Page Cache will provide even better results if your site has a mix of anonymous and authenticated traffic as it provides caching of both of those user types.

For more complex sites that serve personalized content to users, the Internal Page Cache module is inadequate because the personalized (or dynamic) parts of the page should not be cached. Our recommendation, in this case, would be to use the Dynamic Page Cache module. This module will still cache the majority of a given page, but also provides the essential ability to turn dynamic parts of the page into placeholders, which can be populated with the correct content for the current user.

The Cacheability of render arrays documentation page provides a great breakdown of the thought process behind caching in Drupal. This can help immensely when considering your own caching strategy.

BigPipe

The idea behind BigPipe caching is to effectively separate the personalised or uncacheable portions of a page into smaller chunks which can then be ‘streamed’ into the page, providing a huge improvement to perceived performance to visitors. This can result in a massive reduction to page load times and also means that caching can still be implemented on pages with dynamic content, in fact, it is strongly recommended to use the BigPipe module in conjunction with the Dynamic Page Cache module.

Check out our Don’t break your cache, use BigPipe instead article for implementation details and tips & tricks for getting BigPipe working on your site.

Redis

Redis in-memory caching.

Out of the box, Drupal utilizes the database to cache many objects. While this is a nice feature to have, it can become problematic on high traffic sites because the database is also being used to handle many other queries related to page requests, this can result in the database becoming a bottleneck. Using Redis as a drop-in replacement for database caching can yield substantial performance improvements. Redis is an in-memory, key-value data store, highly optimized for storing, reading and writing cache data, in addition, it is preventing the need for the database to handle these requests.

The Redis module provides the necessary features to connect Drupal with a Redis service. Our Configuring Redis Caching with Drupal 8 article also provides a more detailed Redis overview along with some additional implementation tips.

Media Optimization

Website Media Optimization.

Image in graphic by Karina Vorozheeva.

Images are critical for a website and are consistently responsible for the largest amount of data transfer when a page is loaded. A website performance audit will often reveal the need to implement or refine the delivery of images throughout your Drupal site.

There are a few optimization strategies that we can use to ensure that our images look great and load quickly.

Image Optimization

A module such as Image Optimize can be used to perfect the balance between quality and performance for images throughout a Drupal site. In addition, the quality for each file type can be optimized individually and new derivatives can be generated, such as WebP Image files.

Image Optimize allows pipelines to be defined for any given requirement, each with a specific set of optimizations. For example, perhaps hero images can be compressed more heavily to reduce file size whilst still looking great whereas your blog images need a higher quality setting for maximum impact.

Responsive Images

In addition to optimizing image files, varying screen sizes and densities should be accommodated. This is often seen as a way to ensure high-end devices render the best possible quality image, but the main goal of responsive images is to allow devices with smaller or lower-resolution screens to download smaller versions of an image where appropriate.

The Responsive Image module is included in Drupal Core and allows for appropriately sized images to be served to your site visitors by using the HTML5 picture tag and theme-specific breakpoints. An alternative option to the <picture> element is to output a simple <img> tag that leverages srcset to provide responsive image values. Our Responsive Images in Drupal 8 Using "srcset" article provides a comprehensive tutorial for why and how to implement responsive images using srcset in Drupal.

When used in conjunction with well-optimized images, configuring responsive images will result in large performance gains over a typical out of the box configuration.

Lazy Loaded Images

Lazy loading may sound like something that could slow you down, however this technique actually brings huge performance gains with it by decreasing page load time.

Lazy loading is when a resource, in this case a potentially large image file, is loaded only when it is actually needed. For a typical web page, an image only needs to be loaded when the user scrolls down to where the image is visible on the page.

There are several popular modules for implementing Lazy Loading in Drupal, including Lazy-load, Image Lazyloader and Blazy.

Browser level native lazy loading is now supported by Chrome by making use of the new `loading’ attribute. This is great to see, with time it will become more widely supported and will make custom lazy loading code or external libraries unnecessary.

Modules & Codebase

Stay up to date

Drupal core and contributed modules are always being updated for security, bug, and performance fixes. We recommend staying on top of these ongoing updates.

Uninstall unused modules

Every module enabled brings some overhead with it, which in turn can negatively impact the performance of your site. As a result, we recommend keeping the number of modules enabled to a minimum in addition to ensuring that any unused modules are disabled before the site is launched.

In addition to ensuring that only essential modules are enabled, any development modules should always be disabled in production environments. These development modules might include Devel, Field UI, Menu UI, and Views UI.

404 Error Pages

The Fast 404 module prevents 404 pages from causing unnecessary load on your hosting infrastructure.

In addition to potentially wasting resources to deliver an error page, the site should be checked for broken links, images and other resources to prevent errors to begin with. A popular and powerful tool for crawling your site for broken links is the SEO Spider Tool by Screaming Frog. This tool can check for broken image and file references, in addition to internal and external page links.

Content Delivery Network (CDN)

Fastly and other Content Delivery Networks (CDN) help your website to perform faster by delivering content to your users from a location which is physically closer to them. In addition, a CDN can help to maintain consistent site performance during high traffic periods due to the distributed nature of the network being used.

Another advantage to utilizing a CDN is that it can help to protect your origin server by responding to requests. Without a CDN, the origin server would be responsible for handling each and every end-user request, potentially resulting in slow response times and high load on your server.

We love Fastly, which comes built-in with some Drupal hosting providers like Pantheon and Platform.sh.

External Resources (JavaScript, CSS, etc.),

External resources include any asset which is loaded from an externally hosted site or service and typically consists of small snippets of code used for things like tracking, advertising and analytics.

Each of these resources introduces an extra request made by your browser which in turn increases latency and page load time. Ideally, your site’s reliance on external resources should be kept to a minimum. A good first step when reviewing external libraries is to look at the performance impact for each resource and discuss the perceived benefit with stakeholders to decide whether it is worth continuing to use.

In the cases where these resources are essential, it is worth investigating the implementation of a tag manager to handle tags as an alternative to just placing the separate tags directly in the page source. In addition to being easier to maintain, tag managers will typically load asynchronously which prevents the loading of these resources from blocking other items from loading.

Leveraging Drupal’s Robust Library System

Drupal 8 introduced asset libraries to manage CSS and JavaScript, for both themes and modules. Utilizing libraries allows for granular inclusion of assets based on the page being loaded, this is a good thing because it can help to decrease page load time and to keep the amount of assets being loaded to a minimum.

base:
  version: 1.x
  css:
    theme:
      build/styles/root.css: { minified: true }
  js:
    build/scripts/root.js: { minified: true }

article-listing:
  version: 1.x
  js:
    build/scripts/03-structures/article/article-feature/article-feature.js: { minified: true }

content:
  version: 1.x
  js:
    build/scripts/content.js: { minified: true }

Drupal uses a high-level principle: assets (CSS or JS) are still only loaded if you tell Drupal it should load them. Drupal does not load all assets (CSS/JS) on all pages because this is bad for front-end performance.

Database Optimization

Drupal uses the database heavily and can quickly become a bottleneck as traffic increases to the site. Well configured Caching and Redis will help greatly with this, here are a couple of additional database-specific tips.

Database Logging

Production sites should not write the logs to the database as it is an extremely inefficient operation. Using the Syslog core module, it’s possible to output all messages to a file, instead of the database. Due to the intensive logging for PHP warnings and errors that are all being written to the database, this will considerably lower the strain on the server.

Table Maintenance

In the past, we have seen instances where database tables have grown to extreme sizes. Frequently the cause for the excessive number of rows in these tables is due to caching or logging of events or errors, such as logging 404 errors.

It is important to keep database tables under control and there are many approaches for doing so, a module like DB Maintenance is one tool which may come in handy.

Hosting / Stack

There are many site-specific needs that will influence a recommendation for the ideal hosting environment, but we typically start with a Platform as a Service (PaaS) provider such as Platform.sh as a default. The following tips are worth referencing when looking for performance and stability improvements to your existing stack.

PHP version

We recommend always using the latest stable version of PHP that your application supports, currently, this is PHP 7.4. Newer versions of PHP provide the latest features, and often include performance improvements over older versions, in addition to including the latest security fixes.

NGINX

Using NGINX as your web server can improve site performance. NGINX is capable of handling high concurrent traffic whilst avoiding high memory utilization issues which are often a problem with Apache. Drupal specific hosting providers such as Platform.sh use NGINX by default.

DNS Hosting (Anycast)

Typically, the DNS Hosting provided by domain registrars is not focused on providing the best possible performance. The DNS solutions offered by the larger providers such as Amazon Route 53, Cloudflare, and DNS Made Easy work in a similar way to a Content Delivery Network and provide multiple redundant geographic locations. Switching to a premium DNS provider will result in lower latency DNS lookups for users which in turn can help with increasing page load performance.

Fine-Tune CSS and JavaScript Asset Delivery

Aggregating multiple files together to a single file can assist with increasing page performance by requiring fewer requests to be made from browser to server when loading all of the required files, this is especially true when using the HTTP/1.1 protocol. If you are using HTTP/2, it may be beneficial to not aggregate assets due to the ability for resources to be transferred in parallel and cached on a more granular level.

Drupal provides CSS and JavaScript aggregation options as part of its Performance Configuration options (/admin/config/development/performance). In addition, the Advanced CSS/JS Aggregation module can be used to further optimize aggregation settings as well as provide some more advanced configuration options related to caching, asset compression, and JavaScript minification.

Inline Critical CSS

As with other externally sourced assets, stylesheets can become a render-blocking resource and may result in an increased page render time if conditions, such as network performance, are not optimal. Inlining critical styles in the document <head> and deferring non-critical styles to be loaded later streamlines rendering the content that’s immediately visible on load, resulting in improved perceived performance.

Inline CSS should be kept to only the styles that apply to “above the fold” markup, otherwise any performance advantage is negated. Tools such as Critical will extract and inline critical CSS, which is typically a much better option than attempting to accurately perform this process manually.

If your project is using HTTP/2, critical CSS can be pushed instead of inlined, allowing browsers to cache these critical styles instead of downloading them over and over again on every new page request.

In Summary

There are many speed optimization tactics for fixing website performance problems in Drupal 8/9. Thanks to some of the options we have just reviewed such as the ability to cache pages containing dynamic content, Drupal website performance is better than ever.

The implementation details will vary on a project by project basis as there is no ‘one size fits all’ approach where website performance optimization is concerned, however, we hope that some of the suggestions here will lead you towards a high performing website. A website performance audit would uncover existing problems and provide prioritized suggestions for improving the performance of your site, a thorough audit will ensure that time is spent wisely when solving performance issues.

Related Posts & Presentations