Not too many people know that Apache2 provides a simple caching module mod_cache.
It’s super simple to enable for a static site like this one and gave me a %65 performance increase!
Here’s how.
Enable the Apache2 mods
First, enable the two cache mods that are installed along with Apache2:
a2enmod cache
a2enmod cache_disk
systemctl reboot
Configure the VirtualHost file
Next, open your site’s VirtualHost file and add the following code block between the <VirtualHost>
tags:
<IfModule mod_cache.c>
CacheQuickHandler on
<IfModule mod_cache_disk.c>
CacheRoot "/var/cache/apache2/mod_cache_disk"
CacheEnable disk "/"
CacheDirLevels 5
CacheDirLength 3
</IfModule>
</IfModule>
Then, restart Apache2:
systemctl restart apache2.service
And you’re done!
mod_cache logging
This step is option but will allow you to see what requests are getting cached.
First, open the main Apache2 configuration. On Debian and Ubuntu this is /etc/apache2/apache2.conf
. Add the following new line:
LogFormat "%r\" \"%{cache-status}e\"" cachelog
This line creates a new log format called cachelog that records the requested file its cache status.
Next, open your site’s <VirtualHost>
file again and add the following new logging line:
CustomLog /var/log/apache2/cache.log cachelog
Restart Apache2 and you’re done.
The new log file will get written to /var/log/apache2/cache.log
. Requests that are served from the cache look like the following:
GET /guides/varnish-loadbalancer-ubuntu-20-04/ HTTP/1.1" "cache hit"
Benchmarks
I used the Siege HTTP benchmarking tool from a second server on a local 100MBps VLAN.
I created a list of URLs with this wget command:
wget --spider --force-html -r -l5 https://<SITE> 2>&1 | grep '^--' | awk '{ print $3 }' >urls.txt
Then I launched Siege with the following settings:
siege -t 10s -b -f urls.txt
This runs Siege for 10 seconds in max-speed, benchmark mode using the list of URLs in urls.txt
.
The average number of successful requests over 10 seconds was:
Cache Status | Result |
---|---|
No mod_cache | 840 |
With mod_cache | 1290 |
That’s over 100 requests per second from a $5 USD per month virtual machine!