The middleware that turns the simulation into a running system, plus a replica-safe litefs.yml. Fly.io ↗ runs LiteFS as a first-class pattern; the same code works anywhere FUSE does.
// Write-forwarding middleware (Hono/Express-style) — the whole trick.
// Reads hit local SQLite replica; writes replay to the primary region.
import { readFileSync, existsSync } from 'node:fs';
const PRIMARY_FILE = '/litefs/.primary'; // LiteFS writes this on replicas
function primaryRegion(): string | null {
// On the primary this file doesn't exist; on replicas it names the primary.
return existsSync(PRIMARY_FILE)
? readFileSync(PRIMARY_FILE, 'utf8').trim()
: null;
}
export function forwardWrites(req: Request): Response | null {
const isWrite = !['GET', 'HEAD', 'OPTIONS'].includes(req.method);
const primary = primaryRegion();
if (isWrite && primary) {
// Fly's proxy replays the full request in the primary's region.
return new Response(null, {
status: 409,
headers: { 'fly-replay': `instance=${primary}` },
});
}
return null; // handle locally — reads are always local
}
/* litefs.yml (replica-safe defaults):
fuse:
dir: "/litefs"
data:
dir: "/var/lib/litefs"
lease:
type: "consul"
candidate: ${FLY_REGION == PRIMARY_REGION} # only primary region runs candidates
promote: true
proxy:
addr: ":8080"
target: "localhost:8081"
db: "app.db"
passthrough: ["/health"]
*/