import sqlite3 from concurrent.futures import ThreadPoolExecutor from tempfile import TemporaryDirectory from pathlib import Path def record(path, request_id, intent): with sqlite3.connect(path, timeout=10) as db: db.execute("BEGIN IMMEDIATE") row = db.execute("SELECT intent FROM requests WHERE id=?", (request_id,)).fetchone() if row: return "replay" if row[0] == intent else "conflict" db.execute("INSERT INTO requests VALUES (?,?)", (request_id, intent)) return "new" if __name__ == "__main__": with TemporaryDirectory() as directory: path = Path(directory)/"ledger.db" with sqlite3.connect(path) as db: db.execute("CREATE TABLE requests(id TEXT PRIMARY KEY, intent TEXT NOT NULL)") with ThreadPoolExecutor(max_workers=8) as pool: outcomes = list(pool.map(lambda _: record(path, "r1", "intent-A"), range(100))) assert outcomes.count("new") == 1 and outcomes.count("replay") == 99 assert record(path, "r1", "intent-B") == "conflict" assert record(path, "r2", "intent-A") == "new" print("100 concurrent submissions: one new record, 99 replays")