惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Troy Hunt's Blog
Blog — PlanetScale
Blog — PlanetScale
Engineering at Meta
Engineering at Meta
F
Full Disclosure
Recorded Future
Recorded Future
The GitHub Blog
The GitHub Blog
Microsoft Security Blog
Microsoft Security Blog
GbyAI
GbyAI
博客园_首页
博客园 - 叶小钗
MongoDB | Blog
MongoDB | Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Recent Commits to openclaw:main
Recent Commits to openclaw:main
H
Hacker News: Front Page
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
博客园 - 司徒正美
Webroot Blog
Webroot Blog
Google DeepMind News
Google DeepMind News
Help Net Security
Help Net Security
Cloudbric
Cloudbric
PCI Perspectives
PCI Perspectives
有赞技术团队
有赞技术团队
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
TaoSecurity Blog
TaoSecurity Blog
L
Lohrmann on Cybersecurity
量子位
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Tailwind CSS Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
B
Blog RSS Feed
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
P
Proofpoint News Feed
N
News and Events Feed by Topic
罗磊的独立博客
T
Threat Research - Cisco Blogs
Schneier on Security
Schneier on Security
T
Tor Project blog
IT之家
IT之家
M
MIT News - Artificial intelligence
S
Security @ Cisco Blogs
O
OpenAI News
AI
AI
S
Securelist
Simon Willison's Weblog
Simon Willison's Weblog
The Last Watchdog
The Last Watchdog
月光博客
月光博客
Security Archives - TechRepublic
Security Archives - TechRepublic
L
LINUX DO - 热门话题

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
True Parallel PHP is Here: Elegant Parallelism, Worker Pools, Self-Healing Clusters & Fractal Concurrency
Reymart A. C · 2026-04-30 · via DEV Community

True Parallel PHP is Here: Elegant Parallelism, Worker Pools, Self-Healing Clusters & Fractal Concurrency

For years, the PHP community has repeated the same mantra: "PHP is single-threaded."

Recently, Fibers (introduced in PHP 8.1) solved the I/O problem. We can now make non-blocking HTTP requests and database queries concurrently. But what happens when you need to parse thousands of massive HTML documents, crunch complex math, or process images?

Fibers block the CPU. If you run a heavy regex on a 5MB string, your entire event loop freezes.

To get true CPU parallelism, you usually have to mess with complex extensions (ext-parallel) or write clunky proc_open wrappers where passing data feels like writing an old-school TCP socket protocol or relying on pcntl wrapper libraries.

I wanted something that felt as natural as writing standard async PHP. So, I built Hibla Parallel: a cross-platform, self-healing, multi-processing engine for PHP 8.4+.

Here’s a look at what makes its syntax and architecture special.

Crossing the Boundary: Value Objects & Clean Syntax

In Hibla, you don't have to manually encode/decode JSON to talk to your background processes. It handles the serialization of closures, variables, and objects seamlessly.

Pass objects in, get objects out.

use App\ValueObjects\ReportResult;
use function Hibla\{parallel, await};

// Spawn a background process, run the closure, and wait for the result
$result = await(parallel(function () {
    $data = heavy_data_processing();

    // Return a rich Value Object directly from the worker
    return new ReportResult(
        status: 'success', 
        rowsProcessed: 50000,
        data: $data
    );
}));

echo get_class($result); // "App\ValueObjects\ReportResult"
echo $result->rowsProcessed; // 50000

Enter fullscreen mode Exit fullscreen mode

Under the hood, Hibla handles the OS-level IPC (Inter-Process Communication), reconstructs your objects, and preserves their types.

Seamless Framework Bootstrapping

When you spawn a new PHP process, it starts as a blank slate. If you want to use Laravel's Eloquent ORM, Symfony's container, or your own legacy global functions inside a worker, you need to load them.

Hibla makes this a one-liner using withBootstrap(). It loads your environment into the worker seamlessly:

use Hibla\Parallel\Parallel;

$pool = Parallel::pool(size: 4)
    // Boot Laravel (or Symfony, etc.) inside every worker process automatically
    ->withBootstrap(__DIR__ . '/bootstrap/app.php', function (string $file) {
        $app = require $file;
        $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
    });

// Now you can freely use your ORM and framework helpers inside the closure!
$pool->run(function () {
    return User::where('active', true)->count();
});

Enter fullscreen mode Exit fullscreen mode

Persistent Worker Pools

Spawning a new process for every small task is expensive, especially if your worker needs to boot up a heavy framework every time.

Hibla solves this with persistent Worker Pools featuring a beautifully expressive, fluent API. You boot the pool and the framework once, and the workers stay alive to crunch through your queue.

$tasks = [/* 10,000 heavy items */];

foreach ($tasks as $item) {
    // Workers are reused. No framework boot penalty per task!
    $pool->run(function () use ($item) {
        return process_item($item);
    })->then(fn($result) => echo "Done: $result\n");
}

$pool->shutdown();

Enter fullscreen mode Exit fullscreen mode

How Does it Compare to Python's Multiprocessing?

Python is famous for making data processing easy, but its multiprocessing library has some infamous quirks. Because of how Python spawns processes across different OS environments (like Windows), you are forced to wrap your execution logic in an if __name__ == '__main__': block, or you trigger an infinite fork bomb.

Python (concurrent.futures):

import concurrent.futures

def process_item(item):
    return item * 2

# This guard is strictly required on Windows and macOS!
if __name__ == '__main__': 
    items = [1, 2, 3, 4, 5]
    with concurrent.futures.ProcessPoolExecutor(max_workers=4) as pool:
        results = list(pool.map(process_item, items))
        print(results)

Enter fullscreen mode Exit fullscreen mode

PHP (Hibla Parallel):
Hibla handles closure AST serialization and fork-bomb prevention safely under the hood. No boilerplate guards required. Using our Promise::map utility combined with the pool's runFn() factory, it becomes a beautiful one-liner:

use Hibla\Parallel\Parallel;
use Hibla\Promise\Promise;
use function Hibla\await;

$pool = Parallel::pool(size: 4);
$items = [1, 2, 3, 4, 5];

// Map concurrently across the process pool without double-wrapping closures!
$results = await(
    Promise::map($items, $pool->runFn(fn($item) => $item * 2))
);

$pool->drain();
print_r($results);

Enter fullscreen mode Exit fullscreen mode

It feels just like writing modern, asynchronous JavaScript, but you are utilizing every CPU core on your server.

Fault-Tolerant Parallelism (The Supervisor Pattern)

In distributed systems, things fail. A worker might hit an Out-Of-Memory (OOM) error, cause a segmentation fault, or trigger a fatal exit(1). In most PHP libraries, this deadlocks your queue or crashes the parent process.

Hibla brings Erlang’s "Let it Crash" philosophy to PHP. If a worker dies, Hibla immediately detects the crash, spawns a fresh replacement to maintain pool capacity, and fires an onWorkerRespawn hook so you can resubmit the lost work.

But true fault tolerance isn't just about recovering from crashes, it's about preventing state corruption and memory leaks. Long-running PHP scripts naturally accumulate memory over time.

To solve this, Hibla gives you PHP-FPM style worker management. You can set hard limits on execution time, memory, and automatically recycle workers to keep RAM usage perfectly flat:

use Hibla\Parallel\Parallel;

$pool = Parallel::pool(size: 4)
    // 1. Proactive Limits: Kill any rogue task taking longer than 60 seconds
    ->withTimeout(60)

    // 2. Memory Sandbox: Isolate the worker's memory limit
    ->withMemoryLimit('256M')

    // 3. FPM-Style Recycling: Retire and replace the worker after 100 tasks 
    // to cleanly flush all framework state and memory leaks
    ->withMaxExecutionsPerWorker(100)

    // 4. Circuit Breaker: Shut down the pool if >5 workers crash in 1 second
    ->withMaxRestartPerSecond(5)

    // 5. Supervisor Hook: Resubmit long-running tasks to the replacement worker
    ->onWorkerRespawn(function ($pool) use ($daemonTask) {
        echo "Worker recycled or crashed! Spawning replacement & resubmitting...\n";
        $pool->run($daemonTask); 
    });

Enter fullscreen mode Exit fullscreen mode

With this setup, your application stays online, recycles its own memory automatically, heals itself from segfaults, and alerts you when things go critically wrong. It's production-grade process supervision, out of the box.

Real-Time Output Streaming

One of the most frustrating things about traditional PHP background processes is that echo and print get swallowed until the process finishes (or they break the IPC protocol entirely).

Hibla intercepts PHP's output buffer and streams it back to the parent process in real-time, completely non-blocking.

use function Hibla\{parallel, await};

await(parallel(function () {
    echo "Starting process...\n";
    sleep(1);
    echo "50% complete...\n";
    sleep(1);
    echo "Finished!\n";
}));
// The parent console prints these lines immediately as they happen in the worker!

Enter fullscreen mode Exit fullscreen mode

Structured Message Passing

Sometimes raw console output isn't enough. If you are running a long-lived task and need to send structured data (like progress updates, partial JSON records, or value objects) back to the parent before the task finishes, Hibla provides the emit() and onMessage() APIs.

Just like return values, emitted messages cross the process boundary with their types preserved:

use Hibla\Parallel\Parallel;
use App\Messages\ProgressUpdate;
use function Hibla\emit;

Parallel::task()
    // The parent process listens for messages asynchronously
    ->onMessage(function ($msg) {
        if ($msg->data instanceof ProgressUpdate) {
            echo "Worker {$msg->pid}: {$msg->data->percent}% complete\n";
        }
    })
    ->run(function () {
        // The worker emits data back to the parent mid-execution
        emit(new ProgressUpdate(percent: 25));
        do_heavy_work();
        emit(new ProgressUpdate(percent: 100));

        return "Task Done!";
    });

Enter fullscreen mode Exit fullscreen mode

This is perfect for building real-time progress bars, logging systems, or streaming data out of a massive batch job.


Exception Teleportation

Debugging distributed systems is a nightmare. Usually, if a child process dies, you just get a generic "Process exited with code 255" error.

Hibla features Exception Teleportation. If your worker throws an exception, Hibla catches it, serializes it, teleports it back to the parent, and merges the stack traces.

use function Hibla\{parallel, await};

try {
    await(parallel(function () {
        throw new \InvalidArgumentException("Invalid CSV format!");
    }));
} catch (\InvalidArgumentException $e) {
    echo $e->getMessage(); // "Invalid CSV format!"

    // The stack trace shows exactly where the parallel() call started 
    // AND where the exception was thrown inside the worker!
    echo $e->getTraceAsString(); 
}

Enter fullscreen mode Exit fullscreen mode


The Holy Grail: Fractal Concurrency

This is where Hibla flexes its architectural muscles. Because Hibla is built on top of a unified Promise and Event Loop system, it doesn't care if a Promise is waiting for an I/O Fiber or an OS-level Process.

You can seamlessly mix async I/O (Fibers) and parallel CPU work (Processes). I call this Fractal Concurrency and from the event loop's perspective, it's all just streams.

Practical Example: High-Performance Web Scraping

Imagine you need to scrape and extract data from 10,000 URLs.

  1. Fetching the HTML is network-bound (I/O). We should use Fibers for this.
  2. Parsing the DOM (running regex or heavy DOM tree parsing) is CPU-bound. If we do this in a Fiber, we block the loop. We should distribute this across our CPU cores using a Process Pool.

By combining Hibla Parallel with the newly released async-first Hibla HTTP Client, we can build a wildly efficient, non-blocking scraper in just a few lines of code:

use Hibla\Parallel\Parallel;
use Hibla\HttpClient\Http;
use Hibla\Promise\Promise;
use function Hibla\await;

// 1. Boot a persistent pool with 1 worker per CPU core
$pool = Parallel::pool(size: 8)->boot();

$urls = [/* 10,000 URLs */];

// 2. Map over the URLs with a concurrency limit of 50 active tasks
$scrapedData = await(Promise::map($urls, function(string $url) use ($pool) {

    // Step A (I/O Bound): Fetch the HTML asynchronously using a Fiber.
    // No process is spawned here. The Event Loop just handles the sockets.
    $response = await(Http::get($url));
    $html = $response->body();

    // Step B (CPU Bound): Offload the heavy HTML parsing to a background worker.
    // The Event Loop is NOT blocked while the worker parses the DOM!
    $parsedResult = await($pool->run(function () use ($html) {
        return my_heavy_dom_parser($html);
    }));

    return $parsedResult;

}, concurrency: 50));

$pool->shutdown();

echo "Successfully parsed " . count($scrapedData) . " pages!";

Enter fullscreen mode Exit fullscreen mode

Why this is amazing:
The Event Loop is orchestrating HTTP socket streams and IPC process streams simultaneously. While Core 1 is parsing HTML, the main thread is downloading the next 49 pages. You get near the raw speed of Go or Node.js, entirely in PHP, without blocking a single thread.

True Cross-Platform Non-Blocking Parallel execution (Yes, Even on Windows)

Have you ever actually run a true parallel PHP script on a Windows machine?

Chances are, you haven't. Or if you did, it broke unexpectedly. Almost all existing PHP multiprocessing libraries rely on pcntl_fork(). There are two massive problems with this:

  1. pcntl simply does not exist on Windows. Your code immediately breaks if you share it with a teammate on a Windows dev environment.
  2. Even on Linux, pcntl_fork() is incredibly dangerous. It clones the entire memory space of the parent process. Shared database connections, Redis instances, and event loops get duplicated across children, leading to bizarre race conditions, corrupted connections, and segfaults.

Hibla doesn't use pcntl_fork(). It spawns fresh, perfectly isolated OS processes using proc_open(). They share nothing, meaning zero chance of corrupted database connections.

But wait, isn't spawning processes from scratch slow?
Yes, it can be. But that is exactly why Hibla features Persistent Worker Pools. Because the workers boot up once and stay alive to receive tasks over IPC streams, the process creation overhead is amortized to zero. The performance impact becomes completely negligible.

But there is a dark secret to proc_open(): Anonymous pipes on Windows ignore stream_set_blocking(false). A blocking read on a Windows pipe will freeze your entire PHP event loop instantly.

Hibla fixes this at the architectural level. When you spawn a worker, Hibla detects your OS. On Linux/macOS, it uses highly optimized kernel pipes. On Windows, it automatically swaps the transport layer to use socket descriptors, ensuring true, 100% non-blocking I/O.

Your code behaves identically on your local Windows dev machine and your production Linux server. No deadlocks. No memory-cloning hacks. Just pure parallelism.

Final Thoughts

I built the Hibla ecosystem because I wanted the multi-processing and async power of modern languages, but with the elegant, standard syntax of modern PHP.

If you are building high-performance CLI apps, web scrapers, daemons, or background workers in PHP, I'd love for you to try it out.

Check out and learn more about the repos here:

(Make sure to drop a ⭐️ on GitHub if you find it useful!)

Let me know what you think in the comments! How are you currently handling heavy background processing in your PHP apps?