Make a job safe to run twice by giving each logical task an idempotency key, claiming that key atomically in a SQLite ledger before doing any work, and returning the recorded result when the key arrives again. Jobs run twice more often than you expect: a host reboots mid-task, a queue redelivers a message because the acknowledgement was lost, or a retry policy fires before the first run finishes. A duplicate is harmless only if identical inputs produce the same outputs and no extra side effects. The ledger below is tiny and runs on a Figment Intel Mac VM at $25 a month.
Which Figment plan fits an idempotency ledger?
Most ledgers are small: SQLite writes, file checks and outbound API calls. The Intel Mac VM ($25 a month, $2 a day, $0.15 an hour) handles that with 4 shared vCPUs, 4GB of RAM and an 80GB SSD. It runs macOS Sequoia with compatible Intel Mac toolchains, including Xcode 26.0 to 26.3. You reach it over SSH, encrypted remote desktop or the browser, and outbound agents connect to your queue or CI service from the VM.
Choose another plan when the job itself needs it:
- Apple Silicon Mac VM ($39 a month, $6 a day): the job executes arm64-only binaries, or needs Xcode 26.4 or later. It has 4 shared vCPUs and 4GB of RAM.
- Dedicated M4 Pro 48 GB ($349 a month, or $299 a month on a 12-month term): heavy builds, or a job that should own the whole Mac (M4 Pro, 48GB RAM, 512GB SSD).
Figment runs the Mac and network layer. Your queue, ledger and job code are yours to manage.
Why do jobs run twice?
Most queue systems, webhooks and managed CI triggers guarantee at-least-once delivery, not exactly-once. That is a deliberate availability trade-off, and the consumer owns deduplication. A job that is not idempotent can:
- send the same email twice,
- open two identical pull requests,
- bill a customer twice, or
- apply the same patch and then conflict on the second run.
An idempotency key ties each logical operation to a single identifier. If the same key arrives again, the second run reads the recorded outcome from the first run and returns it without repeating any side effect.
How do I build the idempotency-key ledger?
Use SQLite with a PRIMARY KEY on the key. SQLite handles concurrent reads safely, needs no server, and survives reboots. INSERT OR IGNORE silently skips a row whose PRIMARY KEY already exists (see SQLite conflict resolution), which makes the claim step atomic. One process wins the insert, and everyone else sees the existing row.
The examples interpolate ${key} into SQL for readability. In production, bind the key as a parameter (for example via sqlite3 -cmd ".param set" or a client library), so a key containing a quote cannot break the statement. Any job touching a credential should pull it from a secret store, not from shell history or a plaintext env file.
#!/usr/bin/env bash
# idempotency-lib.sh: source this in any agent job script
set -euo pipefail
LEDGER_DB="${HOME}/agent-workspace/idempotency.db"
ledger_init() {
sqlite3 "$LEDGER_DB" <<'SQL'
CREATE TABLE IF NOT EXISTS ledger (
key TEXT PRIMARY KEY,
status TEXT NOT NULL, -- 'running' | 'done' | 'failed'
result TEXT,
started_at TEXT NOT NULL,
finished_at TEXT
);
SQL
}
# Claim a key atomically. Returns 0 if this call inserted the row, 1 if not.
ledger_claim() {
local key="$1" now
now=$(date -u +%FT%TZ)
sqlite3 "$LEDGER_DB" <<SQL
INSERT OR IGNORE INTO ledger (key, status, started_at)
VALUES ('${key}', 'running', '${now}');
SQL
local rows
rows=$(sqlite3 "$LEDGER_DB" \
"SELECT COUNT(*) FROM ledger WHERE key='${key}' AND status='running' AND started_at='${now}';")
[[ "$rows" -eq 1 ]]
}
ledger_finish() {
local key="$1" status="$2" result="${3:-}"
local now
now=$(date -u +%FT%TZ)
sqlite3 "$LEDGER_DB" <<SQL
UPDATE ledger
SET status='${status}', result='${result}', finished_at='${now}'
WHERE key='${key}';
SQL
}
ledger_result() {
local key="$1"
sqlite3 "$LEDGER_DB" \
"SELECT result FROM ledger WHERE key='${key}' AND status='done' LIMIT 1;"
}
How do I use the ledger in a job?
The caller supplies the key. If the job generates its own key, two deliveries of the same logical operation become two different keys, and both run. A UUID carried on the task payload works, and so does a deterministic hash of the inputs.
#!/usr/bin/env bash
# job-create-pr.sh: idempotent pull-request creation
set -euo pipefail
source "${HOME}/agent-workspace/idempotency-lib.sh"
ledger_init
IDEMPOTENCY_KEY="${1:?Usage: job-create-pr.sh <idempotency-key> <branch> <title>}"
BRANCH="${2:?}"
PR_TITLE="${3:?}"
log() { echo "[$(date -u +%FT%TZ)] [${IDEMPOTENCY_KEY}] $*"; }
# 1. Return the previous result if this key already completed
PREVIOUS=$(ledger_result "$IDEMPOTENCY_KEY")
if [[ -n "$PREVIOUS" ]]; then
log "Duplicate delivery. Previous result: $PREVIOUS."
echo "$PREVIOUS"; exit 0
fi
# 2. Try to claim the key; only one process wins
if ! ledger_claim "$IDEMPOTENCY_KEY"; then
log "Key already in progress. Exiting."
exit 0
fi
# 3. Do the real work; pull the token from the keychain, not env
log "Creating pull request for branch $BRANCH"
GH_TOKEN=$(security find-generic-password -a "$USER" -s "gh-token" -w)
if ! PR_URL=$(curl --silent --show-error --fail \
-H "Authorization: Bearer $GH_TOKEN" \
-H "Content-Type: application/json" \
-X POST "https://api.github.com/repos/${GITHUB_REPO}/pulls" \
-d "{\"title\":\"${PR_TITLE}\",\"head\":\"${BRANCH}\",\"base\":\"main\"}" \
| jq -r '.html_url'); then
log "PR creation failed"
ledger_finish "$IDEMPOTENCY_KEY" "failed" "api_error"
exit 1
fi
log "PR created: $PR_URL"
ledger_finish "$IDEMPOTENCY_KEY" "done" "$PR_URL"
echo "$PR_URL"
This is an untested illustration, not a benchmark. Run it against your own repository and keychain entry before relying on it.
What does a three-delivery example look like?
A webhook fires three times because the first acknowledgement never came back inside the sender's timeout.
T=0s Delivery 1 arrives. key=abc-123. ledger_claim succeeds.
T=1s Job starts creating the PR on GitHub.
T=2s Delivery 2 arrives. key=abc-123. ledger_claim returns false. Exit 0.
T=4s Delivery 1 finishes. ledger_finish records status=done, result=https://github.com/org/repo/pull/42.
T=5s Delivery 3 arrives. ledger_result returns the PR URL. Exit 0, print the URL.
One pull request, three deliveries handled. You can replay the scenario on the hosted Mac:
bash job-create-pr.sh "abc-123" "feature/x" "Add feature X" & # delivery 1
bash job-create-pr.sh "abc-123" "feature/x" "Add feature X" # delivery 2
sleep 6
bash job-create-pr.sh "abc-123" "feature/x" "Add feature X" # delivery 3
Deliveries 2 and 3 should log a duplicate and exit 0.
How do I check recovery and clean up?
- Run the simulation above and confirm one PR, not three.
- Look for stale running rows:
sqlite3 ~/agent-workspace/idempotency.db "SELECT * FROM ledger WHERE status='running' AND started_at < datetime('now', '-10 minutes');"and decide the recovery policy (requeue, mark failed, or page a human). - Confirm that a
failedrow does not block a deliberate retry. Use a new key for the retried logical operation, not the old one. - Add a TTL sweep so the table does not grow forever:
sqlite3 ~/agent-workspace/idempotency.db "DELETE FROM ledger WHERE finished_at < datetime('now', '-30 days');" - If you run the job from
launchd, use aLabel, keep theProgramArgumentsabsolute, and let launchd own the process lifecycle instead of forking a daemon yourself (Apple: creating launchd jobs).
What does the ledger cost to run?
Almost nothing beyond the plan. A ledger check is a two-statement SQLite round trip, so it should finish in milliseconds on the Intel VM. We have not benchmarked it, so time it on your own host. As a rough size estimate, a million rows with short result strings is on the order of 100 MB, well inside the 80GB disk (which includes the OS) as long as you keep the TTL sweep running and drop or archive very old rows.
The ledger lives on the VM's disk, and a disk is not a backup. Figment does not back up your Mac, so keep your own copy of the ledger. If you restore an older copy, a key that completed after that copy was made will run again. Make the underlying side effect safe to repeat, or reconcile against the downstream system before you replay.
If you only need the ledger and the outbound API calls, the Intel Mac VM ($25 a month) is the direct answer. A two-week run on daily plans costs 14 × $2 = $28. Move to the Apple Silicon Mac VM ($39 a month) when the same job must build or run arm64 binaries or Xcode 26.4 or later.
Where do I start?
Pick a plan on the Mac hosting page. If you already run CI on a self-hosted runner, the ledger drops in beside the runner on the same host.
Related: Mac Safari scheduled PDF · Mac Shortcuts command-line · GitHub Actions self-hosted runner on Mac