Skip to content
AXVI BUILD · WRITE · SHIP
Blog

Loco 1.3 for Laravel Developers: Sessions, Retries, Unique Jobs and Notifications, Side by Side

Loco 1.3 closed the gaps a Laravel developer hits on day one. A map from Auth::login(), $tries, $backoff, ShouldBeUnique and notifications to the Loco code that does the same job, with snippets from a real app.

Loco 1.3 for Laravel Developers: Sessions, Retries, Unique Jobs and Notifications, Side by Side

Loco is the Rust web framework that feels most like Laravel: generators, models, migrations, workers, mailers, a scheduler, all from one CLI. Version 1.3 closed the gaps a Laravel developer hits on day one. You no longer write your own browser login, retries are built in, and emails can go through notifications.

I moved a complete blog to it, and this is the map from the Laravel code you already write to the Loco 1.3 code that does the same job. All snippets come from a real app that runs in production on Postgres.

Login: Auth::login() becomes a session

Before 1.3, browser login in Loco meant a JWT in a cookie and your own extractor. Now there's the auth_session feature: sessions stored in the database, with "Remember me".

# Cargo.toml
loco-rs = { version = "1.3", features = ["auth", "auth_session", "with-db", "worker", "mailer", "notifications"] }
# config/development.yaml
auth:
  session:
    secret: <%= get_env(name="SESSION_SECRET") %>
    store: database          # rows in `loco_sessions`, so logout really ends a session
    sign_in_path: /login     # where a signed-out browser is sent
    ttl: 86400               # one idle day
    remember_for: 2592000    # 30 days with "Remember me"

The login handler, after checking the password:

// `renew()` drops the old session (session fixation), `set_user_id` is `Auth::login($user)`.
let mut session = session.renew().set_user_id(user.pid.to_string());
if form.remember.is_some() {
    session = session.remember()?;
}

Logout is session.clear(), Laravel's Auth::logout() plus session()->invalidate(). A copy of the old cookie no longer works, because the row in the database is gone. Protected handlers take CurrentUser<users::Model>, the equivalent of the auth middleware plus $request->user(). The JSON API can keep its JWT, like Laravel's api guard next to web.

$tries and $backoff

class ProcessPost implements ShouldQueue
{
    public $tries = 4;
    public $backoff = 10;
}
impl BackgroundWorker<WorkerArgs> for Worker {
    /// Laravel's `$tries = 4`: the first run plus 3 retries.
    fn max_retries() -> u32 {
        3
    }

    /// Laravel's `$backoff`: 10 s before the first retry, then 20 s, 40 s.
    fn retry_backoff() -> Duration {
        Duration::from_secs(10)
    }
    // ...
}

Two things to know. Loco counts only the repeats, so $tries = 4 is max_retries() = 3. And the backoff doubles each time, capped at an hour, where Laravel repeats the same number unless you give it an array. The default is 0 retries, as in Laravel, so the first failure is final until you opt in.

Retries work with the persistent queue (BackgroundQueue mode on Postgres or SQLite). A job that ran out of retries stays in the queue table as failed, and cargo loco jobs retry is your php artisan queue:retry all.

ShouldBeUnique

Saving a post three times in a row should process it once:

// Laravel's `ShouldBeUnique` with `uniqueId()`. The key is free again once the job starts.
process_post::Worker::perform_later_unique(
    ctx,
    process_post::WorkerArgs { post_id: post.id },
    format!("post:{}", post.id),
)
.await?;

Notifications

The notifications feature is Laravel's Notification class: a message, channels (via()), and an email built from your own templates.

impl Notifier for NewPost {
    fn message(&self) -> Message {
        Message::new(format!("New post: {}", self.title)).url(&self.url)
    }

    /// Laravel's `via()`.
    fn channels(&self, _ctx: &AppContext) -> Vec<Channel> {
        vec![Channel::email_to(&self.email)]
    }

    fn email(&self, _message: &Message) -> Result<EmailContent> {
        EmailContent::from_template(&template, self)
    }
}

NewPost::new(...).deliver_later(&ctx).await queues one delivery per channel, and each delivery is its own job with its own retries. One bad address no longer fails the whole mailing. I stopped the mail server on purpose and watched the retries come 10, 20 and 40 seconds apart, then go through when it came back. In tests, notifications.stub: true is Notification::fake().

A cache every process can see

cache:
  kind: Database   # CACHE_STORE=database: a `loco_cache` table, shared by web, worker and scheduler

The in-memory cache is faster. On two cores the cached home page served about 20,500 requests per second from memory and about 5,900 from the database, against about 1,500 with no cache. But the in-memory cache belongs to one process. With a separate worker, the worker clears its own cache, and the web server keeps serving the old page until the TTL runs out. For a blog, 5,900 pages a second is plenty, and correct beats fast.

The rest of the map

Laravel Loco 1.3
config/filesystems.php a storage: block in YAML (Local or Aws)
Storage::fake() drivers::mem::new() swapped in from a hook in the test environment
session()->flash() session.insert(...), removed on read
a scheduled queue:prune-failed queue.retention
a worker killed mid-job queue.reaper puts the job back by itself

Where this comes from

This is a condensed version of the changes I made for version 1.1 of my book, Loco for Laravel Developers (release notes). It builds a complete blog in 13 steps, from loco new to Docker on Postgres, and compares every step with Laravel. The code for every step is a tag in axvilab/loco-for-laravel-devs. There's a free sample on the book's page.

If you're a Laravel developer trying Rust for web work: what did you reach for first and couldn't find?

Esc