<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tifeit on Medium]]></title>
        <description><![CDATA[Stories by Tifeit on Medium]]></description>
        <link>https://medium.com/@tifeit?source=rss-6fbb6386efb3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ud_7R6nH52mazMNv</url>
            <title>Stories by Tifeit on Medium</title>
            <link>https://medium.com/@tifeit?source=rss-6fbb6386efb3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:02:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tifeit/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[PHP Fibers: Simplifying Async Code and Speeding Up Development]]></title>
            <link>https://medium.com/manychat-engineering/php-fibers-simplifying-async-code-and-speeding-up-development-519d40ace2d9?source=rss-6fbb6386efb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/519d40ace2d9</guid>
            <category><![CDATA[php-developers]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Tifeit]]></dc:creator>
            <pubDate>Thu, 16 Apr 2026 12:54:48 GMT</pubDate>
            <atom:updated>2026-04-23T15:45:19.061Z</atom:updated>
            <content:encoded><![CDATA[<h3>PHP Fibers: simplifying async code and speeding up development</h3><h4>How serialization overhead, a surprise OpenSSL upgrade, and idle workers pushed us toward PHP 8.1 Fibers, and what changed when we did.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNk_-4vT2EkPLLrIsckpCg.png" /></figure><p>I’m <a href="https://www.linkedin.com/in/maxim-fomichev/">Max</a>, Infrastructure Team Lead at <a href="https://careers.manychat.com/team/engineering">Manychat</a>. This is the next part of our PHP series.</p><p><a href="https://medium.com/manychat-engineering/simulating-%D1%81oncurrent-requests-how-we-achieved-high-performance-http-in-php-without-threads-c3a94bae6c3b">In the previous article</a>, we built concurrent HTTP requests in PHP without threads — using curl_multi_exec to let a single worker handle multiple external calls at once. It worked. Then our AI features expanded, external calls multiplied, and the model started buckling under its own complexity.</p><p>This article is about what we did next: PHP 8.1 Fibers, and how they changed the way our workers process payloads.</p><h3><strong>What was exactly wrong with Concurrent Requests?</strong></h3><p>The curl_multi_exec architecture came with a steep price. To make pseudo-concurrency work, we had to explicitly serialize and deserialize requests, responses and exceptions at every async boundary. That meant a significant refactor, new internal tooling, and conventions developers had to follow just to write new code correctly. As AI features grew in scope and number, the cognitive overhead became impossible to ignore.</p><p><strong>Error Handling complexity.</strong> Handling exceptions, timeouts, and corner cases got increasingly painful. Every new scenario — retries, network failures, edge cases — required explicit handling, and since context had to survive serialization boundaries, each one added another layer of boilerplate</p><p><strong>Scattered Context. </strong>The hardest part wasn’t writing the code — it was reading it afterward. Business logic was split across serialization points: some state lived before the async boundary, some after. Tracing a single payload through the system meant mentally jumping between the sync worker, the async queue, and back. Code reviews became genuinely hard.</p><p><strong>Testing Overhead. </strong>Testing also became more complicated. Tests had to account for the full serialization/deserialization chain. Even a simple mock meant verifying multiple intermediate steps instead of a single function call.</p><p><strong>Idle Workers.</strong> Before Fibers, Meta API calls stayed synchronous — serializing and deserializing state at the point of the call would have required even more refactoring, so we just didn’t touch it. The average response time is around 250ms. Not slow enough to panic over — but not fast enough to ignore at Manychat’s scale. During that time, the worker just sat there.</p><p>Bottom line: the code was getting harder to read, harder to test, and harder to extend. Development was slowing down — and everyone felt it.</p><h3>Three more things that made us rethink</h3><p>While we were sitting with those outcomes, three things happened in parallel:</p><p><strong>1. We solved our memory problem via PCNTL fork.</strong> By using pcntl_fork() to spawn workers, we enabled <a href="https://medium.com/manychat-engineering/slashing-php-cli-memory-consumption-techniques-for-high-performance-apps-b89a6caf1406">OPcache sharing and Linux copy-on-write</a> — significantly reducing the memory footprint of each worker. In theory, we could almost stop worrying about idle workers; they were no longer consuming nearly as much memory. But they still consumed network connections. So the problem wasn’t fully gone.</p><p><strong>2. Ubuntu upgrade revealed a new bottleneck.</strong> We migrated from Ubuntu 20.04 to the new LTS and CPU load jumped 10%. Nothing in our code had changed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4KVtHAE-0MgCZlQnnzyQQ.png" /></figure><p>We dug in. The problem was OpenSSL 3.0 — shipped with the new Ubuntu — which made SSL handshakes significantly more expensive. OpenSSL’s root certificate store on Linux is one large concatenated file — and the new version introduced mutex-style locking when iterating through it. Even Facebook’s own optimization of using a single root certificate file didn’t fully absorb the hit.</p><p>The cause was our still-synchronous calls to the Meta API. Each payload opened a new TCP connection. At Manychat’s scale, that added up fast — and that 10% CPU overhead became the trigger for the next step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J7ukd5COi_A8HnoO3qDPrw.png" /></figure><p>So Anton Gorin, Chief Architect of Manychat, and I decided to combine our existing async worker — built on curl_multi_exec — with Fibers introduced in PHP 8.1.</p><h3><strong>What is a Fiber?</strong></h3><p>Fibers are a low-level mechanism for cooperative multitasking: pause execution at any point, resume it later from exactly the same spot, without — no threads, no processes.</p><pre>&lt;?php<br><br>$fiber = new Fiber(function() {<br><br>    echo &quot;Suspending…\n&quot;;<br><br>    $last = Fiber::suspend(16);<br><br>    echo &quot;Resuming with last value {$last}\n&quot;;<br><br>});<br><br>$last = $fiber-&gt;start();<br><br>echo &quot;Suspended with last value {$last}\n&quot;;<br><br>$fiber-&gt;resume(42);</pre><p>Suspended with last value 16;<br>Resuming with last value 42.</p><p>Unlike true multithreading, Fibers run within a single OS thread and don’t execute in parallel. Instead, they switch context explicitly via Fiber::suspend()<strong> </strong>and resume. That makes them well-suited for I/O-bound work: yield control while waiting for a response, do something else, come back when it’s ready.</p><h3>The new payload processing flow with fibers</h3><p>Previously, every HTTP request meant serialize, hand off, wait, deserialize, restore. Here’s what that looked like in practice:</p><ol><li>The sync worker picks a payload from the queue and starts processing it.</li><li>When execution hits an external HTTP call, the worker serializes the request along with the current business-logic state and writes it to the async task queue.</li><li>The async worker reads from the queue, deserializes multiple requests, and executes them concurrently via curl_multi_exec.</li><li>When a response is ready, the async worker serializes it together with the updated state and writes it back to the sync task queue.</li><li>A sync worker picks it up, deserializes everything, restores business-logic state, and continues from where it left off.</li></ol><p>This is the diagram of this very complex flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*chFJ5NjiHKnFqmu0V-Bozw.png" /></figure><p>With Fibers, the logic was simpler:</p><ol><li>The worker starts a fiber and begins processing a payload.</li><li>When execution hits an external HTTP call — Meta API, LLM, whatever — the fiber suspends, returning the request that needs to be executed.</li><li>The workflow is passed to Guzzle request loop, which executes the request and if there is no response ready with data, the worker immediately starts the next fiber and begins processing another payload.</li><li>If there is any response available in Guzzle loop, the corresponding fiber resumes from exactly where it stopped.</li><li>If that fiber produces another request, it suspends again and goes back into the loop.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*QqwAnEpXIqwGwaClPz0BlA.png" /></figure><p>Within a single worker, multiple fibers may be suspended, waiting for the response to come simultaneously and one actively executed at the same moment of time, depending on configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ytx-8JI2gPYkRJJw3tf5rQ.png" /></figure><h3><strong>What are the wins? And one trade-off</strong></h3><p><strong>More cases to make async — like API calls via Meta SDK</strong><br>Before Fibers, making Meta API calls async meant serializing and deserializing business state around every call. We just didn’t bother. With Fibers, we added a suspend point and called it done. A single Meta API call takes ~250ms — small individually, but Manychat makes billions of them. The compound effect is massive.</p><p><strong>Savings on resources: CPU and connections<br></strong>We rewrote part of the Facebook SDK to reuse connections. One HTTP/2 connection per worker, multiplexed across multiple requests. No repeated TCP handshakes. No OpenSSL overhead per request.</p><p>CPU usage returned to previous levels.</p><p><strong>Asynchronous Sleep<br></strong>Sometimes we need to wait — for example, before retrying after an HTTP 500, or to ensure correct message order before sending the next one. A regular sleep() blocks the entire process. If API errors spike and retry logic misbehaves, you’ve put the whole server to sleep.</p><p>With fibers, we can implement an asynchronous sleep. A specific fiber sleeps for a defined interval while the worker continues processing other fibers.</p><p><strong>Simpler code<br></strong>No more serialization. No more deserialization. Business context stays where it belongs — inside the fiber. Developers don’t even need to know they’re inside a fiber. The code looks like regular PHP — because for all practical purposes, it is.<br>In practice: instead of pushing a request back into the queue on retry, you just do an asynchronous sleep.</p><p><strong>Simpler tests<br></strong>Testing async code with Guzzle required enormous effort — the full serialization/deserialization chain had to be accounted for, and even a simple mock meant verifying multiple intermediate steps. With Fibers, the code reads linearly and tests follow naturally. That said, some things are hard to reproduce outside production — but in practice, if it worked in dev, it worked in prod.</p><p><strong>One trade-off: blast radius<br></strong>Fibers came with one compromise. Previously, our guiding principle was “better to crash hard than silently suffer from error” — non-fatal warning, log it, terminate the worker. One payload lost, clean slate.</p><p>With multiple fibers suspended simultaneously, that no longer works. Terminating the worker interrupts all in-flight payloads at once. We redesigned exception handling so that catchable errors terminate only the affected fiber while the worker continues processing others. Fatal errors — like out-of-memory — still take down the entire process. If five payloads are in flight, all five are lost.</p><p>This meant working through existing technical debt and committing to treating critical errors as critical — actually reacting to them, not letting them slide. Migrating to PHP 8.5 helped: it introduced stack traces for fatal errors, which made them significantly easier to diagnose and fix.</p><h3><strong>Could we have done less work?</strong></h3><p>Probably. Revolt, ReactPHP, AMPHP and OpenSwoole all solve similar problems and would have saved us from building a custom event loop. AMPHP in particular goes further — async SQL queries, not just HTTP, and battle-tested error handling out of the box.</p><p>But we didn’t start from a blank slate. We already had a Guzzle-based event loop from the earlier proof of concept, and adding Fibers on top was the natural next step. Starting over today, we’d look at Revolt first and skip the custom event loop entirely.</p><p>What we’d keep regardless: developers don’t need to know they’re inside a fiber. The wrapping happens under the hood. That was a deliberate choice — and it’s the part that matters most in a large codebase with many contributors.</p><p><em>This article is based on a talk I gave at </em><a href="https://www.meetup.com/barcelona-php-talks"><em>PHP Talks #7</em></a><em>. If you’d rather watch than read — the video is </em><a href="https://www.youtube.com/watch?v=in_XaE0T5IY"><em>here</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=519d40ace2d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/manychat-engineering/php-fibers-simplifying-async-code-and-speeding-up-development-519d40ace2d9">PHP Fibers: Simplifying Async Code and Speeding Up Development</a> was originally published in <a href="https://medium.com/manychat-engineering">Manychat Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Slashing PHP CLI memory consumption: techniques for high-performance apps]]></title>
            <link>https://medium.com/manychat-engineering/slashing-php-cli-memory-consumption-techniques-for-high-performance-apps-b89a6caf1406?source=rss-6fbb6386efb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b89a6caf1406</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Tifeit]]></dc:creator>
            <pubDate>Thu, 12 Feb 2026 11:54:03 GMT</pubDate>
            <atom:updated>2026-04-23T15:56:39.694Z</atom:updated>
            <content:encoded><![CDATA[<h4>PHP CLI workers helped us scale, until memory became the bottleneck. Here’s how we fixed it with fork and copy-on-write.</h4><p>I am <a href="https://www.linkedin.com/in/maxim-fomichev/">Max</a>, and I’m the Infrastructure Team Lead at <a href="https://careers.manychat.com/team/engineering">Manyсhat</a>. One of my main responsibilities is optimizing the performance of our application. This is another story in a series describing how <a href="https://medium.com/manychat-engineering/how-we-tamed-php-to-handle-over-25-000-webhooks-per-second-ce860cb59084">we pushed our PHP application beyond its limits</a>. Before I go on, here’s a brief recap of the previous episodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vXMqzpRB_DBEraReluFDXw.png" /></figure><p>When Manyсhat had to handle around 10K RPS during peak periods, generated by more than 7 billion messages per month, we hit a growth limit where simply scaling the infrastructure stopped working. With <strong>PHP-FPM</strong>, the level of concurrency we could handle was directly tied to the number of worker processes. On every request — even a simple one — PHP-FPM had to initialize opcache, the framework, and autoloading just to execute minimal business logic, such as marking a message as delivered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RC-3GZLPaRFyvtE1PtfNiw.png" /></figure><p>Eventually, we offloaded more processing to <strong>NGINX with Lua</strong>. Lua was used to process incoming webhooks, determine their type, and push them into the appropriate Redis queues. Command-line PHP (CLI) workers then processed these queues and handled the webhooks based on their type. This allowed us to initialize the framework once, process tasks continuously, and absorb traffic spikes by buffering the load instead of trying to handle everything at once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oe1Q39orvE7hbAFns_5ysw.png" /></figure><p>That architectural shift solved our throughput problems (the full story is covered <a href="https://medium.com/manychat-engineering/simulating-%D1%81oncurrent-requests-how-we-achieved-high-performance-http-in-php-without-threads-c3a94bae6c3b">in this article</a>). Webhooks were flowing through queues, workers were stable, and performance was no longer the main concern. But once the system settled into this model, a different kind of problem started to surface.</p><p><strong>Goodbye, Shared Memory</strong></p><p>With PHP-FPM, memory usage has always been relatively predictable. Opcache was shared across workers, but there was also a less well-known mechanism at play: internal string interning. PHP stores identical strings only once and references them from multiple places instead of duplicating them in memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DpT_pHUkf2xsBX5AoIXhEA.jpeg" /><figcaption><em>Reference mechanism for memory strings in PHP.</em><br><em>Source: </em><a href="https://blog.blackfire.io/cache-information-upgrade.html"><em>https://blog.blackfire.io/cache-information-upgrade.html</em></a></figcaption></figure><p>We use <a href="https://getcomposer.org/doc/articles/autoloader-optimization.md">classmap authoritative for composer</a> to optimize autoloading (for SDKs such as AWS, Google, and other third-party libraries). In our case those internal autoload strings took up 4 MB of memory. And this sharing mechanism saved us a significant amount of it.</p><p>We lost that advantage when we moved to PHP CLI workers. Each worker had to maintain its own opcache and internal strings — nothing was shared. You can imagine what happened next: we started hitting memory limits on our servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PnijcZTv-gnZqD6-6bcPjA.png" /></figure><p>The situation became even worse after we introduced LLMs and other external API calls. When a worker calls the ChatGPT API and waits for a response, it does nothing but wait on the network while still occupying memory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X4jsLVbwHxGCVF5ddct-AQ.png" /></figure><p>As a result, overall memory consumption increased even further.</p><p>Opcache was designed primarily for the PHP-FPM model, where each request can reuse compiled opcodes from shared memory. We still used opcache for command-line workers to avoid recompiling files, but the key problem remained: opcache is not shared between CLI workers.</p><p><strong>There Is No Memory Sharing at All in PHP CLI</strong></p><p>I decided to dig deeper to find out whether there was a way to force command-line workers to share anything at all. I started by looking into how PHP supports shared memory. In principle, it’s quite simple: you obtain an IPC key from a common file and use that key to attach to a shared memory segment of a given size. One process can write data into this shared memory, and another process can read it back.</p><p>The file itself is just a coordination mechanism. It doesn’t contain the data — it only serves as a file descriptor that allows multiple processes to attach to the same memory segment. This is the example how to attach to a shared memory segment:</p><pre>&lt;?php<br>$fileName = &#39;/tmp/file&#39;;<br>$projectId = &#39;A&#39;;<br>touch($fileName);<br>$ipcKey = ftok($fileName, $projectId);<br>$shm = shm_attach($ipcKey, 1024*1024);<br>shm_put_var($shm, 42, &#39;serializableValue&#39;);<br>$myKey = shm_get_var($shm, 42);<br>echo $myKey;</pre><p>With this in mind, I dug into the PHP source code to see how PHP-FPM handles memory sharing. I found a function that also opens a file, but what surprised me was that the file is created during memory initialization, given a unique name, and deleted immediately afterward.</p><p>When I looked more closely at how memory is actually allocated, it turned out that this file doesn’t participate in memory sharing at all.</p><p>zend_shared_alloc.c</p><pre>snprintf(lockfile_name, sizeof(lockfile_name), &quot;%s/%sXXXXXX&quot;, lockfile_path, SEM_FILENAME_PREFIX);<br>lock_file = mkstemp(lockfile_name); //UNIQUE RANDOM FILE NAME<br>...<br>unlink(lockfile_name); //AND THE FILE IS DELETED AFTER CREATION</pre><p>shared_alloc_shm.c</p><pre>shmget_flags = IPC_CREAT|SHM_R|SHM_W|IPC_EXCL;<br>...<br> first_segment_id = shmget(first_segment_key, allocate_size, shmget_flags);</pre><p>It turned out that my initial assumption was completely wrong. PHP-FPM works in a completely different way. It doesn’t spawn workers that then attach to shared memory. Instead, the master process performs all the initialization and then forks the workers. The child PHP-FPM processes inherit the shared memory address space, along with lock files that protect memory segments when multiple processes attempt to write to them simultaneously.</p><p>PHP CLI has a built-in function, pcntl_fork, which does essentially the same thing: it forks the current PHP process into two. <br>So I decided to run a quick test. In a single PHP CLI process, I compiled the PHP files and then forked child processes.</p><pre>&lt;?php<br>$pid1 = pcntl_fork();<br>if ($pid1 === 0) {<br>    echo &#39;[Child 1]: &#39; . (opcache_is_script_cached(&#39;test.php&#39;) ? &#39;CACHED&#39; : &#39;NOT CACHED&#39;) . PHP_EOL;<br>    opcache_compile_file(&#39;test.php&#39;);<br>    echo &#39;[Child 1]: &#39; . (opcache_is_script_cached(&#39;test.php&#39;) ? &#39;CACHED&#39; : &#39;NOT CACHED&#39;) . PHP_EOL;<br>    exit(0);<br>}<br>pcntl_waitpid($pid1, $status);<br>$pid2 = pcntl_fork();<br>if ($pid2 === 0) {<br>    echo &#39;[Child 2]: &#39; . (opcache_is_script_cached(&#39;test.php&#39;) ? &#39;CACHED&#39; : &#39;NOT CACHED&#39;) . PHP_EOL;<br>    exit(0);<br>}</pre><pre>% php -dopcache.enable=1 -dopcache.enable_cli=1 -dopcache.file_cache=&quot;&quot; -f opcache.php<br>[Child 1]: NOT CACHED<br>[Child 1]: CACHED<br>[Child 2]: CACHED</pre><p>Those processes were able to share opcache between themselves.<br>I ran more tests on real code in our development environment, and everything worked well. Enthusiastic about the results, I convinced my colleagues to try this approach in production.</p><p><strong>And … We Got Segfaults</strong></p><p>Not everywhere, though. We’re careful with rollouts, but a small portion of users was affected. The issue appeared sporadically under high concurrency and was nearly impossible to reproduce in the development environment without realistic load.</p><p>We analyzed the segmentation fault dumps, and the only reasonable hypothesis was that opcache got corrupted at the file level. Some processes were writing to opcache while others were reading from it, and file locking didn’t work correctly. There are configuration options to lock files, but for some reason, they didn’t work well in our case.</p><p>Based on the segmentation faults, opcache corruption was the most likely cause.</p><p>We decided to warm up all PHP files once during deployment and never recompile them again in command-line workers:</p><pre>&lt;?php<br>#run with php -dopcache.max_accelerated_files=50000 -dopcache.memory_consumption=1024 -dopcache.interned_strings_buffer=512<br><br><br>$directory = new RecursiveDirectoryIterator($this-&gt;backDir);<br>$iterator = new \RecursiveIteratorIterator($directory);<br><br><br>foreach ($iterator as $file) {<br>  $file = (string)$file;<br>  if (str_ends_with($file, &#39;.php&#39;)) {<br>       if (opcache_is_script_cached($file)) {<br>            $this-&gt;alreadyCached++;<br>       } else {<br>            if (@opcache_compile_file($file)) {<br>                $this-&gt;cachedFiles++;<br>           } else {<br>               $this-&gt;failedFiles[] = &quot;$file&quot;;<br>               $this-&gt;failed++;<br>           }<br>        }<br> }<br> $this-&gt;count++;<br>}</pre><p>The code was fairly simple. We iterated through all directories in our bundle, found all PHP files, and compiled them.</p><p>If you plan to do something like this, don’t forget to run the warmer with proper limits: <br>- maximum accelerated files, <br>- memory consumption limits, <br>- and especially the internal string buffer size. <br>If you try to compile, say, 50,000 files at once, you’ll quickly run out of memory in the internal string buffers. So make sure those limits are high enough during deployment preparation.</p><p>This solved the segmentation fault problem.</p><p><strong>Redis Went Crazy</strong></p><p>However, Redis started behaving insanely, returning incorrect values or complete garbage. The number of Redis connections grew very quickly.</p><p>It turned out that when we fork a child process, it inherits all file descriptors from the parent. In Linux, everything is a file — including network connections. The child processes inherited Redis connection descriptors and started using the same connections in parallel. As a result, responses intended for one worker were returned to another.</p><p>Even if we destructed Redis objects before forking, we still had a problem. We use Redis with a persistent connection pool. When a Redis object is destructed, the connection is returned to the pool to be reused later. But in the case of forking, something went wrong: those connections stayed open but were never reused. So workers kept opening new connections.</p><p><strong>The Solution</strong></p><p>We forcefully closed all connections before forking. The child processes then opened and used their own connections.</p><p>This applies not only to pcntl_fork. Even if you use exec, shell_exec, or spawn a Python process or a Bash script, file descriptors will be inherited by the shell or the binary you invoke. Even if you fork with nohup and exit the parent process, the child process will keep those connections alive.</p><p>This wasn’t obvious to me at first, but if you actively use exec, shell_exec, or spawn other workers, make sure you don’t have any open files or network connections — databases, Redis, or anything else — otherwise they will remain open until the child process exits.</p><p>After that, Redis started behaving normally again, and everything else worked as expected.</p><p><strong>The Results (Even Better Than PHP-FPM)</strong></p><p>Here are the results. This chart compares memory consumption for PHP-FPM, command-line workers without forking, and command-line workers with forking. The forked command-line workers performed even better than PHP-FPM:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-F4wAr_JQjHZJR3WD4d9Q.png" /></figure><p>One reason is that we use FPM as a general-purpose server for everything. All endpoints in our application touch different parts of the codebase, so everything ends up in opcache, making it quite large. <br>With <strong>command-line workers, we made them dedicated</strong>. They work only with specific parts of the code, so they don’t need as much opcache.</p><p>There’s also a less obvious factor that saved us even more memory than FPM: <strong>copy-on-write (COW) in Linux</strong>.</p><p>When forking, Linux copies the original process, and assigns it a different virtual address. But under the hood it points to the same physical memory. When a write occurs, only the memory page (the default in Linux is 4 KB), that contains the overwritten part, takes additional memory. If you make any change, the unmodified part stays intact and only the modified pages are duplicated. This saves a lot of memory.</p><p>So unchanged memory stays shared, and only modified parts are duplicated. We call pcntl_fork after the framework is initialized. Everything initialized before the fork stays shared unless it is overwritten. All framework memory that isn’t modified is shared among workers.</p><p>It’s relatively easy to find out how much memory we save. Modern Linux kernels expose this information via special /proc files. This is an example of how to view the details of process memory utilization. Here are some of the numbers we obtained:</p><p>#cat /proc/3506906/smaps_rollup //one of 54 workers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*32hYE2CqnNRjuRsbo692qA.png" /></figure><p>I won’t go into details of every line, but I want to highlight the lines with <em>Anonymous </em>and <em>Pss_Anon</em> memory consumption.<br><em>Anonymous </em>is the working memory, if CoW was not shared, but OPcache was (i.e. OPcache is not included here).<br><em>Pss_Anon </em>is actual Anonymous consumption, because of proportional CoW sharing.<br>So instead of using 7632 kB (<em>Anonymous</em>) the process is using only 997 kB (<em>PSS_Anon</em>). <br>Pretty impressive, huh?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b89a6caf1406" width="1" height="1" alt=""><hr><p><a href="https://medium.com/manychat-engineering/slashing-php-cli-memory-consumption-techniques-for-high-performance-apps-b89a6caf1406">Slashing PHP CLI memory consumption: techniques for high-performance apps</a> was originally published in <a href="https://medium.com/manychat-engineering">Manychat Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simulating Сoncurrent Requests: How We Achieved High-Performance HTTP in PHP Without Threads]]></title>
            <link>https://medium.com/manychat-engineering/simulating-%D1%81oncurrent-requests-how-we-achieved-high-performance-http-in-php-without-threads-c3a94bae6c3b?source=rss-6fbb6386efb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3a94bae6c3b</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Tifeit]]></dc:creator>
            <pubDate>Mon, 15 Dec 2025 12:46:30 GMT</pubDate>
            <atom:updated>2025-12-15T12:53:54.709Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro</h3><p>Your PHP app talks to multiple APIs, but its single-threaded nature keeps users waiting. What if you could handle thousands of concurrent requests — without threads, extra processes, or switching languages?</p><p>I’m Max Fomichev, an Infrastructure Engineer at <strong>Manychat</strong>, and part of my role is optimizing application performance. Today, I’ll share how we overcame the challenges of handling high-concurrency HTTP requests in a PHP application.</p><p>And of course, everyone’s favorite part — code examples!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRUPQHfiJKBpNKt87bUSpA.png" /></figure><p>With Manychat, our customers can create interactive flows to communicate with their subscribers. A conversation can start in many ways: a user scans a QR code, clicks an ad or a link in a social media post, or simply sends a WhatsApp message to the business.</p><p>Let’s take a toy store’s WhatsApp account as an example. A subscriber wants to buy a <strong>Blue Elephant</strong>, and this message becomes the entry point that triggers the entire flow. In our scenario, we instruct a Manychat AI agent to ask the customer about their color preference — pink or blue — and then proceed with creating the order and shipping the correct toy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WSTqA_Hz12NnafuT1jz9JQ.jpeg" /></figure><p>At first glance, this flow looks simple and straightforward.</p><p>In reality, of course, things are usually more complex and often involve a customer’s proprietary systems, like internal web services, CRMs, payment gateways, and so on.</p><p>All of these systems send and receive HTTP requests that Manychat must process quickly and reliably.</p><p>But for the sake of clarity, we’ll stick with the Blue Elephant example.</p><h3>Single thread suck</h3><p>As you probably know, the core problem with HTTP requests in PHP is its <strong>synchronous </strong>nature. There’s only a single thread, and it executes everything step by step. First, you prepare the request — URL, method, headers, body. Then you establish the connection, the SSL handshake, send the request, <strong>wait for the server’s response</strong>, download it, and only after that can you start processing the response.</p><p>This will take forever, and it’s exactly why we don’t want PHP handling all of this work on its own.</p><h3>Making it a bit faster: nginx + PHP-FPM</h3><p>For example, by placing <strong>Nginx</strong> in front of PHP-FPM, we can offload from PHP the heavy work of establishing parallel TCP/SSL connections with clients. Nginx also buffers the incoming request body before passing it to PHP and buffers the outgoing response before sending it back to the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mm2MbWuqTKFfyz9JpVS9gA.jpeg" /><figcaption><em>the nginx + PHP-FPM setup</em></figcaption></figure><p>This approach worked well for us until Manychat began growing exponentially and started handling 10K RPS from 3 billion messages per month.<br>With the nginx + PHP-FPM setup, we would need the same amount of PHP workers to handle all those concurrent requests.</p><h3>Making it even faster: nginx + lua</h3><p>After going through several iterations (read more in <a href="https://medium.com/manychat-engineering/how-we-tamed-php-to-handle-over-25-000-webhooks-per-second-ce860cb59084"><strong>this article</strong></a>), we decided to offload even more processing to nginx, using Lua, its embedded language.</p><p>Simply speaking, we use Lua to process incoming webhooks, determine their type, and push them into the appropriate Redis queue. Then, command-line PHP workers process these queues and handle the webhooks depending on their type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZF2ytJj2dcb6SqKsuCkKw.jpeg" /><figcaption><em>nginx + lua setup</em></figcaption></figure><p>This approach, first of all, saves resources on PHP initialization. Unlike PHP-FPM, a command-line worker can initialize the framework, the “autoloader,” and all other dependencies right when the worker starts and serves the first request. After that, all classes are autoloaded and precompiled in memory, which allows the next requests to be processed much faster.</p><p>Additionally, this setup handles sudden bandwidth spikes far better. When there are too many concurrent requests, we can simply place them into a queue and process them as soon as PHP workers become available. In essence, this solves the first part of the problem.</p><p>However, we still need to send a request to the LLM model that powers Manychat AI. And that means going through the same slow steps in PHP: establishing the connection, sending the request, and, most critically, then <strong><em>waaaaait</em></strong> for the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LbSZkwlYaUxK_1cH4KdVrA.jpeg" /><figcaption><em>AI-step in detail</em></figcaption></figure><p>As you might know, AI models can be a bit unpredictable: they may respond in a second or, in the worst case, take several minutes, depending on the prompt size in tokens.</p><p>If many concurrent requests are sent to the AI model, you can end up with all PHP workers effectively <strong>paused</strong>, idling while they <strong>WAIT</strong> for the response, yet still consuming memory and, even worse, holding database and cache connections, logger connections, and other resources required to keep it all running.</p><p>So our infrastructure engineers at Manychat began thinking about how we could once again rebalance the load and offload this processing from PHP to something else. We started testing a new workflow: instead of making the request on the PHP side, PHP only prepares it, serializes it, and includes the necessary business-logic state (such as information about the customer). The task is then handed off to a more specialized worker, designed with parallelism in mind and capable of running multiple requests in parallel. This <strong>asynchronous worker </strong>can accept requests from several basic <strong>synchronous workers</strong> at once, serve them, serialize the response, and send it back to the pool of sync workers. Those workers then deserialize the response and continue processing the AI model’s output before moving on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Da2YQzJNmiHmguuK7Ut_w.jpeg" /><figcaption><em>Sync-Async-workers flow</em></figcaption></figure><h3>Let’s go, GO!</h3><p>What would be the most suitable programming language for making rapid, concurrent requests in this asynchronous worker? Manychat developers considered several options: <strong>Kotlin</strong>, a popular Java-based language from JetBrains; <strong>Rust</strong>; and even more exotic choices like <strong>Zig</strong>.</p><p>Eventually, we decided to try <strong>Go</strong>, with its coroutines — extremely fast, widely adopted across the industry, and ranked among the top 10 most popular programming languages.</p><p>It wasn’t a quick and simple decision. One of the <a href="https://medium.com/manychat-engineering/care-intensely-basic-principles-that-shape-our-product-engineering-3090e51ef107"><strong>fundamental principles</strong></a><strong> </strong>of Manychat engineering is “Evolution beats Revolution,” “thread carefully,” or maybe “Oldies but Goldies.”</p><p>In practice, this means we try to avoid radical changes to our production stack, especially anything that would require significantly re-writing our codebase. At our level of hyper-efficiency and optimization, all internal components of the Manychat backend are deeply interconnected. Introducing an entirely different ecosystem is no small feat. We would need to deploy the new code in a way that works smoothly with everything else, ensure compatibility across countless internal systems, and integrate it cleanly into the existing Manychat backend architecture.</p><p><strong>Proof of Concept with Guzzle</strong></p><p>Our response to the challenge, as always, was to begin with a Proof of Concept (PoC). Before introducing Go into the Manychat production stack, we needed to verify that we could reliably serialize and deserialize our business logic using PHP alone.</p><p>For that, we have chosen the <strong>Guzzle </strong>library, which we were already using, as a <strong>pseudo-parallel worker</strong>.<strong><br></strong>Initially, we just wanted Guzzle to execute requests sequentially:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6e04XtkLUYj9iPv8_DeXg.jpeg" /></figure><p>However, we knew that Guzzle provides an asynchronous interface that mimics the synchronous one. It still runs in a single thread, but it allows concurrent requests to be processed (establishing a connection, performing an SSL handshake, and so on), thanks to the underlying libcurl multi_* functionality.</p><p>Another side benefit was the opportunity to reuse existing connections. As you can imagine, requests to the same ChatGPT model go to the same URL, which allows us to reuse the already-established connection.<br> And because it’s an HTTP/2 connection, we can take advantage of HTTP/2 multiplexing — sending multiple requests over a single TCP connection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nPPL_-OsbU-o_vmfulbEzw.jpeg" /></figure><p>PoC worked exceptionally well. Here are some numbers we got:</p><p>1. <strong>Sub-milliseconds</strong> to switch between different types of workers vs. waiting for <strong>seconds</strong> or even minutes for the LLM response.<br>2. <strong>10k+ of Sync workers</strong> could be handled by only <strong>~300 Async workers</strong>. In fact, this number is mostly constrained by the minimum number of workers we run per server. Most of the time, these async workers are idle, simply waiting to serve incoming requests.<br>3. These <strong>300 Async workers</strong> handle <strong>10k+ of external “async” requests per minute</strong>.<br>4. We process <strong>100k+</strong> <strong>of incoming requests per minute</strong>, for which we still generate <strong>100k+ of outgoing sync requests</strong>.</p><p>All of this leads to a simple conclusion:<br>The key optimization wasn’t introducing Go or any other new language. It was <strong>rethinking our business logic</strong>, particularly how we send HTTP requests to external systems (such as Meta) when delivering responses to subscribers.<br>And that became our next step.</p><h3>Serializing Business Logic</h3><p>The biggest technical challenge was serializing our business logic.<br>Using PHP’s default serialize() function can lead to a number of issues, such as:</p><ul><li>Objects nested inside other objects that contain <strong>unserializable resources.</strong></li><li>Serialized data becoming <strong>stale very quickly</strong> (for example, database records).</li></ul><p>So for the business-logic part, we decided to implement a completely custom serializer by extending PHP’s JsonSerializable interface. Our serializer and deserializer include custom wake-up procedures that fetch fresh data from the database (or from an intermediate cache) to ensure that everything works correctly from a business-logic perspective.</p><pre>class AsyncRequestHandymanJob extends AbstractHandymanJob<br>{<br>    public function __construct(<br>        public string $url,<br>        public string $method,<br>        public array $headers,<br>        public ?string $payload,<br>        public array $context = []<br>    ) {<br>    }<br><br>class SyncResumeHMJob extends AbstractHandymanJob<br>{<br><br>    public function __construct(<br>        public ?string $responseStr,<br>        public ?array $exceptionArray = null,<br>        public array $context = [],<br>    ) {<br>    }<br><br>    public function process(): void<br>    {<br>        $response = $this-&gt;getResponse();<br>        $exception = $this-&gt;getException();<br><br>        $businessContext = BusinessContext::jsonDeserialize($this-&gt;context);<br><br>        $businessContext-&gt;run($response, $exception);<br>    }</pre><p>Another reason we chose the JsonSerializable approach was that native PHP serialization stores the entire object structure as is. If developers later refactor the code, for example, change a class definition, rename it, or move it to a different folder or namespace, deployment may result in two mismatched versions of the code. This leads to incomplete classes and failures in business logic. To avoid that, we opted for a safer, more controlled approach, requiring developers to handle serialization manually to ensure it’s done properly.</p><p>For the jobs transferred between workers, we decided to take a less strict approach while still using only “primitives” in the data we send (without any resources, of course). We also limited ourselves to <strong>public properties</strong> only, because PHP’s native serializer, for privacy, includes the full class namespace for every property in the serialized string, which makes the resulting object unnecessarily large. It simply makes no sense to serialize that much data. We agreed that it’s acceptable not to refactor these jobs frequently, since there isn’t much to change anyway. If needed, we can always introduce a new object and switch to it instead.</p><p>One more interesting challenge was figuring out how to serialize the request and the response. As it turned out, both are simply standardized HTTP strings, and the Guzzle library provides a basic __toString() method that can serialize a response.</p><p>As you can see, it’s just the HTTP protocol version, the host header, other headers, and the body.</p><pre>namespace GuzzleHttp\Psr7;<br><br>final class Message<br>…<br>public static function toString(MessageInterface $message): string<br>{<br>    if ($message instanceof RequestInterface) {<br>        $msg = trim($message-&gt;getMethod().&#39; &#39;<br>                .$message-&gt;getRequestTarget())<br>            .&#39; HTTP/&#39;.$message-&gt;getProtocolVersion();<br>        if (!$message-&gt;hasHeader(&#39;host&#39;)) {<br>            $msg .= &quot;\r\nHost: &quot;.$message-&gt;getUri()-&gt;getHost();<br>        }<br>    } elseif ($message instanceof ResponseInterface) {<br>        $msg = &#39;HTTP/&#39;.$message-&gt;getProtocolVersion().&#39; &#39;<br>            .$message-&gt;getStatusCode().&#39; &#39;<br>            .$message-&gt;getReasonPhrase();<br>    } else {<br>        throw new \InvalidArgumentException(&#39;Unknown message type&#39;);<br>    }<br><br>    foreach ($message-&gt;getHeaders() as $name =&gt; $values) {<br>        if (is_string($name) &amp;&amp; strtolower($name) === &#39;set-cookie&#39;) {<br>            foreach ($values as $value) {<br>                $msg .= &quot;\r\n{$name}: &quot;.$value;<br>            }<br>        } else {<br>            $msg .= &quot;\r\n{$name}: &quot;.implode(&#39;, &#39;, $values);<br>        }<br>    }<br><br>    return &quot;{$msg}\r\n\r\n&quot;.$message-&gt;getBody();<br>}</pre><h3>Our little contribution</h3><p><em>This string check for the header name (is_string($name)) became our small contribution to the Guzzle library.</em></p><p><em>It turned out that one of our clients decided to send a rather unusual header to their server. Even though it was fully compliant with HTTP protocol, it was just a number as the header name, and the library failed. Our fix, if I may say so myself, works pretty well.</em></p><p>Another thing we had to work on regarding serialization was the exceptions thrown by Guzzle. Unfortunately, the library didn’t provide a native serializer for exceptions, so we had to develop a custom one. Luckily, there weren’t too many exception types to handle.</p><pre>public static function serializeException(\Throwable $reason): array<br>{<br><br>    if ($reason instanceof ConnectException || $reason instanceof TooManyRedirectsException) {<br>        return [<br>            &#39;class&#39; =&gt; $reason instanceof TooManyRedirectsException ? &#39;TooManyRedirectsException&#39; : &#39;ConnectException&#39;,<br>            &#39;message&#39; =&gt; $reason-&gt;getMessage(),<br>            &#39;request_interface&#39; =&gt; Message::toString($reason-&gt;getRequest()),<br>            &#39;response_interface&#39; =&gt; null,<br>            &#39;previous&#39; =&gt; $reason-&gt;getPrevious() !== null ? get_class($reason-&gt;getPrevious()) : null,<br>            &#39;handler_context&#39; =&gt; $reason-&gt;getHandlerContext(),<br>        ];<br>    }<br><br>    if ($reason instanceof BadResponseException) {<br>        return [<br>            &#39;class&#39; =&gt; $reason instanceof ClientException ? &#39;ClientException&#39; : &#39;ServerException&#39;,<br>            &#39;message&#39; =&gt; $reason-&gt;getMessage(),<br>            &#39;request_interface&#39; =&gt; Message::toString($reason-&gt;getRequest()),<br>            &#39;response_interface&#39; =&gt; null !== $reason-&gt;getResponse() ? Message::toString($reason-&gt;getResponse()) : null,<br>            &#39;previous&#39; =&gt; $reason-&gt;getPrevious() !== null ? get_class($reason-&gt;getPrevious()) : null,<br>            &#39;handler_context&#39; =&gt; $reason-&gt;getHandlerContext(),<br>        ];<br>    }<br><br>    if ($reason instanceof InvalidArgumentException) {<br>        return [<br>            &#39;class&#39; =&gt; &#39;InvalidArgumentException&#39;,<br>            &#39;message&#39; =&gt; $reason-&gt;getMessage(),<br>        ];<br>    }<br><br>    return [<br>        &#39;class&#39; =&gt; &#39;RuntimeException&#39;,<br>        &#39;message&#39; =&gt; $reason-&gt;getMessage(),<br>        &#39;orig_exception_class&#39; =&gt; get_class($reason),<br>    ];<br>}</pre><p><em>Our custom-built exception serializer uses the native Message::toString().</em></p><pre>protected function deserializeException(array $serializedException): \Throwable<br>{<br>    return match ($serializedException[&#39;class&#39;]) {<br>        &#39;TooManyRedirectsException&#39; =&gt; new TooManyRedirectsException(<br>            $serializedException[&#39;message&#39;],<br>            Message::parseRequest($serializedException[&#39;request_interface&#39;]),<br>            isset($serializedException[&#39;response_interface&#39;]) ? Message::parseResponse($serializedException[&#39;response_interface&#39;]) : null,<br>            handlerContext: $serializedException[&#39;handler_context&#39;]<br>        ),<br>        &#39;ConnectException&#39; =&gt; new ConnectException(<br>            $serializedException[&#39;message&#39;],<br>            Message::parseRequest($serializedException[&#39;request_interface&#39;]),<br>            handlerContext: $serializedException[&#39;handler_context&#39;]<br>        ),<br>        &#39;ServerException&#39; =&gt; new ServerException(<br>            $serializedException[&#39;message&#39;],<br>            Message::parseRequest($serializedException[&#39;request_interface&#39;]),<br>            isset($serializedException[&#39;response_interface&#39;]) ? Message::parseResponse($serializedException[&#39;response_interface&#39;]) : null,<br>            handlerContext: $serializedException[&#39;handler_context&#39;]<br>        ),<br>        &#39;ClientException&#39; =&gt; new ClientException(<br>            $serializedException[&#39;message&#39;],<br>            Message::parseRequest($serializedException[&#39;request_interface&#39;]),<br>            isset($serializedException[&#39;response_interface&#39;]) ? Message::parseResponse($serializedException[&#39;response_interface&#39;]) : null,<br>            handlerContext: $serializedException[&#39;handler_context&#39;]<br>        ),<br>        &#39;InvalidArgumentException&#39; =&gt; new InvalidArgumentException($serializedException[&#39;message&#39;]),<br>        default =&gt; new \RuntimeException($serializedException[&#39;message&#39;] . ($serializedException[&#39;orig_exception_class&#39;] ?? &#39;&#39;) ?? &#39;Strange external request exception&#39;),<br>    };<br>}</pre><p><em>This is the exception deserializer, which uses the native parseResponse() function from the Message class to take a standard HTTP string and recreate Guzzle’s response object from it.</em></p><p>An especially interesting part of the system is how the worker operates.</p><p>It takes the request from the payload and sends it using Guzzle’s native asynchronous client function sendAsync(). Two closures are provided — one to handle success and another to handle failure.</p><p>There’s also a catch function that performs the same call in case of rejection or error. This function returns almost immediately, because it doesn’t execute the requests right away. Instead, it simply adds the requests and both closures to Guzzle’s internal queue.</p><pre>protected function processJob(AsyncRequestHandymanJob|AbstractHandymanJob $payload): void<br>{<br>    $this-&gt;asyncTasksInFlight++;<br><br>    try {<br>        $request = $payload-&gt;createRequest();<br>        $options = [<br>            &#39;timeout&#39; =&gt; 100,<br>            &#39;connect_timeout&#39; =&gt; 10,<br>        ];<br><br>        $this-&gt;httpClient-&gt;sendAsync(<br>            $request,<br>            $options<br>        )-&gt;then(<br>            function (ResponseInterface $response) use ($payload) {<br>                $this-&gt;processResponse($payload-&gt;onFulfilled($response));<br>            },<br>            function ($reason) use ($payload) {<br>                $this-&gt;processResponse($payload-&gt;onRejected($reason));<br>            }<br>        );<br>    } catch (\Throwable $e) {<br>        $this-&gt;processResponse($payload-&gt;onRejected($e));<br>    }<br>}</pre><p>We can perform this job as many times as needed. In our setup, we assume that <strong>400 requests in flight</strong> is sufficient for a single worker. Each time a new task is added, we increment the counter of active requests, and if the number exceeds 400, we simply stop pushing more tasks to that worker.</p><p>The real magic happens after calling Guzzle’s native tick() function.</p><p>This function processes any new requests in the queue, then checks all registered handlers for completed responses. When a full response body is received, it triggers the corresponding closure we defined earlier: either the success or failure handler.</p><pre>protected function afterIterate(): void<br>{<br>    parent::afterIterate();<br>    if ($this-&gt;thereAreAsyncTaskInProcessingRightNow()) {<br>        //Here goes the magic of async requests<br>        //If there is any request finished,<br>        // -&gt;then() Closures will be invoked here<br>        //This function freezes for select_timeout seconds,<br>        //if there is nothing to do for curl,<br>        //i.e. nothing to send and nothing to receive<br>        $this-&gt;curlHandler-&gt;tick();<br>    }<br>}</pre><p>Here’s what happens under the hood in Guzzle: it adds new requests to the internal queue and calls the curl_multi_select() and curl_multi_exec() functions, the ones that are responsible for all the magic behind the scenes.</p><p>If there’s nothing to process (no new requests to send or no responses ready to be received from the socket) the function simply returns control from the library back to PHP.<br>But if there is work to do, it processes the requests, and once a response has been fully received, it triggers the closures we defined earlier to handle success or failure.</p><pre>namespace GuzzleHttp\Handler;<br><br>class CurlMultiHandler<br>…<br>public function tick(): void<br>{<br>    // Add any delayed handles if needed.<br>    if ($this-&gt;delays) {<br>        $currentTime = Utils::currentTime();<br>        foreach ($this-&gt;delays as $id =&gt; $delay) {<br>            if ($currentTime &gt;= $delay) {<br>                unset($this-&gt;delays[$id]);<br>                \curl_multi_add_handle(<br>                    $this-&gt;_mh,<br>                    $this-&gt;handles[$id][&#39;easy&#39;]-&gt;handle<br>                );<br>            }<br>        }<br>    }<br><br>    // Run curl_multi_exec in the queue to enable other async tasks to run<br>    P\Utils::queue()-&gt;add(Closure::fromCallable([$this, &#39;tickInQueue&#39;]));<br><br>    // Step through the task queue which may add additional requests.<br>    P\Utils::queue()-&gt;run();<br><br>    if ($this-&gt;active &amp;&amp; \curl_multi_select($this-&gt;_mh, $this-&gt;selectTimeout) === -1) {<br>        // Perform a usleep if a select returns -1.<br>        // See: https://bugs.php.net/bug.php?id=61141<br>        \usleep(250);<br>    }<br><br>    while (\curl_multi_exec($this-&gt;_mh, $this-&gt;active) === \CURLM_CALL_MULTI_PERFORM) {<br>        // Prevent busy looping for slow HTTP requests.<br>        \curl_multi_select($this-&gt;_mh, $this-&gt;selectTimeout);<br>    }<br><br>    $this-&gt;processMessages();<br>}</pre><p>Those closures create a job for the synchronous worker.</p><p>In the success case, the closure serializes the response string using the method I showed earlier and passes the context back as is.</p><p>In the failure case, it serializes the exception and sends the same resumed job to the synchronous worker for further processing.</p><pre>public function onFulfilled(ResponseInterface $response): ?AbstractHandymanJob<br>{<br>    try {<br>        return new SyncResumeHMJob(<br>            Message::toString($response),<br>            context: $this-&gt;context,<br>        );<br>    } catch (\Throwable $e) {<br>        return $this-&gt;onRejected($e);<br>    }<br>}<br><br>public function onRejected(\Throwable $reason): ?AbstractHandymanJob<br>{<br>    try {<br>        return new SyncResumeHMJob(<br>            null,<br>            SyncResumeHMJob::serializeException($reason),<br>            context: $this-&gt;context,<br>        );<br>    } catch (\Throwable) {<br>        return null;<br>    }<br>}</pre><h3>Wrapping Up: Simulated Concurrency, Real Performance</h3><p>In the end, the final architecture turned out to be both elegant and efficient.</p><p>Each synchronous PHP worker prepares a request, serializes both the business context and the HTTP request itself, and hands it off to an asynchronous worker.</p><p>Inside this asynchronous worker, we use PHP’s own curl_multi_exec to serve multiple requests “concurrently”. Technically, it’s still a single thread, but thanks to non-blocking I/O and HTTP/2 multiplexing, it behaves as if dozens of requests are being processed simultaneously.</p><p>Once the responses arrive, the worker serializes them back, attaches the corresponding business data, and sends everything to the original synchronous worker, which deserializes, processes, and continues the workflow as usual.</p><p>What’s remarkable here is what we didn’t have to do.<br>We didn’t need pthreads, parallel, or to use a new language like Go. We achieved concurrency inside PHP by leaning on what we already had — Guzzle, curl, and a bit of smart serialization logic.</p><p>Along the way, we save on:</p><ul><li>waiting time, because PHP workers don’t block on long AI responses.</li><li>connection reuse, and</li><li>HTTP/2 multiplexing,</li></ul><p>What is important here is to be careful with serialization: serialize either primitives or write the custom serialization for the objects.</p><p>By following this pattern, we’ve effectively simulated parallelism in PHP — but with real, measurable performance gains.</p><p>For more details check out the full version of my talk:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJKhXFisGbKc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJKhXFisGbKc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJKhXFisGbKc%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/817ce2d7bfe6df78029c854efafb071d/href">https://medium.com/media/817ce2d7bfe6df78029c854efafb071d/href</a></iframe><p><strong>Stay tuned</strong><br>Maybe while reading all this article you were thinking: why bother with all this serialization and deserialization at all? Why not just process all payloads concurrently inside a single PHP worker — maybe even using fiber?</p><p>Well, things aren’t quite that simple, but still possible.</p><p>In the next article, we’ll dive into what real concurrency inside a single PHP process actually looks like, why fibers are powerful but not a silver bullet, and how they can both help and hinder high-load HTTP pipelines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3a94bae6c3b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/manychat-engineering/simulating-%D1%81oncurrent-requests-how-we-achieved-high-performance-http-in-php-without-threads-c3a94bae6c3b">Simulating Сoncurrent Requests: How We Achieved High-Performance HTTP in PHP Without Threads</a> was originally published in <a href="https://medium.com/manychat-engineering">Manychat Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>