Home Backend Development PHP Tutorial Enjoy the powerful combination of PHP and Go [RoadRunner]!

Enjoy the powerful combination of PHP and Go [RoadRunner]!

Nov 12, 2021 pm 02:22 PM
roadrunner

Enjoy the fun of it!


For the past ten years, we have been developing applications for Fortune 500 companies and businesses with 500 users or less. Historically, our engineers have primarily used PHP to develop the backend. But two years ago, some issues arose that seriously affected not only the performance of our products, but also their scalability - so we introduced Golang (Go) into our technology stack.

Almost simultaneously, we discovered that Go not only allowed us to create larger applications, but also improved performance by up to 40x. With it, we are able to extend existing products written in PHP and improve them by combining the best of both languages.

We will tell you through a lot of Go and PHP experience, how to use it to solve real development problems, and how we can turn it into a tool to eliminate some of the problems related to the PHP death model.

Recommended study: "PHP Video Tutorial"

General PHP development environment

is telling how to improve Go Before PHP death model, first understand the regular PHP development environment.

Usually, applications run on nginx and PHP-FPM. nginx handles static requests, while dynamic requests are redirected to PHP-FPM, which executes the PHP code. Maybe you are using Apache and mod_php, but they have the same principle and only slight differences in how they work.

Look at how PHP-FPM executes code. When a request is received, PHP-FPM initializes the PHP subprocess and forwards the request details to it as part of its status (_GET, _POST, _SERVER, etc.).

The state cannot be changed during the execution of the PHP script, so there is only one way to get a new set of input data: clear the process memory and initialize it again.

This performance model has many advantages. You don't need to worry too much about memory consumption, all processes are completely isolated, if one of the processes "dies", it will be automatically recreated and will not affect other processes. However, this approach has drawbacks when you try to scale your application.

Disadvantages and Inefficiencies of a Typical PHP Environment

If you develop professionally in PHP, then you know where to start when creating a new project - choosing a framework . It is a library for dependency injection, ORM, transformations and template methods. Of course, all user-entered data can be conveniently placed in a single object (Symfony / HttpFoundation or PSR-7). These frames are great!

But everything has its price. In any enterprise framework, in order to handle a simple user request or access a database, you have to load at least a few dozen files, create many classes, and parse multiple configurations. But the worst thing is that after each task is completed, you need to reset everything and restart: all the code you just started will become useless, and with its help you will not be able to process another request. Tell this to any programmer writing in other languages ​​- and you'll see the confusion on his face.

For years, PHP engineers have been looking for ways to solve this problem, using lazy loading technology, micro-frames, optimization libraries, caching, etc. But eventually, you still have to abandon the entire application and start over* (Translator's Note: With the emergence of preloading in PHP7.4, this problem will be partially solved) Handle multiple requests?

You can write PHP scripts that last longer than a few minutes (up to hours or days): e.g. Cron jobs, CSV parsers, queue handlers. All of these jobs follow a pattern: they get a task, process it, and then get the next task. The code resides in memory, so additional operations to load frameworks and applications are avoided, saving valuable time.

But developing long-running scripts is not that easy. Any error will kill the process, memory overflow will cause a crash, and F5 cannot be used to debug the program.

The situation has improved since PHP 7: a reliable garbage collector has appeared, it has become easier to handle errors, and extensions to the kernel can avoid memory leaks. Yes, engineers still need to carefully deal with the issue of memory and remembering state in the code (what language allows you not to pay attention to these things?) Of course, in PHP 7, there are not many surprises.

Is it possible to adopt a model of resident PHP scripts for more trivial tasks like handling HTTP requests, thereby eliminating the need to download everything from scratch for every request?

To solve this problem, you first need to implement a server application that can receive HTTP requests and redirect them to the PHP worker one by one instead of killing it every time.

We know that we can write web servers in pure PHP (PHP-PM) or with C extensions (Swoole). While each approach has its merits, neither option worked for us – I wanted something more. We needed more than just a web server - we wanted a solution that would allow us to avoid the problems associated with "restarts" in PHP, while being easily adaptable and extendable for specific applications. That is, we need an application server.

Can Go help solve this problem? We know it can because the language compiles the application into a single binary; it is cross-platform; uses its own parallel processing model (concurrency) and libraries for handling HTTP; and finally, we can put more Open source libraries are integrated into our programs.

Difficulties encountered in merging two programming languages

First, it is necessary to determine how two or more applications communicate with each other.

For example, using Alex Palaestras' go-php library, memory sharing between PHP and Go processes (such as mod_php in Apache) can be achieved. But the functionality of this library limits our use of it to solve problems.

We decided to use another more common approach: structuring the interaction between processes by using sockets / pipelines. This approach has proven its reliability over the past decade and is well optimized at the operating system level.

First, we created a simple binary protocol for exchanging data between processes and handling transmission errors. In its simplest form, this type of protocol resembles a netstring with a fixed-size packet header (17 bytes in our example) that contains information about the packet's type, its size and binary Mask information used to check data integrity.

On the PHP side, we use the pack function, and on the Go side, we use the encoding/binary library.

One protocol is a bit obsolete for us and we added the ability to call net/rpc Go services directly from PHP. This feature helped us a lot in later development because we could easily integrate Go libraries into PHP applications. The results of this work can be seen in another of our open source products, Goridge.

Distribute tasks among multiple PHP Workers

After the interaction mechanism was implemented, we began to think about how to better transfer tasks to the PHP process. When a task arrives, the application server must select an idle worker to execute it. If the worker process terminates with an error or "dies", we clear it and create a new one. If the worker process executes successfully, we return it to the worker pool where it can be used to perform tasks.

Enjoy the powerful combination of PHP and Go [RoadRunner]!

To store the active worker process pool, we use a buffer channel. To clear unexpected "dead" worker processes from the pool, we add a tracking error. and worker process status mechanism.

Finally, we have a working PHP server capable of handling any request rendered in binary form.

In order for our application to start working as a web server, we must choose a reliable PHP standard to handle any incoming HTTP requests. In our case, we simply convert a simple net/http request from Go to PSR-7 format so that it is compatible with most of the PHP frameworks available today.

Since PSR-7 is considered immutable (some would say technically not), developers must write applications that do not, in principle, treat requests as global entities. This is fully consistent with the concept of PHP resident processes. Our final implementation (has not yet received a name) looks like this:

Enjoy the powerful combination of PHP and Go [RoadRunner]!

RoadRunner - High-Performance PHP Application Server

us My first test task was an API backend on which I periodically experienced unpredictable bursts of requests (more frequently than usual). While nginx capabilities are sufficient in most cases, we often encounter 502 errors due to the inability to quickly balance the system under expected load increases.

To solve this problem, we deployed our first PHP/Go application server in early 2018. And achieved amazing results immediately! Not only did we completely eliminate 502 errors, we also reduced the number of servers by two-thirds, saving a ton of money and solving a headache for engineers and product managers.

In the middle of the year, we improved our solution and released it on GitHub under the MIT license under the name RoadRunner, thus emphasizing its amazing speed and efficiency.

How RoadRunner can improve your development stack

The use of RoadRunner allows us to use middleware net/http on the Go side and even do JWT before the request goes into PHP Authentication, and handling of WebSocket and global aggregate state in Prometheus.

Thanks to the built-in RPC, you can open the API of any Go library in PHP without writing an extension package. What's more, with RoadRunner, you can deploy new servers that are different from HTTP. Examples include running AWS Lambda processors in PHP, creating powerful queue selectors, and even adding gRPC to our applications.

Using both PHP and Go, the solution has been steadily improved, improving application performance by 40x in some tests, improving debugging tools, enabling integration with the Symfony framework, and adding Support for HTTPS, HTTP/2, plugins and PSR-17.

Conclusion

Some people are still bound by the outdated concept of PHP, thinking that PHP is a slow, cumbersome language suitable only for writing plugins under WordPress. These people even go so far as to say that PHP has a limitation: when the application gets large enough, you have to choose a more "mature" language and rewrite the code base accumulated over the years.

To these questions, my answer is: think again. We believe it's just you who has set some limits on PHP. You can spend your life moving from one language to another, trying to find the one that perfectly matches your needs, or you can treat languages ​​as tools. With a language like PHP, its supposed flaws may be the real reason for its success. If you combine it with another language like Go, you create a more powerful product than just using one language.

After using Go and PHP interchangeably, we can say that we like them very much. We are not going to sacrifice one for the other, but instead we are going to find ways to get more out of this dual architecture.

Original address: https://sudonull.com/post/6470-RoadRunne...

Translation address: https://learnku.com/php/t/61733

The above is the detailed content of Enjoy the powerful combination of PHP and Go [RoadRunner]!. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles