Say I have a table where I want to use a serial
as primary key to ask for changes from the client. The client will ask "give me the changes after key X". Without using SERIALIZABLE
isolation level or locking, this is prone to race conditions.
Transaction A can start first, and do its writes, then take a long time to commit. Meanwhile transaction B will start and commit, before A commits. The write from B will get a higher primary key than the write from A. If a client now asks for changes it will miss the still uncommitted write from A, and note the newest highest primary key. So even after A commits, the client will never see that change, because its key is lower than the change the client already got.
Is it possible to make the value of a serial
(or similar from a counter) be determined atomically at commit time so that we are guaranteed that it will be higher than all others when committed, and lower than all which will be committed after it? If not what is the best way to solve this problem?