Developers don’t usually worry about performance optimization until the beginning of the deployment phase. The only exception is when a ticket specifying the installation of performance-related modules is assigned.
Performance optimization should be a part of the development process instead of an additional step. Ideally, performance optimization needs to begin during the project's planning phase. It should be improved during the development phase and perfected during deployment. This saves a lot of time spent on debugging performance issues.
But what does one need to keep in mind when working on optimizing a Drupal project?
Find the answer to this question here.
Note: Most of the points mentioned below are also useful for developers not working on Drupal projects.
Phase 1: Initial Planning
The steps that can be taken during the initial planning of a project are:
The first step to ensuring performance optimization involves having the right approach to the entire process. The performance of the application should be given due consideration from the beginning.
When this is compromised, it becomes difficult to cover up in the future. This can lead developers to a stage where rebuilding the major chunk of the application is the only option.
This is the period that decides the overall success of a project. Developers should be very careful when it comes to deciding on various architectural aspects of the project, including:
- Content architecture
- Installation profile
- Type of application, which can be progressively decoupled or completely headless
Always have a column or note related to how performance will be impacted by these factors and ensure that information is used when making final decisions.
Requirement analysis is another important step in the Software Development Life Cycle (SDLC). But does it affect performance?
In my opinion, it brings a lot of clarity regarding what must be developed. It gives developers a good time to focus on non-functional requirements like performance. A clear mindset during Drupal development is important to write cleaner code.
MySQL is the go-to database for Drupal websites because of its wider usage by the community and ease of testing. MariaDB and PostgreSQL are also supported by Drupal and have a considerable advantage over MySQL.
Developers should check this comparison to decide on the database engine for the project. It is also worth noting that using SQLite to run automated tests can help in quicker execution.
Make sure to configure the latest supported version of PHP for a project. This is important to capture all the performance-related improvements in the latest version. All the local and hosted environments should use the same version of PHP.
Don’t forget to update the PHP version once it is supported by Drupal. Recently added PHP JIT (PHP 8.0) can also be enabled for faster execution.
Web Server: Apache Vs. Nginx
Apache and Nginx web servers are widely used with Drupal. Most of the testing of Drupal also happens on these web servers. Because of this, developers are free to pick any of these for a project.
But Nginx has better performance in terms of response time in case of concurrent requests and memory consumption. This means that developers should stick with it unless the platform has some restrictions. Read more to get a detailed comparison between Apache and Nginx.
Most developers prefer turning cache and aggregation off during the beginning of the project as that makes it easier to develop features. This is fine in a local development environment. But when it comes to hosted development and staging, all instances should have cached and aggregation enabled.
The testing should be done with core modules like Internal Page Cache, Dynamic Page Cache, and Big Pipe enabled. Keeping aggregation enabled is also essential to ensure that JS and CSS work as expected.
Phase 2: Development Phase
During the development phase, the following steps should be implemented.
Developers must ensure that they are following best practices while configuring a Drupal website. Content type and fields should be set to make sure that content can be rendered easily without adding a lot of custom logic. Also, view caching should be enabled.
Custom codes should be peer-reviewed to avoid a high execution time. This also helps ensure that the best Drupal/PHP practices are followed. Special attention should be paid to all the code snippets executed on every request.
Developers should try to replace code snippets with different constructs. For example, disable the automated cron module that checks on every request. This should be done if cron has to be executed and an external crontab or trigger is used to run cron.
Preparing a caching strategy and using appropriate cache metadata in renderable arrays is a good practice. Avoid setting cache max-age to 0. Always remember that performance optimization is done to handle more traffic and not run bad code faster.
Avoid excessive preprocessing as it can slow down the execution of a website. Instead, load the asset libraries based on the page requirements. Don’t forget to turn off the development mode and twig debugging in the production environment.
Two main factors decide the impact of cron jobs on the performance of a website:
- Configuration of cron
- Number of cron jobs
Avoid using the core provided Automated Cron module as it executes cron jobs during requests to the website. Cron should be set by running the `drush cron` command using crontab or hitting the cron URL from an external service.
Ultimate Cron can check all the cron jobs in an application. It also helps in disabling the ones that aren’t needed anymore. Also, ensure that cron jobs are running without any errors or warnings.
It is a good practice to disable development-related modules. Configuration Split makes this easier by allowing developers to define configurations that can be used to keep unwanted modules and settings disabled on various instances. Several Drupal core modules like Views UI and Field UI can also be disabled in the production environment.
Phase 3: Contributed Modules
The steps that can be implemented in regards to contributed modules are:
Fast 404 is a contributed module that improves the logic of handling 404 response code requests. Although developers try to eliminate all possible 404 errors resulting from custom codebase and configuration, sometimes it might not be possible. The Fast 404 module should be enabled to save system resources consumed when serving 404 pages to solve this problem.
Advanced CSS And JS aggregation
The Drupal core provides a feature that helps aggregate CSS and JS files. This reduces the number of requests and load time required for a website to load fully. It is highly recommended to keep it enabled in hosted instances.
The Advanced CSS/JS Aggregation module improves the aggregation process and allows developers to perform minification and re-ordering of FE assets. Install and configure this module to achieve good page speed scores.
Internal Page Cache And Dynamic Page Cache
These core modules should be enabled to ensure maximum performance and minimum load time. These modules are similar to inbuilt reverse proxies that reduce the overall computation. Read more about these modules on Drupal’s documentation pages.
Big Pipe is a Facebook-created technique that aims to serve pages faster. It is integrated into the Drupal core, and developers just need to enable the module to benefit from it. BigPipe breaks the pages into small pagelets and implements concepts borrowed from parallel processing to serve a web page quickly.
Images And Images Optimizations
The majority of improvements in the loading of a webpage are done by optimizing the images. Read more to learn everything you should know about working with images in Drupal.
AMP For Mobile Pages
It is best to use the Accelerated Mobile Pages (AMP) module if a website is accessed mostly from mobile devices. This is because the module helps in loading pages at lightning speed on all mobile devices. It also boosts SEO rankings and allows the conversion of normal web pages to AMP pages.
The majority of contributed modules related to performance optimization have been mentioned. But developers are still encouraged to check out all the contributed modules under the Performance and Scalability category.
Phase 4: Deployment And Infrastructure
The steps below should be followed during the deployment and infrastructure phase to ensure proper performance optimization.
Tools like New Relic and Sentry should always be used to keep an eye on a website's performance. Developers should be quick to resolve performance issues as it can become difficult at a later stage. Alerts and automated testing bots should be used to monitor the website's development and production environment performance.
Regularly Updating Modules, Drupal, PHP, Infrastructure, And The Local Setup
No technology is perfect, and there is always a scope for improvement. This is why developers should have a proper procedure for updating everything associated with the technology stack. Start by making a list of items in the beginning and regularly switching them to use the latest stable version.
It is always a good idea to research the latest improvements in web application hosting. One can opt for various options based on website traffic and application requirements. In the case of Drupal, there are several managed hosting service providers such as Acquia, Pantheon, and Platform.sh. This makes it easy to host applications on an enterprise scale.
Switch To HTTP 2
HTTP 2 has various advantages over HTTP 1.1, including:
- Binary nature
- Fully multiplexed
- Better data compression
- Faster encryption
- Reduced round trip times
Developers should switch the web infrastructure to use HTTP 2, and once HTTP 3 is more stable, one should upgrade to that as well.
GZIP And Brotli
Enabling GZIP or Brotli compression on a web server ensures that the data is compressed before serving and extracted at the browser’s end. It is a good step to reduce the request size and latency. Various comparison research has found Brotli to have a better compression algorithm than Gzip.
Redis And Memcache
A significant chunk of execution time in any PHP-MySQL application is spent executing the queries. In the case of Drupal, it is important to optimize this chunk.
Key-value stores like Redis and Memcache help optimize the queries and reduce the execution time spent in getting data from the database. Contributed modules are available for integrating both Redis and Memcache with Drupal.
Varnish, CDN, And Reverse Proxy
Varnish, CDN, and Reverse Proxy are tools that introduce a caching layer that sits over a web server and caches the DOM and assets of a website. Because of this, there is no need to bootstrap the Drupal application. This reduces the load on the web server.
The only challenge in integrating these tools with Drupal is ensuring that cache invalidation is respected and the user's latest and updated content is served. Check out the Purge module to understand more about integrating these tools with Drupal.
S3 For Assets
All the images, documents, and other static assets can be stored and served from the Amazon S3 bucket. This reduces the load on the server and minimizes storage costs. S3FS is a contributed module that can be easily used to perform this integration.
Despite having all the caching and supplement tools available, there can be a situation where an application might take up too much to load. The main cause behind this could be the absence of a no-cache build.
Effective caching warming can be used as a tool or a simple script to emulate the user behavior and develop a cache. When the actual user accesses the website, it loads faster as the cache has been developed.
Phase 5: Performance Testing
The steps to ensure performance optimization during performance testing are given below.
Google Page Speed, YSlow, And Lighthouse
These tools highlight several issues related to the performance of a website. Developers should use these tools frequently to resolve those issues.
XHProf is a tool for profiling PHP. It is useful in debugging a very heavy back-end execution time. Read more to learn about the contributed module that can help set up XHProf.
Load testing is essential to verify whether the infrastructure will be able to handle the expected traffic or not. Based on the outcome, developers can identify different areas for improvement. Popular load test frameworks like JMeter or Siege can be used for this.
Leverage Browser Caching
Front-end performance testing tools highlight another important server-level configuration. There is also the functionality of setting expiry headers for all static assets so that browsers do not send additional requests. Instead, it is directly displayed from the system cache.
Some additional steps that can be followed to ensure better performance optimization are:
The unwanted tables can be truncated to speed up the queries. DB Maintenance module can be installed for further improvements.
Errors And Warnings
Resolve all the error messages and warnings shown in the system logs, recent log messages, and browser console. Also, ensure that the database logging module is disabled in the production environment and the configuration is set to use Syslog instead.
Optimized Composer Autoloader
Add the composer dump-autoload -o as part of the production deployment process. This allows PHP to load classes in the fastest possible way.
Static Site Generator
The entire Drupal application can be converted into a static HTML website using tools like Tome. These can also boost applications significantly as serving static websites is cheaper.About the Author
Gaurav Kapoor, Senior Drupal Engineer
Gaurav is a storyteller. An Arsenal FC fan, he also enjoys reading Amish Tripathi's works on Hindu Mythology. He has been spending every Friday evening at his favorite bar for more than two years now. Need a dose of sarcasm? He is your guy!