After moving this blog to Laravel Rust, I wanted to try something I wouldn’t build the same way in a typical Laravel PHP app. So I built Dots, a shared pixel canvas.

It uses a few techniques that aren’t possible in a traditional PHP request/response app.

Dots, a shared pixel playground

Dots started out as something closer to Reddit’s r/place: place a pixel, wait a few seconds, place another one. I soon wanted to just draw, so I removed the cooldown and added freehand drawing and a line tool.

Everyone shares the same 500 × 500 canvas and 16 colors. You can zoom in to work on individual pixels, or zoom out and draw across the board.

Keeping the canvas in memory

In a Laravel PHP app running under PHP-FPM, I can’t keep a single canvas in ordinary application memory and share it between requests. I’d normally store the drawing in Redis or a database and use a WebSocket server to send updates. PHP can run long-lived apps too, for example with Octane, but that’s a different setup from the usual PHP-FPM request lifecycle.

With Laravel Rust, I can keep the canvas and the open connections in the app itself. That’s what I wanted to try here.

I didn’t add a database for the drawing. A pixel is just a number from 0 to 15, pointing to a color in the palette. One byte per pixel makes the raw canvas data 250 KB.

The Canvas service holds the pixels and tracks changes that haven’t been sent to the browsers yet:

<span class="hl-keyword">pub</span> <span class="hl-keyword">struct</span> <span class="hl-type">Canvas</span> {
    <span class="hl-variable">state</span>: Mutex<State>,
    <span class="hl-variable">changes</span>: broadcast::Sender<Bytes>,
}

I register it as a singleton, so all connections use the same canvas. The Tokio mutex protects the state while a connection reads or changes it. The broadcast channel sends updates to the connected browsers.

Dots runs on Laravel Cloud. I’ve turned off autoscaling and scale to zero, so the app stays running on one instance.

Since the drawing lives in memory, a second instance would have its own canvas. Before adding more instances, I’d need a way to share changes between them.

Of course, I don’t want a deploy to erase everyone’s drawing. Every five seconds, the app saves a snapshot to object storage, but only if something changed. It loads that snapshot on boot.

That doesn’t mean new visitors see a drawing that’s five seconds old. They get the current canvas from memory. The saved copy is for recovering after a restart. A crash can still lose changes made since the last successful save.

These snapshots contain the drawing as it is now. They don’t keep a history of every stroke.

Updating the browsers

Laravel Rust is built on Axum, which has WebSocket support. I use that directly through a route in the app:

<span class="hl-keyword">pub</span> <span class="hl-keyword">fn</span> <span class="hl-type">routes</span>(<span class="hl-variable">route</span>: <span class="hl-keyword">&</span><span class="hl-keyword">mut</span> Router) {
    route.get(<span class="hl-value">"</span><span class="hl-value">/</span><span class="hl-value">"</span>, canvas::show);
    route.get(<span class="hl-value">"</span><span class="hl-value">/canvas/config</span><span class="hl-value">"</span>, canvas::config);
    route.get(<span class="hl-value">"</span><span class="hl-value">/ws</span><span class="hl-value">"</span>, canvas_connections::show);
}

I didn’t want a separate Reverb cluster for this. With people drawing freely, per-message pricing could get expensive. The app handles the WebSocket connections itself.

When a browser connects, it receives the full canvas as a binary message. After that, the server sends batches of changed pixels every 50 milliseconds. A change takes four bytes: three for its position and one for its color. There’s also one byte at the start to identify the message type.

If someone paints the same pixel several times before a batch goes out, I only keep the latest color. There’s no point sending colors that have already been painted over.

Laravel Rust has ticks for recurring work. Here’s the one that sends the pending changes:

ticks
    .every(<span class="hl-number">50.</span>milliseconds(), async <span class="hl-keyword">|</span>canvas: Inject<Canvas><span class="hl-keyword">|</span> {
        canvas.flush().await;
    })
    .when(|<span class="hl-variable">host</span>| host.is_server());

Names and cursor positions travel over the same connection. For cursors, the server keeps the latest update until the next tick, rather than sending every mouse movement to everyone else.

In closing

If you’d like to try it, open Dots and draw something. The code is on GitHub, and pull requests are welcome.

We use Flare to keep an eye on errors and performance in Dots. It’s ready for Laravel Rust, and I like to think it’s the most beautiful error tracker for Rust apps. Adding it to the app takes one service provider:

.with_providers(|<span class="hl-variable">providers</span>| {
    providers.add(flareapp::laravel::provider(flareapp::config<span class="hl-keyword">!</span>()));
})

At Spatie, we’ve also been bringing our PHP packages to Rust and, more recently, to Go. I’ve written about how we used AI for those ports and how the work on the Rust packages helped with the Go versions.

Categories: PHP