Core Concepts
Locking Strategies
Decide when to lock a row before making a decision and when to check that its version is still current at write time.
The capacity check and the write that reserves a slot have to agree. When two requests compete for the last slot, we can make one wait while the other checks and writes. We can also let both read and reject an update if the data has changed since that read.
Lock before making the decision
Two gateways in the ChatGPT design can both see the last slot in the same model pool. If both reserve that slot, the pool exceeds capacity. A lock makes a conflicting operation wait while another transaction controls the resource. In pessimistic locking, we take that lock before checking the state we are about to change. In PostgreSQL, SELECT ... FOR UPDATE locks the rows it selects against conflicting writes or locking reads until the transaction ends. An ordinary read can still use its snapshot. PostgreSQL row-level locking
In the ChatGPT design, the gateway first locks the account's capacity row and checks the retry ID again. For a genuinely new turn that passes the rate check, it locks the selected pool row. It checks both limits, increments both used counts, and saves the pending turn inside that transaction. The separate Redis rate check has its own short timeout and accounting. A later slot rejection can still spend rate allowance.
Suppose A and B have different accounts and both reach P3. A locks P3 while the used count is 3. B arrives and waits for that same lock. A accepts its turn and commits the pool count of 4. At PostgreSQL Read Committed, B's locking read now returns the updated row. B sees that the pool is full and rolls back without saving a turn. The required locks last through commit, and work on unrelated rows can still proceed. PostgreSQL Read Committed and locking reads
Keep the lock through the check and the write. Committing after the read releases the lock and lets another transaction change the count before the write. Keep the transaction short because B holds a database connection while it waits. The gateway commits the reservation before the model worker starts a potentially long generation. PostgreSQL explicit locking and deadlocks
Check the version when saving
Consider a separate operations screen that lets an operator rename a worker pool. Reading the name and deciding what to enter might take minutes. Keep the version number from the read, then save only if the same version is still current. This is optimistic concurrency control. The application makes its decision without holding a lock across the read and edit, then checks for a conflict when it writes.
Suppose two operators load P3 with display name General at version 7. A renames it to Interactive. The update checks version 7 and stores version 8. B tries to save Priority using the previous version. Its update returns no row. The application loads the current name so the operator can decide whether to keep A's change or submit another one.
UPDATE pool_settings
SET display_name = $1,
version = version + 1
WHERE pool_id = $2 AND version = $3
RETURNING version;The WHERE clause and the mutation run together inside the database. A separate application read followed by an unconditional update would leave a gap for another writer. PostgreSQL still locks rows while executing successful updates. At Read Committed, a competing update can wait for the earlier write and then check its condition against the committed row. At Repeatable Read, a row changed after the transaction's snapshot can produce a serialization failure. PostgreSQL UPDATE · PostgreSQL transaction isolation
Checking an expected state can be enough for a one-way transition. For example, a ChatGPT worker can claim a pending turn by changing it to running with a condition on the current status. Use a version when a value can change and later look the same. A row going from General to Interactive and back to General has passed through new versions. Comparing only the name would miss both changes. Every writer that changes these settings must advance the version, including admin scripts and other screens.
Control waiting and retries
A deadlock occurs when transactions form a cycle of waits. Imagine one code path locks account A7 then asks for pool P3, while another locks P3 then asks for A7. If each gets its first lock, neither can get its second. PostgreSQL detects a deadlock and aborts one transaction. The application should recognize the error and, when the operation can be retried, start the entire transaction again with fresh reads and decisions.
Use one lock order for paths that acquire both rows, such as account then pool. A bounded lock wait prevents callers from spending their whole request budget on one row. PostgreSQL's lock_timeout applies to each lock acquisition. Keep the operation's overall deadline separately. Under heavy contention, bound retries and measure both lock wait and the rate of conflicts. Transaction retries may re-execute application code. Schedule external effects after commit or through a durable outbox when the send must survive a crash. PostgreSQL lock timeout · PostgreSQL transaction retry guidance
An optional queue variant is FOR UPDATE SKIP LOCKED. A locking read can pass over a locked pending row and claim another one. This can improve pickup by concurrent consumers while allowing later jobs to pass an earlier locked job. It gives a deliberately incomplete view of available rows, so use it where skipping a row is acceptable. PostgreSQL locking clause
Protect the resource that holds the rule
The pool limit has an existing row for every admission to consult. That makes a row lock a direct match for the rule. A unique alias is different. If neither transaction finds an existing spring alias, there is no selected alias row for FOR UPDATE to lock. Put a unique constraint on the alias and let the database arbitrate the two inserts. A constraint protects the rule for every writer to the table. PostgreSQL unique constraints
A version on one row covers edits to that row. A business rule spanning several rows needs a shared point of coordination or an isolation level that checks the transactions' combined behavior. A lock inside one gateway process covers its own tasks. Multiple gateway processes need the shared database or another authority to coordinate the same resource.
See also
- Concurrency vs Parallelism - see why tasks can race on a single application thread.
- ACID Transactions - commit the reservations and the accepted turn together.
- Isolation Levels and MVCC - follow the snapshots and update conflicts behind a lock.
- Distributed Locking and Fencing Tokens - protect a write after a worker's ownership expires.
Used in
- ChatGPT - admission locks the account and pool capacity rows before deciding whether to reserve a slot.
- URL Shortener - a unique alias constraint lets one create win even when competing requests see an available alias.
Done reading? Mark it so it sticks in your dashboard.