Remo Remo - 2 months ago 8
Ruby Question

Ensure consistency when caching data in after_commit hooks

For a specific database table, we need an in-memory cache of this data that is always in-sync with the database. My current attempt is to write the changes to the cache in an

after_commit
hook - this way we make sure not to write any changes to the cache that could get reverted later.

However, this strategy is vulnerable to the following scenario:


  1. Thread A locks and updates record, stores value
    1

  2. Thread A commits the change

  3. Thread B locks and updates record, stores value
    2

  4. Thread B commits the change

  5. Thread B runs the
    after_commit
    hook, so the cache now has value
    2

  6. Thread A runs the
    after_commit
    hook, so the cache now has value
    1
    but should have value
    2



Am I right about this problem and how would one solve this?

Answer

The solution we came up with is to lock the cache for read / write before_commit and unlock it in the after_commit. This seems to do the trick.

Comments