This is something I've never quite managed to master, and want to know if I am doing it right and have it sanity checked.
....
I have a database links
, lets keep it simple, 2 columns
ID int(10) PK, Status enum('ready', 'in progress', 'complete'); 1 'ready' 2 'ready' 3 'ready'
....
I then have an API that when queried returns the ID of a 'ready' item, this API could be called many time concurrently and I want to ensure that the ID is only given out once.
....
API MySQL queries..
LOCK TABLES `links` WRITE SELECT ID FROM links WHERE status = 'ready' LIMIT 1 // gets a ready one UPDATE links SET status = 'in progress' WHERE ID = 'X' // updates the one just got from line above to be in progress (so not selected by another API call UNLOCK TABLES
So if two API calls hit it 0.01 seconds apart, the first one should lock the tables update it to in progress, after unlock the second one gets it's chance and does the same but selects a different ID to that the first one got.
Is this correct? or the best way to do such a thing? As it seems to cause long delays on MySQL traffic with some queries waiting 5 minutes or so and then MySQL hits max connections and that causes all sorts of other problems.
The table is InnoDB and is relatively small with approximately 165k rows, with an index on status, thank you in advance for any advice or pointers.