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:
      1. Supposing we have a SQL table like this:
        id
        name
        value
        1Monday20
        2Tuesday30
        3Wednesday40

        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)

      2. Supposing we have a SQL table like this:
        id
        name
        value
        1Monday20
        2Tuesday30
        3Wednesday40

        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.

  • Solution

    1. Supposing we have a SQL table like this:
      id
      name
      value
      1Monday20
      2Tuesday30
      3Wednesday40

      Let’s add new column, call it: ‘last_modifiled’

      id
      name
      value
      last_modified
      1Monday20(null)
      2Tuesday301434437200
      3Wednesday401434437258

      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 = 1434437258

      When 2 clients submit the Edit Form at the same time, our Web Application will check result from the above SQL query,

      1. if it’s successful with 1 row updated => nothing special, but
      2. 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.
  • 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

Add a Comment

Scroll Up