Eien
Eien is Leaf's runtime for apps that need more speed than a classic PHP setup gives them. It runs your app on FrankenPHP in worker mode, where the app boots once and every request after that is served from memory.
You don't rewrite anything to use it. Install Eien, and leaf serve starts running your app on it:
leaf install eien
leaf serveHow it works
On a classic setup PHP starts from nothing on every request. It loads Composer's autoloader, builds the Leaf instance, reads your config and registers every route, then throws all of that away once the response is sent.
Under Eien that work happens once per worker. Your index.php runs from the top as usual, and when it reaches app()->run() Leaf stays there and handles requests in a loop instead of answering one and exiting. Routes, middleware, config and loaded classes stay in memory between requests, while each request gets its own request and response objects.
<?php
require __DIR__ . '/vendor/autoload.php';
app()->get('/', function () {
return response()->json(['message' => 'Hello']);
});
app()->run();This is a complete Eien app. Leaf MVC apps work the same way, since Leaf\Core::runApplication() ends in the same run() call.
Installation
Install Eien, then update Leaf and its modules to their latest releases:
leaf install eien
composer updateEien needs Leaf 5.1 and the HTTP module 5.1 or newer. If your app uses Auth, Form, Lingo, Inertia, CSRF, CORS, Vite or Mail, their latest releases are the ones that clear their per-request state in a worker (see Leaf modules).
Then serve your app the way you always have:
leaf serveThe first run downloads FrankenPHP into a .eien folder in your home directory. That happens once and is shared by all your apps. If the download fails, or there is no build for your machine, leaf serve tells you and carries on with PHP's built-in server. From then on leaf serve runs your app in worker mode, and restarts the workers whenever you edit a PHP file or your .env, so your changes still show up on the next request.
| Command | What it does |
|---|---|
leaf serve | Serves the app on Eien in worker mode, restarting workers when files change |
leaf serve --prod | Serves the way production does: no file watching, no file checks, two workers per CPU core |
leaf serve --no-eien | Uses PHP's built-in server, as if Eien was not installed |
Vite, the queue worker and the other processes leaf serve starts alongside your app keep working as before.
Needs Leaf CLI 5.1
The leaf serve integration is in Leaf CLI 5.1 and leafs/mvc-core 5.3. If your versions predate it, use the eien command below.
The eien command
Eien also ships its own command in your vendor folder. It is what leaf serve calls, and it is the one to use on a server where the Leaf CLI is not installed:
php vendor/bin/eien serve --prod| Command | What it does |
|---|---|
eien serve | Same as leaf serve with Eien installed |
eien info | Shows how Eien would serve the app, without starting anything |
eien install | Downloads FrankenPHP ahead of time |
serve and info accept --port, --host, --prod, --threads, --no-worker, --no-watch, --jit and --verbose. Run php vendor/bin/eien help for the full list.
Eien writes the server config it generates, and the server's log, into a .eien folder in your project. That folder ignores itself in git.
With FrankenPHP directly
Eien is a thin layer over FrankenPHP, so you can skip it and run FrankenPHP yourself. Install FrankenPHP, then start it from your project root with your entry file as the worker script:
frankenphp php-server --root public --worker public/index.php --listen :8000frankenphp php-server --worker index.php --listen :8000If you prefer a Caddyfile, this is the equivalent for an MVC app:
{
frankenphp {
worker {
file ./public/index.php
num 8
}
}
}
:8000 {
root * public
php_server
}num is how many copies of your app stay booted. Each one serves a single request at a time, so it is also the number of requests PHP can work on at once.
What to know about worker mode
Most Leaf apps run under Eien unchanged. What differs is that the process keeps running after the response is sent, and everything in this section follows from that.
Code changes restart the workers
A worker keeps your code in memory, so an edit does nothing until the worker restarts. In development Eien handles that for you: it watches your PHP files and your .env, and restarts the workers when one changes. Folders your app writes to or that only change on install (vendor, node_modules, storage) are left out.
With --prod nothing is watched, so restart the server when you deploy new code.
Statics and singletons outlive the request
Anything you store in a static property, a global, or an object you keep around is still there when the next request arrives, and that request may belong to a different visitor.
class Cart
{
protected static $items = [];
public static function add($item)
{
static::$items[] = $item;
}
}On a classic setup Cart::$items starts empty on every request. In a worker it keeps growing, and one visitor's items show up for the next. Keep per-visitor data in the session, the database or the request instead.
Caching things that are the same for everybody is fine and is part of why worker mode is fast. A parsed config file or a compiled list of routes can safely live in a static.
Ending a request early
response()->exit(), response()->redirect() and app()->halt() work as they always have. Under Eien they end the request and leave the worker running.
The same goes for the places where Leaf ends a request for you: a failed CSRF check (with or without your own onError handler), an auth middleware that turns a visitor away, and the answer to a CORS preflight request.
A raw exit() or die() in your own code still works, but PHP gives Leaf no way to catch it, so the worker shuts down and boots again. The response is correct and that one request pays the full boot cost. Prefer the response helpers.
Sessions
Sessions are isolated between requests by FrankenPHP itself, so session() and $_SESSION behave the way you expect.
Leaf does two things to keep them cheap:
- A session starts when a visitor needs one. With CSRF protection on, Leaf waits until your app asks for the token before it starts a session. A crawler or an API client that never submits a form leaves no session file behind. See When the session starts.
- Expired sessions are cleared on a timer. PHP normally clears them on a random 1 in 100 requests, and that request waits while every session file is checked. A worker does it every five minutes instead, after the response has gone out. If you have set
session.gc_probabilityto0, Leaf takes that to mean you clear sessions yourself and leaves them alone.
Leaf modules
Several Leaf modules remember things about the current request on objects that now live across requests. Their latest releases clear that state before every request:
| Module | What is reset between requests |
|---|---|
| Auth | The resolved user, auth errors and the in-memory role cache |
| Form | Validation errors |
| Lingo | A locale forced with overrideCurrentLocale() |
| Inertia | Props shared during a request and the history flags. Props shared while booting are kept. |
| CSRF | Each request gets its own session and token, started when the token is first needed |
| CORS | Headers are worked out again for every request, so each one is answered for its own origin |
| Error pages | Breadcrumbs and request details on crash reports |
| Database | A query that was built but never run. A transaction the request left open is rolled back as soon as the request ends. |
| Vite | The list of preloaded assets, the check for a running dev server, and a CSP nonce that Vite generated. The build manifest stays in memory. |
| Errors from earlier sends | |
| Redis | A connection that sat idle is checked before it is used again, and reopened if the server closed it |
The cache, Redis, queue, file system, session and cookie modules were reviewed too and needed no changes, since they keep nothing about a request once it is over.
One thing is left to you: a CSP nonce you pass in yourself, as in Vite::useCspNonce($nonce), stays until you set it again. Set it inside a middleware so every request gets its own. A nonce that Vite generates for you, with Vite::useCspNonce() and no argument, is replaced before every request wherever you call it.
Database connections
A worker keeps its database connection open between requests, which saves the cost of connecting every time. Two things follow from that, and Leaf handles both for Leaf Db and for models in Leaf MVC:
- A transaction has to end with its request. If a request starts a transaction and finishes without committing it, Leaf rolls it back as soon as the response is sent, so the next request never runs inside it.
- Idle connections get closed by the database server. When a query finds its connection gone, Leaf Db connects again and runs the query once more. A query inside a transaction is not retried, since the earlier work in that transaction is already lost, and you get the error instead.
For module authors
If your package keeps anything about the current request on a long-lived object or a static, register a reset with App::onWorkerRequest(). Leaf runs it before every request a worker serves, and never calls it on a classic setup.
if (\defined('LEAF_WORKER') && \LEAF_WORKER && \method_exists('Leaf\App', 'onWorkerRequest')) {
\Leaf\App::onWorkerRequest(function () {
\Leaf\Config::get('cart')->resetRequestState();
});
}The method_exists check keeps your package working on versions of Leaf that predate worker mode. LEAF_WORKER is true when the current process was started as a worker.
If your package holds something the request must let go of straight away, like a lock or an open transaction, use App::afterWorkerRequest() instead. Leaf runs it right after the response is sent, without waiting for the next request to arrive.
If your package ends a request itself, replace exit with Leaf\Http\Halt::now(). Send your response first, then call it. In a worker it stops the request and keeps the worker running, and on a classic setup it exits as before.
response()->json(['error' => 'Not allowed'], 403);
if (\method_exists('Leaf\Http\Halt', 'now')) {
\Leaf\Http\Halt::now();
}
exit;The method_exists check and the trailing exit keep the package working with versions of the HTTP module that predate worker mode.
Performance
These are our own measurements, and yours will differ with hardware and with what your routes do.
On a 15-core Mac, a fresh Leaf MVC app served through FrankenPHP:
| Route | Classic mode | Worker mode |
|---|---|---|
| JSON response | 10,681 req/s | 54,671 req/s |
| Route with a parameter | 10,698 req/s | 54,968 req/s |
| Blade view | 9,886 req/s | 44,501 req/s |
The slowest 1% of JSON requests took about 17.6 ms in classic mode and 1.5 ms in worker mode. Each figure is the median of three runs with 32 connections, taken from the best session we recorded for that route, and the routes did not touch a database.
In an earlier test on a 6 vCPU Linux VM, using a hand-written worker script, a bare Leaf app with three routes went from about 40,000 to about 75,000 requests per second, between 1.7 and 1.9 times faster. The gain is larger for MVC apps because they do more work while booting, and that is the work a worker skips.
Sessions have their own cost. On the same machine, a bare Leaf app with CSRF protection on, in worker mode:
| Request | Before | Now |
|---|---|---|
| JSON route, visitor with no session | 1,974 req/s | 53,458 req/s |
| JSON route, returning visitor | 1,756 req/s | 36,183 req/s |
| Route that prints the token, visitor with no session | 1,568 req/s | 17,370 req/s |
"Before" is Leaf starting a session on every request and PHP clearing expired sessions inside requests. That run left about 100,000 session files behind within a minute, and scanning them is what held it down. The last row still creates a session per request, since every new visitor who is shown a form needs one.
Routes that spend most of their time in the database will see a smaller difference, since worker mode removes boot time and leaves query time as it is.
What Eien does not do yet
- WebSockets.
app()->ws()was removed in Leaf 5 and Eien does not replace it yet. - Windows and Intel Macs. FrankenPHP publishes a Windows build that Eien does not use yet, and it has no build for Intel Macs. On both,
leaf servekeeps using PHP's built-in server, so having Eien installed changes nothing. - Swoole and ReactPHP. An earlier version of this page described a rebuild around those runtimes. Eien runs on FrankenPHP instead, and the Swoole-based version of Eien is no longer maintained.
If you run Eien on a real app, tell us how it goes on GitHub or Discord.
