Boost Laravel performance with OPCache

  • avatar
  • 3.5K Views
  • 6 Likes
  • 9 mins read

Enhancing the performance of Laravel applications brings a smoother and faster user experience. One powerful tool for achieving this is OPCache. OPCache is a PHP extension that stores precompiled script bytecode in memory, which reduces the overhead of parsing and compiling scripts with each request. This results in faster execution and improved overall efficiency.

Install OPCache extension

Ensure OPCache is installed on your server. You can verify this by listing all installed modules for your PHP setup:

php --modules

If it's not already installed, the command to install the OPCache extension is:

sudo apt install php8.x-opcache

Replace php8.x-opcache with the appropriate version you are using, such as php8.3-opcache.

Configure OPCache extension

Configuring OPCache through the php.ini file is straightforward. Begin by locating the php.ini file, which serves as the main configuration file for PHP. The location of this file can vary depending on your server setup. You can find its location by running the command:

php --ini

In our case, the file is located in the following directory:

/etc/php/8.3/cli/php.ini

Alternatively, instead of editing the php.ini file, you can create a separate configuration file for OPCache settings, which is often done to keep configurations organized. Create a new file named 10-opcache.ini (the number ensures it’s loaded in the correct order) in the PHP configuration directory.

In our case the file is located in the following directory:

/etc/php/8.3/cli/conf.d/10-opcache.ini

Here is an example of what the OPCache configuration file should look like.

[opcache]
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.revalidate_freq=2
opcache.fast_shutdown=1
opcache.enable_cli=1
opcache.jit=off

The configuration values are settings that control how the OPCache extension works in PHP. Adjusting settings like the memory size allocated to OPCache and the frequency for cache checks allows fine-tuning for specific needs. Below is an explanation of the most important and commonly used OPCache configuration directives:

  1. zend_extension:

    zend_extension=opcache.so

    This directive enables the OPCache extension. It's typically added automatically when OPCache is installed, but it's essential to ensure it's present.

  2. opcache.enable:

    opcache.enable=1

    This setting enables or disables the OPCache extension. Setting it to 1 enables OPCache, while 0 disables it.

  3. opcache.memory_consumption:

    opcache.memory_consumption=128

    This directive sets the amount of memory (in megabytes) allocated to OPCache for storing precompiled script bytecode. Adjust this value based on the memory available on your server and the size of your application.

  4. opcache.interned_strings_buffer:

    opcache.interned_strings_buffer=8

    This sets the amount of memory (in megabytes) allocated for interned strings in the OPCache. Interned strings are strings that PHP uses internally to save memory. Increasing this can improve performance if your application uses a lot of strings.

  5. opcache.max_accelerated_files:

    opcache.max_accelerated_files=10000

    This setting determines the maximum number of PHP files that can be cached by OPCache. Increase this value if your application has a large number of PHP files.

  6. opcache.revalidate_freq:

    opcache.revalidate_freq=2

    This directive sets the frequency (in seconds) at which OPCache checks for script updates. Setting it to 0 means OPCache will check for updates on every request, which is useful for development but should be set to a higher value in production.

  7. opcache.fast_shutdown:

    opcache.fast_shutdown=1

    Enabling fast shutdown allows OPCache to use a faster mechanism to free up the memory, which can improve performance.

  8. opcache.enable_cli:

    opcache.enable_cli=1

    This setting enables OPCache for the PHP CLI (command-line interface). It's useful for scripts run from the command line that can benefit from caching.

  9. opcache.validate_timestamps:

    opcache.validate_timestamps=1

    When enabled (1), OPCache will validate the timestamps of scripts to determine if they have been updated. Disabling it (0) can improve performance but should only be done if the scripts never change.

  10. opcache.file_cache:

    opcache.file_cache=/path/to/cache

    This setting specifies a directory for storing precompiled script bytecode on disk. It can be useful if you want to persist the cache between server reboots.

  11. opcache.file_update_protection:

    opcache.file_update_protection=2

    This directive sets the time (in seconds) that must pass before a file is eligible for caching after being updated. It can prevent caching issues related to concurrent updates.

  12. opcache.max_wasted_percentage:

    opcache.max_wasted_percentage=5

    This specifies the percentage of "wasted" memory (memory that is not used for active scripts) allowed before OPCache attempts to restart. Setting this helps manage memory usage effectively.

Create Laravel preload script

Preload script includes the files that you want to preload into OPCache and allows you to load PHP files into memory when the server starts. This means that these preloaded files are available for all subsequent requests without the need for recompilation. In the context of OPCache, this feature ensures that essential scripts are always ready to be executed quickly, enhancing performance.

Here’s an example of what the script might look like:

<?php

// Preload important files
require __DIR__ . '/vendor/autoload.php';

// Preload Laravel files
require __DIR__ . '/bootstrap/app.php';

// Preload all files in specific directories
$directories = [
__DIR__ . '/src',
__DIR__ . '/lang',
];

foreach ($directories as $directory) {
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));

foreach ($files as $file) {
if ($file->isFile() && $file->getExtension() === 'php') {
require_once $file->getPathname();
}
}
}

You can name the script as preload.php and place it in the root directory of your Laravel project.

Configure PHP to use the preload script

In the same OPCache configuration file that was mentioned and configured above, you should add the following directive to specify the preload script:

opcache.preload=/path/to/your/laravel/preload.php
opcache.preload_user = www-data

Replace the path with the actual path to your preload script and user with the correct user under which your web server is running.

Why preloading script in Laravel with OPCache

Preloading scripts in Laravel with OPCache can significantly improve your application's performance in several ways:

  1. Faster Execution: by preloading scripts, you ensure that crucial parts of your Laravel application are compiled and cached once during server startup. This reduces the time needed to compile and load these scripts for each request, resulting in faster response times.

  2. Reduced Overhead: preloading minimizes the overhead associated with parsing and compiling scripts repeatedly. This is particularly beneficial for Laravel applications that rely on complex logic or handle high traffic, as it lowers CPU usage and boosts efficiency.

  3. Consistency: preloading ensures that the same version of the preloaded scripts is used throughout the application's lifecycle. This consistency can help avoid issues that might arise from dynamic code changes during the application's runtime.

  4. Enhanced Performance: by keeping frequently used classes and functions preloaded, your Laravel application can deliver a more responsive and efficient user experience. This is particularly useful for applications that require high availability and quick response times.

Notes on Preloading

Preloading offers many advantages, but there are some important points to consider when running a server with OPCache.

  1. Memory usage: preloading can significantly increase memory usage, so ensure your server has sufficient memory allocated to OPCache.

  2. File changes: when preloaded files are changed, you need to restart the web server to reload them into OPCache.

  3. Order of preloading: ensure that the order of preloading respects dependencies. Preload the autoload files and core framework files first before other application-specific files.

By following these steps, you can use OPCache preloading to improve the performance of your Laravel application, reducing load times and increasing responsiveness.

Apply OPCache configuration

After making these changes, you need to restart your web server for the new settings to take effect.

  • For Apache:

    sudo systemctl restart apache2
  • For Nginx with PHP-FPM:

    sudo systemctl restart php8.x-fpm
    sudo systemctl restart nginx

    Replace php8.x-fpm with the appropriate version you are using, such as php8.3-fpm.

Verify OPCache status and preloading script

Check if preloading is working by creating a PHP script that calls opcache_get_status() and outputs the status information. Place this script in your Laravel project root and run it from the CLI or create a specific route and access it via your browser.

For instance, you can create a file named opcache.php with the following content:

<?php

$status = opcache_get_status();

print_r($status);

And execute it to get detailed statistics on OPCache usage and configuration.

php opcache.php

Reviewing the statistics section in the output will ensure that file preloading is operating as expected.

Flush OPCache

To flush OPCache in PHP, you can use one of the following methods:

  1. Restart PHP: A straightforward way to flush OPCache is to restart the PHP process or web server. This will clear the entire OPCache, ensuring that all cached bytecode is invalidated.

  2. Using PHP Script: You can create a PHP script specifically for clearing OPCache and execute it through the command line or a web request. Here's a simple example script:

    opcache_reset();

    echo 'OPCache flushed successfully.';
  3. Using OPCache Control Panel (OPCache GUI): If you have OPCache Control Panel installed and configured, you can use its interface to flush OPCache. This is a more user-friendly approach and provides additional insights into OPCache usage and performance.

Choose the method that best fits your workflow and requirements.

Conclusion

OPCache is a simple yet effective way to speed up your Laravel applications by reducing the overhead of repeatedly compiling scripts. By caching the compiled code, OPCache helps deliver faster response times and a more efficient server. Integrating and configuring OPCache correctly can give your application the performance boost it needs without much hassle.

 Join Our Monthly Newsletter

Get the latest news and popular articles to your inbox every month

We never send SPAM nor unsolicited emails

0 Comments

Leave a Reply

Your email address will not be published.

Replying to the message: View original

Hey visitor! Unlock access to featured articles, remove ads and much more - it's free.