Replacing Laravel with Rust: A Practical Migration Guide for 2026
Derar SattoufUpdated Backend & databases

I ship Laravel, Next.js, and Python for a living, and I like all three. Laravel in particular is one of the most productive ways to build a web backend that exists: Eloquent, queues, mail, auth, validation, testing, and a scheduler arrive in one coherent package, with docs that are genuinely good. So this is not a "Laravel is slow, rewrite it" post.
It is a guide for the narrower situation where Rust is on the table: a hot service that is expensive to run, a long-lived connection workload, a correctness-critical core, or a team that already has Rust skills. If that is you, the real questions are what to move, in what order, and how to avoid a two-year rewrite that never ships.
Most Laravel apps shouldn't be rewritten in Rust. If your bottleneck is N+1 queries, missing indexes, or no caching, fix those first. That's days of work, not months. When a migration is justified, do it incrementally, never big-bang: put a reverse proxy (nginx, Caddy, Traefik) in front, route one endpoint at a time to a Rust service, and keep Laravel serving everything else (the strangler fig pattern). Start with the hottest, most self-contained endpoints: high-traffic read APIs, webhooks, ingestion, streaming, websockets, anything CPU-bound.
Share the database first, not the code. Keep Laravel migrations as the schema source of truth during the transition, and have Rust read the same tables with SQLx. Auth is the easiest thing to get wrong: verify existing bcrypt or argon2 hashes in Rust, validate Sanctum tokens by hashing and looking them up, and don't try to read Laravel's PHP-serialized sessions.
Axum + SQLx + Tower + tracing is the default stack. Use Loco only if you want a Rails-style framework and accept its conventions. Plan for the people cost, too. Rust has a learning curve (ownership, async, error handling), so budget a 30/60/90 day ramp and keep the first service boring. And verify with contract tests: record golden responses from Laravel and replay them against Rust. Behavior parity is the whole game.
The code uses Axum 0.8-era and SQLx 0.8-era APIs. Versions move fast, so wherever a crate API matters, the text says to verify against current docs.
Should you migrate at all? A decision framework
Why teams consider Rust
| Motivation | What is real | What is overstated |
|---|---|---|
| Throughput and latency | Rust services handle far more requests per core and have flat tail latency (no GC, no per-request bootstrapping) | A well-cached Laravel app on Octane or FrankenPHP is often fast enough; DB time usually dominates |
| Memory and cost | A Rust process typically needs a small fraction of the memory of PHP worker pools, which can cut instance counts | Only matters at scale; for a few servers, the engineering cost exceeds the savings |
| Safety | Memory safety, no data races in safe code, exhaustive match, Option instead of null | Rust does not prevent logic bugs, SQL injection via string concatenation, or bad authorization checks |
| Concurrency | Tokio handles tens of thousands of concurrent connections cheaply; great for websockets, SSE, fan-out | PHP can do this too with Octane (Swoole, RoadRunner) or by offloading to a dedicated service |
| Long-lived services | Single static binary, predictable memory, no worker recycling | Laravel queue workers are long-lived too and work fine with supervisor/Horizon |
| Correctness | Types encode invariants; refactors are safer | Slower to write; compile times; steeper onboarding |
Honest reasons not to migrate
- Developer velocity. Laravel gets a CRUD feature with validation, policy, resource, queue job, and test shipped in an afternoon. The same feature in Rust takes noticeably longer, especially in the first months.
- Ecosystem batteries. Laravel ships (or has first-party packages for) auth scaffolding, Socialite, Cashier (Stripe billing), Scout (search), Horizon, Telescope, Nova/Filament admin panels, Pennant (feature flags), Livewire/Inertia. In Rust you assemble or build most of this yourself.
- Hiring. PHP/Laravel developers are plentiful. Rust backend developers are fewer and more expensive in most markets, though the gap is closing.
- Your bottleneck is not PHP. Most slow Laravel apps are slow because of queries, missing caching, synchronous third-party calls, or oversized payloads. Rust will not fix those.
- Admin panels and back-office UIs. Filament and Nova have no real Rust equivalent. Keep them in Laravel.
- Churn risk. A rewrite freezes features, splits attention, and routinely overruns. Joel Spolsky's "never rewrite from scratch" essay is old but its core argument still holds.
Scorecard
Score each line from 0 (no) to 2 (strongly yes). Add up.
| Signal | 0 | 1 | 2 |
|---|---|---|---|
| You have profiled and the bottleneck is CPU or per-request framework overhead, not the database | No | Partly | Yes |
| You have already applied caching, indexes, eager loading, queues, and Octane or FrankenPHP | No | Some | All |
| Infrastructure cost for this workload is material (for example, a large fraction of your cloud bill) | No | Noticeable | Major |
| Workload involves long-lived connections, streaming, or heavy fan-out | No | Some | Core |
| Correctness or security of a specific module is business-critical (billing, ledger, protocol parsing) | No | Somewhat | Yes |
| At least two engineers already know Rust, or you have 3+ months of ramp budget | No | One | Yes |
| The target is a bounded, well-tested module with a clear HTTP or queue boundary | No | Mostly | Yes |
| Leadership accepts a multi-month period with two stacks | No | Reluctantly | Yes |
How to read the score:
- 0-5: Stay on Laravel. Optimize it. Revisit in a year.
- 6-10: Extract one or two hot endpoints or a worker into Rust as an experiment. Do not commit to more yet.
- 11-16: A phased strangler migration is justified. Still keep Laravel for admin, billing integrations, and anything low-traffic.
Decision tree in words
- Have you profiled? If no, stop and profile. Use Laravel Telescope, Clockwork, Blackfire, or APM traces. If the database dominates, fix queries and caching first.
- Is the slow part a handful of endpoints? If yes, extract only those into a Rust service behind your proxy. Leave the rest.
- Is the cost concentrated in a background workload (image processing, parsing, ETL, notifications fan-out)? Write a Rust worker that consumes from its own queue. This is the lowest-risk migration there is.
- Is it websockets, SSE, or other long-lived connections? Put those in a Rust service. Laravel Reverb is good, but if you are operating at a scale where it is a cost problem, Rust is a reasonable place to go.
- Is the pain developer velocity or maintainability, not performance? Rust will likely make that worse in the short run. Consider modular monolith refactoring in Laravel instead.
- Do you have no Rust experience and a hard deadline? Do not start with Rust on the critical path. Prototype on a side project or an internal tool first.
- Is the whole application a candidate? Only if the app is small, well-specified, well-tested, and the team wants Rust for its own sake. Otherwise stay incremental.
Alternatives to consider before Rust
| Option | When it is enough |
|---|---|
| Laravel Octane (FrankenPHP, Swoole, RoadRunner) | Per-request bootstrap overhead is the problem |
| Caching, query tuning, read replicas | The database is the bottleneck |
| Move queue-heavy work to a dedicated worker pool | Web latency is fine, background throughput is not |
| Go or Node for a specific service | The team wants faster services without Rust's learning curve |
| Keep Laravel, rewrite just the CPU-heavy function as a Rust library (via FFI, or a small CLI/HTTP sidecar) | One function is slow, not the framework |
If you are comparing Rust with Go and Zig for the backend, my Rust vs Go vs Zig decision guide covers that trade-off in detail.
Concept mapping: Laravel to Rust
Almost everything in Laravel has a Rust equivalent, but it is usually a library you choose, not a framework feature. This table is the cheat sheet. Crate names are real; check current versions and feature flags before pinning.
| Laravel concept | Rust equivalent | Notes |
|---|---|---|
Routing (routes/api.php) | axum::Router with route, nest, merge | Axum 0.8 path params use curly braces: /orders/{id} |
| Controllers | Handler functions (and optionally modules per resource) | Handlers are plain async fns with extractors as arguments |
| Middleware | Tower layers (tower, tower-http) and axum::middleware::from_fn | Same ecosystem as hyper and tonic |
| Eloquent ORM | SQLx (raw SQL, compile-time checked), SeaORM (ActiveRecord-ish), Diesel (typed query DSL) | See the data layer section; SQLx is the closest in spirit to "just write SQL" |
| Query builder | sqlx::QueryBuilder, sea-query, Diesel DSL | |
| Migrations | sqlx migrate, sea-orm-cli migrate, diesel migration | Keep Laravel migrations as source of truth during transition |
| Seeders / factories | SQL fixtures, fake crate, plain builder functions in tests | |
| FormRequest validation | validator crate (#[derive(Validate)]) plus a custom extractor | Reproduce Laravel's 422 JSON shape if clients depend on it |
| Auth guards | Custom extractor (FromRequestParts) or middleware | |
| Sessions | tower-sessions (with sqlx or redis stores) | Cannot read Laravel's PHP-serialized sessions directly |
| Sanctum tokens | Hash token with SHA-256, look up in personal_access_tokens | See the auth and security parity section |
| Passport / OAuth2 server | oxide-auth, or keep Laravel as the identity provider | Writing an OAuth2 server is a big surface; keep it in Laravel if you can |
| JWT | jsonwebtoken | |
| Password hashing | argon2, bcrypt crates | Verify existing $2y$ bcrypt hashes directly |
| Policies / Gates | Plain functions or traits taking (user, resource), or casbin for rule engines | Explicit beats magic here |
| Queues / Horizon | apalis, a Postgres SKIP LOCKED table, or Redis-based workers; fang is another option | Verify current apalis API; it has changed between releases |
Scheduler (schedule:run) | tokio-cron-scheduler, or system cron / Kubernetes CronJob invoking a binary | Prefer CronJob for multi-instance deployments |
| Events / Listeners | tokio::sync::broadcast, channels, or an explicit service call; for durability use an outbox table | |
| Mail / Mailables | lettre (SMTP), provider HTTP APIs via reqwest, templates via askama or minijinja | |
| Notifications | Explicit channel functions (mail, Slack webhook, push) | No built-in multi-channel abstraction |
| Cache | moka (in-process), redis / deadpool-redis / bb8-redis | |
| Filesystem / S3 | object_store, aws-sdk-s3 | |
Config / .env | dotenvy, config, figment, or plain std::env into a typed struct | Parse once at startup, fail fast |
| Service container | AppState struct (cloned into handlers via State) | Explicit wiring, no reflection |
| Blade / Livewire / Inertia | askama, maud, tera, minijinja; or keep Inertia/Next.js frontend and make Rust an API | Usually keep the frontend as is |
artisan commands | clap subcommands in the same binary | tinker has no direct equivalent; use evcxr or a scratch test |
| Testing (Pest, PHPUnit) | cargo test, #[sqlx::test], tower::ServiceExt::oneshot, insta snapshots, wiremock | Faster than PHP tests once compiled |
| API Resources | serde::Serialize structs, often one per response shape | |
| Pagination | Explicit query params and LIMIT/OFFSET or keyset pagination | Reproduce Laravel's data, links, meta envelope only if clients need it |
| Broadcasting / Echo / Reverb | Axum WebSocket / SSE, tokio::sync::broadcast, Redis pub/sub | |
Rate limiting (throttle) | tower_governor, or Redis-based limiter | |
| Localization | rust-i18n, fluent | |
| OpenAPI docs (Scribe, L5-Swagger) | utoipa (with utoipa-axum, utoipa-swagger-ui) | Generated from code |
| Logging (Monolog) | tracing, tracing-subscriber | Structured by default |
A mental model that helps: in Laravel the framework owns the request lifecycle and you fill in the blanks. In Axum, you compose the lifecycle from small pieces (Router, extractors, layers, state), and the compiler checks the composition.
Choosing a Rust web framework
| Framework | Style | Choose it when | Avoid it when |
|---|---|---|---|
| Axum | Thin, Tower-based, extractor-driven | You want the mainstream default, a strong middleware ecosystem, and the least magic. Primary recommendation for most Laravel migrations | You want scaffolding and generators |
| Actix Web | Actor-heritage, very fast, mature | Your team already knows it, or you rely on its ecosystem | You want to share middleware with the Tower/tonic world |
| Loco | Rails/Laravel-like batteries (built on Axum and SeaORM, with generators, jobs, mailers, auth) | You miss Laravel's conventions and want scaffolding, background workers, and a CLI | You want to pick your own ORM, or you dislike convention-heavy frameworks |
| Rocket | Ergonomic macros and guards | Small projects, developers who like the macro style | Large teams that need broad Tower middleware reuse |
How to think about it:
- Axum is the default. It is maintained under the Tokio organization, composes with Tower and tower-http (CORS, compression, tracing, timeouts, request limits), and its handler model is easy to teach. The code below uses Axum.
- Loco is the most "Laravel-like". It gives you generators (
cargo loco generate ...), a CLI, background workers, mailers, and an auth scaffold. It is a good fit for greenfield Rust apps built by people coming from Laravel or Rails. It is a worse fit for a surgical strangler migration, where you want a small service with custom wiring. Check the current Loco release and its docs, because it has been evolving quickly toward and past 1.0. - Actix Web is excellent and fast; the main reason to pick Axum over it today is ecosystem alignment, not capability.
- Rocket is pleasant, but a smaller share of the production ecosystem.
For a first extraction, I would choose Axum plus SQLx and add pieces only when you feel the pain.
Migration strategies
Rewrite everything vs incremental
| Dimension | Big-bang rewrite | Strangler fig (incremental) |
|---|---|---|
| Risk | Very high; value arrives only at the end | Low per step; value arrives continuously |
| Feature work | Frozen or duplicated | Continues in Laravel for untouched areas |
| Rollback | Hard | Flip a proxy route back |
| Team learning | All at once | Gradual |
| Total cost | Often underestimated by 2-3x | Higher coordination cost, but bounded |
| When it fits | Small, well-specified apps | Almost everything else |
My default recommendation: strangler fig, one route at a time, with Laravel remaining the owner of whatever you never migrate. Many teams end up with "Laravel for admin and CRUD, Rust for the hot paths" permanently, and that is a fine outcome, not a failure.
Architecture during the transition
+-----------------------------+
Clients -----> | Reverse proxy (nginx/Caddy |
| /Traefik), route-by-route |
+--------------+--------------+
|
+------------------+------------------+
| |
/api/v1/orders (migrated) everything else
| |
+-------v--------+ +--------v---------+
| Rust service | | Laravel (FPM / |
| Axum + SQLx | | Octane) |
+-------+--------+ +--------+---------+
| |
+-------------> Postgres / MySQL <----+
(shared during transition)
Redis (cache, queues - separate keys)Route-by-route routing in nginx
upstream laravel {
server 127.0.0.1:9000; # php-fpm via fastcgi, or 127.0.0.1:8000 for Octane
}
upstream rust_api {
server 127.0.0.1:8080;
keepalive 32;
}
# Percentage-based canary: 10% of clients hit Rust for the migrated route.
split_clients "${remote_addr}${http_user_agent}" $orders_backend {
10% rust_api;
* laravel;
}
server {
listen 80;
server_name example.com;
# Fully migrated routes
location ^~ /api/v1/health {
proxy_pass http://rust_api;
}
# Canaried route: only GET /api/v1/orders
location ~ ^/api/v1/orders {
if ($request_method = GET) {
proxy_pass http://$orders_backend;
}
proxy_pass http://laravel;
}
# Everything else stays on Laravel
location / {
proxy_pass http://laravel;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Request-Id $request_id;
}
}Two nginx footnotes. First, proxy_pass with a variable and if inside location has well-known sharp edges; test the config and consider map blocks instead of if for production. Second, in practice you will use a map on $request_method plus $orders_backend to select the upstream. The point is the shape: the proxy owns routing, so switching a route is a config change, not a deploy.
The same idea in Caddy:
example.com {
@rust_routes path /api/v1/health /api/v1/orders*
handle @rust_routes {
reverse_proxy 127.0.0.1:8080
}
handle {
reverse_proxy 127.0.0.1:8000
}
}Traefik does this with routers and PathPrefix rules plus weighted services for canaries. Pass X-Request-Id through both backends so you can correlate logs.
What to extract first
Rank candidates by (traffic and cost) times (isolation) divided by (business logic complexity):
- Read-heavy, cacheable APIs: product listings, search endpoints, public feeds. Low risk, high payoff.
- Webhook receivers and ingestion endpoints: signature verification, parse, enqueue. Small and well-defined.
- Workers: image/PDF processing, exports, ETL, notification fan-out.
- Realtime: websocket or SSE gateways.
- Write-heavy transactional logic: only after you have the pattern down, and with extra contract tests.
- Leave for last (or forever): admin panels, reporting UIs, OAuth server, billing integrations built on Cashier.
Shared database period
During the transition both stacks talk to the same database. Rules that keep this safe:
- One writer per table where possible. If Rust owns
orderswrites, Laravel should only read them (or call Rust). Dual writers need the same invariants enforced twice. - Laravel migrations remain the schema source of truth. Rust never runs DDL in this phase. Commit a schema dump (
php artisan schema:dump) that your Rust CI uses to build a test database. - Expand/contract migrations. Add columns as nullable first, deploy readers, then writers, then tighten constraints. Both stacks must tolerate each intermediate state.
- Respect Laravel conventions in SQL:
deleted_atfor soft deletes,updated_atupdated by the application (there are no DB triggers), polymorphic*_typecolumns containing PHP class names, and JSON columns that Eloquent casts. - Do not reuse Eloquent model events. Observers,
creating/savedhooks, and cascading cache invalidation live in PHP. If Rust writes rows directly, those side effects silently stop. Inventory them before migrating a write path.
Dual-write pitfalls
Writing the same data from both stacks (or to two databases) looks easy and fails in subtle ways:
- Partial failure: the first write succeeds, the second fails, and you have no transaction spanning them.
- Ordering: concurrent updates arrive in different orders in the two systems.
- Hidden side effects: PHP observers fire only on one path.
- Clock and rounding differences: timestamps, decimals, float to money conversions.
Prefer instead: a single writer behind an API, an outbox table (write the event in the same transaction as the data and publish asynchronously), or change data capture. If you must dual-write briefly, make one side authoritative, log divergences, and reconcile with a diff job before cutover.
Contract tests, feature flags, canary, rollback
- Contract tests: for every migrated route, capture request/response pairs from Laravel (status, headers that matter, JSON body) and replay them against Rust. Ignore volatile fields (ids, timestamps) with explicit rules. This is covered in depth in the AI agent guide below.
- Shadow traffic: mirror a copy of production GET requests to Rust, discard the response, and diff it against the Laravel response offline. nginx's
mirrordirective does this. - Feature flags: route by header, cookie, user id, or percentage (see the
split_clientsexample). Internal staff first, then 1%, 10%, 50%, 100%. - Canary metrics: compare error rate, p50/p95/p99 latency, and business metrics (orders created per minute) between backends.
- Rollback: set the route back to Laravel. This only works if you did not make irreversible data changes. Another reason for a single writer and expand/contract schema changes.
A phased 12-24 week plan
| Phase | Weeks | Goals | Exit criteria |
|---|---|---|---|
| 0. Discovery | 1-2 | Profile; list routes by traffic and cost; inventory Eloquent observers, jobs, and policies; pick the first route; write the scorecard | Written go/no-go and a target route list |
| 1. Foundations | 3-5 | Rust workspace, CI (fmt, clippy, tests, audit), Docker image, config, tracing, health checks, proxy in place with 0% traffic | /healthz served by Rust behind the proxy in staging |
| 2. First route (read-only) | 6-8 | Port one GET endpoint, contract tests, shadow traffic, canary 1% to 100% | Rust serves the route in production with parity and a rollback tested |
| 3. Auth and shared concerns | 9-12 | Sanctum token validation, password verify, rate limits, error format parity, API docs via utoipa | Authenticated routes work with existing clients and tokens |
| 4. Writes and workers | 13-18 | Port one transactional write path and one background job; outbox for events; reconcile checks | Writes owned by Rust for that table; job latency and failure rates at or better than Laravel |
| 5. Scale-out | 19-24 | Port further hot routes in descending value; retire dead Laravel code; document the permanent boundary | Decision recorded: stop here, or continue with a funded plan |
If the first route in Phase 2 takes more than twice your estimate, stop and reassess before continuing. That is the cheapest signal you will get about the true cost.
A full worked example: the "orders" feature
The feature: authenticated users create orders with line items, list their own orders with pagination, view one order, and cancel it. Creating an order dispatches a background job that sends a confirmation email. A user may only see their own orders (admins see all).
I show Laravel first, then the Rust equivalent. The Rust code is written against Axum 0.8, SQLx 0.8, validator, thiserror, chrono, and serde; treat signatures as "verify against current docs" when you upgrade.
Laravel version
Migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('status', 20)->default('pending'); // pending|paid|cancelled|shipped
$table->unsignedBigInteger('total_cents');
$table->char('currency', 3)->default('USD');
$table->text('notes')->nullable();
$table->timestampTz('created_at')->useCurrent();
$table->timestampTz('updated_at')->useCurrent();
$table->softDeletesTz();
$table->index(['user_id', 'created_at']);
});
Schema::create('order_items', function (Blueprint $table) {
$table->id();
$table->foreignId('order_id')->constrained()->cascadeOnDelete();
$table->foreignId('product_id')->constrained();
$table->unsignedInteger('quantity');
$table->unsignedBigInteger('unit_price_cents');
});
}
public function down(): void
{
Schema::dropIfExists('order_items');
Schema::dropIfExists('orders');
}
};Eloquent model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
class Order extends Model
{
use HasFactory, SoftDeletes;
protected $fillable = ['user_id', 'status', 'total_cents', 'currency', 'notes'];
protected $casts = [
'total_cents' => 'integer',
'status' => \App\Enums\OrderStatus::class,
];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function items(): HasMany
{
return $this->hasMany(OrderItem::class);
}
}FormRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreOrderRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user() !== null;
}
public function rules(): array
{
return [
'currency' => ['sometimes', 'string', 'size:3'],
'notes' => ['nullable', 'string', 'max:1000'],
'items' => ['required', 'array', 'min:1', 'max:50'],
'items.*.product_id' => ['required', 'integer', 'exists:products,id'],
'items.*.quantity' => ['required', 'integer', 'min:1', 'max:100'],
];
}
}Policy
<?php
namespace App\Policies;
use App\Models\Order;
use App\Models\User;
class OrderPolicy
{
public function view(User $user, Order $order): bool
{
return $user->id === $order->user_id || $user->is_admin;
}
public function cancel(User $user, Order $order): bool
{
return $this->view($user, $order) && $order->status->value === 'pending';
}
}API Resource
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class OrderResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'status' => $this->status->value,
'total_cents' => $this->total_cents,
'currency' => $this->currency,
'notes' => $this->notes,
'items' => $this->whenLoaded('items', fn () => $this->items->map(fn ($i) => [
'product_id' => $i->product_id,
'quantity' => $i->quantity,
'unit_price_cents' => $i->unit_price_cents,
])),
'created_at' => $this->created_at->toIso8601String(),
];
}
}Controller and queued job
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreOrderRequest;
use App\Http\Resources\OrderResource;
use App\Jobs\SendOrderConfirmation;
use App\Models\Order;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class OrderController extends Controller
{
public function index(Request $request)
{
$orders = Order::query()
->where('user_id', $request->user()->id)
->latest()
->paginate(min((int) $request->query('per_page', 20), 100));
return OrderResource::collection($orders);
}
public function store(StoreOrderRequest $request)
{
$order = DB::transaction(function () use ($request) {
$products = Product::whereIn('id', collect($request->items)->pluck('product_id'))
->get()->keyBy('id');
$total = 0;
$lines = [];
foreach ($request->items as $item) {
$price = $products[$item['product_id']]->price_cents;
$total += $price * $item['quantity'];
$lines[] = [
'product_id' => $item['product_id'],
'quantity' => $item['quantity'],
'unit_price_cents' => $price,
];
}
$order = Order::create([
'user_id' => $request->user()->id,
'total_cents' => $total,
'currency' => $request->input('currency', 'USD'),
'notes' => $request->input('notes'),
]);
$order->items()->createMany($lines);
return $order;
});
SendOrderConfirmation::dispatch($order->id)->afterCommit();
return (new OrderResource($order->load('items')))
->response()->setStatusCode(201);
}
public function show(Order $order)
{
$this->authorize('view', $order);
return new OrderResource($order->load('items'));
}
public function destroy(Order $order)
{
$this->authorize('cancel', $order);
$order->update(['status' => 'cancelled']);
return response()->noContent();
}
}<?php
namespace App\Jobs;
use App\Mail\OrderConfirmation;
use App\Models\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;
class SendOrderConfirmation implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 5;
public array $backoff = [10, 60, 300];
public function __construct(public int $orderId) {}
public function handle(): void
{
$order = Order::with('user')->findOrFail($this->orderId);
Mail::to($order->user->email)->send(new OrderConfirmation($order));
}
}That is roughly 200 lines and it already includes validation, authorization, a transaction, soft deletes, and a queued job with retries. Laravel earns its reputation here.
Rust project layout
orders-api/
├── Cargo.toml
├── .env.example
├── .sqlx/ # offline query metadata (commit this)
├── migrations/ # only used in tests/greenfield; Laravel owns schema for now
├── src/
│ ├── main.rs # wiring: config, pool, router, graceful shutdown
│ ├── lib.rs # pub fn router(state) for tests
│ ├── config.rs
│ ├── state.rs
│ ├── error.rs
│ ├── auth.rs # Sanctum token extractor, password verification
│ ├── extract.rs # ValidatedJson
│ ├── orders/
│ │ ├── mod.rs
│ │ ├── model.rs # row types, DTOs
│ │ ├── policy.rs
│ │ ├── repo.rs # SQL
│ │ ├── handlers.rs
│ │ └── jobs.rs
│ └── jobs.rs # generic job table runner
└── tests/
└── orders.rsCargo.toml
[package]
name = "orders-api"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower = "0.5"
tower-http = { version = "0.6", features = ["trace", "cors", "timeout", "limit", "request-id", "compression-gzip"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.8", features = ["runtime-tokio", "tls-rustls", "postgres", "chrono", "macros", "migrate"] }
chrono = { version = "0.4", features = ["serde"] }
validator = { version = "0.20", features = ["derive"] }
thiserror = "2"
anyhow = "1"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
sha2 = "0.10"
hex = "0.4"
dotenvy = "0.15"
bcrypt = "0.17"
argon2 = "0.5"
lettre = { version = "0.11", default-features = false, features = ["builder", "smtp-transport", "tokio1", "tokio1-rustls-tls"] }
[dev-dependencies]
http-body-util = "0.1"
tower = { version = "0.5", features = ["util"] }Version numbers above are indicative for late 2026 and may be behind; run cargo add to get current ones, and check the changelogs of axum, sqlx, and validator (the validator derive attributes have changed across 0.16 to 0.20). As of November 2026, axum 0.8.x and sqlx 0.8.x are the stable lines, with a sqlx 0.9 line appearing in some ecosystem crates, so verify before pinning.
Config and AppState
Laravel's service container and config() become two plain structs.
// src/config.rs
use std::env;
#[derive(Clone, Debug)]
pub struct Config {
pub database_url: String,
pub bind_addr: String,
pub db_max_connections: u32,
pub smtp_host: String,
}
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
let _ = dotenvy::dotenv(); // add `dotenvy = "0.15"` to Cargo.toml
Ok(Self {
database_url: env::var("DATABASE_URL")?,
bind_addr: env::var("BIND_ADDR").unwrap_or_else(|_| "0.0.0.0:8080".into()),
db_max_connections: env::var("DB_MAX_CONNECTIONS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(10),
smtp_host: env::var("SMTP_HOST").unwrap_or_else(|_| "localhost".into()),
})
}
}// src/state.rs
use crate::config::Config;
use sqlx::PgPool;
use std::sync::Arc;
#[derive(Clone)]
pub struct AppState {
pub db: PgPool,
pub config: Arc<Config>,
}One error type that implements IntoResponse
This is the Rust analogue of Laravel's exception handler. It also reproduces Laravel's validation error shape (message plus errors) so existing clients keep working.
// src/error.rs
use axum::{http::StatusCode, response::{IntoResponse, Response}, Json};
use serde_json::json;
use std::collections::BTreeMap;
#[derive(Debug, thiserror::Error)]
pub enum AppError {
#[error("unauthenticated")]
Unauthenticated,
#[error("forbidden")]
Forbidden,
#[error("not found")]
NotFound,
#[error("bad request: {0}")]
BadRequest(String),
#[error("conflict: {0}")]
Conflict(String),
#[error("validation failed")]
Validation(#[from] validator::ValidationErrors),
#[error("database error")]
Db(#[from] sqlx::Error),
#[error(transparent)]
Internal(#[from] anyhow::Error),
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
match self {
AppError::Unauthenticated => (
StatusCode::UNAUTHORIZED,
Json(json!({ "message": "Unauthenticated." })),
).into_response(),
AppError::Forbidden => (
StatusCode::FORBIDDEN,
Json(json!({ "message": "This action is unauthorized." })),
).into_response(),
AppError::NotFound => (
StatusCode::NOT_FOUND,
Json(json!({ "message": "Not found." })),
).into_response(),
AppError::BadRequest(m) => (
StatusCode::BAD_REQUEST,
Json(json!({ "message": m })),
).into_response(),
AppError::Conflict(m) => (
StatusCode::CONFLICT,
Json(json!({ "message": m })),
).into_response(),
AppError::Validation(errs) => {
// Mirror Laravel: 422 with { message, errors: { field: [msgs] } }
let mut out: BTreeMap<String, Vec<String>> = BTreeMap::new();
for (field, list) in errs.field_errors().iter() {
let msgs = list
.iter()
.map(|e| {
e.message
.as_ref()
.map(|m| m.to_string())
.unwrap_or_else(|| format!("The {} field is invalid ({}).", field, e.code))
})
.collect();
out.insert(field.to_string(), msgs);
}
(
StatusCode::UNPROCESSABLE_ENTITY,
Json(json!({ "message": "The given data was invalid.", "errors": out })),
).into_response()
}
AppError::Db(e) => {
// Never leak SQL errors to clients.
tracing::error!(error = ?e, "database error");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ "message": "Server Error" })),
).into_response()
}
AppError::Internal(e) => {
tracing::error!(error = ?e, "internal error");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ "message": "Server Error" })),
).into_response()
}
}
}
}
pub type AppResult<T> = Result<T, AppError>;Note that validator::ValidationErrors::field_errors() has changed its return type across versions; the loop above only relies on iteration, to_string, message, and code, which survive those changes. Nested errors (#[validate(nested)]) land in different maps, so for nested items flatten them yourself if clients expect items.0.quantity keys.
A validating JSON extractor (FormRequest)
// src/extract.rs
use axum::{extract::{FromRequest, Request}, Json};
use serde::de::DeserializeOwned;
use validator::Validate;
use crate::error::AppError;
pub struct ValidatedJson<T>(pub T);
impl<T, S> FromRequest<S> for ValidatedJson<T>
where
T: DeserializeOwned + Validate,
S: Send + Sync,
{
type Rejection = AppError;
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
let Json(value) = Json::<T>::from_request(req, state)
.await
.map_err(|e| AppError::BadRequest(e.body_text()))?;
value.validate()?;
Ok(ValidatedJson(value))
}
}Axum 0.8 removed the need for the async_trait macro on extractors; if you are on an older version you will see #[async_trait] in examples.
Auth extractor (Sanctum-compatible)
Sanctum stores a SHA-256 hash of the plain token in personal_access_tokens.token. The token a client sends is id|plaintext (with a checksum suffix in newer Sanctum versions). The extractor below splits at the pipe, hashes the remainder, and compares with the row. Verify the exact token format against the Sanctum version you run.
// src/auth.rs
use axum::{extract::FromRequestParts, http::request::Parts};
use sha2::{Digest, Sha256};
use crate::{error::AppError, state::AppState};
#[derive(Clone, Debug)]
pub struct CurrentUser {
pub id: i64,
pub is_admin: bool,
}
impl FromRequestParts<AppState> for CurrentUser {
type Rejection = AppError;
async fn from_request_parts(
parts: &mut Parts,
state: &AppState,
) -> Result<Self, Self::Rejection> {
let header = parts
.headers
.get(axum::http::header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.ok_or(AppError::Unauthenticated)?;
let token = header
.strip_prefix("Bearer ")
.ok_or(AppError::Unauthenticated)?;
let (id_part, plain) = token.split_once('|').ok_or(AppError::Unauthenticated)?;
let token_id: i64 = id_part.parse().map_err(|_| AppError::Unauthenticated)?;
let hash = hex::encode(Sha256::digest(plain.as_bytes()));
let row = sqlx::query!(
r#"
SELECT u.id, u.is_admin
FROM personal_access_tokens t
JOIN users u ON u.id = t.tokenable_id
WHERE t.id = $1
AND t.token = $2
AND t.tokenable_type = 'App\\Models\\User'
AND (t.expires_at IS NULL OR t.expires_at > now())
"#,
token_id,
hash,
)
.fetch_optional(&state.db)
.await?
.ok_or(AppError::Unauthenticated)?;
Ok(CurrentUser { id: row.id, is_admin: row.is_admin })
}
}Two production notes. Compare hashes in constant time if you want to be strict (the subtle crate); because the lookup is by id and the comparison happens inside the database over a SHA-256 of a high-entropy secret, timing attacks are not practical here, but constant-time habits are cheap. And Laravel updates last_used_at on each use; if anything reads that column, update it asynchronously (not on the hot path).
Row types, DTOs, and the policy
// src/orders/model.rs
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use validator::Validate;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, sqlx::Type)]
#[sqlx(type_name = "text", rename_all = "lowercase")]
#[serde(rename_all = "lowercase")]
pub enum OrderStatus {
Pending,
Paid,
Cancelled,
Shipped,
}
#[derive(Debug, sqlx::FromRow)]
pub struct Order {
pub id: i64,
pub user_id: i64,
pub status: OrderStatus,
pub total_cents: i64,
pub currency: String,
pub notes: Option<String>,
pub created_at: DateTime<Utc>,
}
#[derive(Debug, Serialize)]
pub struct OrderItemOut {
pub product_id: i64,
pub quantity: i32,
pub unit_price_cents: i64,
}
// API Resource equivalent: the wire shape is its own type.
#[derive(Debug, Serialize)]
pub struct OrderOut {
pub id: i64,
pub status: OrderStatus,
pub total_cents: i64,
pub currency: String,
pub notes: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub items: Option<Vec<OrderItemOut>>,
pub created_at: DateTime<Utc>,
}
impl OrderOut {
pub fn from_order(o: Order, items: Option<Vec<OrderItemOut>>) -> Self {
Self {
id: o.id,
status: o.status,
total_cents: o.total_cents,
currency: o.currency,
notes: o.notes,
items,
created_at: o.created_at,
}
}
}
#[derive(Debug, Deserialize, Validate)]
pub struct CreateOrder {
#[validate(length(equal = 3, message = "The currency field must be 3 characters."))]
pub currency: Option<String>,
#[validate(length(max = 1000, message = "The notes field must not exceed 1000 characters."))]
pub notes: Option<String>,
#[validate(length(min = 1, max = 50, message = "Provide between 1 and 50 items."), nested)]
pub items: Vec<CreateItem>,
}
#[derive(Debug, Deserialize, Validate)]
pub struct CreateItem {
#[validate(range(min = 1))]
pub product_id: i64,
#[validate(range(min = 1, max = 100, message = "Quantity must be between 1 and 100."))]
pub quantity: i32,
}
#[derive(Debug, Deserialize)]
pub struct ListParams {
pub page: Option<i64>,
pub per_page: Option<i64>,
}
#[derive(Debug, Serialize)]
pub struct Page<T> {
pub data: Vec<T>,
pub meta: PageMeta,
}
#[derive(Debug, Serialize)]
pub struct PageMeta {
pub current_page: i64,
pub per_page: i64,
pub total: i64,
pub last_page: i64,
}// src/orders/policy.rs
use super::model::{Order, OrderStatus};
use crate::{auth::CurrentUser, error::AppError};
pub fn can_view(user: &CurrentUser, order: &Order) -> bool {
user.is_admin || order.user_id == user.id
}
pub fn authorize_view(user: &CurrentUser, order: &Order) -> Result<(), AppError> {
if can_view(user, order) { Ok(()) } else { Err(AppError::Forbidden) }
}
pub fn authorize_cancel(user: &CurrentUser, order: &Order) -> Result<(), AppError> {
authorize_view(user, order)?;
if order.status == OrderStatus::Pending { Ok(()) } else { Err(AppError::Forbidden) }
}Compared with a Laravel policy, this is more typing and less magic. Nothing registers it, nothing resolves it by naming convention; a missing authorize_* call is visible in review. Many teams write a test per handler asserting 403 for the wrong user, since forgetting the call is the main risk.
Repository: SQL, transactions, N+1 avoidance
Notice how the product lookup is a single ANY($1) query (the equivalent of whereIn plus keyBy) and the item insert is one UNNEST statement instead of a per-line loop.
// src/orders/repo.rs
use std::collections::HashMap;
use sqlx::{PgPool, Postgres, Transaction};
use super::model::*;
use crate::error::{AppError, AppResult};
pub async fn create(
pool: &PgPool,
user_id: i64,
input: &CreateOrder,
) -> AppResult<(Order, Vec<OrderItemOut>)> {
// 1. Fetch all product prices in ONE query.
let ids: Vec<i64> = input.items.iter().map(|i| i.product_id).collect();
let prices: HashMap<i64, i64> = sqlx::query!(
"SELECT id, price_cents FROM products WHERE id = ANY($1)",
&ids,
)
.fetch_all(pool)
.await?
.into_iter()
.map(|r| (r.id, r.price_cents))
.collect();
let mut total: i64 = 0;
let mut product_ids = Vec::new();
let mut quantities = Vec::new();
let mut unit_prices = Vec::new();
for item in &input.items {
let price = *prices
.get(&item.product_id)
.ok_or_else(|| AppError::BadRequest(format!("unknown product {}", item.product_id)))?;
total += price * i64::from(item.quantity);
product_ids.push(item.product_id);
quantities.push(item.quantity);
unit_prices.push(price);
}
// 2. Insert order + items atomically.
let mut tx: Transaction<'_, Postgres> = pool.begin().await?;
let order = sqlx::query_as!(
Order,
r#"
INSERT INTO orders (user_id, status, total_cents, currency, notes)
VALUES ($1, 'pending', $2, COALESCE($3, 'USD'), $4)
RETURNING id, user_id, status AS "status: OrderStatus",
total_cents, currency AS "currency!", notes, created_at
"#,
user_id,
total,
input.currency.as_deref(),
input.notes.as_deref(),
)
.fetch_one(&mut *tx)
.await?;
sqlx::query!(
r#"
INSERT INTO order_items (order_id, product_id, quantity, unit_price_cents)
SELECT $1, * FROM UNNEST($2::bigint[], $3::int[], $4::bigint[])
"#,
order.id,
&product_ids,
&quantities,
&unit_prices,
)
.execute(&mut *tx)
.await?;
// 3. Enqueue the confirmation job IN THE SAME TRANSACTION (outbox pattern).
// This is the Rust analogue of ->afterCommit(), but stronger: the job row
// commits atomically with the order.
sqlx::query!(
"INSERT INTO rust_jobs (kind, payload) VALUES ('send_order_confirmation', $1)",
serde_json::json!({ "order_id": order.id }),
)
.execute(&mut *tx)
.await?;
tx.commit().await?;
let items = product_ids
.into_iter()
.zip(quantities)
.zip(unit_prices)
.map(|((product_id, quantity), unit_price_cents)| OrderItemOut {
product_id,
quantity,
unit_price_cents,
})
.collect();
Ok((order, items))
}
pub async fn find(pool: &PgPool, id: i64) -> AppResult<Order> {
sqlx::query_as!(
Order,
r#"
SELECT id, user_id, status AS "status: OrderStatus",
total_cents, currency AS "currency!", notes, created_at
FROM orders
WHERE id = $1 AND deleted_at IS NULL
"#,
id,
)
.fetch_optional(pool)
.await?
.ok_or(AppError::NotFound)
}
pub async fn items_for(pool: &PgPool, order_id: i64) -> AppResult<Vec<OrderItemOut>> {
Ok(sqlx::query_as!(
OrderItemOut,
"SELECT product_id, quantity, unit_price_cents FROM order_items WHERE order_id = $1 ORDER BY id",
order_id,
)
.fetch_all(pool)
.await?)
}
pub async fn list_for_user(
pool: &PgPool,
user_id: i64,
page: i64,
per_page: i64,
) -> AppResult<(Vec<Order>, i64)> {
let total = sqlx::query_scalar!(
r#"SELECT COUNT(*) AS "count!" FROM orders WHERE user_id = $1 AND deleted_at IS NULL"#,
user_id,
)
.fetch_one(pool)
.await?;
let rows = sqlx::query_as!(
Order,
r#"
SELECT id, user_id, status AS "status: OrderStatus",
total_cents, currency AS "currency!", notes, created_at
FROM orders
WHERE user_id = $1 AND deleted_at IS NULL
ORDER BY created_at DESC, id DESC
LIMIT $2 OFFSET $3
"#,
user_id,
per_page,
(page - 1) * per_page,
)
.fetch_all(pool)
.await?;
Ok((rows, total))
}
pub async fn cancel(pool: &PgPool, id: i64) -> AppResult<()> {
sqlx::query!(
"UPDATE orders SET status = 'cancelled', updated_at = now() WHERE id = $1 AND status = 'pending'",
id,
)
.execute(pool)
.await?;
Ok(())
}Four details worth calling out:
updated_atis your job. Eloquent touches it automatically; raw SQL does not. Forgetting this is the most common parity bug.WHERE deleted_at IS NULLis Eloquent'sSoftDeletesglobal scope, reimplemented by hand. Put it in a view or a helper, and test it.- The
status AS "status: OrderStatus"override tells the SQLx macro to decode a text column into your enum. Similar overrides ("col!","col?") force non-null or nullable inference. - The
rust_jobstable is a new table owned by Rust. Laravel does not need to know about it.
Handlers and router
// src/orders/handlers.rs
use axum::{
extract::{Path, Query, State},
http::StatusCode,
response::IntoResponse,
Json,
};
use super::{model::*, policy, repo};
use crate::{auth::CurrentUser, error::AppResult, extract::ValidatedJson, state::AppState};
pub async fn index(
State(state): State<AppState>,
user: CurrentUser,
Query(params): Query<ListParams>,
) -> AppResult<Json<Page<OrderOut>>> {
let per_page = params.per_page.unwrap_or(20).clamp(1, 100);
let page = params.page.unwrap_or(1).max(1);
let (rows, total) = repo::list_for_user(&state.db, user.id, page, per_page).await?;
let last_page = ((total + per_page - 1) / per_page).max(1);
Ok(Json(Page {
data: rows.into_iter().map(|o| OrderOut::from_order(o, None)).collect(),
meta: PageMeta { current_page: page, per_page, total, last_page },
}))
}
pub async fn store(
State(state): State<AppState>,
user: CurrentUser,
ValidatedJson(input): ValidatedJson<CreateOrder>,
) -> AppResult<impl IntoResponse> {
let (order, items) = repo::create(&state.db, user.id, &input).await?;
Ok((StatusCode::CREATED, Json(OrderOut::from_order(order, Some(items)))))
}
pub async fn show(
State(state): State<AppState>,
user: CurrentUser,
Path(id): Path<i64>,
) -> AppResult<Json<OrderOut>> {
let order = repo::find(&state.db, id).await?;
policy::authorize_view(&user, &order)?;
let items = repo::items_for(&state.db, order.id).await?;
Ok(Json(OrderOut::from_order(order, Some(items))))
}
pub async fn cancel(
State(state): State<AppState>,
user: CurrentUser,
Path(id): Path<i64>,
) -> AppResult<StatusCode> {
let order = repo::find(&state.db, id).await?;
policy::authorize_cancel(&user, &order)?;
repo::cancel(&state.db, order.id).await?;
Ok(StatusCode::NO_CONTENT)
}// src/orders/mod.rs
pub mod handlers;
pub mod model;
pub mod policy;
pub mod repo;
use axum::{routing::get, Router};
use crate::state::AppState;
pub fn routes() -> Router<AppState> {
Router::new()
.route("/orders", get(handlers::index).post(handlers::store))
.route("/orders/{id}", get(handlers::show).delete(handlers::cancel))
}// src/lib.rs
pub mod auth;
pub mod config;
pub mod error;
pub mod extract;
pub mod jobs;
pub mod orders;
pub mod state;
use axum::{routing::get, Router};
use std::time::Duration;
use tower_http::{limit::RequestBodyLimitLayer, timeout::TimeoutLayer, trace::TraceLayer};
use crate::state::AppState;
pub fn router(state: AppState) -> Router {
Router::new()
.route("/healthz", get(|| async { "ok" }))
.nest("/api/v1", orders::routes())
.layer(RequestBodyLimitLayer::new(1024 * 1024))
.layer(TimeoutLayer::new(Duration::from_secs(15)))
.layer(TraceLayer::new_for_http())
.with_state(state)
}TimeoutLayer::new is deprecated in some recent tower-http versions in favor of with_status_code; verify against current docs. The same goes for exact layer ordering; layers added later wrap the earlier ones.
Background job and mail
The job runner polls the rust_jobs table with FOR UPDATE SKIP LOCKED, which gives you safe concurrent workers on Postgres without extra infrastructure. If you prefer a library, apalis (with Redis or SQL storage) is the usual choice; its API has changed across releases, so verify before copying snippets from older blog posts.
-- Created by a Laravel migration (or sqlx migration in greenfield):
CREATE TABLE rust_jobs (
id BIGSERIAL PRIMARY KEY,
kind TEXT NOT NULL,
payload JSONB NOT NULL,
attempts INT NOT NULL DEFAULT 0,
max_attempts INT NOT NULL DEFAULT 5,
run_at TIMESTAMPTZ NOT NULL DEFAULT now(),
locked_at TIMESTAMPTZ,
last_error TEXT,
done_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX rust_jobs_ready_idx ON rust_jobs (run_at) WHERE done_at IS NULL;// src/jobs.rs
use std::time::Duration;
use sqlx::PgPool;
use tokio::sync::watch;
pub async fn run_worker(pool: PgPool, mut shutdown: watch::Receiver<bool>) {
loop {
if *shutdown.borrow() {
tracing::info!("worker shutting down");
return;
}
match claim_and_run(&pool).await {
Ok(true) => continue, // processed something; look for more immediately
Ok(false) => {} // queue empty
Err(e) => tracing::error!(error = ?e, "worker loop error"),
}
tokio::select! {
_ = tokio::time::sleep(Duration::from_secs(1)) => {}
_ = shutdown.changed() => {}
}
}
}
async fn claim_and_run(pool: &PgPool) -> anyhow::Result<bool> {
let mut tx = pool.begin().await?;
let job = sqlx::query!(
r#"
SELECT id, kind, payload, attempts, max_attempts
FROM rust_jobs
WHERE done_at IS NULL AND run_at <= now() AND attempts < max_attempts
ORDER BY run_at
FOR UPDATE SKIP LOCKED
LIMIT 1
"#,
)
.fetch_optional(&mut *tx)
.await?;
let Some(job) = job else { return Ok(false) };
let result = dispatch(&job.kind, &job.payload, pool).await;
match result {
Ok(()) => {
sqlx::query!("UPDATE rust_jobs SET done_at = now() WHERE id = $1", job.id)
.execute(&mut *tx)
.await?;
}
Err(e) => {
// Exponential backoff: 10s, 20s, 40s ...
let delay_secs = 10_i64 * 2_i64.pow(job.attempts as u32);
sqlx::query!(
r#"UPDATE rust_jobs
SET attempts = attempts + 1,
last_error = $2,
run_at = now() + make_interval(secs => $3)
WHERE id = $1"#,
job.id,
e.to_string(),
delay_secs as f64,
)
.execute(&mut *tx)
.await?;
}
}
tx.commit().await?;
Ok(true)
}
async fn dispatch(kind: &str, payload: &serde_json::Value, pool: &PgPool) -> anyhow::Result<()> {
match kind {
"send_order_confirmation" => {
let order_id = payload["order_id"].as_i64().ok_or_else(|| anyhow::anyhow!("missing order_id"))?;
crate::orders::jobs::send_confirmation(pool, order_id).await
}
other => Err(anyhow::anyhow!("unknown job kind {other}")),
}
}This holds a transaction (and row lock) while the job runs. That is fine for short jobs. For long jobs, mark the row as locked with locked_at, commit, run, then update; and add a reaper for abandoned locks. Make jobs idempotent; at-least-once delivery means a job can run twice.
// src/orders/jobs.rs
use lettre::{
message::Mailbox, transport::smtp::authentication::Credentials, AsyncSmtpTransport,
AsyncTransport, Message, Tokio1Executor,
};
use sqlx::PgPool;
pub async fn send_confirmation(pool: &PgPool, order_id: i64) -> anyhow::Result<()> {
let row = sqlx::query!(
r#"SELECT u.email, u.name, o.total_cents, o.currency AS "currency!"
FROM orders o JOIN users u ON u.id = o.user_id
WHERE o.id = $1"#,
order_id,
)
.fetch_one(pool)
.await?;
let email = Message::builder()
.from("Shop <no-reply@example.com>".parse::<Mailbox>()?)
.to(format!("{} <{}>", row.name, row.email).parse::<Mailbox>()?)
.subject(format!("Order #{order_id} confirmed"))
.body(format!(
"Thanks, {}! Your order total is {:.2} {}.",
row.name,
row.total_cents as f64 / 100.0,
row.currency
))?;
let mailer = AsyncSmtpTransport::<Tokio1Executor>::relay(&std::env::var("SMTP_HOST")?)?
.credentials(Credentials::new(
std::env::var("SMTP_USER")?,
std::env::var("SMTP_PASS")?,
))
.build();
mailer.send(email).await?;
Ok(())
}In a real service build the mailer once and keep it in AppState; creating it per job is for brevity. Add pub mod jobs; to src/orders/mod.rs.
main.rs with graceful shutdown
// src/main.rs
use orders_api::{config::Config, jobs, router, state::AppState};
use sqlx::postgres::PgPoolOptions;
use std::sync::Arc;
use tokio::{net::TcpListener, signal, sync::watch};
use tracing_subscriber::{fmt, EnvFilter};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::try_from_default_env().unwrap_or_else(|_| "info,sqlx=warn".into()))
.json()
.init();
let config = Config::from_env()?;
let pool = PgPoolOptions::new()
.max_connections(config.db_max_connections)
.acquire_timeout(std::time::Duration::from_secs(5))
.connect(&config.database_url)
.await?;
let state = AppState { db: pool.clone(), config: Arc::new(config.clone()) };
let (tx, rx) = watch::channel(false);
let worker = tokio::spawn(jobs::run_worker(pool, rx));
let listener = TcpListener::bind(&config.bind_addr).await?;
tracing::info!(addr = %config.bind_addr, "listening");
axum::serve(listener, router(state))
.with_graceful_shutdown(async move {
shutdown_signal().await;
let _ = tx.send(true);
})
.await?;
let _ = worker.await;
Ok(())
}
async fn shutdown_signal() {
let ctrl_c = async { signal::ctrl_c().await.expect("ctrl-c handler") };
#[cfg(unix)]
let terminate = async {
signal::unix::signal(signal::unix::SignalKind::terminate())
.expect("SIGTERM handler")
.recv()
.await;
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! { _ = ctrl_c => {}, _ = terminate => {} }
}Remove the unused fmt import if your compiler warns. Because this runs the worker in the same process as the API, you can scale them together; split into a second binary (src/bin/worker.rs) once their resource profiles diverge.
Tests: sqlx::test plus tower::oneshot
#[sqlx::test] creates a fresh database per test and (when migrations is configured) applies migrations. While Laravel owns the schema, load a dumped schema as a fixture or SQL script instead; see the section on testing against the Laravel schema below.
// tests/orders.rs
use axum::{body::Body, http::{Request, StatusCode}};
use http_body_util::BodyExt;
use orders_api::{config::Config, router, state::AppState};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use sqlx::PgPool;
use std::sync::Arc;
use tower::ServiceExt; // for `oneshot`
fn test_state(pool: PgPool) -> AppState {
AppState {
db: pool,
config: Arc::new(Config {
database_url: String::new(),
bind_addr: "127.0.0.1:0".into(),
db_max_connections: 5,
smtp_host: "localhost".into(),
}),
}
}
/// Insert a user + Sanctum-style token; returns the bearer token string.
async fn seed_user_with_token(pool: &PgPool, email: &str, token_id: i64) -> (i64, String) {
let user_id: i64 = sqlx::query_scalar!(
"INSERT INTO users (name, email, password, is_admin) VALUES ('T', $1, 'x', false) RETURNING id",
email,
)
.fetch_one(pool)
.await
.unwrap();
let plain = "abcdefghijklmnopqrstuvwxyz0123456789ABCD";
let hash = hex::encode(Sha256::digest(plain.as_bytes()));
sqlx::query!(
"INSERT INTO personal_access_tokens (id, tokenable_type, tokenable_id, name, token, abilities)
VALUES ($1, 'App\\Models\\User', $2, 't', $3, '[\"*\"]')",
token_id, user_id, hash,
)
.execute(pool)
.await
.unwrap();
(user_id, format!("{token_id}|{plain}"))
}
async fn json_body(res: axum::response::Response) -> Value {
let bytes = res.into_body().collect().await.unwrap().to_bytes();
serde_json::from_slice(&bytes).unwrap()
}
#[sqlx::test(fixtures("schema", "products"))]
async fn creates_order_and_enqueues_job(pool: PgPool) {
let (_, token) = seed_user_with_token(&pool, "a@example.com", 1).await;
let app = router(test_state(pool.clone()));
let res = app
.oneshot(
Request::post("/api/v1/orders")
.header("authorization", format!("Bearer {token}"))
.header("content-type", "application/json")
.body(Body::from(
json!({ "items": [{ "product_id": 1, "quantity": 2 }] }).to_string(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::CREATED);
let body = json_body(res).await;
assert_eq!(body["status"], "pending");
assert_eq!(body["items"][0]["quantity"], 2);
let jobs = sqlx::query_scalar!("SELECT COUNT(*) FROM rust_jobs")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(jobs, Some(1));
}
#[sqlx::test(fixtures("schema", "products"))]
async fn validation_errors_match_laravel_shape(pool: PgPool) {
let (_, token) = seed_user_with_token(&pool, "b@example.com", 2).await;
let app = router(test_state(pool));
let res = app
.oneshot(
Request::post("/api/v1/orders")
.header("authorization", format!("Bearer {token}"))
.header("content-type", "application/json")
.body(Body::from(json!({ "items": [] }).to_string()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);
let body = json_body(res).await;
assert_eq!(body["message"], "The given data was invalid.");
assert!(body["errors"]["items"].is_array());
}
#[sqlx::test(fixtures("schema", "products"))]
async fn other_users_cannot_view_my_order(pool: PgPool) {
let (_, owner_token) = seed_user_with_token(&pool, "c@example.com", 3).await;
let (_, other_token) = seed_user_with_token(&pool, "d@example.com", 4).await;
let app = router(test_state(pool));
let created = app
.clone()
.oneshot(
Request::post("/api/v1/orders")
.header("authorization", format!("Bearer {owner_token}"))
.header("content-type", "application/json")
.body(Body::from(json!({ "items": [{ "product_id": 1, "quantity": 1 }] }).to_string()))
.unwrap(),
)
.await
.unwrap();
let id = json_body(created).await["id"].as_i64().unwrap();
let res = app
.oneshot(
Request::get(format!("/api/v1/orders/{id}"))
.header("authorization", format!("Bearer {other_token}"))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::FORBIDDEN);
}Fixture files live in fixtures/schema.sql and fixtures/products.sql at the crate root (by default, fixtures/ next to the test file's crate; verify the lookup path against the sqlx::test docs for your version). Generate schema.sql from your Laravel database with pg_dump --schema-only or php artisan schema:dump, so Rust tests run against the exact schema Laravel produces. Note that #[sqlx::test] needs DATABASE_URL pointing at a Postgres server where it may create and drop test databases.
Data layer details
SQLx, SeaORM, or Diesel?
| Library | Model | Strengths | Trade-offs | Pick it when |
|---|---|---|---|---|
| SQLx | Raw SQL, async, optional compile-time checks | You see exactly what runs; no ORM impedance mismatch; great for reusing Laravel's schema | No relationship layer, more boilerplate | Default for migrations from Laravel; you know SQL |
| SeaORM | ActiveRecord-style entities on top of SQLx | Closest to Eloquent ergonomics: entities, relations, migrations, find_related; used by Loco | Heavier abstraction; entity generation from an existing DB via sea-orm-cli generate entity | You want Eloquent-like productivity and are comfortable with a code generator |
| Diesel | Typed query DSL, sync (with diesel-async for async) | Strong compile-time guarantees, mature | Steeper learning curve, DSL complexity, async via a separate crate | Teams who value type-level query checking and accept the DSL |
My recommendation for a Laravel migration: SQLx for the first service. You already have the schema, you already think in SQL, and keeping queries visible makes parity reviews far easier than reverse-engineering an ORM's generated SQL. Reach for SeaORM when relation-heavy CRUD is the bulk of the work. Verify the current major versions (the SeaORM 1.x and Diesel 2.x lines were current as of November 2026; both are moving).
Compile-time checked queries and offline mode
sqlx::query! and sqlx::query_as! connect to a database at compile time, run PREPARE on your SQL, and give you typed results (and a compile error for a typo'd column or a wrong parameter type). In CI and Docker builds you often do not have a database, so SQLx supports offline mode:
# one-time
cargo install sqlx-cli --no-default-features --features rustls,postgres
# with DATABASE_URL pointing at a dev database that has the Laravel schema loaded
cargo sqlx prepare # writes .sqlx/ query metadata; commit it
# in CI / Docker (no database needed)
SQLX_OFFLINE=true cargo build --release --locked
# CI check that metadata is current
cargo sqlx prepare --checkRules of thumb:
- Commit
.sqlx/. Fail CI ifcargo sqlx prepare --checkreports drift. - If the Laravel schema changes, regenerate
.sqlx/. This is the cost of the shared-database period, and it is also a feature: a Laravel migration that breaks a Rust query fails the Rust build, not production. - Use
query_as!with explicit overrides ("col!","col?","col: Type") when nullability or custom types are ambiguous. Views and expressions often need!. - If you want to avoid the database at compile time entirely, use the function forms (
sqlx::query_as::<_, Order>(...)), and lose compile-time checks. Test coverage becomes your safety net.
Migrations: who is the source of truth?
| Phase | Source of truth | Rust's role |
|---|---|---|
| Coexistence (Laravel still writes the schema) | Laravel migrations | Read-only consumer; schema dump into test fixtures; .sqlx/ regenerated on change |
| Shared ownership by table | Laravel for legacy tables; sqlx migrate for new Rust-owned tables (separate migrations table, naming convention such as a rust_ prefix) | Owns its tables only |
| Post-Laravel | sqlx migrate or SeaORM migrations | Full ownership; Laravel retired |
Mechanics:
sqlx migrate add -r create_rust_jobs # creates up/down files under migrations/
sqlx migrate run # applies pending migrations
sqlx migrate infoEmbed migrations in the binary with sqlx::migrate!("./migrations").run(&pool).await? if you want the service to migrate on startup (I prefer a separate release step so that crashing pods do not race on DDL).
Two different tools both want to own a migrations table. Laravel uses migrations; SQLx uses _sqlx_migrations. They do not collide, but they also do not know about each other's ordering, so keep Rust-owned tables independent of Laravel-owned ones, or coordinate foreign keys carefully.
Testing against the Laravel schema
# Laravel side: a single consolidated schema file (prunes old migrations when you add --prune)
php artisan schema:dump
# or directly from Postgres
pg_dump --schema-only --no-owner --no-privileges "$DATABASE_URL" > fixtures/schema.sqlLoad it with #[sqlx::test(fixtures("schema"))] as shown earlier, or run it once into a long-lived CI database. Add a CI job that checks out the Laravel repo, runs its migrations into a scratch database, and builds the Rust crate against it. That job is the strongest guard against schema drift.
Mapping Laravel conventions
| Laravel feature | What is in the database | Rust handling |
|---|---|---|
| Timestamps | created_at, updated_at; $table->timestamps() creates nullable timestamp(0) columns without time zone on Postgres | Use Option<NaiveDateTime> for nullable naive columns, or change to timestampTz + NOT NULL in Laravel so Rust uses DateTime<Utc>. Laravel writes in the app timezone (often UTC); confirm |
| Soft deletes | Nullable deleted_at | Add deleted_at IS NULL to every read; write deleted_at = now() for deletes |
| Casts: enums | String or int column | Rust enum with sqlx::Type and rename_all matching stored values |
| Casts: JSON / array | json / jsonb column | serde_json::Value or sqlx::types::Json<T> for a typed struct |
| Casts: boolean | tinyint(1) on MySQL, boolean on Postgres | bool (MySQL needs care with tinyint mapping) |
| Casts: decimal / money | decimal(10,2) | rust_decimal::Decimal or integer cents; never f64 |
| Casts: encrypted | Laravel-encrypted ciphertext in a text column | You need the APP_KEY decryption routine from the APP_KEY and encryption format section |
| Polymorphic relations | *_type containing PHP class names (for example App\Models\Post) and *_id | Match the string literally in SQL; or add a Rust-side mapping table |
| Pivot tables | Table with two ids (alphabetical naming) | Plain join queries |
| Primary keys | bigint unsigned (MySQL) or bigint | i64 (MySQL UNSIGNED maps to u64); UUID/ULID via uuid crate |
Auto-touching of parents ($touches) | Application behavior | Reimplement explicitly |
Relationships and N+1 avoidance
Eloquent's lazy loading hides N+1 queries; in Rust there is no lazy loading, so N+1 shows up only if you write a loop with a query in it. The patterns:
// Anti-pattern: N+1
for order in &orders {
let items = repo::items_for(&pool, order.id).await?; // one query per order
}
// Batch: one query, group in memory (the Rust equivalent of with('items'))
let ids: Vec<i64> = orders.iter().map(|o| o.id).collect();
let rows = sqlx::query!(
"SELECT order_id, product_id, quantity, unit_price_cents
FROM order_items WHERE order_id = ANY($1) ORDER BY id",
&ids,
)
.fetch_all(&pool)
.await?;
let mut by_order: std::collections::HashMap<i64, Vec<OrderItemOut>> = Default::default();
for r in rows {
by_order.entry(r.order_id).or_default().push(OrderItemOut {
product_id: r.product_id,
quantity: r.quantity,
unit_price_cents: r.unit_price_cents,
});
}For read-heavy endpoints, a single SQL statement with json_agg or a LATERAL join often beats any ORM eager-loading strategy. Turn on Postgres pg_stat_statements and watch query counts per request in the first week of canary traffic.
Transactions
pool.begin()returns aTransaction; dropping it withoutcommit()rolls back, which is the safe default.- Pass
&mut *txto queries inside a transaction. - Keep transactions short and never hold one across an HTTP call or an
awaiton something slow. - Laravel's
DB::transactionretries on deadlock (second argument); Rust does not, so wrap deadlock-prone paths in a retry for SQLSTATE40P01or40001. - Isolation levels:
sqlx::query("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")immediately after begin, or usepool.begin_with(...)where your version supports it (verify).
Connection pool sizing
The classic mistake is sizing for the app and forgetting the database's max_connections.
total DB connections = (Rust instances x pool max) + (PHP-FPM workers x 1) + (Laravel queue workers) + (admin/BI tools)
must be under: database max_connections minus headroom (typically 10-20 percent)- Start with a pool of 10 per Rust instance. Rust's async model needs far fewer connections than PHP-FPM needs workers, because connections are held only while a query runs.
- Watch
sqlxpool wait time: if requests wait for a connection, the pool (or your queries) is the bottleneck; adding connections beyond what the database can execute in parallel makes things worse. - Use PgBouncer in transaction mode if you have many instances. SQLx prepared statements and PgBouncer transaction pooling need care; check the PgBouncer version's prepared statement support, or set
statement_cache_capacity(0)on the connect options. - During the migration, PHP-FPM can burn through the connection budget. Measure before you shift traffic.
Auth and security parity
Authentication is where parity bugs become security incidents, so be deliberate. The key insight: share credentials and tokens, never PHP internals.
Verifying existing passwords
Laravel's default hasher is bcrypt ($2y$ prefix, 12 rounds by default in recent versions); some apps use argon2i/argon2id ($argon2id$...). Both are verifiable from Rust without any migration of user data.
use argon2::{password_hash::{PasswordHash, PasswordVerifier}, Argon2};
pub fn verify_laravel_password(plain: &str, stored_hash: &str) -> bool {
if stored_hash.starts_with("$argon2") {
match PasswordHash::new(stored_hash) {
Ok(parsed) => Argon2::default().verify_password(plain.as_bytes(), &parsed).is_ok(),
Err(_) => false,
}
} else if stored_hash.starts_with("$2y$") || stored_hash.starts_with("$2a$") || stored_hash.starts_with("$2b$") {
bcrypt::verify(plain, stored_hash).unwrap_or(false)
} else {
false
}
}Notes:
- The
bcryptcrate accepts the$2y$prefix PHP emits. Add a test using a hash generated byphp artisan tinker(Hash::make('secret')) so you never rely on memory. - bcrypt is CPU-bound; run verification on
tokio::task::spawn_blockingso it does not stall the async runtime. The same applies to argon2. - Rehashing on login: Laravel can rehash when parameters change (
Hash::needsRehash). If Rust rehashes into argon2id, Laravel must be able to verify it. Laravel's hasher can be configured to refuse hashes from a different algorithm (thehashing.verifyoption in recent versions), which would lock users out while both stacks run. Keep bcrypt during coexistence unless you have tested Laravel's behavior. - Laravel's bcrypt only uses the first 72 bytes of a password. Rust's
bcryptcrate has its own handling of long inputs (in recent versions it errors for inputs over 72 bytes unless you opt into truncation). Test long passwords on both sides. - Rate-limit login and password endpoints (see 7.5) and return identical errors for unknown user vs bad password.
Laravel's APP_KEY and encryption format
If you must read Laravel-encrypted values (the encrypted cast, Crypt::encryptString, encrypted cookies), know the format:
APP_KEYisbase64:followed by a base64-encoded 32-byte key (for AES-256).- The default cipher is
AES-256-CBC;AES-256-GCMis also supported. Checkconfig/app.php. - A payload is base64 of a JSON object with
iv,value,mac, and (for GCM)tag. For CBC,mac = HMAC-SHA256(iv_b64 + value_b64, key)is verified before decrypting. - By default values are PHP-
serialized before encryption (Crypt::encrypt), whileencryptStringdoes not serialize. TheencryptedEloquent cast uses the string form. - Cookies add a prefix derived from the cookie name and key before the value, and the value is usually serialized, then encrypted.
In Rust that means base64, hmac + sha2, and aes + cbc (or aes-gcm) from RustCrypto. It is doable, and I recommend wrapping it in a small, heavily tested module with known-answer tests generated by PHP. But treat it as a stopgap: do not make Rust depend on decrypting Laravel cookies or sessions. Decrypting a session cookie only yields a session id; the session data itself is PHP-serialized in the store (file, database, Redis), and parsing PHP serialization from Rust is fragile.
Sessions, cookies, and tokens: what to share
| Mechanism | Share with Rust? | How |
|---|---|---|
| Sanctum personal access tokens (API clients, mobile) | Yes | SHA-256 lookup in personal_access_tokens (see the auth extractor in the worked example) |
| Sanctum SPA cookie auth (stateful) | Avoid | Put the SPA's API calls for migrated routes on a token or short-lived JWT; or keep these routes in Laravel until you can change the client |
| Laravel session cookie | Avoid | Terminate sessions at Laravel; have it mint a short-lived signed token (JWT with jsonwebtoken) for Rust, or forward an authenticated user header from the proxy using an auth_request subrequest |
| Passport / OAuth2 access tokens (JWT) | Yes, if JWT | Validate signature with Laravel's public key (jsonwebtoken), check the jti against oauth_access_tokens for revocation |
JWT issued by Laravel (tymon/jwt-auth) | Yes | Same secret or key; match claims (sub, exp) |
A pattern that works well during transition is nginx auth_request: nginx asks Laravel (/internal/auth) whether the session is valid, and Laravel returns X-User-Id / X-User-Roles headers that nginx forwards to Rust. Rust trusts those headers only from the proxy (bind Rust to a private interface, strip the headers from external requests). It moves the session problem out of Rust entirely, at the price of one extra hop per request (cacheable).
If you later want Rust-native sessions, tower-sessions provides a session layer with pluggable stores (including SQLx and Redis stores in companion crates). Verify current store crate names and versions. Sessions would then be a Rust-owned concept, and you would migrate login itself.
CSRF and CORS
- CSRF applies to cookie-authenticated, browser-submitted state-changing requests. A bearer-token JSON API has no CSRF exposure because browsers do not attach the token automatically. If Rust serves any cookie-authenticated routes, you need CSRF protection (double-submit token or
SameSite=Lax/Strictplus anOrigincheck) because Laravel'sVerifyCsrfTokenwill not be there. - CORS: use
tower_http::cors::CorsLayerwith an explicit origin list. Do not use a wildcard together with credentials. Match what Laravel'sconfig/cors.phpallowed, includingAccess-Control-Expose-Headersand preflight max-age.
use axum::http::{header, HeaderValue, Method};
use tower_http::cors::CorsLayer;
pub fn cors() -> CorsLayer {
CorsLayer::new()
.allow_origin("https://app.example.com".parse::<HeaderValue>().unwrap())
.allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE])
.allow_headers([header::AUTHORIZATION, header::CONTENT_TYPE])
.max_age(std::time::Duration::from_secs(3600))
}Rate limiting
Laravel's throttle:60,1 has a counterpart in tower_governor (a Tower layer around the governor crate), or a Redis-backed limiter if limits must be shared across instances.
use std::sync::Arc;
use tower_governor::{governor::GovernorConfigBuilder, GovernorLayer};
// Verify the builder API against the tower_governor version you install;
// key extractors and layer construction have changed between releases.
let config = Arc::new(
GovernorConfigBuilder::default()
.per_second(2)
.burst_size(20)
.finish()
.unwrap(),
);
let limited = router.layer(GovernorLayer { config });Important detail: in-process limiters are per instance. With three Rust replicas a "60 per minute" limit becomes roughly 180 per minute. For exact limits use Redis (a token bucket or sliding window script) or do rate limiting at the proxy. Also configure the key extractor to use the real client IP from a trusted proxy header, otherwise everyone shares the proxy's IP.
Secure headers, validation, secrets
- Headers: set
X-Content-Type-Options,Referrer-Policy,Strict-Transport-Security(usually at the proxy), and a CSP where you serve HTML.tower_http::set_header::SetResponseHeaderLayerhandles this. - Input validation: validate at the edge with typed DTOs plus
validator. Rust gives you strong typing, but aStringis still any string: enforce lengths, formats, and ranges. Useserde(deny_unknown_fields)where strictness is wanted; note Laravel ignores unknown fields by default, so strictness can break existing clients. - SQL injection: SQLx parameter binding is safe;
format!into SQL is not. Make "no string-built SQL" a review rule and grep for it in CI. - Mass assignment: Eloquent's
$fillablehas no analogue, because Rust DTOs only contain fields you declare. That is better by default. - Secrets: load from environment or a secrets manager; never commit
.env. Wrap secrets insecrecy::SecretStringso they do not appear inDebugoutput or logs. - Dependency hygiene:
cargo audit(RustSec advisories) andcargo deny(advisories, licenses, duplicate versions) in CI. - Error responses: never return raw database or internal errors. The
AppErrormapping in the worked example does this.
Authorization parity checklist
- List every Laravel
authorize(), policy method, gate, middleware (can:,role:), and inlineabort_if. - Write a Rust test per rule: allowed user, forbidden user, unauthenticated.
- Replay existing feature tests as HTTP-level contract tests (the AI agent guide below covers how).
- Review query scopes: global scopes in Eloquent (multi-tenancy, soft deletes, "published only") silently filter queries. They must appear in every Rust query on those tables. A missing tenant filter is a data leak.
Queues, scheduling, mail, and files
Queues
| Approach | Good for | Caveats |
|---|---|---|
Postgres table with FOR UPDATE SKIP LOCKED (see the background job example) | Moderate throughput, strong consistency with business data (outbox), zero new infrastructure | Polling latency; table bloat if you never delete finished rows; not for millions of jobs per minute |
apalis (Redis, Postgres, SQLite storages and a middleware model) | A job-processing framework with retries, concurrency, and monitoring-style features | The API has changed a lot between versions; read the version-specific docs and examples; do not copy older snippets |
| Redis lists/streams directly | High throughput | You own reliability: acks, retries, visibility timeouts |
A message broker (RabbitMQ via lapin, Kafka via rdkafka, NATS) | Cross-service eventing | Operational cost |
| Keep Laravel's queue and let Rust enqueue | Transition period | See below |
Do not try to have Rust consume Laravel's own queue payloads. Laravel's Redis/database queue payloads contain PHP-serialized job objects (SerializesModels, closures), which you cannot sensibly deserialize from Rust. Two clean options instead:
- Rust enqueues, Laravel processes: Rust inserts a well-formed Laravel job row, or better, calls a small Laravel endpoint or publishes an event that a Laravel listener turns into a job. This works for the transition period when the job logic still lives in PHP.
- Separate queues by owner: new Rust workers consume a Rust-owned queue; Laravel keeps its queues. Port job types one at a time, switching the producer when the Rust consumer is ready.
Whichever you choose, design every job to be idempotent, add a dead-letter state (the max_attempts column above), and expose queue depth and oldest-job age as metrics.
Scheduler
Laravel's schedule:run every minute becomes one of:
- Kubernetes CronJob / system cron running a subcommand of your binary (
orders-api cron nightly-report). It is simple, observable, and safe with multiple replicas because exactly one pod runs per tick. This is my default. tokio-cron-schedulerinside the process. Convenient for single-instance deployments; with multiple replicas you must add leader election or a Postgres advisory lock so a task does not run N times.
use tokio_cron_scheduler::{Job, JobScheduler};
pub async fn start_scheduler(pool: sqlx::PgPool) -> anyhow::Result<JobScheduler> {
let sched = JobScheduler::new().await?;
// Six-field cron with seconds: every day at 02:00:00.
sched
.add(Job::new_async("0 0 2 * * *", move |_uuid, _lock| {
let pool = pool.clone();
Box::pin(async move {
// Single-run guarantee across replicas via advisory lock
let got: bool = sqlx::query_scalar("SELECT pg_try_advisory_lock(424242)")
.fetch_one(&pool)
.await
.unwrap_or(false);
if !got {
return;
}
tracing::info!("running nightly report");
// ... do the work, then release the lock
let _ = sqlx::query("SELECT pg_advisory_unlock(424242)").execute(&pool).await;
})
})?)
.await?;
sched.start().await?;
Ok(sched)
}Caveat: session-level advisory locks are tied to a single connection, and a pool can hand you a different connection for the unlock call. For production use a dedicated connection (pool.acquire() held for the duration) or pg_advisory_xact_lock inside a transaction. This is a classic bug; the CronJob approach avoids it entirely.
Mail and notifications
lettreis the standard SMTP client (async with Tokio, TLS via rustls or native-tls features). Build a transport once and reuse it.- Prefer a transactional email provider's HTTP API (Postmark, SES, Resend, Mailgun) via
reqwestfor deliverability features, bounce handling, and templates. - Templates:
askama(compile-time checked, Jinja-like),minijinja, ortera(runtime). Keep HTML emails in template files, not format strings. - Notifications: Laravel's channel abstraction (mail, database, Slack, SMS) does not exist. A
trait Notifierwith one implementation per channel is enough. Store in-app notifications in the samenotificationstable if Laravel's UI still reads it (note itsdataJSON column andtypeclass name).
Files and object storage
object_store(the Apache Arrow project's crate) gives one trait over S3, GCS, Azure, and local disk, which is the closest thing to Laravel'sStoragefacade.aws-sdk-s3is the official AWS SDK; use it when you need S3-specific features (multipart control, presigned URLs, object lock).- Presigned URLs keep large uploads and downloads off your service. Laravel's
Storage::temporaryUrlhas a direct equivalent in the SDK. - Keep path conventions identical to Laravel's
Storagedisks (prefixes, hashed filenames) so both stacks read each other's files during the transition. - Stream uploads (
axum::extract::Multipart, orBodystreaming into the store) rather than buffering whole files in memory. SetRequestBodyLimitLayerper route.
Observability and operations
Tracing, logs, and OpenTelemetry
tracing is the structured logging and span library; tracing-subscriber formats it; tracing-opentelemetry with opentelemetry-otlp exports spans to any OTLP backend (Tempo, Jaeger, Honeycomb, Datadog). The OpenTelemetry Rust crates change often, so pin a coherent set and verify the current setup docs.
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
pub fn init_tracing() {
tracing_subscriber::registry()
.with(EnvFilter::try_from_default_env().unwrap_or_else(|_| "info,sqlx=warn,tower_http=info".into()))
.with(tracing_subscriber::fmt::layer().json())
// .with(tracing_opentelemetry::layer().with_tracer(tracer)) // add once OTLP is wired
.init();
}Practical advice:
- Put a request id on every request (
tower_http::request_id) and propagate the proxy'sX-Request-Idso one id spans nginx, Rust, and Laravel logs. - Use
#[tracing::instrument(skip(pool))]on repo functions to get per-query spans. - Propagate W3C
traceparentheaders across the Laravel/Rust boundary so a single trace covers both. OpenTelemetry PHP auto-instrumentation on the Laravel side makes this work end to end. - For LLM-specific tracing, see my post on OpenTelemetry for LLM apps.
Metrics
Expose Prometheus metrics at /metrics using the metrics facade with metrics-exporter-prometheus (or a helper crate such as axum-prometheus; verify its current Axum compatibility). Track:
- Request rate, error rate, and latency histograms per route (use the matched path, not the raw URL, to avoid cardinality explosions).
- DB pool in-use and wait time.
- Job queue depth and age of the oldest pending job.
- Business counters (orders created), so a canary can be compared on outcomes, not just HTTP codes.
Health checks and graceful shutdown
/healthz(liveness): process is up. Do not check the database here, or a DB blip restarts every pod./readyz(readiness): database reachable, migrations at the expected version. Fail it during shutdown.- Graceful shutdown (as in the main.rs example): on SIGTERM stop accepting connections, finish in-flight requests, stop the job worker, close the pool. Set Kubernetes
terminationGracePeriodSecondsabove your longest request, and add a shortpreStopsleep so the load balancer deregisters the pod before it stops accepting traffic.
Docker multi-stage build with cargo-chef
cargo-chef caches dependency compilation in a Docker layer, which cuts rebuild times dramatically when only your code changes.
# syntax=docker/dockerfile:1.7
FROM rust:1.90-bookworm AS chef
RUN cargo install cargo-chef --locked
WORKDIR /app
FROM chef AS planner
COPY . .
RUN cargo chef prepare --recipe-path recipe.json
FROM chef AS builder
COPY --from=planner /app/recipe.json recipe.json
# Build and cache dependencies only
RUN cargo chef cook --release --recipe-path recipe.json
COPY . .
ENV SQLX_OFFLINE=true
RUN cargo build --release --locked --bin orders-api
FROM gcr.io/distroless/cc-debian12:nonroot AS runtime
WORKDIR /app
COPY --from=builder /app/target/release/orders-api /app/orders-api
EXPOSE 8080
USER nonroot
ENTRYPOINT ["/app/orders-api"]Pin the Rust image tag to a version you have tested (the tag above is an example; use a current stable release). Because SQLX_OFFLINE=true, the build uses the committed .sqlx/ directory and needs no database.
Static musl binaries
For a scratch or tiny image, build a fully static binary:
rustup target add x86_64-unknown-linux-musl
cargo build --release --locked --target x86_64-unknown-linux-muslWith rustls (not OpenSSL) for TLS, the result has no system library dependencies. Caveats: musl's allocator is slower under heavy multi-threaded allocation (consider mimalloc or tikv-jemallocator), and a few C-dependent crates are harder to build for musl. Distroless cc with the default glibc target is a pragmatic middle path.
CI pipeline
name: ci
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: postgres
ports: ["5432:5432"]
options: >-
--health-cmd pg_isready --health-interval 5s --health-timeout 5s --health-retries 10
env:
DATABASE_URL: postgres://postgres:postgres@localhost:5432/postgres
SQLX_OFFLINE: "true"
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy, rustfmt
- uses: Swatinem/rust-cache@v2
- run: cargo fmt --all -- --check
- run: cargo clippy --all-targets --locked -- -D warnings
- run: cargo install cargo-nextest --locked
- run: cargo nextest run --locked
- run: cargo install cargo-deny cargo-audit --locked
- run: cargo deny check
- run: cargo auditTips: use prebuilt binaries for cargo-nextest, cargo-deny, and cargo-audit via an install action to avoid compiling them every run; cargo nextest does not run doctests, so add cargo test --doc if you have them; run cargo sqlx prepare --check in a job with a real database.
Compile time and CI cost
Be honest with your team about this. A cold release build of a mid-sized Axum + SQLx service can take several minutes; incremental debug builds are seconds. Mitigations:
Swatinem/rust-cache,sccache, andcargo-cheffor caching.- Split into a workspace of crates so unchanged crates are not rebuilt (but do not over-split).
- Faster linkers (
moldon Linux,lld) and[profile.dev] debug = "line-tables-only"for quicker local builds. - Avoid unnecessary heavy dependencies and macro-heavy crates.
- Release profile for production:
lto = "thin",codegen-units = 1costs build time and buys a little runtime speed; measure whether it matters for you.
PHP has no compile step, so your CI used to be faster than it will be. Budget for it.
Deployment
- Run Rust as a container (ECS, Kubernetes, Fly, Cloud Run, Nomad) or a systemd service behind the same proxy as Laravel.
- Roll out with the proxy-level canary (see the migration strategies section), not with a big-bang deploy.
- Keep Laravel and Rust deploys independent. A Rust deploy should not require a Laravel deploy, and vice versa.
- Store config in environment variables; keep one
.env.exampledocumenting every variable. - Run migrations as a separate release step, never from pod startup under autoscaling.
Performance: what to expect and how to measure it
I am deliberately not going to give you a "Rust is Nx faster than Laravel" number. Such numbers depend on the workload, hardware, caching, database, and how well each side was tuned, and most published comparisons are hello-world benchmarks that say little about a real application. What I can give you is a method.
Realistic expectations
- For database-bound endpoints, the framework matters little. If 90 percent of a request is waiting on Postgres, rewriting the other 10 percent cannot give a large end-to-end improvement.
- For CPU-bound or serialization-heavy endpoints (large JSON, parsing, cryptography, image or document processing), Rust typically wins clearly.
- For memory, a Rust service has a small, stable footprint, while PHP-FPM memory scales with the worker count times per-worker memory. This often changes how many instances you pay for.
- For tail latency, no GC and no per-request bootstrapping make p99 more predictable.
- For concurrency, Tokio makes holding many idle connections cheap, which is what matters for websockets and SSE.
For a rigorous third-party view of framework overhead on standardized tests, see the TechEmpower Framework Benchmarks (linked in further reading), keeping in mind that they measure specific synthetic scenarios.
The baseline you should compare against
Compare against a tuned Laravel, not default php artisan serve:
- PHP 8.4 or newer with OPcache enabled and tuned (and JIT evaluated, not assumed).
- Laravel Octane (FrankenPHP, Swoole, or RoadRunner), which keeps the framework booted between requests.
config:cache,route:cache,event:cache,view:cache, and an optimized autoloader (composer install --optimize-autoloader --classmap-authoritative).- Eager loading, indexes, and response caching applied.
- Realistic worker counts for PHP-FPM, or sized Octane workers.
If the tuned-Laravel number is already within your latency and cost targets, you have your answer.
How to benchmark fairly
- Define the question. For example: "At 500 requests per second of the real production mix, what are p99 latency and CPU needed?"
- Same data, same database, same indexes, same hardware class. Production-sized data, not ten rows.
- Same behavior. Both implementations must return equivalent responses (use your contract tests), do the same validation, auth, and logging.
- Warm up both (OPcache, connection pools, JIT, caches), then measure.
- Open-loop load at a fixed arrival rate (k6
constant-arrival-rate,wrk2,oha) to avoid coordinated omission, which makes closed-loop tools under-report tail latency. - Measure at the proxy/client, plus server-side CPU, memory, and DB metrics, with the load generator on a separate machine.
- Report percentiles (p50/p95/p99) and error rate, not just an average or max throughput.
- Find the saturation point by stepping the rate up until latency or errors spike, and then compare cost at a safe load (say 50 to 60 percent of capacity), not at the breaking point.
- Repeat runs and report variance. Run the Rust build in
--release. - Profile before concluding.
cargo flamegraphorperffor Rust; Blackfire, Xdebug profiling, or SPX for PHP.
Pitfalls
- Benchmarking a Rust
debugbuild. - Comparing cached Rust against uncached Laravel (or the reverse).
- Different JSON payload sizes or compression settings.
- Load generator on the same box, stealing CPU.
- Closed-loop tests with few connections that hide queuing.
- Ignoring the connection pool, a 10-connection pool can cap throughput regardless of language.
- Reporting a single best run.
A simple cost model
monthly_cost_laravel = instances_php x price_per_instance
monthly_cost_rust = instances_rust x price_per_instance
migration_cost = engineers x months x loaded_monthly_cost + opportunity_cost
payback_months = migration_cost / (monthly_cost_laravel - monthly_cost_rust)Fill in instances_* from your own benchmark at your target load. If the payback is longer than your planning horizon, or the saving is small next to one engineer-month, stop. Teams that skip this arithmetic are the ones who regret the rewrite.
Team and hiring
The learning curve
| Topic | Why it is hard for PHP developers | Practical approach |
|---|---|---|
| Ownership and borrowing | There is no equivalent concept in PHP | Start by cloning liberally (.clone()) and passing owned values; optimize later |
| Lifetimes | Visible only when returning references | Avoid storing references in structs at first; use owned String and Vec |
| Async | Futures, Send bounds, blocking vs async, .await points | Use Tokio and Axum defaults; never block inside async (use spawn_blocking) |
| Error handling | Result and ? rather than exceptions | One AppError enum plus thiserror; anyhow for internal plumbing |
| Type system | Enums with data, traits, generics | Use enums heavily (they are the payoff); defer advanced generics |
| Compile errors | Long, but usually informative | Read them top to bottom; the first error is the real one |
| Tooling | cargo, clippy, rustfmt | Adopt them on day one; they teach idiom |
Rust features to avoid at first
- Writing your own macros (
macro_rules!, proc macros). unsafe. Forbid it in the crate (#![forbid(unsafe_code)]) unless justified.- Complex generic abstractions and trait objects with lifetimes; prefer concrete types and
Arc<dyn Trait>only where needed. - Manual
Pin, hand-writtenFutures, and custom executors. - Cleverness with iterator chains when a
forloop is clearer. - Premature optimization (zero-copy parsing, arena allocators).
- Too many crates; each is a dependency to audit and upgrade.
Pair programming and code review
- Pair a Rust-experienced engineer with a Laravel expert on each ported endpoint. The Laravel expert knows the behavior and edge cases; the Rust engineer knows the idioms. This is the single most effective practice.
- Review checklist for Rust PRs: error mapping, missing authorization call, missing soft-delete filter, missing
updated_at, unbounded queries, blocking calls in async,unwrap()outside tests, secrets in logs, transaction scope. - Enforce
clippy -D warningsandrustfmtso review is about substance. - Ban
unwrap()andexpect()in handlers and services (lint withclippy::unwrap_used); allow them in tests and startup. - Write a short internal "How we write Rust services" doc with the layout from the Rust project layout section and keep it current.
30/60/90-day learning plan
| Period | Focus | Deliverable |
|---|---|---|
| Days 1-30 | The Rust Book chapters on ownership, enums, Result; Rustlings; build a tiny CLI; read the Axum examples | Each engineer ships a small CLI or internal tool; the team agrees on the project layout and error strategy |
| Days 31-60 | Async and Tokio basics; SQLx; port one read-only endpoint as a pair; write contract tests | One GET endpoint behind the proxy at a small canary percentage |
| Days 61-90 | Auth extractor, transactions, a background job, observability; the first on-call rotation shadowing | One write endpoint and one job in production, with dashboards and alerts, and a retrospective on estimates |
Hiring
- Hire for backend fundamentals (SQL, concurrency, HTTP, debugging); Rust syntax can be learned, system understanding takes years.
- Growing internal Rust skill is usually cheaper and more reliable than hiring specialists, especially for a bounded service.
- Expect a smaller candidate pool and higher salary expectations for experienced Rust engineers. Check your local market.
- Keep a bus factor of at least two on every Rust service. A migration owned by one enthusiast is a liability.
- Be honest in interviews and onboarding that the stack is mixed (PHP and Rust) so no one is surprised.
Pitfalls, anti-patterns, and the cost of a rewrite
Anti-patterns
- Rewriting without profiling. You move the problem to a new language.
- Big-bang cutover. No rollback, no learning loop.
- Re-creating Laravel's magic. Building your own service container with
Arc<dyn Any>, a homemade facade layer, or reflection-like registries. Use explicitAppState. - Over-abstraction on day one. Traits for everything, generic repositories, a hexagonal architecture before the first endpoint works.
- Fighting the borrow checker with
Arc<Mutex<...>>everywhere. A sign of shared mutable state that should be a channel or a database row. - Blocking in async. CPU-heavy work,
std::thread::sleep, synchronous file or DNS calls, and bcrypt on the runtime thread. Usespawn_blocking. - Holding a lock or transaction across an await on slow I/O.
unwrap()in request paths. One panic per bad input is a denial-of-service vector (catch panics withtower_http::catch_panicas a safety net, not a strategy).- Unbounded everything. No request body limits, no timeouts, no pool acquire timeout, unbounded channels.
- Ignoring Eloquent side effects. Observers, events, accessors and mutators, casts,
$touches, and global scopes that no longer run when Rust writes directly. - Float money. Use integer cents or
rust_decimal. - Different JSON semantics. Laravel emits
[]for empty arrays that are objects elsewhere; integer vs string ids (JavaScript clients andbigint); null vs missing keys; date formats (ISO 8601 with offset vsZ). Contract tests catch these. - Timezone drift. Naive timestamps written in the app timezone, read as UTC.
- Different validation rules. Laravel's
stringaccepts"123"for an integer field in some cases;serdeis strict. Decide whether to be lenient to keep clients working. - Two sources of truth for schema. Be explicit in each phase about who owns migrations.
- Shipping without observability. You cannot canary what you cannot measure.
The cost of a rewrite
A realistic budget should include:
- Engineering time to port, test, and operate two stacks in parallel.
- Features not built while engineers port code.
- Ramp-up and review overhead during the first 3 to 6 months.
- Extra infrastructure and CI for a second runtime.
- Ongoing cost of two ecosystems: PHP/Composer upgrades and Rust/Cargo upgrades, security patching both.
- Recruiting and onboarding differences.
A common rule of thumb, not a measured result: take your first estimate for the first route, and for planning the remainder, multiply by at least two until the team has shipped several routes. Revisit the plan after every phase.
When NOT to migrate (summary)
Do not migrate to Rust if any of these is true:
- You have not profiled and fixed obvious problems (queries, caching, queue offloading, Octane).
- The slow part is the database or a third-party API.
- The team has no Rust experience and the deadline is fixed.
- The application is mostly CRUD with low traffic and the main goal is "modernization".
- You depend heavily on Laravel's ecosystem (Nova/Filament, Cashier, Livewire, Scout, Socialite, Telescope) for core functionality.
- The product is still finding fit and requirements change weekly.
- You cannot afford a multi-month period of reduced feature velocity.
- The motivation is mostly résumé-driven or curiosity. Try Rust on a side project or an internal tool instead.
AI agent guide: porting a Laravel route to Rust
This section is written so that a coding agent (or a human supervising one) can port one route at a time with verifiable correctness. The core idea: the agent never "translates code"; it reproduces observable behavior and proves it with tests.
Inputs the agent needs
For each route, gather:
- The route definition, middleware stack, and route-model binding (
routes/api.php,php artisan route:list --json). - The controller method, FormRequest, Policy, Resource, and any jobs, events, observers, and notifications triggered.
- The Eloquent models involved:
$casts,$fillable, accessors/mutators, global scopes, soft deletes,$touches. - The DB schema for each table (columns, nullability, defaults, indexes, foreign keys).
- Existing feature tests for the route.
- Golden responses: recorded real or test responses for representative cases (success, validation failure, unauthorized, forbidden, not found).
Prompt template
You are porting ONE Laravel route to Rust (Axum 0.8, SQLx 0.8, validator, thiserror).
Route: POST /api/v1/orders
Laravel files: [paste controller method, FormRequest, Policy, Resource, Job]
Schema: [paste CREATE TABLE statements]
Golden responses: [paste JSON for 201, 422, 401, 403]
Constraints:
- Do not change the response shape, status codes, or field names.
- Use the project's AppError, AppState, CurrentUser, and ValidatedJson. Do not invent new patterns.
- All SQL via sqlx::query! / query_as! with parameter binding. No string-built SQL.
- Reproduce side effects: updated_at, soft-delete filter, global scopes, events/jobs dispatched.
- No unwrap()/expect() outside tests. No blocking calls in async code.
- Output: (1) a behavior inventory table, (2) the Rust code, (3) tests, (4) a list of anything you could not verify.
Before writing code, list every observable behavior of the Laravel route: inputs, validation rules and messages, auth and authorization, DB reads and writes, side effects, response codes, headers, and JSON shape.Agent workflow
- Inventory behavior in a table: input, rule, output. Include implicit behavior (Eloquent events, casts, hidden attributes via
$hidden,$appends, default values, ordering). - Write the contract test first: HTTP-level tests that send requests and assert on status and body for each golden case. They must run against Laravel and Rust (see 13.4).
- Implement DTOs, validation, repo functions, policy, handler, in that order.
- Run:
cargo fmt,cargo clippy -- -D warnings,cargo sqlx prepare --check,cargo nextest run. - Diff against golden responses with explicit normalization of volatile fields.
- Report gaps: list behaviors it could not reproduce or verify, rather than guessing.
- Stop at the route boundary. Do not refactor neighbors.
Contract tests and golden responses
A simple, language-agnostic approach: store cases as JSON and run them against any base URL.
{
"name": "create order - validation error",
"request": {
"method": "POST",
"path": "/api/v1/orders",
"headers": { "authorization": "Bearer ${TOKEN_USER_A}", "accept": "application/json" },
"body": { "items": [] }
},
"expect": {
"status": 422,
"json_subset": { "message": "The given data was invalid." },
"json_has_keys": ["errors.items"],
"ignore": ["errors.items[0]"]
}
}# Record from Laravel, replay against Rust, diff normalized output
BASE=http://laravel.internal ./contract-run cases/orders/ --record golden/
BASE=http://rust.internal ./contract-run cases/orders/ --compare golden/ \
--ignore '$.data[*].id' --ignore '$.created_at' --ignore '$.updated_at'contract-run is whatever small harness you write (a Node, Python, or Rust script); the point is the workflow. For snapshots inside Rust tests, insta works well with assert_json_snapshot! and redactions for volatile fields. For consumer-driven contracts, Pact is an established option.
Verification checklist for an agent-produced port
- Status codes match for success, validation, auth, authorization, not found, and conflict cases.
- JSON keys, nesting, casing, null vs omitted, number vs string types match.
- Timestamps use the same format and timezone as Laravel's output.
- Pagination envelope and query parameters match (
page,per_page,meta,links) where clients rely on them. - Validation messages and error keys match (including nested keys like
items.0.quantity). - Authorization rules are covered by a test for each role.
- Soft-delete filter, global scopes, and tenant scoping are applied in every query.
-
updated_atand any other implicit writes are performed. - Side effects (jobs, events, notifications, cache invalidation) still happen exactly once.
- No
unwrap()outside tests; no string-built SQL; no blocking calls in async paths. - Queries are batched; no per-row query inside a loop.
- The
.sqlx/metadata is regenerated and committed. - A rollback is possible by flipping the proxy route.
Guardrails for agents
- Give agents read-only database credentials for exploration; use a scratch database for tests.
- Never let an agent run destructive migrations or point at production.
- Require every agent PR to include the behavior inventory and test evidence.
- Treat agent output as a draft: the human reviewer owns correctness, especially authorization and money.
- Keep prompts and golden files in the repo so the process is repeatable.
Final migration checklist
Before you start
- Profiled production; bottlenecks identified with evidence.
- Laravel-side optimizations (queries, caching, Octane, queues) tried or ruled out.
- Scorecard completed; leadership accepts the cost model and timeline.
- Team has at least two people committed to learning Rust, and a plan for on-call.
Foundations
- Rust workspace with
fmt,clippy, tests,cargo deny,cargo auditin CI. -
.sqlx/committed and checked in CI; schema dump available for tests. - Reverse proxy in front of Laravel; routes switchable by config;
X-Request-Idpropagated. - Config, tracing, metrics,
/healthz,/readyz, graceful shutdown in place. - Docker image built with cargo-chef; deploy and rollback rehearsed.
Per route
- Behavior inventory written (including Eloquent side effects).
- Contract tests recorded from Laravel and passing against Rust.
- Authorization tests for each role.
- Shadow traffic compared; canary at 1%, 10%, 50%, 100% with metrics watched.
- Rollback tested; old Laravel code kept for a defined period, then removed.
Data and ownership
- One writer per table; schema ownership documented.
- Expand/contract process for schema changes agreed by both teams.
- Connection budget calculated across Laravel and Rust.
After
- Dashboards and alerts for latency, errors, saturation, queue age.
- Post-migration cost and latency compared to the baseline.
- Documentation of the permanent Laravel/Rust boundary and the decision on what to leave in PHP.
Questions that come up
Which database library is closest to Eloquent?
SeaORM is closest in ergonomics. SQLx is closest to "just SQL" and is my default for a migration, because you keep full control of queries.
Can Rust consume Laravel's queue, and what replaces Horizon?
Not sensibly. Payloads are PHP-serialized objects. Use separate queues per owner, or have Rust enqueue and Laravel process during the transition. To replace queues and Horizon, use a Postgres SKIP LOCKED job table, apalis, or a Redis/broker-based worker. Make jobs idempotent and expose queue depth and age as metrics.
How do I replace the scheduler?
A Kubernetes CronJob or system cron calling a subcommand of your binary is the simplest. tokio-cron-scheduler works in-process but needs a lock when you run several replicas.
How do I keep Blade, Livewire, or Inertia pages?
Keep them in Laravel and migrate the API only. If you need server-rendered HTML in Rust, use Askama, Maud, Tera, or MiniJinja, but this is rarely the best first move.
How much faster will Rust be?
It depends entirely on the workload. Database-bound endpoints see little change; CPU-bound and high-concurrency workloads can see large gains. Measure with open-loop load tests against a tuned Laravel (Octane), not assumptions.
How long does a migration take?
For one hot route plus the shared foundations, expect weeks, not days. A phased plan for a meaningful slice of an application is 12 to 24 weeks, and a full rewrite of a large app is often more than a year.
Sources and docs
- Axum documentation and the Tokio blog announcement of axum 0.8
- Axum examples on GitHub
- SQLx on GitHub, including the README sections on compile-time verification and
sqlx-cli - SeaORM and Diesel
- Loco and Actix Web
- tower-http, tower-sessions, tower_governor
- validator, utoipa, lettre, apalis, tokio-cron-scheduler, object_store, argon2, bcrypt
- cargo-chef, cargo-nextest, cargo-deny
- The Rust Book and Rustlings
- Laravel Sanctum docs, Laravel Octane docs, and Laravel encryption docs
- Martin Fowler on the Strangler Fig pattern
- TechEmpower Framework Benchmarks
- Zero to Production in Rust (Luca Palmieri), a book on production Rust web services
- On this site: Building production Rust web services with Axum and Tokio, Rust vs Go vs Zig for backends, and Laravel performance optimization