惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
雷峰网
雷峰网
V
V2EX
博客园_首页
Engineering at Meta
Engineering at Meta
博客园 - 聂微东
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Apple Machine Learning Research
Apple Machine Learning Research
GbyAI
GbyAI
H
Help Net Security
A
About on SuperTechFans
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Blog — PlanetScale
Blog — PlanetScale
W
WeLiveSecurity
云风的 BLOG
云风的 BLOG
D
Docker
Security Archives - TechRepublic
Security Archives - TechRepublic
Help Net Security
Help Net Security
N
News and Events Feed by Topic
Simon Willison's Weblog
Simon Willison's Weblog
G
Google Developers Blog
A
Arctic Wolf
T
The Blog of Author Tim Ferriss
博客园 - 叶小钗
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Google DeepMind News
Google DeepMind News
博客园 - 三生石上(FineUI控件)
aimingoo的专栏
aimingoo的专栏
Hacker News: Ask HN
Hacker News: Ask HN
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 司徒正美
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy International News Feed
T
Troy Hunt's Blog
T
Tenable Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Recorded Future
Recorded Future
F
Fortinet All Blogs
D
DataBreaches.Net
B
Blog
T
Threat Research - Cisco Blogs
MyScale Blog
MyScale Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
The GitHub Blog
The GitHub Blog
Security Latest
Security Latest
M
MIT News - Artificial intelligence

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
SQLite Backup Strategy for Production SaaS: WAL, Litestream, Recovery Tests
HelperX · 2026-06-16 · via DEV Community

Running SQLite in production for a multi-tenant SaaS means giving up the operational comfort of a managed database. No automatic backups, no point-in-time recovery dashboards, no on-call DBA. You build all of that yourself, or you find out the hard way during your first incident.

We've been running SQLite for HelperX — 200+ slot databases plus a global database — for over a year. In that time we've had two real recovery events and a few dozen test recoveries. Here's the backup architecture that survived contact with production.

The constraints we needed to satisfy

The backup strategy had to hit four numbers:

Metric Target Why
RPO (data loss tolerance) < 60 seconds We're processing user actions; missing the last hour is unacceptable
RTO (restore time) < 15 minutes per slot Customers expect their slot back fast
Cost < $10/month total Doesn't justify cloud DB pricing if backup eats the savings
Operational overhead < 1 hour/week Solo founder; no DBA budget

These constraints rule out a few common patterns:

  • Daily sqlite3 .backup cron jobs — RPO of 24 hours is way too lossy
  • Full filesystem snapshots only — slow restore, costly storage
  • Block-level replication — overkill, expensive, requires specialized infra
  • Managed backup services — most don't support SQLite, the ones that do are pricey

What works in our constraints: WAL-mode SQLite + Litestream for continuous streaming + filesystem snapshots as a secondary backup + monthly recovery tests.

Why WAL mode is the foundation

Before any backup tool, you need WAL (Write-Ahead Logging) mode enabled. WAL changes how SQLite handles writes — instead of writing directly to the main database file, changes go to a .wal file first and are eventually checkpointed to the main file.

For backups, WAL has two important properties:

  1. Reads don't block writes and vice versa. A backup tool can read the database concurrently with application writes. Without WAL, a backup would block all writes (or fail).
  2. Litestream and similar tools watch the WAL file to stream incremental changes to a remote target. This is what makes continuous backup possible.

Enabling WAL on every slot database:

function getSlotDb(slotId) {
  const db = new Database(`data/slots/${slotId}.db`);
  db.pragma('journal_mode = WAL');
  db.pragma('synchronous = NORMAL'); // important for backup tooling
  db.pragma('wal_autocheckpoint = 1000'); // checkpoint every 1000 pages
  db.pragma('busy_timeout = 5000');
  return db;
}

synchronous = NORMAL is a careful trade-off: it's faster than FULL, slightly less durable on crash, but compatible with how Litestream needs to read the WAL. We accept the trade because our continuous streaming gives us better effective durability than synchronous = FULL without streaming.

Litestream: the primary backup mechanism

Litestream is a small Go binary that watches a SQLite WAL file and streams its contents to a remote target (S3, B2, GCS, SFTP). It's the closest thing SQLite has to write-ahead replication.

Architecture:

SQLite (with WAL)  →  Litestream sidecar  →  S3/B2 bucket
                          │
                          └─ uploads WAL segments every N seconds

Our Litestream config:

# litestream.yml
dbs:
  - path: /app/data/global.db
    replicas:
      - type: s3
        bucket: helperx-backups
        path: global
        endpoint: s3.us-west-001.backblazeb2.com
        sync-interval: 30s
        retention: 168h
        retention-check-interval: 1h
        snapshot-interval: 24h

  - path: /app/data/slots/slot_abc.db
    replicas:
      - type: s3
        bucket: helperx-backups
        path: slots/slot_abc
        endpoint: s3.us-west-001.backblazeb2.com
        sync-interval: 30s
        retention: 168h
        snapshot-interval: 24h

  # ... one block per slot, generated dynamically

The configuration is generated by a small script when slots are created or deleted:

function regenerateLitestreamConfig() {
  const slots = db.prepare('SELECT id FROM slots WHERE active = 1').all();
  const config = {
    dbs: [
      { path: '/app/data/global.db', replicas: [GLOBAL_REPLICA_CONFIG] },
      ...slots.map(({ id }) => ({
        path: `/app/data/slots/${id}.db`,
        replicas: [{
          type: 's3',
          bucket: 'helperx-backups',
          path: `slots/${id}`,
          endpoint: S3_ENDPOINT,
          'sync-interval': '30s',
          retention: '168h',
          'snapshot-interval': '24h',
        }],
      })),
    ],
  };
  fs.writeFileSync('/etc/litestream.yml', yaml.dump(config));
  execSync('systemctl reload litestream');
}

Whenever a slot is added or removed, Litestream gets a hot reload of its config. No restart needed.

What Litestream actually backs up

Litestream uploads:

  1. Periodic snapshots (every 24 hours) — a complete copy of the database at that point in time
  2. WAL segments — small files representing the incremental changes since the last snapshot, uploaded every sync-interval

To restore, Litestream combines the most recent snapshot with all subsequent WAL segments. This is how you get sub-minute RPO without doing a full backup every minute.

Storage cost

Backblaze B2 pricing: $0.005 per GB/month for storage, $0.01 per GB egress (only paid on restores).

Our backup footprint:

  • 200 slots × ~3 MB compressed snapshot = ~600 MB
  • 24 hours of WAL segments × all slots = ~150 MB
  • Global database snapshot + WAL: ~5 MB
  • Retention overhead (7 days of history): ~5x multiplier = ~3.8 GB total

Monthly cost: 3.8 GB × $0.005 = $0.019. Practically free.

Egress is the more interesting line. If we restored everything once a month: 3.8 GB × $0.01 = $0.038. Also negligible.

We added Backblaze API calls for class A/B operations, which Litestream uses frequently. That ran us another $0.50/month. Total: under $1/month, well under our $10 budget.

The actual RPO with Litestream

With sync-interval: 30s, the worst-case RPO is roughly 30-45 seconds. WAL changes that happened in the last 30 seconds may not yet be uploaded when disaster strikes. Acceptable for our use case; for stricter requirements you can lower sync-interval to 10s at the cost of more API calls.

Filesystem snapshots: the secondary backup

Litestream is great for normal recovery scenarios. It does not protect against:

  1. Logical corruption — a buggy migration that corrupts data across all slots
  2. Operator errorDELETE FROM audit_log; without a WHERE clause
  3. Litestream itself failing — bugs, misconfiguration, S3 outages

For these cases, we run filesystem snapshots of the entire data/ directory once per day:

#!/bin/bash
# /etc/cron.daily/snapshot-data.sh

set -euo pipefail

DATE=$(date +%Y%m%d-%H%M)
SNAPSHOT_DIR="/backup/snapshots/$DATE"

mkdir -p "$SNAPSHOT_DIR"

# Pause writes briefly using a lock
flock /app/data/.snapshot-lock -c "
  rsync -a --link-dest=/backup/snapshots/latest /app/data/ '$SNAPSHOT_DIR/'
"

# Update latest symlink
ln -sfn "$SNAPSHOT_DIR" /backup/snapshots/latest

# Prune old snapshots (keep 7 daily, 4 weekly, 3 monthly)
find /backup/snapshots -maxdepth 1 -type d -mtime +7 -name '20*-*' -exec rm -rf {} \;

# Encrypt and upload to off-site
tar czf - "$SNAPSHOT_DIR" | \
  gpg --symmetric --batch --passphrase-file /etc/backup-pass --cipher-algo AES256 | \
  aws s3 cp - "s3://helperx-snapshots/$DATE.tar.gz.gpg"

A few important details:

  • rsync --link-dest makes snapshots cheap. Unchanged files are hardlinked, not copied. A 480MB data directory only uses ~50MB of new disk per snapshot when most files haven't changed.
  • flock briefly serializes with the application to ensure a consistent snapshot. The lock is held for the duration of the rsync, typically 2-3 seconds.
  • GPG encryption before upload — the snapshot is encrypted on disk before it leaves our server. The B2 bucket holds only ciphertext.
  • The local copy is the fast restore path. Off-site is for disaster scenarios.

This catches the failure modes Litestream misses. If a bad migration runs at 02:30, the 02:00 snapshot has the pre-migration state and we can restore from there.

Recovery: the playbook

A backup that's never been tested is not a backup. Here are the documented recovery procedures.

Scenario 1: Single slot database corrupted

The most common scenario. A specific slot's database is unreadable, but everything else is fine.

# 1. Stop the worker process for this slot
curl -X POST http://localhost:3000/admin/slots/$SLOT_ID/stop

# 2. Move the corrupted database aside (don't delete yet)
mv /app/data/slots/$SLOT_ID.db /tmp/$SLOT_ID.db.corrupt

# 3. Restore from Litestream
litestream restore \
  -o /app/data/slots/$SLOT_ID.db \
  s3://helperx-backups/slots/$SLOT_ID

# 4. Verify integrity
sqlite3 /app/data/slots/$SLOT_ID.db 'PRAGMA integrity_check;'

# 5. Restart the worker
curl -X POST http://localhost:3000/admin/slots/$SLOT_ID/start

# 6. Sanity check via app dashboard

Typical recovery time: 2-4 minutes per slot. Well under our RTO target.

Scenario 2: Global database lost or corrupted

The global database holds user accounts, billing, plan info. Losing it is worse than losing any single slot.

# 1. Put the application in maintenance mode
curl -X POST http://localhost:3000/admin/maintenance/on

# 2. Stop the application
systemctl stop helperx

# 3. Restore from Litestream (use the closest point in time)
litestream restore \
  -o /app/data/global.db \
  s3://helperx-backups/global

# 4. Run integrity check
sqlite3 /app/data/global.db 'PRAGMA integrity_check;'

# 5. Run a cross-check script
node scripts/verify-global-restore.js

# 6. Restart and disable maintenance mode
systemctl start helperx
curl -X POST http://localhost:3000/admin/maintenance/off

Recovery time: 7-12 minutes.

The verify-global-restore.js script does sanity checks:

// scripts/verify-global-restore.js
const db = new Database('/app/data/global.db', { readonly: true });

const userCount = db.prepare('SELECT COUNT(*) as c FROM users').get().c;
const slotCount = db.prepare('SELECT COUNT(*) as c FROM slots WHERE active = 1').get().c;
const recentActivity = db.prepare(`
  SELECT COUNT(*) as c FROM users WHERE last_login > datetime('now', '-7 days')
`).get().c;

console.log(`Restored: ${userCount} users, ${slotCount} active slots, ${recentActivity} recent logins`);

if (userCount < 100 || slotCount < 100) {
  console.error('SUSPICIOUS: counts look too low');
  process.exit(1);
}

// Verify a known recent user exists
const canary = db.prepare("SELECT id FROM users WHERE email = ?").get('canary@helperx.app');
if (!canary) {
  console.error('FAIL: canary user not found');
  process.exit(1);
}

console.log('OK: restore verified');

The canary user is a real account we use only as a restore probe. If it's not present, the restore didn't include the data we expected.

Scenario 3: Full disaster — server is gone

Server-level failure. We need to spin up a new instance and restore everything.

# 1. Provision a new server, install dependencies
# 2. Pull the application code
git clone https://github.com/helperx/helperx-app.git
cd helperx-app && npm install

# 3. Restore global database
litestream restore -o /app/data/global.db s3://helperx-backups/global

# 4. Get list of slots from restored global db
SLOTS=$(sqlite3 /app/data/global.db 'SELECT id FROM slots WHERE active = 1')

# 5. Restore each slot in parallel
for slot in $SLOTS; do
  (litestream restore -o /app/data/slots/$slot.db s3://helperx-backups/slots/$slot) &
done
wait

# 6. Verify all restored
node scripts/verify-full-restore.js

# 7. Update DNS, start application

Recovery time: 45-90 minutes. Most of it is the parallel slot restores. With 200 slots, even at 30-60 seconds per restore, the parallelization gets it done in roughly the time of the slowest 5-10 slots.

This is the only scenario where we'd realistically miss our RTO target. We accept it because full disasters are extremely rare; the prior likelihood is dominated by Scenarios 1 and 2.

The monthly recovery test

This is the part most teams skip. We don't. Once a month, on the first Saturday at 09:00, we run a full recovery test against a staging environment.

The test:

  1. Provision a fresh staging server
  2. Run the Scenario 3 recovery procedure against the production backups
  3. Run a battery of verification scripts
  4. Tear down the staging environment

The verification scripts check:

  • All slot databases pass PRAGMA integrity_check
  • The most recent audit log entry is from within the expected RPO window
  • A randomly-chosen slot has the expected number of recent actions
  • The global database's user count matches a sanity range
  • Litestream config matches the slot list from the restored global db

The test takes about 90 minutes and costs ~$1 in cloud compute. We've caught real issues twice:

  • Once: Litestream had silently stopped backing up 3 slots due to a config drift. The recovery test failed because those slots' restores returned old data.
  • Once: a recent migration added a column the verification script didn't know about. Restore succeeded but verification flagged it — we updated the script.

Both bugs would have been catastrophic in a real incident. The monthly test caught them in a safe environment.

What we don't back up

Some things deliberately aren't in the backup:

  • The WAL itself. Litestream handles it; we don't snapshot it separately.
  • Application logs — rotated to a separate log aggregation system, not backed up to S3.
  • Temp directories. No durability requirement.
  • Browser session caches — large and regeneratable.
  • node_modules — regenerated from package-lock.json on restore.

Cutting these out keeps the backup footprint small and the restore fast.

Key takeaways

  1. WAL mode is the prerequisite for any sane SQLite backup strategy.
  2. Litestream gives you sub-minute RPO at near-zero cost for most workloads.
  3. Filesystem snapshots are your secondary defense against logical corruption that Litestream can't help with.
  4. Encrypt snapshots before they leave the server. Storage provider zero-knowledge is non-negotiable for user data.
  5. Recovery is three scenarios, not one. Document each separately.
  6. Monthly recovery tests are the only way to know your backups work. Skip them and you'll find out the hard way.
  7. Verification scripts must include canaries — a known record that should always be present.
  8. Total backup cost can be under $5/month for a typical multi-tenant SQLite SaaS. The math is much better than managed databases.

A backup strategy is only as good as the recovery test. Run them. The day you need them, you won't have time to discover they were broken.


HelperX ships with a recommended Litestream config and recovery scripts as part of the self-hosted distribution. Free 30-day trial — full source, no markup on infrastructure.