How Litestream works

Litestream is a background Go process that watches a SQLite database's write-ahead log and ships every committed change to object storage, so a lost disk costs seconds of data. It never sits in your app's read or write path.

The whole system

  • 1 Capture: WAL frames to local files.
  • 2 LTX files: the immutable file format.
  • 3 Replicate: upload to eight backends.
  • 4 Compact: merge and prune by time level.
  • 5 Restore: replay files into a database.
  • 6 CLI and control: config, commands, socket.
  • 7 VFS: query the replica without restoring.
Litestream processYour serverwritesrunsone per DBwrites L0queuedWALuploadsmergesYour appSQLite DB+ WAL CLI and control6 Store: compact4 Capture1 LTX files2 Replicate3Objectstorage Restoreto a new DB5 VFSread-only apps7Litestream processYour serverwritesrunsone per DBwrites L0queuedWALuploadsmergesYour appSQLite DB+ WAL CLI and control6 Store: compact4 Capture1 LTX files2 Replicate3Objectstorage Restoreto a new DB5 VFSread-only apps7

One commit

commit (append frames)Sync: read new frameswrite L0 .ltx locallynotifyWriteLTXFile level 0checkpoint, WAL restartsYour appSQLite WALCapture (DB)ReplicaObject storageYour appSQLite WALCapture (DB)ReplicaObject storage
  1. Your app commits a transaction. SQLite appends frames to the WAL; Litestream holds a long read transaction so no one else's checkpoint can erase frames it has not copied yet.
  2. The monitor wakes (every 1 s by default) and calls Sync. It reads the new frames, up to the last commit marker.
  3. Capture writes them as an L0 file named `<minTXID>-<maxTXID>.ltx` in a local metadata directory, and wakes the replica.
  4. The replica monitor picks the file up (also 1 s pacing) and sends it to the storage client.
  5. The client stores it as `ltx/0/…` on a file replica, or `0000/…` on S3.
  6. Later, a checkpoint folds the WAL into the main file. Litestream copies what it still needs first, then lets the WAL restart.

Size of each part

    Capture is the densest logic. The CLI is large because of configuration, not replication.

    Layers

    LayerOwnsFile
    CLIConfig, wiring, signalscmd/litestream
    StoreMany databases, maintenance timersstore.go
    DBOne SQLite file: WAL, checkpointsdb.go
    ReplicaOne destination for that DBreplica.go
    ReplicaClientRaw storage verbsreplica_client.go

    Line counts are from the cloned tree at commit 3e0fdc0. Design claims follow the repo's architecture notes, checked against the code.

    Litestream

    Capture: from WAL to local files

    One DB per database file. It is where nearly all the hard SQLite knowledge lives.

    What it keeps hold of

    writelong read transactionreads framescommitted frames onlycheckpoint blocked by the readlockOther connectionsWALLitestream connectionWALReaderL0 .ltx filewritelong read transactionreads framescommitted frames onlycheckpoint blocked by the readlockOther connectionsWALLitestream connectionWALReaderL0 .ltx file

    SQLite only folds the WAL back into the main file when no reader needs those frames. Litestream's standing read transaction makes it that reader, so outside checkpoints cannot discard unseen data. Other connections keep writing meanwhile.

    Litestream also creates a _litestream_lock table in your database to take SQLite's write lock around checkpoints. It is expected and rolled back, never holds rows.

    When it checkpoints

    checkpointIfNeeded tries these in order.

    yesWAL restarted and small againnot enoughnoyesnoyesnoAfter a syncWAL over the truncate size?121,359 pages, about 500MB at 4 KBTry PASSIVE firstDoneTRUNCATE: blocking, forcedWAL at least 1,000 pages?PASSIVEChanges synced and quietfor 1 minute?Nothing

    PASSIVE never blocks writers and is skipped quietly on a busy database. TRUNCATE is the emergency exit that stops a stuck reader from growing the WAL without bound.

    What can go wrong reading a WAL?

    Frames carry salts and a running checksum, and only those ending at a commit marker count. The WAL can restart without changing length, so size polling alone misses it; verify and detectFullCheckpoint compare salts and the last matching page. SQLite's reserved lock page is skipped.

    Litestream

    LTX: the one file format

    Every transfer, merge and restore uses LTX, a library Litestream imports. A file is an immutable range of transactions.

    Anatomy and name

    Header100 B: page size, commitsize, TXID range, timestampPageslatest version of eachchanged page, compressedPage indexpage number to offsetTrailer16 B: post-apply and filechecksumsHeader100 B: page size, commitsize, TXID range, timestampPageslatest version of eachchanged page, compressedPage indexpage number to offsetTrailer16 B: post-apply and filechecksums

    The name is the range it covers: 0000000000000003-0000000000000007.ltx holds transactions 3 to 7. A file with min TXID 1 is a full snapshot; anything else needs its predecessors.

    Where files go

    L0: raw, one per syncL1L2L3L9: full snapshots
    BackendPath for level 1
    File<root>/ltx/1/<name>.ltx
    S3<prefix>/0001/<name>.ltx

    Neither keeps a manifest. A restore lists a level and each file carries its own index.

    Litestream

    Replicate: one interface, eight backends

    Replica tracks how far storage has got and uploads; it knows nothing about S3.

    The seam

    Replicaupload loop, positionReplicaClientfiles3gsabsosssftpnatswebdav

    Each backend implements: Init, LTXFiles (list a level in TXID order), OpenLTXFile (byte range), WriteLTXFile, DeleteLTXFiles, DeleteAll. A missing file must match os.ErrNotExist, and the LTX header timestamp must survive upload.

      S3 is the reference: multipart uploads, pagination, and the lease code in s3/leaser.go.

      Position and resume

      Replica.Pos is the TXID and checksum it last uploaded. At startup Capture compares local and remote positions; if storage is ahead, local metadata is refreshed. Streams use a ResumableReader: after a dropped connection it reopens at the current byte offset.

      Failures back off exponentially, up to 5 minutes between retries, with rate-limited logging.

      Litestream

      Compact: many small files into few big ones

      Left alone, one file per second would pile up. Store runs timers that merge them.

      The ladder

      every 30 severy 5 minevery 1 hevery 24 h, from the databaseL0every syncL1L2L3L9 snapshotevery 30 severy 5 minevery 1 hevery 24 h, from the databaseL0every syncL1L2L3L9 snapshot

        The Store checks whether a level is due and has new data, then compacts it. A merge keeps the latest version of each page and takes its timestamp from the newest input, so time-based restore stays accurate. It prefers local input and falls back to a resumable remote read.

        What gets deleted

        • L0 files go after L1 compaction, on their own hourly check.
        • Snapshots go past a 24 hour cutoff.
        • Middle levels go older than the oldest retained snapshot.

        A Store can also validate that levels have no TXID gaps, and ping a heartbeat URL (5 minutes by default). With retention disabled, deletion is left to your bucket's lifecycle rules.

        Litestream

        Restore: replay a chain

        Restore targets the latest point, a TXID, or a timestamp (not both).

        Planning

        Target: latest, TXID or timeNewest L9 snapshot beforethe targetThen higher-TXID files fromL3, L2, L1, L0, eachcontiguous with the lastMerge with the LTXcompactor, newest pagewinsWrite to a temporary pathRename into place

        Files stream through resumable readers, fetched one after another in plan order; the -parallelism flag is still accepted but has no effect. The plan is checked for contiguity, and a gap is an error instead of a silent hole.

        Variants

        • Follow mode keeps applying new files every second and records the last applied TXID in a sidecar file.
        • Legacy v0.3.x backups on S3 and file replicas restore through a separate path (v3.go).
        • EnsureExists restores a missing database before replication starts, if a backup exists.
        Litestream

        CLI and control: running it

        litestream replicate reads a YAML config, builds the objects above, opens the Store and waits for a signal.

        Startup and commands

        litestream.ymlmain.go: parse, defaultsOne DB + Replica per entryStore.Open: validate levels,init clients, open DBsCompaction, retention,validation, heartbeatmonitorsOptional: control socket,metrics, directory watcher,MCP
        CommandDoes
        replicateRun the daemon
        restoreRebuild a database
        ltx, databases, list, infoInspect files and state
        register, unregister, start, stop, sync, statusChange a running daemon over the socket
        reset, versionLocal maintenance

        Extras

        The control socket (off by default, /var/run/litestream.sock, mode 0600) exposes /register, /sync, /txid, /list and debug routes. A directory watcher adopts databases that appear under a path. Prometheus metrics come from addr. Shutdown is bounded by shutdown-timeout (30 s default); a second signal quits at once.

        Litestream

        VFS: read straight from the replica

        A SQLite extension, litestream-vfs, so a reader needs no restore.

        How a read works

        yesnoSELECT in your appLitestream VFSPage in 10 MiB LRU cache?Return pageFetch byte range from LTXin storagePoll every 1 s for new files

        Load it with .load litestream-vfs.so and open file:db?vfs=litestream. It can also hydrate a local copy in the background and query older states by timestamp. Write mode exists but is documented as experimental.

        Building needs CGO and a vfs build tag, which is why it lives apart from the daemon.