Skip to content
Jaskaran Singh

Rust and Laravel in production: four ways across the runtime boundary

Laravel's bottleneck is no longer the framework — it is the CPU-bound work inside your requests. Four honest ways to hand that work to Rust, with the overhead maths, the production evidence, and the caveats nobody puts in the tutorial.

Published
Category
Engineering
Read time
14 min
Author
Jaskaran Singh

Laravel applications almost never slow down because of Laravel. The framework-bootstrap cost that dominated a decade of performance complaints has been engineered away — Octane boots the application once and keeps it in memory, and FrankenPHP worker mode claims a 3.5× improvement over PHP-FPM on vendor benchmarks. What remains after that work is the part nobody can cache away: the compute inside your own requests.

Meanwhile, the PHP world quietly started running on non-PHP infrastructure. FrankenPHP is written in Go and has been officially supported by the PHP Foundation since May 2025. Meilisearch, the search engine Laravel Scout supports as a first-party engine, is written in Rust. Mago, the linter and static analyser gaining real traction in PHP shops, is a Rust binary you install through Composer. And a growing list of production teams — Aerospike, Proton Mail, Appwrite among them — ship PHP extensions written in Rust rather than C.

The question for a Laravel team in 2026 is not whether Rust fits the stack. It already does. The question is where your hot path is, and which of the four boundaries you want to pay for: a CLI binary, a sidecar service, a raw FFI library, or a native extension.

Where Laravel actually hits the wall

The evidence is hiding in plain sight. The awesome-ext-php-rs list of production Rust extensions reads like a taxonomy of everything PHP userland is bad at:

  • Parsing — Flow PHP's arrow-ext reads and writes Apache Parquet; Proton Mail's Rust library parses iCalendar; php-sqlx-rs leans on Rust's simd-json for lazy JSON decoding
  • Cryptography — Appwrite's php-scrypt password hashing, Paragon Initiative's post-quantum ext-pqcrypto, and the OpenPGP extension that has encrypted email for the addy.io aliasing service for years
  • Document generation — ext-typst embeds the Typst typesetting engine to render PDFs, a job PHP libraries do slowly and memory-hungrily
  • Transport — rabbit-rs, a native RabbitMQ extension with a Laravel queue driver, covered below
  • Media — image and video pipelines, usually handed to Rust or C tooling through binaries rather than extensions

None of these are fixed by Octane. Worker mode removes the cost of booting your framework per request; it does nothing about a request that spends 900 milliseconds resizing images or parsing a 40 MB CSV. That time is compute, and compute is what Rust is for.

The one rule: pay for the boundary once

Every integration pattern is the same deal: PHP hands work to Rust, Rust hands results back. The compute is equally fast no matter which pattern you choose — a zstd compression inside Rust runs at the same speed whether you reached it through an extension call or an HTTP request. What differs is the cost of crossing the boundary, and how much data crosses with you:

  1. Extension call — effectively free; direct access to PHP's own memory structures
  2. FFI call — cheap for fat calls; expensive if you touch the foreign memory from PHP
  3. Process spawn — milliseconds, every time
  4. Localhost HTTP — milliseconds plus serialisation, every time

That ladder produces the single most important design rule in this article: make each crossing of the boundary do more work. A PHP loop that calls into Rust ten thousand times pays the crossing cost ten thousand times. Move the loop inside Rust and you pay it twice — once in, once out.

Diagram: chatty versus fat boundary crossings between PHP and Rust. In the chatty lane a PHP loop calls into Rust once per row, paying the crossing cost ten thousand times. In the fat lane the whole payload crosses once, the loop runs inside Rust, and one result crosses back.

Keep this picture in mind — it decides every one of the four patterns below.

Pattern one: a Rust binary and the Process facade

The pragmatic default. Compile your hot path into a static binary, ship it next to the application, and invoke it from a queued job with Laravel's Process facade:

php
use Illuminate\Support\Facades\Process;

$result = Process::timeout(120)->run([
    storage_path('bin/media-pipeline'),
    '--input', $upload->path,
    '--output', $outputPath,
    '--sizes', '640,1280,2560',
]);

if ($result->failed()) {
    throw new MediaPipelineException($result->errorOutput());
}

The Rust side is an ordinary CLI program — read arguments, do the work, write files or JSON to stdout, exit non-zero on failure:

rust
fn main() {
    let args: Vec<String> = std::env::args().collect();
    // parse --input / --output / --sizes, then:
    if let Err(err) = pipeline::run(&args) {
        eprintln!("{err}");
        std::process::exit(1);
    }
}

Why this wins so often: process work is usually batch work. Image resizing, video transcoding, PDF rendering, large imports — these belong in queued jobs, and in a queued job a 5-millisecond spawn cost is rounding error. Rust cross-compiles to static binaries, so distribution is one file in your deployment artifact. There is zero coupling to the PHP version, the build, or the thread-safety mode, a crash in Rust takes down nothing but its own process, and Process::fake() gives you full test coverage without running anything.

Where it loses: per-request hot paths. Spawning a process inside a web request adds milliseconds you can see, and passing large data through files or pipes adds serialisation on top. If the work happens a hundred times per request, this pattern is already wrong — but honestly, so is doing that work in the request at all. It is no accident that the PHP ecosystem's own tooling went this way: Mago ships as a Rust binary installable via composer require carthage-software/mago, no cargo or Rust toolchain required on the machine that runs it.

Pattern two: a sidecar service

One step further along the same axis: the Rust code is not just a separate process, it is a separate service — long-lived, independently deployed, talking HTTP or gRPC over localhost or the network.

The Laravel ecosystem already treats this as normal, because its favourite example is everywhere: Meilisearch is written in Rust, and its engine ships inside laravel/scout itself — the old meilisearch-laravel-scout bridge package is deprecated precisely because core Scout absorbed it. (A caution for listicle writers: Typesense, the other Scout engine, is C++, not Rust.) Your application already knows how to talk to a Rust service; hundreds of thousands of Laravel apps do it on every search query.

Why this wins: the unit of work is large. A search query, a report render, an inference call — the compute inside the service dwarfs the millisecond of network overhead, so the boundary cost disappears into the noise. You get crash isolation, independent scaling, independent deployment, and the full async Rust ecosystem (tokio, axum, tonic) with no compromises. The service is also reusable: every app in the fleet can call it, not just the Laravel one.

Where it loses: operations. You now own another service — health checks, deploys, versioning, observability. And for small units of work the maths inverts: serialising a payload, crossing localhost, and deserialising can cost more than the compute you outsourced. If you catch yourself building an RPC wrapper around a parser, stop — that work wants to be in-process, which is what the next two patterns are for.

Pattern three: PHP FFI and a Rust cdylib

Since PHP 7.4 the language can call a C-shared library directly — no extension compilation, no phpize. Rust produces exactly such a library with one line of configuration:

toml
# Cargo.toml
[lib]
crate-type = ["cdylib"]
rust
use std::ffi::{c_char, CStr};

#[no_mangle]
pub extern "C" fn fingerprint_batch(input: *const c_char) -> u64 {
    let json = unsafe { CStr::from_ptr(input) }.to_str().unwrap_or("");
    pipeline::fingerprint_batch(json) // the whole batch, inside Rust
}
php
$ffi = FFI::cdef(
    "uint64_t fingerprint_batch(const char *input);",
    "/var/www/app/bin/libfingerprint.so"
);

$hash = $ffi->fingerprint_batch(json_encode($rows));

This is genuinely useful, and genuinely constrained. Three facts from the PHP manual decide whether it fits:

ffi.enable is a system-level setting. It defaults to "preload", which restricts FFI to the CLI SAPI and preloaded scopes, and it is INI_SYSTEM — only an administrator editing php.ini can turn it on for web requests (configuration reference). There is no per-project opt-in, which kills this pattern on shared hosting and makes it a deliberate infrastructure decision everywhere else.

The famous "FFI is slow" warning is misquoted. The manual says accessing FFI data structures is about twice as slow as native PHP arrays — that is about touching FFI\CData fields from PHP, not about the cost of the call itself. The correct takeaway is the boundary rule from earlier: design fat calls. Scalars in, all heavy lifting inside one Rust invocation, scalar out. If you find PHP reading struct fields in a loop, you built a chatty crossing.

You get functions, not an API. No classes, no type marshalling beyond what you write by hand, no IDE stubs, no error conventions. The Rustonomicon's FFI chapter is your documentation, and memory bugs corrupt the PHP process exactly as they would in a C extension.

When it wins: one or two fat, CPU-bound calls; you control php.ini or can use the preload path; you want zero build infrastructure — just a .so file in the deploy. It is also the fastest way to prototype and benchmark whether Rust even helps your workload before you commit to pattern four.

Pattern four: a native extension with ext-php-rs

The deep end: a real PHP extension, written in Rust with ext-php-rs, loaded by the engine itself. The crate is at 0.16.5 as of November 2026, supports PHP 8.1 through 8.6, and has matured rapidly — the 0.16 series this autumn brought a large soundness overhaul of the Zend API bindings and support for statically linking extensions into php-src.

rust
use ext_php_rs::prelude::*;

#[php_function]
pub fn fingerprint_batch(input: &str) -> u64 {
    pipeline::fingerprint_batch(input)
}

#[php_module]
pub fn module(module: ModuleBuilder) -> ModuleBuilder {
    module.function(wrap_function!(fingerprint_batch))
}

From PHP's side this is now a native function — no scaffolding, no bootstrap code, IDE-autocompletable through the stubs cargo php stubs generates from your doc comments:

php
$hash = fingerprint_batch(json_encode($rows));

The two historic objections to this pattern have recently collapsed. Distribution used to mean every user needed a Rust toolchain and the Zend headers; then PIE — the PHP Foundation's official replacement for PECL — started distributing pre-compiled extension binaries per PHP version, platform, and thread-safety mode, so installation is pie install vendor/ext. And ergonomics used to mean writing C against undocumented macros; the ext-php-rs guide now covers classes, methods, enums, named arguments, and even implementing PHP interfaces from Rust traits.

The reference implementation for what "done right" looks like is rabbit-rs: a native RabbitMQ transport written in Rust with forbid(unsafe_code) applied workspace-wide, shipping a Laravel queue driver (composer require goopil/rabbit-rs-laravel), supporting Laravel 12 and 13 across CLI, FPM and every Octane server. Its published benchmark — 12,963 ops/s against 2,255 ops/s for the pure-PHP php-amqplib on the same workload, a 5.7× throughput gain — comes with methodology, and its CI includes an overnight kill-soak that terminates the broker mid-stream and verifies zero lost messages. That is what production-grade means in this space.

Why this wins: the crossing cost approaches zero, so even chatty workloads survive — this is the only pattern where calling into Rust a thousand times per request is a defensible design. You write an idiomatic PHP API surface (classes, typed signatures, stubs) backed by Rust's crate ecosystem.

Where it loses, honestly stated:

  • Stability. The crate is pre-1.0 and says so: no backwards-compatibility guarantee for the foreseeable future. Pin exact versions — ext-php-rs = "0.16.5" — and budget for migration on upgrades. The 0.14 series changed the macro surface itself.
  • Blast radius. A segfault in your extension kills the PHP worker, not a subprocess. The 0.16.0 changelog's long list of soundness fixes is evidence the boundary is still being hardened — impressive progress, and a reminder that you are writing code whose failure mode is the whole process.
  • The build matrix. Binaries must match PHP minor version, platform, libc, and ZTS versus NTS — FrankenPHP needs ZTS builds. PIE solves this for public extensions you ship pre-built; for private ones, it is your CI problem.
  • Platform edges. Windows builds require nightly Rust; memory is Zend-request-allocated, so state cannot simply persist across requests; there is no native async story (the community bridge is php-tokio).

Choosing the boundary

Cost per crossingDistributionCrash blast radiusWork shapeIn the wild
Binary + Processmilliseconds (spawn)one static file in the deploynothing but the childbatch jobs, file in/file outMago-style tooling
Sidecar servicelocalhost network + serialisationits own service and deploynothing — process isolationlarge or stateful unitsMeilisearch via Scout
PHP FFI + cdyliblow for fat callsa .so plus php.ini accessthe PHP processone or two fat CPU callsprototypes, internal libs
ext-php-rs extensioneffectively zeroPIE binaries or a build matrixthe PHP workermany small calls per requestrabbit-rs, Aerospike, ext-typst

Read the table with the boundary rule and the answer usually picks itself: queued batch work — binary; big or stateful work — sidecar; a couple of fat calls and full control of the server — FFI; a hot path called constantly per request — extension. When in doubt, start one level up the ladder than you think you need. Moving a binary's logic into an extension later is a refactor of the boundary, not of the Rust code.

The ecosystem already decided

Worth noticing how complete the shift is. PHP 8.6 shipped on 19 November 2026; ext-php-rs supported it within days. The PHP Foundation officially supports an application server written in Go. Laravel's first-party search path depends on a Rust engine, and the tools PHP developers run all day increasingly are Rust binaries. Writing PHP extensions is no longer a C-only guild — it is a normal thing infrastructure teams do in a memory-safe language with a package manager.

The practical effect: the risk profile inverted. Five years ago, choosing Rust for PHP infrastructure was the exotic bet. In 2026, the exotic bet is handwriting new Zend C.

The honest caveats

Three, because they are what the tutorials omit.

There is no credible universal benchmark. Nobody has published a rigorous "same algorithm, PHP versus Rust extension" number, and the 5.7× rabbit-rs figure is a transport workload — meaningful, but not yours. The only defensible number is the one you measure on your own hot path; the FFI pattern above is the cheapest way to get it in an afternoon.

Rust does not fix your actual bottleneck if it is the usual one. N+1 queries, missing indexes, chatty HTTP calls to third parties — these dominate real Laravel profiles, and none of the four patterns helps them. Profile first. If the flame graph shows the database, this article is not your next step.

This is systems programming adjacent to a runtime that assumes ownership of memory. Request-scoped allocation, ZTS builds, bailout semantics — the extension path in particular rewards teams that read the ext-php-rs guide end to end before writing the wrapper, not after the first corruption report. The ceiling is high; the floor is real.

None of which changes the shape of the decision. Laravel gives you one of the most productive application frameworks ever shipped; Rust gives you memory-safe compute at native speed. The boundary between them is a design decision with four well-understood options — and for most teams, the binary in a queued job is fifteen minutes of work away from a measured answer.

I build web products and the performance work behind them — book a call if your hot path is due for its own measurement.

Primary sources

Share this post

Comments

Discussion

Questions and notes on “Rust and Laravel in production: four ways across the runtime boundary”

Loading comments…

More posts

Sign in

Join the discussion.

One click with GitHub — your name and avatar come across. No passwords, no email verification step.

By continuing you agree to the comment policy: be kind, stay on topic, no spam. Moderated by the site owner.