Do not speak Portuguese? Translate this site with Google or Bing Translator
Boost Laravel performance with OPCache

Posted on: July 22, 2024 09:51 AM

Posted by: Renato

Categories: PHP Laravel Laravel

Views: 136

Boost Laravel performance with OPCache

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:

Source code
1 line
php --modules

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

Source code
1 line
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:

Source code
1 line
php --ini

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

Source code
1 line
/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:

Source code
1 line
/etc/php/8.3/cli/conf.d/10-opcache.ini

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

Source code
10 lines
[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:

    Source code
    1 line
    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:

    Source code
    1 line
    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:

    Source code
    1 line
    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:

    Source code
    1 line
    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:

    Source code
    1 line
    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:

    Source code
    1 line
    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:

    Source code
    1 line
    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:

    Source code
    1 line
    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:

    Source code
    1 line
    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:

    Source code
    1 line
    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:

    Source code
    1 line
    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:

    Source code
    1 line
    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:

Source code
23 lines
<?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:

Source code
2 lines
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:

    Source code
    1 line
    sudo systemctl restart apache2
  • For Nginx with PHP-FPM:

    Source code
    2 lines
    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:

Source code
5 lines
<?php
 
$status = opcache_get_status();
 
print_r($status);

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

Source code
1 line
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:

    Source code
    3 lines
    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.

Fonte: https://www.hibit.dev/posts/179/boost-laravel-performance-with-opcache?utm_source=laravelnews&utm_medium=link&utm_campaign=laravelnews

1

Share

Donate to Site


About Author

Renato

Developer

Add a Comment
Comments 0 Comments

No comments yet! Be the first to comment

Blog Search


Categories

OUTROS (16) Variados (109) PHP (133) Laravel (171) Black Hat (3) front-end (29) linux (114) postgresql (39) Docker (28) rest (5) soap (1) webservice (6) October (1) CMS (2) node (7) backend (13) ubuntu (56) devops (25) nodejs (5) npm (3) nvm (1) git (8) firefox (1) react (7) reactnative (5) collections (1) javascript (7) reactjs (8) yarn (0) adb (1) Solid (2) blade (3) models (1) controllers (0) log (1) html (2) hardware (3) aws (14) Transcribe (2) transcription (1) google (4) ibm (1) nuance (1) PHP Swoole (5) mysql (31) macox (4) flutter (1) symfony (1) cor (1) colors (2) homeOffice (2) jobs (3) imagick (2) ec2 (1) sw (1) websocket (2) markdown (1) ckeditor (1) tecnologia (14) faceapp (1) eloquent (14) query (4) sql (40) ddd (3) nginx (9) apache (4) certbot (1) lets-encrypt (3) debian (12) liquid (1) magento (2) ruby (1) LETSENCRYPT (1) Fibonacci (1) wine (1) transaction (1) pendrive (1) boot (1) usb (1) prf (1) policia (2) federal (1) lucena (1) mongodb (4) paypal (1) payment (1) zend (1) vim (4) ciencia (6) js (1) nosql (1) java (1) JasperReports (1) phpjasper (1) covid19 (1) saude (1) athena (1) cinnamon (1) phpunit (2) binaural (1) mysqli (3) database (42) windows (6) vala (1) json (2) oracle (1) mariadb (4) dev (12) webdev (24) s3 (4) storage (1) kitematic (1) gnome (2) web (2) intel (3) piada (1) cron (2) dba (18) lumen (1) ffmpeg (2) android (2) aplicativo (1) fedora (2) shell (4) bash (3) script (3) lider (1) htm (1) csv (1) dropbox (1) db (3) combustivel (2) haru (1) presenter (1) gasolina (1) MeioAmbiente (1) Grunt (1) biologia (1) programming (22) performance (3) brain (1) smartphones (1) telefonia (1) privacidade (1) opensource (3) microg (1) iode (1) ssh (3) zsh (2) terminal (3) dracula (1) spaceship (1) mac (2) idiomas (1) laptop (2) developer (37) api (5) data (1) matematica (1) seguranca (2) 100DaysOfCode (9) hotfix (1) documentation (1) laravelphp (10) RabbitMQ (3) Elasticsearch (1) redis (2) Raspberry (4) Padrao de design (4) JQuery (1) angularjs (4) Dicas (43) Kubernetes (3) vscode (2) backup (1) angular (3) servers (2) pipelines (1) AppSec (1) DevSecOps (4) rust (1) RustLang (1) Mozilla (1) algoritimo (1) sqlite (1) Passport (2) jwt (5) security (2) translate (1) kube (2) iot (1) politica (2) bolsonaro (1) flow (1) podcast (1) Brasil (1) containers (3) traefik (1) networking (1) host (1) POO (2) microservices (2) bug (1) cqrs (1) arquitetura (3) Architecture (4) sail (3) militar (1) artigo (1) economia (1) forcas armadas (1) ffaa (1) autenticacao (2) autorizacao (2) authentication (4) authorization (3) NoCookies (1) wsl (4) memcached (1) macos (2) unix (2) kali-linux (1) linux-tools (5) apple (1) noticias (2) composer (1) rancher (1) k8s (1) escopos (1) orm (1) jenkins (4) github (5) gitlab (3) queue (1) Passwordless (1) sonarqube (1) phpswoole (1) laraveloctane (1) Swoole (1) Swoole (1) octane (1) Structurizr (1) Diagramas (1) c4 (1) c4-models (1) compactar (1) compression (1) messaging (1) restfull (1) eventdrive (1) services (1) http (1) Monolith (1) microservice (1) historia (1) educacao (1) cavalotroia (1) OOD (0) odd (1) chatgpt (1) openai (3) vicuna (1) llama (1) gpt (1) transformers (1) pytorch (1) tensorflow (1) akitando (1) ia (1) nvidia (1) agi (1) guard (1) multiple_authen (2) rpi (1) auth (1) auth (1) livros (2) ElonMusk (2) Oh My Zsh (1) Manjaro (1) BigLinux (2) ArchLinux (1) Migration (1) Error (1) Monitor (1) Filament (1) LaravelFilament (1) replication (1) phpfpm (1) cache (1) vpn (1) l2tp (1) zorin-os (1) optimization (1) scheduling (1) monitoring (2) linkedin (1) community (1) inteligencia-artificial (2) wsl2 (1) maps (1) API_KEY_GOOGLE_MAPS (1) repmgr (1) altadisponibilidade (1) banco (1) modelagemdedados (1) inteligenciadedados (4) governancadedados (1) bancodedados (2) Observability (1) picpay (1) ecommerce (1) Curisidades (1) Samurai (1) KubeCon (1) GitOps (1) Axios (1) Fetch (1) Deepin (1) vue (4) nuxt (1) PKCE (1) Oauth2 (2) webhook (1) TypeScript (1) tailwind (1) gource (2)

New Articles



Get Latest Updates by Email