Every SQL database on Tissue Cloud has a copy on another edge, a few frames behind the original. The code that does it is a Rust crate called walship, and we've open-sourced it.
Each c3 database lives on one edge. That's where its writes go, and until September it was also the only place its data was current. We kept warm copies on the other edge, refreshed every one to fifteen minutes depending on size, so losing that machine meant losing up to fifteen minutes of writes. For a sign-in database, or a sensor log that gets a row every ten seconds, that's a lot.
Since September each database also has a replica on the other edge that trails the original by about one batch of WAL frames. It's a normal SQLite file, and promoting it is one call. The code behind it started inside c3, our database service. We've pulled it out into a crate, walship, and put it on crates.io under MIT or Apache 2.0.
WAL stands for write-ahead log. In WAL mode, a commit doesn't touch the database file. SQLite appends the changed pages to a second file next to it, orders.db-wal beside orders.db, and readers look in that log before the main file. Every so often a checkpoint copies the logged pages back into the main file and the log starts over. Every change goes through the log first, so if you copy the log to another machine as it grows, you can keep a second copy of the database current there.
let shipper = Shipper::builder("/var/lib/app/db", "http://standby.internal:7350")
.token(token)
.start(tokio::runtime::Handle::current())?;
shipper.track("orders");
// after a commit
shipper.wake("orders");
We have a lot of small databases, and one process creates, restores and drops them while it runs. We wanted a copy of each on another machine that we could open in seconds, with nothing between the two machines except HTTP.
Litestream came closest. It streams the WAL to object storage, and you get a database back by restoring it from there, which takes as long as the download. It's also configured per database and runs as its own process, watching files another process owns. When c3 swaps a file out from under it during a restore, it loses its place. c3 is the only thing that knows when a database is created, replaced or dropped, so that's where replication had to live.
LiteFS puts a FUSE filesystem under the database and needs a lease service to pick a primary. libSQL has replication too, but both of its forms put a server in the middle: embedded replicas pull from a sqld primary, and Turso's sync talks to Turso Cloud. We didn't want another moving part on the write path.
If you want backups or point-in-time restore, Litestream is the better tool, and it works with stock SQLite from any language. walship keeps only the latest state. It's for a Rust program on libSQL that wants a hot standby.
Each entry in the WAL is called a frame. A frame holds one changed page of the database, the full page and not a diff, behind a 24-byte header. A transaction is a run of frames, and its last frame is marked as a commit. A frame isn't SQL, just the bytes of a page and its page number, so the other side doesn't have to run any queries. It writes the pages into its own WAL in the same order.
Upstream SQLite has no API for reading frames out of a WAL or writing them into another one. libSQL, the fork of SQLite's C code that takes outside contributions, adds a few: libsql_wal_frame_count, libsql_wal_get_frame, and an insert session with libsql_wal_insert_begin, _frame and _end. walship is built on those.
The shipper reads committed frames past the last one the peer acknowledged and posts them in batches of up to 512, which is 2 MiB with 4 KiB pages. The receiver writes them into its own copy through an insert session and answers with its committed frame count. After any error, the next send starts from that count. Both sides keep their position on disk, so a restart on either end picks up where it stopped.
A batch can end halfway through a transaction. The receiver keeps its insert session open until the commit frame arrives, so a reader on the replica never sees half a transaction. If the receiver restarts with a session open, libSQL throws the uncommitted frames away and the shipper resends from the last commit.
Frames are page images, so they only mean something on top of the exact file they were written against. walship replicates in generations. A generation starts with a base. SQLite has a few checkpoint modes, and TRUNCATE is the thorough one: it waits for writers, copies every frame into the main file, and cuts the -wal file down to zero bytes. Once it finishes, the main file holds the whole database and the log is empty. The primary runs one and then sends its main file byte for byte. Frames written after that are numbered from 1.
That means checkpoints can't just happen whenever SQLite feels like it. If frames get folded into the main file before they're shipped, the replica can't get them anymore and needs a whole new base. So checkpoints are off on every connection to a shipped database, and the shipper decides when to fold. Once a database has gone quiet with more than 1,000 frames in its WAL, all of them acknowledged, it runs a PASSIVE checkpoint. That's the gentle mode: it copies whatever frames it can without waiting for anyone and leaves the WAL file where it is. It only counts the fold if the checkpoint took exactly the acknowledged frames. If a writer got in first, those frames get shipped and the fold waits for the next quiet moment.
After a full fold, SQLite restarts the log at frame 1 on the next write and puts a new salt in the WAL header. The salt is a random number that changes every time the log starts over, and it's how SQLite tells a current frame from a leftover one. The shipper treats that as the start of the next generation, and the replica checkpoints its own copy when the first frames of it arrive. The same salt check catches anything that changes the WAL behind the shipper's back, like a checkpoint from another process. A salt it didn't expect, or a frame count lower than the acknowledged one, and it sends a fresh base.
If the peer is down, the WAL keeps growing while the shipper retries. At 50,000 waiting frames, about 200 MiB, it checkpoints anyway and sends a full base when the peer comes back.
Most of the time on this went into finding out how the WAL functions behave, because the docs don't say. We wrote each finding down as a test, so a libSQL upgrade that changes one fails the build. A few of them would have cost us data.
libsql_wal_frame_count takes the WAL write lock without waiting, so it returns SQLITE_BUSY whenever any writer has a transaction open. It also returns the connection's cached copy of the WAL index, and SELECT 1 doesn't refresh it. In our tests a commit moved the WAL from 3 frames to 7, and the shipper's connection still said 3 after a SELECT 1. Reading sqlite_master fixes it, so walship does that first.
Inserting a frame with a gap in front of it doesn't fail. If the replica has 4,202 frames and you insert frame 4,206, libSQL quietly writes it as 4,203. We tested this by skipping three frames of a transaction and sending the rest. Every call returned OK, PRAGMA quick_check on the replica said ok, and the replica had 33,977 rows where the primary had 36,977. The receiver checks that every batch starts exactly one past its own count, because libSQL won't.
libSQL also accepts frames onto a file they weren't written against. We tried building a base with VACUUM INTO instead of a byte copy. VACUUM INTO renumbers pages, so every frame shipped after it lands on the wrong page. That replica passed PRAGMA integrity_check and was missing a fifth of its rows. This is why a base is the file itself, copied right after a TRUNCATE.
Some of it works in your favour. Inserted frames go through the normal append path, so the replica's WAL has its own salts and checksums and recovers from a crash like any other WAL. And an insert session that ends without a commit frame leaves nothing visible behind, which is what makes mid-transaction batches safe.
The first was bad. To send a base, the first version opened the main database file with an ordinary read-only open, read it, and closed it. On Linux, closing any descriptor to a file drops every POSIX lock the process holds on that file, including the shared lock SQLite keeps on every database in WAL mode. SQLite tracks its own locks in a table that still said we held it, so nothing inside c3 noticed. Three hours later the hourly backup ran. It opened each database read-write, found no lock in its way, and checkpointed and deleted the WAL of databases that were in the middle of writes. Five busy databases were damaged before we turned shipping off. We restored them from backup. Since then, walship reads the main file through the handle SQLite already has open (SQLITE_FCNTL_FILE_POINTER and the file's own xRead), so there's no extra descriptor to close. The test for it has to fork a child and probe the lock from outside, because a process can't see its own lost lock any better than SQLite could.
The second was quieter. Promoting a replica moves its file into the primary's data directory with rename. Under systemd, each ReadWritePaths entry is its own bind mount, so the two directories were on different mount points and every rename failed with EXDEV. Our failover script falls back to the older warm copy when a promotion fails, so a real failover would have worked and quietly lost up to fifteen minutes of writes. We found it on the first promotion drill. walship now copies, syncs and deletes when a rename says EXDEV. On the next drill we promoted a 256 MB sensor database with 1.96 million rows while it was being written to, and the replica had every row up to the moment the primary stopped.
One trap is waiting for anyone who adopts walship. Your program has to open its databases through the same libSQL build walship links, either with the libsql crate or with libsql-ffi on the same 0.9 line. A process with two copies of SQLite has two sets of POSIX locks that can't see each other, and that corrupts databases.
Cargo won't catch it for you. libsqlite3-sys, the crate under rusqlite and sqlx, declares links = "sqlite3", so Cargo refuses two versions of it. libsql-ffi declares no links key, so a second version of it, or libsqlite3-sys next to it, builds without a word. The README has a short shell check that fails when Cargo.lock holds more than one. Put it in CI.
walship doesn't notice that a machine died and doesn't decide when to promote. On Tissue Cloud that's a separate decider that checks with the nameservers before it acts. In walship it's one call, and when to make it is up to you:
match receiver.take("orders", Path::new("/var/lib/app/db/orders.db"))? {
Take::Moved { generation, frames, bytes } => { /* open it */ }
Take::Busy => { /* a reader held off the checkpoint, try again */ }
Take::Absent => { /* no replica by that name */ }
}
Each database gets one replica. There's no history, so no point-in-time restore. Data goes over the wire uncompressed and unencrypted, so run it over TLS or a private network; ours goes over WireGuard. A base is a full copy of the file, and the receiver refuses bases over 8 GiB unless you raise the limit. Any number of nodes can each own some of the databases and replicate to a peer, in a ring or to one standby.
On a laptop, with a writer, the shipper and a reader on the replica all running over a simulated 56 ms link, the writer did 259 transactions a second and the replica trailed by 42 frames on average and 55 at most. The reader ran quick_check 929 times during the run and never got a failure, and at the end a checksum of every row matched on both sides. That run is examples/stress.rs in the repo.
[dependencies]
walship = "0.1"
It's 0.1, and the API will change before 1.0. The libSQL behaviours above are written up in more detail in the README and pinned by tests in src/wal.rs. Bug reports and pull requests go to github.com/tissue-systems/walship.