I have loved Rust for a long time. Laravel even longer: DevSense, the site you are reading right now, is built on it. So when the Laravel Rust beta came out on 1 December 2026, I could not just watch from the side. The familiar routes, middleware and .env, but one binary instead of php-fpm. Yes, the framework is still raw, version 0.1.5. All the more interesting.
On 3 December the first DevSense route started answering from Rust. Not in a sandbox and not in a demo project, but in production, next to a live Laravel app, on the same database.
This is the first entry of a day-by-day series: how a live project moves from Laravel to Laravel Rust. No gloss — code, pitfalls and numbers.
In short
- What we did: the page view counter
POST /api/visitis now served by Rust. Everything else is still PHP. - How: nginx gives Rust one address. If Rust stays silent, the same request quietly goes to PHP.
- The hard part: not Rust itself, but the seam with PHP — sessions, cookies and a shared database.
- Memory: the whole Rust service takes 16 MB. One php-fpm process takes 62 MB on average.
Why not "rewrite everything over the weekend"
The temptation is clear. But a live site has users, and a beta will have breaking changes. Rewriting everything and flipping a switch means betting the whole site on one evening.
We picked a boring but reliable path: route by route.
Visitor → Cloudflare → nginx ─┬─ POST /api/visit → Laravel Rust ─┐
│ (on 502/503/504 → PHP) ├─→ PostgreSQL
└─ everything else → Laravel (PHP) ─┘
Three rules we set on day one:
- The fallback lives in nginx. Rust is down — the request goes to PHP. The visitor notices nothing, and we get time to look into it.
- One database. Rust and PHP write to the same PostgreSQL. Tables and migrations stay with PHP.
- Login and logout stay in PHP. Login, logout, "remember me" and password changes do not move until everything moves. Rust only reads the session.
This way every mistake costs one address, not the whole site.
Sessions: twins separated at birth
Laravel Rust reads the same sessions table as PHP: same columns, same keys inside. But one look at the payload column shows the twins grew up in different families.
| What | Laravel PHP | Laravel Rust 0.1.5 | Result |
|---|---|---|---|
sessions table |
id, user_id, ip_address, user_agent, payload, last_activity |
same columns | ✅ |
payload |
base64 of JSON | plain JSON | ❌ |
| Keys inside | _token, _previous.url, _flash |
the same | ✅ |
| Who is logged in | login_web_59ba36… → user id |
_auth.web → {id, fingerprint} |
❌ |
| CSRF | _token |
_token |
✅ |
The upshot: out of the box, Laravel Rust cannot read a session written by PHP. It expects JSON and gets base64. Say we decode the base64 — it still will not find the user. PHP keeps the user under login_web_ plus the sha1 of the guard class name, while Rust looks for _auth.web.
We did not change PHP to suit Rust: the sessions of live users must survive the move. Rust learns to read the PHP way instead. Laravel Rust already has the hooks for that — custom session stores and registering a guard.
Cookies: here it all lines up
Cookies were a pleasant surprise: encryption and signing match exactly.
- Cipher: AES-256-CBC, the
APP_KEYinbase64:…format, previous keys supported. - Envelope: base64 of JSON
{iv, value, mac, tag}, signed with HMAC-SHA256. - Bound to the name: before encryption, a prefix is glued to the value, so a cookie of one name cannot pass for another.
value = hmac_sha1(cookie_name + "v2", APP_KEY) + "|" + real_value
cookie = encrypt(value)
We did not take it on trust and checked both directions. A small PHP script on real Laravel 13.43 classes issues a cookie and a payload with a throwaway key, and Rust tests decode them. The same script in reverse checks that PHP accepts what Rust wrote. A wrong cookie name or a wrong key — refused, as it should be.
The only mismatch is "remember me". In PHP it is remember_web_<sha1> holding id|token|hash, in Laravel Rust it is remember_web holding JSON. There is already issue #660 about it. It does not bother us yet: login stays in PHP.
An adapter with three jobs
A small internal crate, devsense-php-compat, closes all the gaps. It does exactly three things:
- decrypts and encrypts cookies in Laravel's format — on top of the framework's own function, with no crypto of its own;
- reads and writes the session
payloadas base64 of JSON; - finds the logged-in user by the
login_web_…key.
The test samples are made by real Laravel, not by hand. If a Laravel update changes the format, the test fails at once.
We are in no hurry to publish the adapter on crates.io. First it has to prove itself in production. Then we will offer it to laravel/rust-framework as small pull requests — each with a documentation update. A feature nobody can read about does not exist for anyone else.
The test subject: POST /api/visit
DevSense serves guest pages from the Cloudflare cache. A small script counts the view: it sends the page path to /api/visit. A better candidate for the first move is hard to imagine:
- no login — no session and no cookies, so they do not get in the way yet;
- frequent — it fires on every guest view, and each such request used to take a php-fpm worker;
- checkable — one row in
page_visits, easy to compare with the row from PHP; - safe — the worst a bug can do is lose some page views.
One controller, two languages
Below is real production code, not simplified. First PHP, which stays as the fallback:
class VisitBeaconController extends Controller
{
public function __invoke(Request $request): Response
{
$site = $request->headers->get('Sec-Fetch-Site');
$origin = $request->headers->get('Origin');
$originHost = is_string($origin) ? parse_url($origin, PHP_URL_HOST) : null;
$crossSite = (is_string($site) && $site !== 'same-origin')
|| (is_string($origin) && $originHost !== $request->getHost());
$path = $request->input('p');
$userAgent = (string) $request->userAgent();
$detection = CrawlerDetector::detect($userAgent);
if ($crossSite || $detection['is_bot'] || ! is_string($path) || ! $this->validPath($path)) {
return response()->noContent();
}
$trimmed = ltrim((string) parse_url($path, PHP_URL_PATH), '/');
$first = explode('/', $trimmed)[0];
$referer = $request->input('r');
try {
PageVisit::create([
'ip_hash' => hash('sha256', $request->ip() ?: '127.0.0.1'),
'url' => substr(rtrim((string) config('app.url'), '/').$path, 0, 500),
'path' => substr($trimmed === '' ? '/' : $trimmed, 0, 255),
'user_agent' => substr($userAgent, 0, 500),
'crawler_name' => null,
'is_bot' => false,
'is_ai' => false,
'locale' => in_array($first, SetLocale::SUPPORTED_LOCALES, true) ? $first : config('app.locale'),
'referer' => is_string($referer) && str_starts_with($referer, 'http') ? substr($referer, 0, 500) : '',
]);
} catch (\Throwable) {
// Counting must never break anything for the visitor.
}
return response()->noContent();
}
}
Now the same thing in Rust. The route looks familiar to anyone who has written routes/api.php:
route.post("/visit", visit::store)
.middleware(Throttle::per_minute(30).bucket("visit"));
And the handler itself:
#[laravel::input]
pub struct Beacon {
p: Option<String>,
r: Option<String>,
}
pub async fn store(request: Request) -> Response {
let user_agent = request.header("user-agent").unwrap_or_default().to_owned();
let cross_site = is_cross_site(
request.header("sec-fetch-site"),
request.header("origin"),
&request.host(),
);
let ip = request.ip().to_string();
let beacon: Option<Beacon> = request.parse().ok();
let path = beacon.as_ref().and_then(|b| b.p.clone());
let Some(path) = path.filter(|p| !cross_site && !is_bot(&user_agent) && valid_path(p)) else {
return no_content();
};
let referer = beacon.and_then(|b| b.r);
let row = Visit::new(&ip, &path, &user_agent, referer.as_deref());
let saved = db::table("page_visits")
.insert(db::values! {
ip_hash: row.ip_hash,
url: row.url,
path: row.path,
user_agent: row.user_agent,
crawler_name: Option::<String>::None,
is_bot: false,
is_ai: false,
locale: row.locale,
referer: row.referer,
created_at: db::raw!("LOCALTIMESTAMP(0)"),
updated_at: db::raw!("LOCALTIMESTAMP(0)"),
})
.await;
if let Err(error) = saved {
tracing::warn!(%error, "counting a visit failed");
}
no_content()
}
What stands out:
- Almost line for line. Same steps, same order. Porting code like this is easier than it looks.
- Input is a type. Instead of
$request->input('p')and anis_stringcheck, there is aBeaconstruct withOption<String>. A missing or non-string field is visible right in the type. - An error is a value, not an exception. PHP catches everything in
catch (\Throwable)and stays quiet. Rust gets aResultfrom the database and logs a warning. Either way the visitor gets204. - No model. PHP writes through Eloquent, Rust through the query builder
db::table(…).insert(…). One insert does not need a model, and the database sets the time itself. - The regex became code. The path check is two
preg_matchcalls in PHP and a few lines of parsing in Rust, with no regex library. Longer, but each condition stands on its own. - Easier to test.
Visit::new,valid_pathandis_cross_siteare plain functions with no request and no database. Unit tests cover them, not HTTP tests.
One subtle point — trusted proxies. The site sits behind Cloudflare, and the visitor's real IP arrives in X-Forwarded-For. Get the setting wrong, and every visitor gets the IP of a Cloudflare node, so the 30-requests-a-minute limit becomes one limit for everyone. Rust takes the same list of Cloudflare networks as PHP. But in Laravel Rust * means "take the first address in the header", and the client chooses that one. So we do not accept * — only an explicit list.
Day one pitfalls
The code took the least time. Everything else went into the environment.
| What happened | Why | What we did |
|---|---|---|
The service got stuck in FATAL |
The supervisor config was added before the binary arrived, and supervisor gave up after a few tries | Started it by hand and wrote down the order of steps |
| CI did not restart the service | supervisorctl status returns an error when the program is not running, and CI read that as "not set up" |
CI now reads the command output and starts the service from any state |
.env ended up with an empty key and password |
The file was built from shell variables, and the command was rerun in a new terminal session | Recreated it in one paste; we check the key length without showing the key |
/up answered 200, but no row was written |
The health check does not touch the database | We check with a real request and a SELECT |
| A direct request in production was refused | In production, Laravel Rust answers only for the host from APP_URL |
We send Host: devsense.work in every check |
Security headers came twice, plus CORS * |
Both nginx and the framework's middleware set them | Removed SecurityHeaders and HandleCors from the Rust pipeline |
The final check went through the whole path: Cloudflare → nginx → Rust → database. Then we stopped Rust and sent the same request. PHP answered, the row was written, and a visitor would have noticed nothing. Three rows — a direct request to Rust, a request through nginx and the PHP fallback — came out identical.
And a bonus. Comparing the Rust and PHP rows, we found a bug in PHP itself: server-side view tracking ran before the locale was set and stored en for every page. We fixed the code and the old rows. The move had barely started and already paid for itself.
The scoreboard
The whole Rust service uses 16 MB of memory. One php-fpm process uses 62 MB on average. Requests to /api/visit no longer take php-fpm workers, and our 1 GB server has only a handful of them.
We are not comparing speed under load yet. At our traffic such a test would show nothing, and we do not trust synthetic benchmarks.
What comes next
Each next step adds exactly one new difficulty:
- A route with a token. The pre-commit file check in the DevSense team space (
POST /api/zones/{project}/check). No session there, but token authentication. - Routes for logged-in users. This is where everything about sessions and cookies pays off: a session store in PHP's format and a guard that finds the user by
login_web_…. Both read-only. - A contribution to the framework. Once the adapter has worked on several routes, we will offer it to Laravel Rust — together with documentation.
An honest review — later. When more routes have moved to Rust, I will write a separate review with no varnish:
- performance on our server and our data, not in a synthetic test;
- the cost of the move: how long a route takes and where the time goes;
- the pitfalls. The main one is the lack of equivalents for familiar packages. Laravel PHP has a package for almost everything, while for Laravel Rust only some have been ported so far, such as Spatie's first packages. Whatever is missing, we will have to write ourselves.
And to answer the main question: is it worth it for a project our size.
Day one in a nutshell. Laravel Rust is raw, but already fit for real production — if you move one route at a time and keep the PHP fallback within reach. The hardest part was not the Rust code but the seam with PHP. The next route is coming in "Day 2".
Links
- Laravel Rust announcement — Laravel blog
- Laravel Rust documentation: sessions, authentication, middleware, routing, rate limiting, packages
- laravel-rust on docs.rs — API reference
- github.com/laravel/rust — the application skeleton
- github.com/laravel/rust-framework — the framework core
- Laravel Rust: what it is and what it means for PHP developers — our review of the beta