I have two application servers running Ruby on Rails sharing the same MySQL database server, using InnoDB engine.
Sometimes under heavy load I find that IDs from the records are skipped in the table Users, X and Y and are not sequential.
This is the pseudo code:
user = Create user x in table Users
user_x = Find user x
Insert a tuple into an auxiliary table X
Insert a tuple into an auxiliary table Y
Update the tuple that was inserted in table X
Insert a tuple into an auxiliary table Z
Tables X, Y, Z, are all related in someway, and I am not deleting any records.
However, I find that sometimes record IDs will skip one or two during heavy load.
Would transaction help with this case?
Start transaction
user = Create user x
user_x = Find user x
Insert a tuple into an auxiliary table X
Insert a tuple into an auxiliary table Y
Update the tuple that was inserted in table X
Insert a tuple into an auxiliary table Z
Commit
Noobie question, this code works fine when there is no load, but once if there is a load. ie multiple users hitting the same resource at the exact same time, then the above happens. Would a transaction help?
What disadvantages would there be to wrap everything in transaction blocks?
I’m not sure about MYSQL, but in Postgres ids are only allocated once from the autoincrementing sequence and will be unused if a transaction is rolled back or aborted.
You’re best off looking at why it is a problem that some ids are skipped. Anything relying on them to be sequential is suspect.
Are you using Foreign Keys between Users and tables X, Y, and Z? Or does the relationship depend on the ids incrementing in parallel?