Race condition in Web Application: Be aware and prevent it
What is race condition
Race conditions arise in software when an application depends on the sequence or timing of processes or threads for it to operate properly – wikipedia
Examples
- Let’s look at these 2 examples:
- Supposing we have a SQL table like this:idnamevalue
1 Monday 20 2 Tuesday 30 3 Wednesday 40 We know that `last_insert_id` is 3. If our webapp depends on this value when inserting new record, for example: “INSERT INTO calendar (id, name, value) VALUES (3+1, ‘Thursday’, 50)”, there will be case when we make above queries twice, at the same time (when we have more than 1 client make the same request at the same time)
- Supposing we have a SQL table like this:idnamevalue
1 Monday 20 2 Tuesday 30 3 Wednesday 40 And we have a Web form to edit those values.
If 2 clients open that Web Form at the same time to edit row with id == 3, there will be an unexpected result to 1 (and only one) client.
- Supposing we have a SQL table like this:
- Let’s look at these 2 examples:
Solution
- Supposing we have a SQL table like this:idnamevalue
1 Monday 20 2 Tuesday 30 3 Wednesday 40 Let’s add new column, call it: ‘last_modifiled’
idnamevaluelast_modified1 Monday 20 (null) 2 Tuesday 30 1434437200 3 Wednesday 40 1434437258 With every Edit transaction, instead of the classic query, like this:
`UPDATE calendar SET value = 50 WHERE id = 3`, we will add one more condition:
`UPDATE calendar SET value = 50 AND last_modified = UNIX_TIMESTAMP() WHERE id = 3 AND last_modifiled = 1434437258When 2 clients submit the Edit Form at the same time, our Web Application will check result from the above SQL query,
- if it’s successful with 1 row updated => nothing special, but
- if it’s successful with 0 row updated => race condition happened => we can be able to inform client right away (with the message, for example, ‘Someone made the changes, please refresh your page’) OR the application should refresh itself after informing clients.
- Supposing we have a SQL table like this:
Conclusion
- There’re many solutions to prevent race condition. I just want to mention how easy we’re gonna meet this issue in a web application and how important it is.
- Above is a solution suggested to prevent race condition. Any suggestion or discussion, please feel free to drop me an email at tuan_nh@septeni-technology.jp