Two local workers share a provider quota of one request per fixed window. Both can read a counter showing zero before either has recorded an attempt. Make the reservation itself a write that only one of them can commit.
The following example counts attempts, not successes. It assumes one quota bucket per window, one shared SQLite database on local storage, and a positive cap set by the application. If the provider counts tokens, uses a rolling window or applies different limits per credential, define a different bucket and accounting rule.
CREATE TABLE quota (
w INTEGER PRIMARY KEY,
used INTEGER NOT NULL CHECK (used >= 0),
cap INTEGER NOT NULL CHECK (cap > 0)
);
Inside one write transaction initialize the row if necessary, then conditionally increase it:
INSERT INTO quota(w, used, cap) VALUES (:w, 0, :cap)
ON CONFLICT(w) DO NOTHING;
UPDATE quota SET used = used + 1
WHERE w = :w AND used < cap;
Check the affected row count of the UPDATE and the success of the transaction commit. Only one updated row plus a successful commit permits dispatch. Zero rows means the cap was reached. A busy error means the database did not grant the reservation; handle it separately with a bounded wait or defer the job. Do not keep a transaction open during the network call. The stored cap is fixed on the first insert for that window; changing policy mid-window needs an explicit update policy of its own.
In a local SQLite test, two separate connections contested one slot. After both transactions finished, one UPDATE reported one row changed and the other zero. This checks the reservation condition on that database. It says nothing about a real provider’s reset clock or requests issued by other clients.
Although often described as a lease, this example is a nonrefundable window reservation. If a process crashes after committing but before sending, the window loses one unit of capacity. Returning that unit on a timeout would risk over-admission if the provider actually saw the request. SQLite transactions and UPSERT describe the database primitives.
This article was created with AI assistance.
Top comments (0)