Skip to main content

Optimizing Apache Performance

1. Tuning KeepAlive Settings

Directive Values Description
KeepAlive On | Off Enables or disables persistent connections.
KeepAliveTimeout 5 seconds (default) Number of seconds to wait for additional requests on a persistent connection.
MaxKeepAliveRequests 100 (default) Maximum number of requests allowed per persistent connection.

Example: KeepAlive Configuration

<IfModule mod_keepalive.c>
    KeepAlive On
    KeepAliveTimeout 60
    MaxKeepAliveRequests 200
</IfModule>
Note: Increasing KeepAliveTimeout can improve performance for clients with slow networks, but may increase server resource usage.
Warning: Setting MaxKeepAliveRequests too high can lead to resource exhaustion on high-traffic servers.

2. Optimizing MaxRequestWorkers Value

Configuration Directive Values Description
MaxRequestWorkers 150 (default) Maximum number of simultaneous requests that can be served
MaxRequestWorkers 200 to 1000+ Adjust based on available RAM and CPU cores
Note: MaxRequestWorkers was formerly known as MaxClients in older versions of Apache.

Example: Setting MaxRequestWorkers

<IfModule mpm_prefork_module>
    MaxRequestWorkers 500
</IfModule>

Optimization Guidelines

  • Start with MaxRequestWorkers at 2x the number of CPU cores
  • Increase to 1000+ for high-memory systems with 8GB+ RAM
  • Monitor server load and adjust downward if CPU usage exceeds 80%

3. Configuring Timeout Values

Directive Default Value Description
Timeout 60 Timeout for initial connection and read/write operations in seconds. Affects overall request handling time.
KeepAliveTimeout 5 Number of seconds the server will wait for a subsequent request on a persistent connection before closing it.
KeepAlive On Enables or disables persistent connections (HTTP/1.1 Keep-Alive). Reduces connection overhead.
MaxKeepAliveRequests 100 Maximum number of requests allowed per persistent connection before closing it.

Example: Setting Timeout Values

<IfModule mod_timeout.c>
    Timeout 30
    KeepAliveTimeout 2
    MaxKeepAliveRequests 50
</IfModule>
Note: Adjust Timeout based on expected request duration and network latency. Lower values may cause premature timeouts for long-running requests.

4. Tuning MPM Settings

MPM Configuration Directive Description Default Value
worker ServerLimit Sets the maximum value for MaxRequestWorkers and ThreadsPerChild 256
worker MaxRequestWorkers Maximum number of simultaneous requests that can be served 150
worker ThreadsPerChild Number of worker threads per child process 64
worker MaxConnectionsPerChild Maximum number of connections a child process will handle before dying 10000
prefork ServerLimit Sets the maximum value for MaxRequestWorkers 256
prefork MaxRequestWorkers Maximum number of simultaneous requests that can be served 256
prefork MaxConnectionsPerChild Maximum number of connections a child process will handle before dying 10000
event ServerLimit Sets the maximum value for MaxRequestWorkers and ThreadsPerChild 256
event MaxRequestWorkers Maximum number of simultaneous requests that can be served 150
event ThreadsPerChild Number of worker threads per child process 64
event MaxConnectionsPerChild Maximum number of connections a child process will handle before dying 10000

Example: Worker MPM Configuration

<IfModule mpm_worker_module>
    ServerLimit 256
    MaxRequestWorkers 200
    ThreadsPerChild 64
    MaxConnectionsPerChild 10000
</IfModule>

Example: Prefork MPM Configuration

<IfModule mpm_prefork_module>
    ServerLimit 256
    MaxRequestWorkers 256
    MaxConnectionsPerChild 10000
</IfModule>

Example: Event MPM Configuration

<IfModule mpm_event_module>
    ServerLimit 256
    MaxRequestWorkers 200
    ThreadsPerChild 64
    MaxConnectionsPerChild 10000
</IfModule>
Note: The worker and event MPMs are more efficient for handling a large number of concurrent connections, while prefork is more stable and compatible with modules that are not thread-safe.

5. Enabling and Tuning Compression

Directive Values Description
AddOutputFilterByType DEFLATE text/html Enables compression for specified content types
DeflateCompressionLevel 6 Compression level (1-9), default is 6
DeflateBufferSize 8192 Buffer size for compression in bytes

Example: Enabling Compression

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/css text/plain
    DeflateCompressionLevel 6
    DeflateBufferSize 8192
</IfModule>
Note: Compression can reduce bandwidth usage but increases CPU load. Monitor server performance after enabling.
Warning: Avoid compressing already compressed content (e.g., images, videos) as it can increase file size.

6. Implementing Caching Strategies

Directive Description Values Notes
CacheEnable Enables caching for a specific URL or directory disk:/path/to/cache, mem:/path/to/cache Available in mod_cache and mod_cache_disk
CacheRoot Specifies the root directory for cache storage /var/cache/apache2 Must be writable by the Apache user
CacheDefaultExpire Sets default expiration time for cached content 3600 (seconds) Defaults to 3600 seconds if not set
CacheLastModifiedFactor Adjusts cache expiration based on Last-Modified header 0.1 to 1.0 Value between 0 and 1; affects how long content is cached

Example: Enabling Disk Caching

<IfModule mod_cache.c>
    CacheEnable disk /
    CacheRoot /var/cache/apache2
    CacheDefaultExpire 3600
</IfModule>

Example: Configuring Cache Expiration

<IfModule mod_cache.c>
    CacheEnable disk /
    CacheDefaultExpire 3600
    CacheLastModifiedFactor 0.5
</IfModule>
Note: Caching strategies can significantly improve performance but require careful configuration to avoid serving stale content.

Cache Directive Summary

  • CacheEnable: Enables caching for specified paths.
  • CacheRoot: Sets the directory where cached content is stored.
  • CacheDefaultExpire: Sets default cache duration in seconds.
  • CacheLastModifiedFactor: Adjusts cache expiration based on Last-Modified header.

7. Optimizing SSL/TLS Performance

Directive Description Default Notes
SSLEngine Enables or disables SSL/TLS for a virtual host off Must be set to on to enable SSL
SSLCertificateFile Path to the server certificate file None Required when using SSL
SSLCertificateKeyFile Path to the private key file None Required when using SSL
SSLCipherSuite Specifies the list of ciphers to use for TLS ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256 Customize for security and performance
SSLProtocol Specifies the TLS versions to support -ALL +TLSv1.2 +TLSv1.3 Disables older insecure protocols
SSLHonorCipherOrder Enforces cipher order specified in SSLCipherSuite on Improves performance by prioritizing faster ciphers
SSLSessionCache Configures session caching for TLS shmcb:logs/ssl_scache(512000) Improves performance by reusing sessions
SSLSessionTimeout Duration of session cache entries 300 Set to 5 minutes by default

Example: Optimized SSL Configuration

<VirtualHost *:443>
    SSLEngine on
    SSLCertificateFile /path/to/cert.pem
    SSLCertificateKeyFile /path/to/key.pem
    SSLCipherSuite ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256
    SSLProtocol -ALL +TLSv1.2 +TLSv1.3
    SSLHonorCipherOrder on
    SSLSessionCache shmcb:logs/ssl_scache(512000)
    SSLSessionTimeout 300
</VirtualHost>
Note: Ensure that the mod_ssl module is loaded before using these directives.
Warning: Older TLS versions (e.g., TLSv1.0, TLSv1.1) should be disabled for security reasons.

8. Reducing DNS Lookups

Directive Description Default Notes
HostnameLookups Controls whether Apache resolves hostnames to IP addresses for logging and error messages. Off Setting to On causes DNS lookups for each request, which can slow performance.
UseCanonicalName Controls whether Apache uses the canonical server name or the server name from the request for logging and redirects. Off When set to On, it may trigger DNS lookups for canonical name resolution.

Example: Disable DNS lookups for logging

HostnameLookups Off
Note: Disabling HostnameLookups prevents Apache from resolving hostnames to IP addresses, which can significantly improve performance in high-traffic environments.

9. Disabling Unused Modules

Module Description Enabled by Default Performance Impact
mod_alias Defines aliases for URLs Yes Low
mod_rewrite URL rewriting engine Yes Medium
mod_ssl SSL/TLS support No High (if enabled)
mod_status Server status information No Low (if enabled)
mod_info Server configuration information No Low (if enabled)
mod_autoindex Directory listing generation Yes Low to Medium
mod_headers HTTP header manipulation No Low (if enabled)
mod_expires Cache expiration control No Low (if enabled)

Example: Disabling Unused Modules

# Disable mod_ssl if not needed
# LoadModule ssl_module modules/mod_ssl.so

# Disable mod_info if not required for debugging
# LoadModule info_module modules/mod_info.so

# Keep essential modules enabled
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
Note: Disabling unused modules reduces memory usage and improves startup time. Always test after disabling modules to ensure functionality is not affected.

10. Optimizing Log Writing

Directive Description Default Notes
ErrorLog Specifies the path to the error log file logs/error_log Use absolute paths for reliability
CustomLog Defines a custom log format and destination None Can be used to offload logs to external systems
LogFormat Defines a log format string for use with CustomLog %h %l %u %t "%r" %>s %b Custom formats can reduce disk I/O
TransferLog Specifies the path to the transfer log file (deprecated) None DEPRECATED in Apache 2.0+

Example: Custom Log Format

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
CustomLog logs/access_log combined

Example: Asynchronous Logging

CustomLog "|/usr/sbin/cronolog /var/log/apache2/access-%Y-%m-%d.log" combined
Note: Using external loggers like cronolog can help reduce I/O contention on the main server process.
Warning: Frequent log writes can cause performance bottlenecks. Consider rotating logs with tools like logrotate.

11. Using Content Delivery Networks

CDN Type Description Benefits Considerations
Global CDN Geographically distributed network of servers Reduced latency, improved availability, better caching Higher cost, potential for content inconsistency
Edge CDN Proximity to end users for faster delivery Improved user experience, reduced bandwidth costs Requires content optimization for edge delivery
Hybrid CDN Combines global and edge delivery methods Balanced performance and cost efficiency Complex setup and management

Example: Configuring Apache to Work with CDN

# Enable mod_cache and mod_cache_disk
LoadModule cache_module modules/mod_cache.so
LoadModule cache_disk_module modules/mod_cache_disk.so

# Configure cache storage
CacheRoot /var/cache/apache2
CacheEnable disk /

# Set cache expiration for static content
CacheDefaultExpire 3600
CacheLastModifiedFactor 0.1
Note: Ensure your CDN and Apache configurations are aligned to avoid content inconsistencies.
Warning: Misconfigured CDN settings can lead to stale content delivery or increased latency.

12. Implementing Connection Pooling

Directive Description Default Value Notes
KeepAlive Enables persistent connections On Improves performance by reusing connections
KeepAliveTimeout Time (in seconds) to wait for additional requests 5 Higher values may increase memory usage
MaxKeepAliveRequests Maximum number of requests per connection 100 Set to 0 for unlimited requests

Example: Configuring KeepAlive Settings

<IfModule mod_keepalive.c>
    KeepAlive On
    KeepAliveTimeout 10
    MaxKeepAliveRequests 200
</IfModule>
Note: Connection pooling is particularly effective for sites with high concurrent request volumes.

Was this article helpful?