Skip to content

Lesson 11 of 14 · 20m

SQLite for tool state: dedup tables and resumable work queues

When state.json outgrows a dict — INSERT OR IGNORE dedup, WAL mode, and a status column that survives kill -9.

Your dedup set of seen IOCs lives in state.json. At 4,000 entries it's fine. At 400,000 it takes eleven seconds to load, and at 4,000,000 it doesn't fit in memory at all — plus a kill -9 mid-save leaves you a torn file and a corrupted run. JSON files are for small state; the moment state has to be queried, indexed, or touched by more than one process, the right tool is already in the stdlib: sqlite3, the embedded database that's a file format and a query engine, not a service.

The wrong model: databases are for servers

SQLite is not a server. It's a single file plus a library — Python's sqlite3 module has shipped since Python 2.5 and requires zero setup beyond import sqlite3. The mental cost people avoid is "standing up a database"; there is none. conn = sqlite3.connect("state.db") and you're querying. What it buys over a JSON blob:

  • Indexing — WHERE value = ? on 4M rows is instant; seen dict lookups in a 4M-entry JSON file mean loading 4M entries first.
  • Atomic commits — a kill -9 mid-write leaves the last committed transaction, never a torn file.
  • Concurrent readers — WAL mode lets readers proceed while a writer works.
  • Querying — COUNT, GROUP BY, ORDER BY on state you currently for-loop over in Python.

A dedup table that's a real table

import sqlite3

conn = sqlite3.connect("feedwatch.db")
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("""
    CREATE TABLE IF NOT EXISTS seen (
        guid TEXT PRIMARY KEY,
        first_seen TEXT NOT NULL
    )
""")
conn.commit()

def is_new(guid):
    cur = conn.execute(
        "INSERT OR IGNORE INTO seen (guid, first_seen) VALUES (?, datetime('now'))",
        (guid,))
    conn.commit()
    return cur.rowcount == 1   # 1 = inserted (new), 0 = already present (dup)

INSERT OR IGNORE plus the PRIMARY KEY constraint is dedup — one statement, no race window, no read-before-write. rowcount tells you whether it inserted, which is exactly the "seen before?" answer. WAL mode (PRAGMA journal_mode=WAL) is one line and switches on the concurrent-readers behavior that makes it safe for a cron job and a debugging shell to touch the same file. busy_timeout (PRAGMA busy_timeout = 5000) adds a wait for a contending writer instead of an instant database is locked error.

The work-queue pattern: resumable scans

The pattern that makes long jobs resumable: a work table where each row is a unit of work with a status column. A run claims rows WHERE status='pending', marks them running, and flips to done/failed. A crash mid-run leaves honest state — you re-run, pending items resume, finished items are skipped. This is the difference between "the job started over from scratch after the timeout" and "the job continued."

conn.execute("""
    CREATE TABLE IF NOT EXISTS work (
        id INTEGER PRIMARY KEY,
        target TEXT NOT NULL,
        status TEXT NOT NULL DEFAULT 'pending',   -- pending|running|done|failed
        updated TEXT
    )
""")
conn.execute("CREATE INDEX IF NOT EXISTS idx_status ON work(status)")

Claim work inside BEGIN IMMEDIATE (one writer at a time), then UPDATE ... SET status='running' WHERE id=? and commit — that pair is a real dequeue. Real tools do exactly this: fail2ban stores its ban list in /var/lib/fail2ban/fail2ban.sqlite3 — not Redis, not Postgres, a file — because the same argument applies: enough structure to be safe, no service to operate.

Try this

Convert the feedwatch state — seen GUIDs and last-fetch timestamps — to sqlite3 with the seen table above. Kill it mid-run (kill -9), restart, confirm the dedup state survived intact and no partial write corrupted the file.

Field notes

  • ? placeholders only. Never f-string values into SQL — sqlite3 parameter substitution is the injection boundary, same rule as subprocess argv.
  • conn.commit() after writes. The context manager (with conn:) commits on clean exit and rolls back on exception; bare execute buffers.
  • When to stay with JSON: a dict of a few hundred keys, one writer, and os.replace atomic writes — that's the automation lesson's save_state, and it's fine there.
  • The bug that ships: json.load + json.dump on state.json as your "database" at scale — the first big file and the first kill both lose.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.