laravel-rust-bridge maintained by olgunozoktas
Laravel Rust Bridge
Use any Rust crate — including first-party Laravel for Rust (laravel-rust) crates — inside Laravel 11 / 12 / 13 and PHP 8.2 / 8.3 / 8.4 / 8.5 / 8.6 applications through typed PHP interfaces and Laravel dependency injection.
src/ contains only the pure bridge core (no image, HTTP, or domain logic). Every Rust feature plugs in as an independent native extension or Tokio sidecar — including the standalone examples in examples/.
Quick Start · ext-php-rs vs Tokio Sidecar · PHP & Laravel Compatibility · Examples · Build Your Own Extension · Benchmarks · Website · Documentation
Architecture at a Glance
flowchart LR
App["Laravel App (Controllers, Services, Horizon Jobs)"]
Bridge["Pure Bridge Core (RustBridge / BridgeManager)"]
App -->|"Typed PHP Contract (DI)"| Bridge
subgraph InProcess["Path A: In-Process Native Extension (ext-php-rs)"]
Detector["NativeExtensionRegistry (Cached ABI Check)"]
RustExt["Compiled Rust .so / .dylib (~55 us FFI, catch_unwind)"]
PhpFallback["Pure PHP Fallback + NativeFallbackTriggered"]
Detector -->|"Loaded & ABI Match"| RustExt
Detector -->|"Missing & auto mode"| PhpFallback
end
subgraph OutOfProcess["Path B: Out-of-Process Tokio Sidecar (NDJSON RPC v1)"]
SidecarMgr["SidecarManager (default + Named Connections)"]
Breaker["CircuitBreakerTransport + Persistent Socket"]
Daemon["Standalone Tokio Sidecar (laravel_rust_bridge_sidecar)"]
SidecarMgr --> Breaker
Breaker -->|"Unix 0600 or Loopback TCP"| Daemon
end
Bridge -->|"NativeModuleDefinition"| Detector
Bridge -->|"SidecarModuleDefinition"| SidecarMgr
ext-php-rs vs Tokio Sidecar
This bridge supports two Rust execution models behind one unified Laravel API (RustBridge). Understanding the difference takes 30 seconds:
- Native Extension (
ext-php-rs) compiles to a.so/.dylibloaded inside PHP (likeext-gdorext-redis). Calls pass raw bytes directly over C FFI (~55 µs overhead) with zero sockets or JSON encoding. - Tokio Sidecar (
laravel_rust_bridge_sidecar) runs as a separate long-lived Rust daemon beside PHP-FPM / Horizon over a persistent Unix socket (0600) or loopback TCP (NDJSON RPC v1). One Tokio runtime stays warm across thousands of PHP requests and works with any PHP version (8.2–8.6) without recompiling.
flowchart TD
Start["Which Rust Transport Fits Your Crate?"]
Q1{"Needs Tokio, async I/O, persistent pools, or laravel-rust?"}
Q2{"Passes multi-MB raw bytes or needs <0.5 ms call overhead?"}
Q3{"Need crash isolation or zero PHP-version ABI coupling?"}
Sidecar["Use Tokio Sidecar (laravel_rust_bridge_sidecar)"]
Native["Use Native Extension (ext-php-rs + optional PHP fallback)"]
Start --> Q1
Q1 -->|Yes| Sidecar
Q1 -->|No| Q2
Q2 -->|Yes| Native
Q2 -->|No| Q3
Q3 -->|Yes| Sidecar
Q3 -->|No| Native
Native Extension (ext-php-rs) |
Tokio Sidecar (SidecarModule) |
|
|---|---|---|
| Runs where | Inside PHP-FPM / Horizon process | Separate long-lived Rust process |
| Overhead | ~55 µs (+0.055 ms, zero IPC) |
~0.2–1.5 ms (Unix socket / TCP NDJSON) |
| Best for | CPU-bound transforms on bytes or strings (images, Markdown, HTML, CSV, PDF, hashing, compression) | Async I/O, connection pools, 10k–100k concurrent tasks, gRPC, streaming, first-party laravel-rust |
| Large binary payloads | Fast (BinarySlice zero-IPC bytes) |
Avoid over JSON (pass file paths instead) |
| Persistent pools across PHP requests | Tied to each PHP worker | Shared warm across all PHP workers |
| Crash isolation | Wrap every entry in catch_unwind |
Process-isolated + optional CircuitBreakerTransport |
| PHP version coupling | Compile per PHP minor (ZEND_MODULE_API) |
Zero coupling — upgrade PHP independently |
| Built-in PHP fallback | Yes (auto / native / php modes) |
Optional in your PHP service |
| Examples in this repo | examples/image-variants/ |
examples/laravel-http/, examples/async-fanout/ |
Rule of thumb:
- Need Tokio, async I/O, persistent connection pools, process isolation, or
laravel-rust? → Tokio Sidecar. - Running synchronous CPU work on bytes/strings or need sub-millisecond FFI latency? →
ext-php-rs. - Need both? Combine them in the same Laravel controller or Horizon job — both inject as normal typed interfaces.
Read the complete deep dive, sequence diagrams, workload catalog, and pitfalls: docs/ext-php-rs-vs-sidecar.md.
PHP & Laravel Compatibility
The pure Composer package (src/) requires PHP ^8.2 and Laravel 11 / 12 / 13.
| PHP Version | ZEND_MODULE_API |
Laravel Versions | Bridge Core (src/) |
Tokio Sidecars | Native ext-php-rs (0.16.5) |
|---|---|---|---|---|---|
| PHP 8.2 | 20220829 |
Laravel 11, 12 | Supported | Supported (no rebuild) | Supported (compile with php8.2-dev) |
| PHP 8.3 | 20230831 |
Laravel 11, 12 | Supported | Supported (no rebuild) | Supported (compile with php8.3-dev) |
| PHP 8.4 | 20240924 |
Laravel 11, 12, 13 | Supported & tested | Supported & benchmarked | Supported, tested & benchmarked |
| PHP 8.5 | 20250925 |
Laravel 12, 13 | Supported & lint-verified | Supported (no rebuild) | Supported (compile with php8.5-dev) |
| PHP 8.6 | 20260924 |
Future / dev | Supported & lint-verified | Supported (no rebuild) | Supported (compile with php8.6-dev) |
Why sidecars survive PHP upgrades untouched: A Tokio sidecar communicates over NDJSON RPC v1 and never links against
libphp. Upgrading PHP 8.2 → 8.4 → 8.5 requires zero sidecar changes. Forext-php-rsextensions, rebuild once per target PHP minor version withPHP=/usr/bin/php8.X PHP_CONFIG=/usr/bin/php-config8.X cargo build --release.
Quick Start
1. Install the Pure Bridge Package
composer require olgunozoktas/laravel-rust-bridge
php artisan vendor:publish --tag=rust-bridge-config
RustBridgeServiceProvider and the RustBridge facade auto-register via Composer package discovery.
2. Inspect Active Modules & Sidecars
php artisan rust-bridge:status
php artisan rust-bridge:status --no-probe
Standalone Examples (examples/)
Everything outside the pure bridge core lives cleanly under examples/:
laravel-rust-bridge/
├── src/ # Pure Laravel <-> Rust bridge core only
├── config/rust_bridge.php # Pure bridge config (native mode + sidecars)
├── rust/sidecar/ # Pure reusable Tokio RPC server library crate
├── docs/ # Complete documentation hub (docs/README.md)
├── .claude/skills/ # Bundled AI agent skill for building extensions
├── benchmarks/ # Reproducible PHP vs Rust benchmarks
└── examples/
├── image-variants/ # Standalone ext-php-rs WebP extension + PHP GD fallback
├── laravel-http/ # Standalone Tokio sidecar powered by laravel-rust =0.1.4
├── async-fanout/ # Standalone Tokio sidecar (100,000 concurrent async jobs)
└── laravel-app/ # Complete Laravel 13 app integrating all three examples
Example 1: Native ext-php-rs in a Controller & Horizon Job (examples/image-variants)
Decodes a screenshot once in Rust and returns [768, 960, 1536] WebP variants in a single call, falling back transparently to PHP GD in auto mode if the extension is not installed:
use Illuminate\Http\Request;
use Olgun\RustBridge\Examples\ImageVariants\Contracts\ImageVariantGenerator;
final class ScreenshotController
{
public function store(Request $request, ImageVariantGenerator $variants)
{
$batch = $variants->generateWebpVariants(
imageBytes: (string) $request->getContent(),
widths: [768, 960, 1536],
quality: 80,
);
return response()->json([
'backend' => $batch->backend, // "native" or "php-gd"
'sizes' => array_map(fn ($v) => [$v->width, $v->height, $v->sizeBytes], $batch->variants),
]);
}
}
Horizon job example (examples/image-variants/src/Jobs/GenerateScreenshotVariantsJob.php):
use Olgun\RustBridge\Examples\ImageVariants\Jobs\GenerateScreenshotVariantsJob;
GenerateScreenshotVariantsJob::dispatch(
sourcePath: 'screenshots/homepage.png',
outputDirectory: 'screenshots/homepage/variants',
disk: 'local',
screenshotId: 'shot-42',
)->onQueue('media');
Example 2: First-Party laravel-rust =0.1.4 HTTP Sidecar (examples/laravel-http)
Start the long-lived sidecar once:
./target/release/laravel-rust-http-sidecar --listen tcp://127.0.0.1:7878
Inject ConcurrentHttpClient anywhere in Laravel:
use Olgun\RustBridge\Examples\LaravelHttp\Contracts\ConcurrentHttpClient;
use Olgun\RustBridge\Examples\LaravelHttp\Data\HttpBatchRequest;
final class CatalogAggregator
{
public function __construct(private ConcurrentHttpClient $http) {}
public function fetchDashboard(): array
{
$batch = $this->http->sendBatch([
HttpBatchRequest::get('catalog', 'https://internal.service/catalog'),
HttpBatchRequest::get('pricing', 'https://internal.service/pricing'),
HttpBatchRequest::postJson('audit', 'https://internal.service/events', ['type' => 'view']),
], maxConcurrency: 8);
return [
'laravel_rust_version' => $batch->crateVersion, // "0.1.4"
'catalog' => $batch->get('catalog')?->json(),
'pricing' => $batch->get('pricing')?->json(),
];
}
}
Example 3: 100,000 Concurrent Async Tasks (examples/async-fanout)
use Olgun\RustBridge\Examples\AsyncFanout\Contracts\ConcurrentTaskRunner;
$report = app(ConcurrentTaskRunner::class)->runSimulatedIoJobs(count: 100_000, delayMs: 1000);
// ~1,079 ms wall, ~48.3 MB peak RSS (368 bytes/job)
See examples/laravel-app/README.md to run the full Laravel 13 example application.
Build Your Own Rust Extension (No Fork Needed)
Ship an independent Composer package + Rust extension or sidecar and register it in your package's ServiceProvider::boot().
Plug in a Native ext-php-rs Extension
use Illuminate\Contracts\Foundation\Application;
use Olgun\RustBridge\Data\NativeExtensionSpec;
use Olgun\RustBridge\Facades\RustBridge;
use Olgun\RustBridge\Modules\NativeModuleDefinition;
use Olgun\RustBridge\Native\NativeExtensionDetector;
RustBridge::registerNativeModule(new NativeModuleDefinition(
name: 'acme-markdown',
extension: NativeExtensionSpec::forExtension(
extensionName: 'acme_markdown',
expectedAbiVersion: 1,
requiredFunctions: ['acme_markdown_to_html'],
),
nativeFactory: fn (Application $app, NativeExtensionDetector $detector) => new NativeMarkdownRenderer($detector),
fallbackFactory: fn (Application $app) => new PhpMarkdownRenderer(),
contract: MarkdownRenderer::class,
package: 'acme/laravel-rust-markdown',
));
Plug in a Dedicated Tokio Sidecar Daemon
use Illuminate\Contracts\Foundation\Application;
use Olgun\RustBridge\Contracts\SidecarTransportInterface;
use Olgun\RustBridge\Data\SidecarEndpointConfig;
use Olgun\RustBridge\Facades\RustBridge;
use Olgun\RustBridge\Modules\SidecarModuleDefinition;
RustBridge::registerSidecar('acme-search', new SidecarEndpointConfig(
endpoint: 'unix:///run/acme-search.sock',
authToken: config('acme_search.token'),
circuitBreakerEnabled: true,
));
RustBridge::registerSidecarModule(new SidecarModuleDefinition(
name: 'acme-search',
factory: fn (Application $app, SidecarTransportInterface $transport) => new RustSearchClient($transport),
contract: FullTextSearch::class,
sidecarConnection: 'acme-search',
package: 'acme/laravel-rust-search',
));
Full third-party authoring guide: docs/building-a-third-party-package.md and docs/protocol-v1.md.
AI Agent Skill
This repository ships a dedicated agent skill at .claude/skills/laravel-rust-bridge/SKILL.md with focused optimization and security references:
.claude/skills/laravel-rust-bridge/SKILL.md: transport selection workflow (ext-php-rsvs Tokio sidecar), SOLID registration, and build/verification commands..claude/skills/laravel-rust-bridge/references/ext-php-rs-optimization.md: zero-copyBinarySlice/Binary,catch_unwindpanic guards, bounded worker pools, thread-local buffer reuse, ABI versioning, and decompression-bomb limits..claude/skills/laravel-rust-bridge/references/sidecar-optimization.md: embeddinglaravel_rust_bridge_sidecar,SidecarModule, persistent Unix sockets (0600), constant-time auth,SafeDnsResolverSSRF blocking, andCircuitBreakerTransport.
Building the Reference Extensions (Separate from Composer)
Composer installs PHP code only. Build the Rust workspace crates separately for your target host and PHP version (PHP 8.2, 8.3, 8.4, 8.5, or 8.6 on Linux or macOS):
# Linux — set PHP_VER to 8.2, 8.3, 8.4, or 8.5
PHP_VER=8.4
PHP="/usr/bin/php${PHP_VER}" \
PHP_CONFIG="/usr/bin/php-config${PHP_VER}" \
cargo build --release \
-p laravel-rust-image-variants-ext \
-p laravel-rust-http-sidecar \
-p laravel-rust-async-fanout-sidecar
# macOS — Homebrew PHP (php@8.2, php@8.3, php@8.4, or php) + Xcode Command Line Tools
PHP=/opt/homebrew/bin/php \
PHP_CONFIG=/opt/homebrew/bin/php-config \
LIBCLANG_PATH=/Library/Developer/CommandLineTools/usr/lib \
cargo build --release \
-p laravel-rust-image-variants-ext \
-p laravel-rust-http-sidecar \
-p laravel-rust-async-fanout-sidecar
Hardened production sidecar example (Unix socket 0600, constant-time auth, anti-DNS-rebinding SSRF blocking):
export RUST_BRIDGE_SIDECAR_TOKEN="replace-with-high-entropy-secret"
./target/release/laravel-rust-http-sidecar \
--listen unix:///run/laravel-rust-bridge/http-sidecar.sock \
--auth-token-env RUST_BRIDGE_SIDECAR_TOKEN \
--block-private-networks \
--allowed-hosts api.example.com,*.trusted.example
Full Linux phpenmod, php8.4-fpm, Horizon restart, and macOS instructions: docs/building-the-extension.md.
Benchmarks
Measured uncontended on 2026-12-02 (macOS arm64, PHP 8.4.24, Rust 1.99.1 --release):
1. Native ext-php-rs (examples/image-variants, 1920x1080 PNG → [768, 960, 1536] WebP, 30 iterations)
Each preset (effort = 4 and effort = 2) was run in its own paired three-tier benchmark (benchmarks/results-latest.json and benchmarks/results-effort2.json). Both paired PHP GD baselines are shown below so the speedup denominators stay explicit:
| Run & Tier | Mean wall (ms) | p95 wall (ms) | CPU / iter (ms) | Gain vs Paired GD Baseline |
|---|---|---|---|---|
Run A (effort = 4): Pure PHP GD baseline (results-latest.json) |
131.205 |
137.186 |
130.767 |
Run A baseline |
Run A: PHP → ext-php-rs (effort = 4, strict GD parity) |
57.793 |
58.419 |
94.724 |
2.27x mean (2.35x p95, 1.38x CPU) |
Run B (effort = 2): Pure PHP GD baseline (results-effort2.json) |
146.227 |
290.091 |
136.822 |
Run B baseline |
Run B: PHP → ext-php-rs (effort = 2, fast Horizon preset) |
35.512 |
35.928 |
57.677 |
4.12x vs Run B GD (146.227 ms) · 3.70x vs Run A GD (131.205 ms) · +55 µs FFI delta |
2. Tokio Sidecar Concurrency (examples/async-fanout, 100,000 × 1s Async Jobs)
| Runner | Jobs | Wall (ms) | Peak Mem (MB) | Bytes / Job |
|---|---|---|---|---|
| PHP sequential (exact math) | 100,000 |
100,000,000 (27h 46m) |
n/a | n/a |
| PHP 8.4 Fibers | 10,000 |
1,055.5 |
168.00 |
17,406 |
| PHP → Tokio sidecar | 100,000 |
1,079.3 |
48.34 |
368 (47.3x smaller) |
3. First-Party laravel-rust =0.1.4 HTTP (examples/laravel-http, 200 × 100ms Concurrent Requests)
- PHP
curl_multi(Http::pool):138.9 mswall,10.50 msPHP CPU. - PHP →
laravel-rust-http-sidecar:112.8 mswall (1.23xfaster),1.19 msPHP CPU (8.8xless PHP CPU).
Run the benchmarks yourself:
php benchmarks/run_all.php --iterations=30 --warmup=5 --effort=4 --profile
php benchmarks/run_all.php --iterations=30 --warmup=5 --effort=2 --profile
NO_PROXY=127.0.0.1,localhost php benchmarks/run_concurrency_bench.php
Verification & Tests
# Rust workspace tests
cargo test --release -p laravel-rust-bridge-sidecar -p bridge-image-variants -p bridge-async-fanout -p bridge-laravel-http
# Package Pest suite (without and with native extension)
php vendor/bin/pest
php -d extension=./target/release/liblaravel_rust_image_variants.dylib vendor/bin/pest
# Real Laravel 13 example application tests
cd examples/laravel-app
php vendor/bin/pest
php -d extension=../../target/release/liblaravel_rust_image_variants.dylib vendor/bin/pest
Documentation (/docs)
Browse the complete index at docs/README.md:
| Guide | Purpose |
|---|---|
docs/ext-php-rs-vs-sidecar.md |
Detailed comparison of native ext-php-rs extensions vs Tokio sidecar modules |
docs/building-the-extension.md |
Linux PHP 8.4 & macOS compilation, installation, and daemon supervision |
docs/building-a-third-party-package.md |
Ship your own Laravel + Rust Composer package without forking |
docs/adding-a-crate.md |
Add a new standalone example crate inside this workspace |
docs/protocol-v1.md |
Sidecar NDJSON RPC Wire Protocol v1 specification |
docs/architecture-and-security.md |
SOLID design patterns, performance architecture, and defense-in-depth security |
docs/benchmarks.md |
Full methodology, hardware specs, and stage profiles |
docs/adr/0001-dual-transport-and-laravel-rust-integration.md |
Architecture Decision Record for dual transport & laravel-rust |
docs/laravel-rust-ecosystem-audit.md |
Verified public APIs and features of official laravel-rust crates |
More products by the same author
Other production web applications and developer tools maintained by the same author:
| Logo | Product | What it is |
|---|---|---|
| Main App | Curated multi-platform application directory (macOS, web, iOS, Windows) running Laravel + Livewire. | |
| FindUtils | 460+ free browser tools — converters, formatters, PDF tools, generators, and calculators with no signup and local-first browser processing. | |
| Emoji Favicons | Turn any of 3,773 Unicode emojis into an edge-hosted SVG, PNG, or ICO favicon with one <link> tag and a documented API. |
|
| DataVisitors | Privacy-first software analytics for websites, apps, and servers — no cookies on visitors by default, tracking sources, behavior, and conversions. |
License
MIT — see LICENSE.