I deployed a second copy of my agent at 11:40 PM. By 7 AM, 1,847 customers had two of everything.
The deploy was the same command I'd run a hundred times: pull, restart the worker, go to bed. What I didn't know was that the old worker never died. It was mid-batch, systemd sent SIGTERM, my process had no handler for it, and the service manager eventually gave up and started the new one anyway. For six hours, two workers pulled from the same job table, in the same SQLite file, on the same Pi.
Every job ran twice. Every email went out twice.
I found out from a customer reply at 7:12 AM: "Hey — did you mean to send this twice?"
The locking I thought was protecting me
I had a lock. I want to be clear about that, because "you forgot to lock it" is the easy version of this story and it isn't what happened.
My worker took a flock on /var/lock/agent-worker.lock at startup and exited if it couldn't get it. I'd tested it: start a second copy by hand, watch it refuse to run. It worked.
The problem is that a per-process file lock protects you from accidental double starts. It does nothing about a deploy where the old process is still alive and the new one is started by a different unit invocation with a different lock path. Mine used %p in the path — the PID — so each process happily got its own lock and each one logged worker: lock acquired.
I had built a lock that could never fail, which means it could never tell me anything.
The race is three lines long
Here's the claim logic, minus the logging:
row = db.execute( "SELECT id, payload FROM jobs WHERE status = 'pending' ORDER BY created_at LIMIT 1" ).fetchone() if row is None: continue db.execute("UPDATE jobs SET status = 'running' WHERE id = ?", (row["id"],)) db.commit() process(row) # sends the email db.execute("UPDATE jobs SET status = 'done' WHERE id = ?", (row["id"],)) db.commit() Read, then write. Two processes, one row, no transaction around the pair. Worker A selects job 4471. Worker B selects job 4471. Worker A updates it to running and commits. Worker B updates it to running and commits — because my UPDATE had no WHERE status = 'pending' guard, so it wasn't a compare-and-swap, it was just an assignment.
Then both of them send the email.
SQLite serialized the writes perfectly. That's the part that fooled me for a week afterward, because I kept staring at the database looking for corruption and finding none. The database was consistent. The problem was that consistency at the write layer doesn't help when the side effect — an HTTP POST to my email provider — happens next to the transaction instead of inside it.
What the numbers actually looked like
- 1,847 jobs processed twice
- 3,694 emails sent instead of 1,847
- 41 replies, 12 of them annoyed, 4 unsubscribes
- 3 customers I refunded because one of the duplicate emails was a renewal reminder and they thought they'd been charged twice
- About 6 hours of cleanup, most of it spent writing apology emails one at a time so they didn't look automated
The API bill for the double run was $0.61. The refunds were $87. The unsubscribes cost more than both.
Fix 1: make the claim atomic
The first fix is to stop treating "select then update" as a unit of work. SQLite 3.35+ supports RETURNING, so the claim can be a single statement:
BEGIN IMMEDIATE; UPDATE jobs SET status = 'running', claimed_by = :worker_id, lease_until = datetime('now', '+5 minutes') WHERE id = ( SELECT id FROM jobs WHERE status = 'pending' OR (status = 'running' AND lease_until < datetime('now')) ORDER BY created_at LIMIT 1 ) RETURNING id, payload; COMMIT; BEGIN IMMEDIATE takes the write lock up front, so two workers can't both get through the subquery. The second one sees zero rows and sleeps. The lease_until clause also handles the case my old code never did: a worker that dies mid-job leaves rows stuck in running forever, so the queue silently drains itself to zero and looks healthy while nothing is being processed.
That last one is worth its own paragraph. My queue table had 300 rows stuck in running from crashes over the previous month. I never noticed, because my dashboard only counted pending. A queue with a dead-letter state you never look at is a queue that lies to you.
Fix 2: an idempotency key, written before the side effect
Atomic claiming stops two workers from grabbing the same row. It does not stop the same work from being enqueued twice by an upstream bug, and it doesn't survive a crash between "send" and "mark done" — which is exactly the window I hit during the redeploy.
So the second fix is a guard table:
CREATE TABLE send_guards ( idem_key TEXT PRIMARY KEY, created_at TEXT NOT NULL DEFAULT (datetime('now')) ); key = hashlib.sha256( f"{job['id']}:{job['recipient']}:{job['template_version']}".encode() ).hexdigest() cur = db.execute( "INSERT INTO send_guards (idem_key) VALUES (?) ON CONFLICT DO NOTHING", (key,) ) if cur.rowcount == 0: log.info("duplicate suppressed job=%s", job["id"]) return send_email(job) # only happens after the key is committed Note the ordering, because it's a deliberate trade: the key is committed before the send. If the process dies in between, that email is lost rather than duplicated. For renewal reminders and digests, losing one is annoying and duplicating one is a support ticket. I picked at-most-once on purpose, and I wrote that decision in the module docstring so the next version of me doesn't "fix" it back.
Including template_version in the key matters more than it looks. Without it, editing a template and re-running the job for a legitimate reason gets silently swallowed, and you spend an afternoon debugging a "missing" email that the guard table ate.
Fix 3: separate deciding from sending
The structural fix, and the one I should have done first, is an outbox. Deciding what to send and actually sending it are two different jobs with two different failure modes, and I had them tangled in one function.
Now the worker writes a row to outbox inside the same transaction that marks the job done. A separate sender process reads unsent outbox rows, sends them, and marks them sent. If the sender crashes, nothing is lost — the row is still there. If the sender runs twice, the idempotency key catches it.
The bonus is observability. "How many emails are queued right now" became a single SELECT count(*) FROM outbox WHERE sent_at IS NULL, which is the metric I actually wanted all along and never had.
Fix 4: a shutdown that drains
stopping = threading.Event() def on_term(signum, frame): log.info("SIGTERM: finishing current job, then exiting") stopping.set() signal.signal(signal.SIGTERM, on_term) while not stopping.is_set(): job = claim_next() ... Plus TimeoutStopSec=90 in the unit file, so systemd waits for the current job instead of killing it mid-send. That one change is what would have prevented the whole incident: the old worker would have finished its job, exited, and the new one would have started cleanly.
The lesson I keep relearning
I thought my problem was concurrency. My problem was that I had put the guarantee in the wrong place. A lock on the process, a transaction around the database write, a status column that said done — none of those describe the thing I actually needed, which is "this customer receives this email exactly once." The only place that promise can be kept is at the boundary where the side effect happens, and the only way to keep it is to make the side effect safe to repeat.
Exactly-once delivery doesn't exist. Idempotent delivery does, and it costs one unique index.
If you take one thing from this: when you find yourself writing a clever lock, check whether a unique constraint would do the same job. Mine would have. I just liked the lock because it was code I wrote, and the constraint felt like admitting I didn't trust my own queue.
I write up the specific patterns — atomic claims, leases, outbox tables, and the deploy checklist I now run before every restart — in The Solo Operator's AI Agent Playbook. Code LAUNCH90 at checkout makes it $1.90. If it doesn't save you 5 hours in week one, reply to the receipt for a refund.

