HANDS-ON LAB Intermediate

SQLite online backup while an API writes: restore validation and WAL pitfalls

A local standard-library Python lab: back up SQLite during API writes, demonstrate missing WAL data, and validate integrity, restored content and persistent writes.

Vibe DevOps·· ~11 min read
PythonSQLiteHTTPWAL

Key Takeaways & Prerequisites

  • Use a separate source connection and a fresh destination, not live-file copying.
  • Check structure, content and persistent writes on an isolated restore.
  • Committed data may remain in WAL; a main-only copy can pass integrity checks while missing rows.

Architecture & Execution Flow

  1. 01 →API writes
  2. 02 →Separate backup
  3. 03 →Validate
  4. 04 →Restore drill
Table of Contents

1. Choose the right backup layer

An API may return 201 while a copied SQLite file omits the acknowledged row. In WAL mode, committed changes can still live in the write-ahead log rather than the main database. Copying only the main file can yield a structurally valid but stale database. Copying the main file, WAL and shared-memory file sequentially while writes continue does not establish a consistent recovery point.[2]

Unlike a filesystem snapshot with rsync or a PostgreSQL dump, this lab uses SQLite’s Online Backup API through sqlite3.Connection.backup. It backs up while a local API writes, then restores to a separate database. Only the Python standard library, a regular user account and loopback networking are used: no containers, cloud resources, installation or credentials.

A cold backup after stopping the application is simpler but requires downtime. The Backup API allows writes between steps, at the cost of I/O and possible copy restarts when another connection changes the source. VACUUM INTO is another option for a compact copy; here the priority is progress callbacks and an exercised recovery path.[1] Online does not mean zero operational cost.

2. Scope and prerequisites

Use Bash and Python 3.10 or later with sqlite3, a local filesystem and a few tens of MB of free space. Inspect the linked SQLite version rather than inferring it from Python. The current WAL documentation says the WAL-reset fix is included in SQLite 3.51.3 and later, with backports including 3.44.6 and 3.50.7. Use a patched runtime before applying multi-connection concurrency.[2] The measured runtime here was Python 3.14.7 with SQLite 3.53.1; this guide does not install or upgrade software.

Create a dedicated working directory and save the program as lab.py. Its data-directory argument must not exist: refusing an existing directory prevents accidental replacement of old databases. The server picks a free port and binds only to 127.0.0.1. POST /events has an empty body; the server generates synthetic rows and never accepts caller-supplied SQL or filesystem paths. There is no authentication: never expose this lab publicly.

The sequence is padding data → WAL counterexample → API → backup through a separate source connection → validation → rename → restore → write test. Each API request owns its connection. Do not disable thread checks to share the writer connection. The client sends requests sequentially, so this does not model contention among multiple simultaneous writers.

3. Complete runnable lab

Copy the complete Python block. The backup helper opens a fresh destination connection and a source connection separate from API writers. Do not run backup on a connection holding an active write transaction. closing actually closes connections; the connection context manager alone manages commit and rollback, not closure.[3]

The single shutil.copyfile call is explicitly WRONG: it is an isolated counterexample on synthetic data, not a backup step. Never transfer that line into a real backup routine. Keeping the original connection open preserves the first committed row in the WAL. The wrong copy may still pass integrity_check, demonstrating why structural validation alone does not prove completeness.

import hashlib
import json
import shutil
import sqlite3
import sys
import threading
import time
from contextlib import closing
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.request import Request, urlopen

root = Path(sys.argv[1]).resolve()
root.mkdir(mode=0o700)  # Refuse an existing directory.
db = root / 'live.db'
stop = threading.Event()
started = threading.Event()
five = threading.Event()
acks, errors, progress = [], [], []


def connect(path):
    return sqlite3.connect(path, timeout=1)


def verify(path):
    with closing(connect(path)) as c:
        assert c.execute('PRAGMA integrity_check').fetchall() == [('ok',)]
        assert c.execute('PRAGMA foreign_key_check').fetchall() == []
        rows = c.execute('SELECT id, payload FROM events ORDER BY id').fetchall()
        assert rows and all(p == 'event-' + str(i) for i, p in rows)
        assert [i for i, _ in rows] == list(range(1, len(rows) + 1))
        return rows


class API(BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass

    def do_POST(self):
        if self.path != '/events':
            self.send_error(404)
            return
        with closing(connect(db)) as c, c:
            c.execute('PRAGMA foreign_keys=ON')
            n = c.execute('SELECT COALESCE(MAX(id),0)+1 FROM events').fetchone()[0]
            c.execute('INSERT INTO events VALUES (?, ?)', (n, 'event-' + str(n)))
        body = json.dumps({'id': n}).encode()
        self.send_response(201)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Content-Length', str(len(body)))
        self.end_headers()
        self.wfile.write(body)


def writer(url):
    try:
        if not started.wait(5):
            raise TimeoutError('backup did not start')
        for _ in range(60):
            if stop.is_set():
                break
            with urlopen(Request(url, data=b'', method='POST'), timeout=2) as r:
                assert r.status == 201
                acks.append((json.load(r)['id'], time.monotonic()))
            if len(acks) >= 5:
                five.set()
            time.sleep(0.01)
    except Exception as exc:
        errors.append(repr(exc))
        five.set()


def backup(source, target, callback=None):
    deadline = time.monotonic() + 15

    def tick(status, remaining, total):
        if time.monotonic() > deadline:
            raise TimeoutError('backup deadline exceeded')
        if callback:
            callback(status, remaining, total)

    # Source is separate from every API writer; target is a fresh connection.
    with closing(connect(source)) as src, closing(connect(target)) as dst:
        src.backup(dst, pages=16, progress=tick, sleep=0.01)


with closing(connect(db)) as keeper:
    assert keeper.execute('PRAGMA journal_mode=WAL').fetchone()[0] == 'wal'
    keeper.execute('PRAGMA wal_autocheckpoint=0')
    keeper.executescript('CREATE TABLE events(id INTEGER PRIMARY KEY, payload TEXT NOT NULL);'
                         'CREATE TABLE padding(data BLOB);')
    keeper.executemany('INSERT INTO padding VALUES (?)', [(b'x' * 4000,)] * 1000)
    keeper.commit()
    keeper.execute('PRAGMA wal_checkpoint(TRUNCATE)')
    keeper.execute("INSERT INTO events VALUES (1, 'event-1')")
    keeper.commit()
    wal_bytes = Path(str(db) + '-wal').stat().st_size
    # Deliberately WRONG, isolated demonstration only; never use for backups.
    bad = root / 'wrong-main-only.db'
    shutil.copyfile(db, bad)
    with closing(connect(bad)) as c:
        bad_count = c.execute('SELECT COUNT(*) FROM events').fetchone()[0]
        bad_integrity = c.execute('PRAGMA integrity_check').fetchone()[0]
    assert bad_count == 0 and wal_bytes > 0
    print(json.dumps({'step': 'wal-pitfall', 'wal_bytes': wal_bytes,
                      'committed_rows': 1, 'wrong_copy_rows': bad_count,
                      'wrong_copy_integrity': bad_integrity}), flush=True)
    server = ThreadingHTTPServer(('127.0.0.1', 0), API)
    service = threading.Thread(target=server.serve_forever)
    service.start()
    client = threading.Thread(target=writer,
                              args=(f'http://127.0.0.1:{server.server_port}/events',))
    client.start()
    partial, final = root / 'backup.partial.db', root / 'backup.db'

    def measured_tick(status, remaining, total):
        progress.append((status, remaining, total))
        if not started.is_set():
            started.set()
            assert five.wait(3), 'no concurrent writes'
            assert not errors, errors
        time.sleep(0.002)  # Lab pacing only, not a production tuning value.

    try:
        begin = time.monotonic()
        backup(db, partial, measured_tick)
        end = time.monotonic()
        snap = verify(partial)
        partial.rename(final)  # Publish only a closed, validated backup.
        stop.set()
        client.join(4)
        assert not client.is_alive() and not errors, errors
        during = [i for i, t in acks if begin < t < end]
        assert len(during) >= 5
        live = verify(db)
        assert len(live) == len(acks) + 1
        assert 1 <= len(snap) <= len(live)
        assert snap == live[:len(snap)]
        print(json.dumps({'step': 'online-backup', 'seconds': round(end-begin, 3),
                          'http_201': len(acks), 'commits_during_backup': len(during),
                          'progress_calls': len(progress), 'snapshot_rows': len(snap),
                          'live_rows': len(live), 'integrity': 'ok'}), flush=True)
        restored = root / 'restored.db'
        backup(final, restored)
        assert verify(restored) == snap
        with closing(connect(restored)) as c, c:
            c.execute('INSERT INTO events VALUES (?, ?)',
                      (len(snap)+1, 'event-' + str(len(snap)+1)))
        assert len(verify(restored)) == len(snap) + 1
        assert verify(final) == snap
        digest = hashlib.sha256(final.read_bytes()).hexdigest()
        print(json.dumps({'step': 'restore', 'rows_equal': True,
                          'restored_write': 'ok', 'backup_unchanged': True,
                          'sha256': digest, 'python': sys.version.split()[0],
                          'sqlite': sqlite3.sqlite_version}), flush=True)
    finally:
        stop.set()
        started.set()
        client.join(4)
        server.shutdown()
        service.join(3)
        server.server_close()
        partial.unlink(missing_ok=True)

4. Run and read the evidence

After saving the file, run the commands below in its directory. For another run, use a new name such as run-02 rather than deleting real data to bypass the existence guard. No external service or firewall change is required.

The first callback marks backup as started and waits for at least five completed HTTP writes. Acknowledged commits are timestamped using a monotonic clock; assertions require at least five 201 responses inside the backup start/end interval. This proves overlapping writes rather than two sequential tasks labelled online.

The first measured run had a 4,152-byte WAL. The wrong main-only copy contained zero rows although the source had committed one. Backup took 0.954 seconds, with 60 HTTP 201 responses during backup, 393 callbacks and 61 rows in both snapshot and source. Scheduling and hardware affect these figures; assertions, not matching the duration, define success. The screenshots render captured real stdout in HTML: they are neither a live dashboard nor invented sample output.

python3 -c "import sqlite3; print(sqlite3.sqlite_version)"
python3 -m py_compile lab.py
python3 lab.py ./run-01
Step 1 — rendered actual stdout: main-only copying misses a committed WAL row.
Step 1 — rendered actual stdout: main-only copying misses a committed WAL row.
Step 2 — rendered actual stdout: concurrent HTTP writes, backup and restore checks.
Step 2 — rendered actual stdout: concurrent HTTP writes, backup and restore checks.

5. Restore validation must include content and writes

verify runs integrity_check and foreign_key_check, checks contiguous IDs and validates every payload against its ID. The sample schema has no foreign keys, so that check is a guard for schema extensions rather than proof of testing complex relationships. Snapshot rows must equal a prefix of the live rows: consistency does not require including every write made after the backup finished.

The closed and validated .partial.db is renamed to backup.db. Restore uses the Backup API from that sealed artifact into a separate restored.db; all rows must equal the snapshot. The test then inserts a row, closes and reopens the restored database to check persistence, and reads the backup again to ensure it was not altered. SHA-256 identifies the exact file but cannot replace a restore drill.

Never overwrite a serving database for a drill. A real recovery requires stopping every database user, checking paths and permissions, and managing sidecars so an old WAL is not paired with a new main file. Application cutover requires its own approved procedure. This lab does not test production cutover, power loss or atomic recovery across multiple ATTACH databases.

6. Failure modes and operational limits

Backup never finishes: writes through another connection can restart copying, so remaining pages need not decrease monotonically.[1] The lab bounds the writer at 60 requests and checks a 15-second deadline in the callback. Connection timeout=1 is not an overall backup deadline, and sleep is not a dependable bandwidth limiter. A callback cannot interrupt kernel I/O that is already stuck. For a hard deadline, supervise a separate worker process.

Locked database or full disk: report failure, do not publish partial files, retain the previous good backup, and investigate free space and long transactions. WAL still permits only one writer at a time. Long readers can delay checkpoint progress, and a large WAL is not itself proof of corruption.[2] Never delete a live WAL to reclaim space or force TRUNCATE checkpoints under load merely to make backups appear smaller.

Process termination: finally stops the server and removes a partial file for ordinary Python exceptions; SIGKILL may leave an incomplete file. Scheduled use needs overlap prevention, unique artifact names, metadata, least privilege, recurring recovery tests and protected off-host copies. A same-filesystem rename alone does not prove power-loss durability. Same-disk backups do not protect against disk failure or ransomware. Do not use WAL on a network filesystem.

7. Cleanup and conclusion

The program closes HTTP service and database connections. Data is retained for inspection. Run the cleanup command only from the dedicated lab directory after confirming its location; it targets run-01 without wildcards or root privileges. If execution failed before a complete backup existed, inspect the dedicated directory manually before removing it.

The operational contract is to copy through SQLite, publish only a validated artifact, then restore independently and check business content. Local execution verifies this path on synthetic data, not production latency, large datasets, retention, encryption or off-host transfer. No corresponding video exists, so no player is fabricated.

# Run only inside your dedicated lab directory.
python3 -c "import shutil; from pathlib import Path; p=Path('run-01'); assert p.is_dir() and (p/'backup.db').is_file(); shutil.rmtree(p)"

Official sources

[1] SQLite Online Backup API: consistent snapshots, incremental steps and restart behaviour.

[2] SQLite Write-Ahead Logging: checkpointing, filesystem limits and WAL-reset updates.

[3] Python sqlite3: Connection.backup: target connections, pages, progress and transaction contexts. Retrieved on 15 November 2026; only the local execution described above was performed.

Read critically, test before applying. Examples reflect Vibe DevOps lab environments; adjust parameters to your infrastructure and verify in staging first.← Back to Hands-on Labs

Next Recommended Labs