A small document archive gives every file it takes in a permanent ID number. The number comes from a counter kept in a SQLite ledger, and the file is stored in a folder named after it. For a long time only one program wrote to that ledger: the archive’s own backend. Then a desktop registrar started bringing files in through a second door, and it asked the same ledger for numbers.

Read, then write, in two steps

The function that handed out a number did two things in sequence. It read the counter’s next value, and then, in a separate statement, wrote that value plus one back. With a single caller, that is fine. With two programs running as different processes, nothing stops both of them from reading the same value before either has written the new one. Both walk away with the same ID.

That was the theory. To see whether it happened in practice, we ran the issuing function from four processes at the same time. Of 160 numbers issued, 120 overlapped with a number another process had also been given. The duplicates did not silently overwrite anything: the registration that came second found that a folder with that ID already existed and failed. So the visible symptom would have been registrations failing for no obvious reason, not files being lost.

The log I am working from records this repro, not a duplicate seen in normal use. Whether the two doors ever collided on real files before the fix is not recorded.

One statement instead of two

The fix was to make reading and advancing the counter a single statement: an UPDATE that adds one to the counter and uses RETURNING to hand back the value it just claimed. The same statement also refuses to go past the counter’s capacity, so the “is there room left” check moved inside it as well. There is no longer a gap between reading and writing for another process to land in.

The same four-process run after the change: 0 overlaps. A short note went into the project’s own rules, next to the line explaining that two different processes register into the same ledger, so the next person who touches that function knows why it is written as one statement.

What this does not cover: the test was four processes on one machine, not every way the two programs might be run. And the repro shows the old code could collide, not how often it would under ordinary use, where the two doors are rarely busy at the same moment.

The counter code had been correct for as long as it had one caller. It stopped being correct the day a second program was pointed at the same ledger, without a line of it changing. When something that hands out unique values gains a second user, check whether “read, then write” is still one step.