For three days Rust learned to answer requests: it counted views, checked tokens and read the PHP session. All of that happened while the user waited for a response. Today, for the first time, Rust does its work later: in the background, in a separate process, with retries on failure.
In other words, DevSense now has a second queue worker. And the first thing we found out: it is not going to make friends with the first one.
In short
- What we move: the "token was just used" mark (
last_used_atandlast_ip) — out of the request and into a Rust background job. - The big discovery: PHP and Laravel Rust queues are incompatible, both in the job format and in the failed jobs table. So each side dispatches and runs its own jobs.
- How it works: a
TouchTokenjob, a dedicatedrustqueue in Redis, a dedicatedrust_failed_jobstable, a dedicated worker under supervisor. - The safety net: if the queue is not set up or Redis is unreachable, Rust writes to the database inline, as before.
Test subject number four
On Day 2 we moved the Zones check to Rust. Before every commit, a git hook knocks on the server with a personal token. And the server, just like PHP, notes when and from which address the token was last used. That way a person in their dashboard can see which token is alive and which one is due to be revoked.
In PHP it is three lines in a middleware:
// Best-effort usage tracking without a DB write on every request.
if (Cache::add('mcp_token_touch_v1_'.$token->id, '1', now()->addMinutes(5))) {
$token->forceFill(['last_used_at' => Carbon::now(), 'last_ip' => $request->ip()])->save();
}
No more than once every five minutes per token, right inside the request. It works. But it is the perfect candidate for a first background job:
- tiny — a single
UPDATE, no mail, no S3, no external APIs; - the user does not need it right now — the hook cares about the "go ahead and commit" answer, not about a date in the dashboard;
- idempotent — running it twice does no harm, so retrying on failure is safe;
- already in Rust — the route moved on day two, so the code dispatching the job will be Rust.
That last point turned out to be the key one. Why — see the next section.
Why we cannot just borrow the PHP queue
The first idea was the obvious one: the PHP worker is already spinning under supervisor, the jobs table already exists. Let Rust drop its jobs in there, and let its own worker pick them up from the same place.
No such luck. We dug into the Laravel Rust source and compared:
| PHP Laravel | Laravel Rust 0.1.5 | |
|---|---|---|
| A job in the queue | a serialized PHP object | JSON: the job name and its fields |
jobs.available_at, reserved_at |
integers (Unix time) | timestamp |
| Failed jobs table | uuid, exception |
job_id, error |
| Redis keys | with the application prefix | no prefix: queues:{default} |
The PHP worker will not understand a Rust job, and the Rust worker will not understand a PHP one. Worse still, a failed Rust job written to PHP's failed_jobs simply will not fit into someone else's columns.
Hence the rule of day four: each side has its own queue, and a job is dispatched by the same side that runs it. PHP jobs stay in the jobs table with laravel-worker. Rust jobs live in Redis, in a separate database 3 (PHP occupies 0 and 1), in the rust queue. Failed Rust jobs land in a separate rust_failed_jobs table.
The table is created by a PHP migration: migrations, for us, still live only in PHP. The columns are exactly the ones Laravel Rust writes:
Schema::create('rust_failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('job_id', 36)->unique();
$table->string('connection');
$table->string('queue');
$table->longText('payload');
$table->longText('error');
$table->timestamp('failed_at');
$table->index(['connection', 'queue', 'failed_at']);
});
A job in Rust: #[job] instead of implements ShouldQueue
For comparison, here is one of DevSense's real PHP jobs:
class ForgetOgCards implements ShouldQueue
{
use Queueable;
public int $tries = 3;
public function __construct(public string $dir) {}
public function handle(): void
{
if (! Str::startsWith($this->dir, 'og-cards/') || str_contains($this->dir, '..')) {
return;
}
$disk = OgCards::disk();
foreach ($disk->files($this->dir) as $file) {
OgCards::forgetReady($file);
$disk->delete($file);
}
}
}
And here is our first job in Rust:
#[derive(Queueable)]
pub struct TouchToken {
pub token_id: i64,
pub ip: String,
}
#[job(name = "tokens.touch", queue = "rust", tries = 3, backoff = [10.seconds(), 1.minutes()], timeout = 30.seconds())]
impl TouchToken {
async fn handle(self) -> laravel::Result<()> {
Self::write(self.token_id, &self.ip).await
}
}
impl TouchToken {
/// The write itself, also used inline when the queue is not set up or does not take the job.
/// A revoked or deleted token simply matches no row.
pub async fn write(token_id: i64, ip: &str) -> laravel::Result<()> {
db::table("portfolio_tokens")
.filter(col("id").eq(token_id))
.update(db::values! {
last_used_at: db::raw!("LOCALTIMESTAMP(0)"),
last_ip: ip,
updated_at: db::raw!("LOCALTIMESTAMP(0)"),
})
.await?;
Ok(())
}
}
The family resemblance is obvious: the job data are fields, the work is a handle method, the number of tries is a setting. But there are some pleasant differences too.
- All the settings in one attribute. Name, queue, tries, the pauses between them (10 seconds, then a minute) and the timeout — one line above the
impl. In PHP these are separate class properties and methods. - A stable name. By default Laravel Rust writes the type path into the job, for example
app::jobs::TouchToken. Rename the module, and the jobs already waiting in the queue will not find their type. Hencename = "tokens.touch". - Nothing to register. The worker finds the job on its own.
- An honest timeout. A job that runs past 30 seconds is cancelled at the next
.await.
Dispatching the job, with a safety net
The most interesting part is the spot where the job gets dispatched. Once again we applied the principle of the previous days, "not sure — don't risk it":
// Day 4: in the background on Rust's own queue when it is set up; inline otherwise, and
// also when Redis does not take the job, so the mark is never lost to a queue problem.
if jobs::ready() {
let job = TouchToken {
token_id: token.id,
ip: ip.to_owned(),
};
match job.dispatch().await {
Ok(_) => return Ok(()),
Err(error) => tracing::warn!(%error, "queueing TouchToken failed; writing inline"),
}
}
TouchToken::write(token.id, ip).await
What jobs::ready() does:
pub fn is_ready(connection: Option<&str>, failed_table: Option<&str>) -> bool {
connection.map(str::trim) == Some("redis") && failed_table.map(str::trim) == Some(FAILED_TABLE)
}
Why all this caution? By default Laravel Rust dispatches jobs to the database connection, that is, to the jobs table. And that is the very same PHP table. If someone forgot the QUEUE_CONNECTION=redis line in Rust's .env on the server, Rust jobs would pour into the PHP worker, which could not read them. So Rust dispatches a job only when its .env explicitly names both Redis and its own failed jobs table. In every other case it writes inline, as before.
The same goes for when Redis does not answer. We checked this locally: pointed Rust at a closed port, and the request went through, the mark was written inline, and a warning showed up in the log. The request did take 1.3 seconds instead of the usual fraction of a second. But that happens no more than once every five minutes per token, and only while Redis is down.
The worker: same binary, different command
In Laravel Rust the worker is not a separate program but the very same binary with a different command:
[program:devsense-rust-worker]
directory=/var/www/devsense/rust
command=/var/www/devsense/rust/devsense-rust queue:work redis --queue=rust --sleep=3
user=ubuntu
autostart=true
autorestart=true
startsecs=2
stopsignal=TERM
stopwaitsecs=70
Two things that are easy to forget:
- The worker has to be restarted after a deploy. It keeps running the binary it started with. So the Rust deploy now restarts
devsense-rust-workeras well, if it is configured. - Shutdown is via
SIGTERM. On receiving it, the worker stops taking new jobs and finishes the current one.stopwaitsecsis more than double the job timeout, so supervisor does not kill a job halfway through.
The check
Locally, on the same Sail database and Redis, we ran the whole path:
- A request to the Zones check with a real token → the response
{"clear":true,…}. In Redis (database 3),queues:{rust}holds one job, and the token'slast_used_atis still empty. devsense-rust queue:work redis --queue=rust --stop-when-empty→tokens.touch 154.5ms. The queue is empty, and the token now has a time and an address.- Redis on a closed port → the same response, the mark written inline, a
queueing TouchToken failed; writing inlinewarning in the log. - Rust's
queue:failedreadsrust_failed_jobs: we checked on a test row that the columns match. - PHP's
jobstable did not change by a single row.
Plus an automated PHP test: rust_failed_jobs has exactly the columns Laravel Rust writes, and PHP's failed_jobs kept its shape.
Honest differences and the price
- One more process. The Rust worker lives next to the PHP worker and the Rust HTTP server. How much memory it eats on a 1 GB droplet, we will show in the honest review at the end of the series.
- One more dependency for Rust. Before, Rust needed only the database; now it needs Redis too. That is why it does not fall over without Redis but writes inline.
- Two queues, two worlds. A job dispatched from PHP will not be run by Rust, and vice versa. While Rust has only a few jobs, that is fine. But once jobs that PHP dispatches move to Rust (deleting OG images, for example), we will need a bridge: either PHP learns to write jobs in Rust's format, or such jobs get dispatched by routes that have already moved to Rust.
- The "once every 5 minutes" counter is still separate on each side. A token can get marked by both PHP and Rust — just like on day two.
The scoreboard
- The first job in Rust:
TouchToken, with retries, pauses and a timeout. - A queue of its own: Redis, database 3, the
rustqueue; failed jobs go torust_failed_jobs. - The worker:
devsense-rust-workerunder supervisor, restarted by the deploy. - The safety net: no configured queue or no Redis — an inline write, and not a single row in PHP's tables.
- Tests: a unit test for
jobs::ready()and a PHP test for the table's shape.
What comes next
Day 5 — migrations. Laravel Rust has its own migration system, and it keeps its history in a migrations table — the same name PHP uses. Before writing the first migration in Rust, we will dig through the source to see what happens when the two meet, and decide whether the two can share it.
Then seeders. And at the end of the series — the promised honest review: speed, memory, the cost of the move, and the packages Rust does not have yet.
Links
- Queues in Laravel Rust —
#[job],dispatch, Redis, the worker, failed jobs - Redis — connections,
REDIS_URLandREDIS_DB - Queues in PHP Laravel — for comparison
- github.com/laravel/rust-framework — the framework core
- From Laravel to Laravel Rust. Day 3 — Rust reads the PHP session
- From Laravel to Laravel Rust. Day 2 — models and token login
- From Laravel to Laravel Rust. Day 1 — the first route