I'm developing a relatively simple, custom web app with a MySQL MyISAM database on the back end. Somehow, I want to avoid the classic concurrency overwrite problem, e.g. that user A overwrites user B's edits because B loads and submits some edit form before A is finished.
That's why I would like to somehow lock a row on displaying the edit form. However...
As I said, I'm using MyISAM, which, as far as I can tell, doesn't support row-level locks. Also, I'm not sure if holding 'real' MySQL locks for a couple of minutes is recommended practice.
I don't really know much about transactions, but from what I've seen, it looks like they're meant to be used inside one connection.
Using some kind of conflict merge system like Git has is not an option really.
Rows would stay locked for a few minutes. Concurrency is very low: there's half a dozen users using the app at any time.
I'm now planning on using a table with details on which user is doing what, and since when. The app can then decide to not show the edit form when some other user recently opened it (e.g. is working on it). This fake lock would be deleted on saving the form.
Would this work? What should I do to avoid deadlocks, livelocks and all that stuff?
You could implement a lock, the easiest would probably be adding two fields to the data you want locked (lock_created Datetime, locked_by int). Then on the edit page (and probably also on the edit button) you check wether (lock_created + lock_interval) < now() - if not, the data is locked for editing and the user should be informed. (Note you always need the check on the edit-page, not just on the edit button.)
Also on the submission page, you need to check the user still has the lock to submit. (See below.)
The one difficult part of this is what to do when someone edits but fails to submit within the lock interval.
So:
The lock_interval is 2 minutes.
At time 0:00 Alice locks the page, edits something, but gets a phone call and doesn't submit her changes
At time 2:30 Bob checks the page, gets the edit lock because Alice's lock has expired, and edits
At time 3:00 Alice gets back to her comp, presses submit -> conflict.
Someone doesn't get their data submitted. There is no way around that if you set locks to expire. (And if you don't, locks can be left forever.)
You can only decide which one to give priority (going with the new lock created by Bob is probably easiest) and inform the other the page has expired and the data won't be sumbitted, and hand them back their edits to redo them.
A note on the table structure: you could create a table 'locks' with fields 'table_name, row_id, lock_created, locked_by' but it probably won't be the easiest way, since joining on variable table names is complex and confusing. Also, there is probably no use to have a single place for all locks to be stored. For a simple mechanism, I think adding uniform fields to every table you want to implement the locking mechanism is easier all around.
You should absolutely not use row-level locks for this scenario.
You can use optimistic locking, which basically means that you have a version field for each row, which is incremented when the row is saved. Before save you make sure that the version field is the same as what it was when the row was loaded, which means that noone else has saved anything since you read the row.
Related
I have discovered a doctrine article about locking : http://doctrine-orm.readthedocs.org/en/latest/reference/transactions-and-concurrency.html?highlight=locking#locking-support
I understand that in some cases involving multiple requests, there is a need to lock tables.
It's not clear for me when do we need to do that. Can someone provide basic use cases where we absolutely need this? Or a more precise definition of what is a case when we need to do it?
For example, say user 1 accesses an entity modification page, and user 2 accesses it after user1. If user1 submits a change request and user2 who had already loaded the data before user1 submit now pushes the update button after user2 has updated the entity, do we need to lock tables ?
Explicitly locking database tables/rows is seldom needed in a web based application and should be avoided. Never lock something while awaiting requests.
Consider what would happen if user 1 check out an entity, locks the table/row and then goes to lunch. Now your database might be locked for an hour or more frustrating other users. And after lunch your user gets run over by a bus. Oopsy.
Doctrine 2 has several built in approaches for concurrency: http://doctrine-orm.readthedocs.org/en/latest/reference/transactions-and-concurrency.html#locking-support. Read carefully and understand which approach is best for your case.
In general you will want to use optimistic locking which assumes that multiple users updating the same record at the same time is a fairly rare event. The first user to update wins. Versioning is used to prevent subsequent users from overriding changes made by the first user. The other users will have to redo their changes but that is better than having incorrect data being entered.
I have a web form that is used to create and update personal information. On save, I collect all the info in a large multidimensional JSON array. When updating the database, the information will potentially consists of three parts. New rows to be created, rows that need to be updated and rows that need to be deleted. These rows will also be across about 5 tables.
My question is this, how should I approach the MySQL queries? My initial thought was to DELETE all the information from all the tables, and do a clean INSERT of all the new information in one go. I guess the other approach would be to do 3 queries: UPDATE all those with an existing ID; DELETE all those marked for deletion and INSERT all the newly created data (data without existing ID's).
Which of these approaches would be best, or is there a better way of doing this? Thanks for any advice. I appreciate it.
delete all and insert all should NEVER be practiced.
reasons:
Too much costly. mostly user performs edit. so for what was just a few update, you did one delete and a hundred inserts.
plays havoc with on-delete-cascade foreign keys.
upsets auto-increment fields even when they were apparently not touched.
you need to implement unit-of-work. I dont know which language you are working with, but some of the languages have an inbuilt support for that. in dot-net we have DataSets.
Basics:
Keep track of each record you fetched from database. secretly maintain a flag for each record to note which were loaded-from-db (ie. untouched), which has modifications (needs update query) and which are added new. for the deleted records, maintain a separate list (maybe of their IDs). How to achieve this feat is matter of separate discussion.
When user clicks Save, start a database transaction. this is not strictly part of current discussion, but is almost always done in similar conditions.
In the transaction, first loop through the deleted items array. fire a delete query for each of them.
Then loop through the modified items array. for each modified item you may simply update all of its columns to the latest values. if the numer of columns is too large (>30) then things change a bit.
then comes the newly created items. fire one insert for each of them.
Finally commit the transaction.
if the language you are programming in supports try/catch blocks then perform all of the above steps (after begining transaction) in try/catch. in catch block rollback the transcation.
this approach looks more complicated and seems to fire more queries than the simple delete/insert/all approach but trust me we have been there, done that and then spent sleeples nights undoing all that was done. never go the delete/insert way unless you can really justify it.
on how to do the change-tracking thing, it depends a lot on language and type of application you are using. even for dot-net the approach differs for desktop applications and web applications. tracking deletions is easy. so as tracking new insertions. the update marks are applied by trapping the edit event on any of the columns of that field.
EDIT
The data spans about five tables. hence the three loops (delete/update/insert) has to be done five times, one for each table. first draw the relationships among the tables. process the top table first. then process the tables which are directly connected to the top level tables and so on. if you have a cyclic relationship among the tables then you have to be specially careful.
The code against the Save operation is about to grow quite long. 5x3=15 operations, each with its own sql. none of these operations are expected to be reusable hence putting them in separate methods is futile. everything is about to go in a large procedural block. hence religiously comment the code. mark the table boundaries and the operations.
You probably don't want to do any deletes. Just mark the obsolete entries as "inactive", or maybe timestamp them as having an ending validity.
In using this philosophy, all edits are actually insertions. No modifications (except to change the "expire" field) and no deletes. To update a name, mark the record as expired and insert a new record with a beginning validity timestamp at the same time.
In such a database, auditing and data recovery are easily performed.
Sometimes you are required to keep your log and records for criminal prevention purpose.
When you give users the permission to delete record, it means that you'll lose evidences.
In ordinary cases, do you actually delete record? or switch the undisplay flag to keep log?
If you allow any modification to data then you will lose evidence. Maybe you should design your database so you never use UPDATE or DELETE, only INSERT.
Unless the government has told you to keep all records, I recommend not going too much out of your way to do it.
Apart from keeping records for auditing purposes as you mention, the use of a 'Deleted' flag also allows you to incorporate 'undo' functionality.
If you physically delete data, then it will be quite a bit of work to get the old data back. But if you use flags then it can be as easy as re-setting the flag to get the data to re-appear.
If a lot of deletes happen in your database, then the downside of flags is that you will be holding on to a lot of data that isn't being used.
You can instead of just deleting is first insert the record into a history table for any type of modification that happens. Then you will always have the data available without having needless information in your main table
I have noticed that using something like delayed_job without a UNIQUE constraint on a table column would still create double entries in the DB. I have assumed delayed_job would run jobs one after another. The Rails app runs on Apache with Passenger Phusion. I am not sure if that is the reason why this would happen, but I would like to make sure that every item in the queue is persisted to AR/DB one after another, in sequence, and to never have more than one write to this DB table happen at the same time. Is this possible? What would be some of the issues that I would have to deal with?
update
The race conditions arise because an AJAX API is used to send data to the application. The application received a bunch of data, each batch of data is identified as belonging together by a Session ID (SID), in the end, the final state of the database has to include the latest most up-to date AJAX PUT query to the API. Sometimes queries arrive at the exact same time for the same SID -- so I need a way to make sure they don't all try to be persisted at the same time, but one after the other, or simply the last to be sent by AJAX request to the API.
I hope that makes my particular use-case easier to understand...
You can lock a specific table (or tables) with the LOCK TABLES statement.
In general I would say that relying on this is poor design and will likely lead to with scalability problems down the road since you're creating an bottleneck in your application flow.
With your further explanations, I'd be tempted to add some extra columns to the table used by delayed_job, with a unique index on them. If (for example) you only ever wanted 1 job per user you'd add a user_id column and then do
something.delay(:user_id => user_id).some_method
You might need more attributes if the pattern is more sophisticated, e.g. there are lots of different types of jobs and you only wanted one per person, per type, but the principle is the same. You'd also want to be sure to rescue ActiveRecord::RecordNotUnique and deal with it gracefully.
For non delayed_job stuff, optimistic locking is often a good compromise between handling the concurrent cases well without slowing down the non concurrent cases.
If you are worried/troubled about/with multiple processes writing to the 'same' rows - as in more users updating the same order_header row - I'd suggest you set some marker bound to the current_user.id on the row once /order_headers/:id/edit was called, and removing it again, once the current_user releases the row either by updating or canceling the edit.
Your use-case (from your description) seems a bit different to me, so I'd suggest you leave it to the DB (in case of a fairly recent - as in post 5.1 - MySQL, you'd add a trigger/function which would do the actual update, and here - you could implement similar logic to the above suggested; some marker bound to the sequenced job id of sorts)
I am designing a system and I don't think it's a good idea to give the ability to the end user to delete entries in the database. I think that way because often then end user, once given admin rights, might end up making a mess in the database and then turn to me to fix it.
Of course, they will need to be able to do remove entries or at least think that they did if they are set as admin.
So, I was thinking that all the entries in the database should have an "active" field. If they try to remove an entry, it will just set the flag to "false" or something similar. Then there will be some kind of super admin that would be my company's team who could change this field.
I already saw that in another company I worked for, but I was wondering if it was a good idea. I could just make regular database backups and then roll back if they commit an error and adding this field would add some complexity to all the queries.
What do you think? Should I do it that way? Do you use this kind of trick in your applications?
In one of our databases, we distinguished between transactional and dictionary records.
In a couple of words, transactional records are things that you cannot roll back in real life, like a call from a customer. You can change the caller's name, status etc., but you cannot dismiss the call itself.
Dictionary records are things that you can change, like assigning a city to a customer.
Transactional records and things that lead to them were never deleted, while dictionary ones could be deleted all right.
By "things that lead to them" I mean that as soon as the record appears in the business rules which can lead to a transactional record, this record also becomes transactional.
Like, a city can be deleted from the database. But when a rule appeared that said "send an SMS to all customers in Moscow", the cities became transactional records as well, or we would not be able to answer the question "why did this SMS get sent".
A rule of thumb for distinguishing was this: is it only my company's business?
If one of my employees made a decision based on data from the database (like, he made a report based on which some management decision was made, and then the data report was based on disappeared), it was considered OK to delete these data.
But if the decision affected some immediate actions with customers (like calling, messing with the customer's balance etc.), everything that lead to these decisions was kept forever.
It may vary from one business model to another: sometimes, it may be required to record even internal data, sometimes it's OK to delete data that affects outside world.
But for our business model, the rule from above worked fine.
A couple reasons people do things like this is for auditing and automated rollback. If a row is completely deleted then there's no way to automatically rollback that deletion if it was in error. Also, keeping a row around and its previous state is important for auditing - a super user should be able to see who deleted what and when as well as who changed what, etc.
Of course, that's all dependent on your current application's business logic. Some applications have no need for auditing and it may be proper to fully delete a row.
The downside to just setting a flag such as IsActive or DeletedDate is that all of your queries must take that flag into account when pulling data. This makes it more likely that another programmer will accidentally forget this flag when writing reports...
A slightly better alternative is to archive that record into a different database. This way it's been physically moved to a location that is not normally searched. You might add a couple fields to capture who deleted it and when; but the point is it won't be polluting your main database.
Further, you could provide an undo feature to bring it back fairly quickly; and do a permanent delete after 30 days or something like that.
UPDATE concerning views:
With views, the data still participates in your indexing scheme. If the amount of potentially deleted data is small, views may be just fine as they are simpler from a coding perspective.
I prefer the method that you are describing. Its nice to be able to undo a mistake. More often than not, there is no easy way of going back on a DELETE query. I've never had a problem with this method and unless you are filling your database with 'deleted' entries, there shouldn't be an issue.
I use a combination of techniques to work around this issue. For some things adding the extra "active" field makes sense. Then the user has the impression that an item was deleted because it no longer shows up on the application screen. The scenarios where I would implement this would include items that are required to keep a history...lets say invoice and payment. I wouldn't want such things being deleted for any reason.
However, there are some items in the database that are not so sensitive, lets say a list of categories that I want to be dynamic...I may then have users with admin privileges be allowed to add and delete a category and the delete could be permanent. However, as part of the application logic I will check if the category is used anywhere before allowing the delete.
I suggest having a second database like DB_Archives whre you add every row deleted from DB. The is_active field negates the very purpose of foreign key constraints, and YOU have to make sure that this row is not marked as deleted when it's referenced elsewhere. This becomes overly complicated when your DB structure is massive.
There is an acceptable practice that exists in many applications (drupal's versioning system, et. al.). Since MySQL scales very quickly and easily, you should be okay.
I've been working on a project lately where all the data was kept in the DB as well. The status of each individual row was kept in an integer field (data could be active, deleted, in_need_for_manual_correction, historic).
You should consider using views to access only the active/historic/... data in each table. That way your queries won't get more complicated.
Another thing that made things easy was the use of UPDATE/INSERT/DELETE triggers that handled all the flag changing inside the DB and thus kept the complex stuff out of the application (for the most part).
I should mention that the DB was a MSSQL 2005 server, but i guess the same approach should work with mysql, too.
Yes and no.
It will complicate your application much more than you expect since every table that does not allow deletion will be behind extra check (IsDeleted=false) etc. It does not sound much but then when you build larger application and in query of 11 tables 9 require chech of non-deletion.. it's tedious and error prone. (Well yeah, then there are deleted/nondeleted views.. when you remember to do/use them)
Some schema upgrades will become PITA since you'll have to relax FK:s and invent "suitable" data for very, very old data.
I've not tried, but have thought a moderate amount about solution where you'd zip the row data to xml and store that in some "Historical" table. Then in case of "must have that restored now OMG the world is dying!1eleven" it's possible to dig out.
I agree with all respondents that if you can afford to keep old data around forever it's a good idea; for performance and simplicity, I agree with the suggestion of moving "logically deleted" records to "old stuff" tables rather than adding "is_deleted" flags (moving to a totally different database seems a bit like overkill, but you can easily change to that more drastic approach later if eventually the amount of accumulated data turns out to be a problem for a single db with normal and "old stuff" tables).