3 ms·
This: INSERT INTO locks (id, lock, revision) VALUES ('Tom', true, 1) IF NOT EXISTS USING TTL 20; looks like a race condition. The same problem co
by Animats 10y ago
This:
INSERT INTO locks (id, lock, revision)
VALUES ('Tom', true, 1)
IF NOT EXISTS USING TTL 20;
looks like a race condition. The same problem comes up in SQL databases - you can't lock a row that doesn't exist yet. If you write, in SQL:
BEGIN TRANSACTION
SELECT FROM locks WHERE id = "Tom" AND lock = true AND revision = 1;
-- if no records returned
INSERT INTO LOCKS locks (id, lock, revision) VALUES ('Tom', true, 1)
COMMIT
you have a race condition. If two threads make that identical request near-simultaneously, both get a no-find from the select, and both do the INSERT.
SELECT doesn't lock rows that don't exist.
The usual solution in SQL is to use UNIQUE indices which will cause an INSERT to fail if the record about to be inserted already exists.
I ran into this reassembling SMS message fragments, where I wanted to detect that all the parts had come in. The right answer was to do an INSERT for each new fragment, then COMMIT, then do a SELECT to see if all the fragments of a message were in. Doing the SELECT first produced a race condition.
- dhd415 10y agoSome SQL databases (e.g., SQL Server and PostgreSQL) offer key-range locking which, along with a serializable isolation level, will prevent this race condition.
- chillaxtian 10y agothis is not a race in cassandra. IF NOT EXISTS causes replicas to agree on the result using PAXOS, and only responds with success if a certain number of replicas concur + write the transaction to disk. i believe it is a quorum for SERIAL consistency level, and local quorum (quorum of replicas in the local DC) for LOCAL_SERIAL.
- linuxhansl 10y agoON DUPLICATE KEY is another construct that is used in some DB (MySQL or HBase with Apache Phoenix and others).