Search code examples
ruby-on-railsrails-activerecordheroku-postgres

Can Rails / ActiveRecord on Heroku with PG really be this slow?


In my Rails-application I need to prevent two people from being assigned the same case.

I do this by looking at an "events" table if the case has already been assigned. If not, it's assigned and a row is created saying that it's already assigned.

This all works - except that sometimes it doesn't. If two people try to access the same case at the same time (we're talking within the same couple of hundred milliseconds) it seems like the events-table isn't updated in time.

  1. Case is assigned User1. Saved to Events-table.
  2. User2 asks to be assigned the same case. Check Events-table if this case has already been assigned.
  3. The same case is assigned to User2, because the write from #1 hasn't been registered by the time we're checking on #2

I'm running Rails 5.0.2 with Postgres on Heroku (Standard-2X dyno and a Standard-2 Postgres).


Solution

  • Unfortunately it's not that uncommon for things like this to happen. If you want to avoid resource contention between multiple threads/requests, you can use ActiveRecord Locking to lock the Case record in question.

    I personally prefer pessimistic locking because it works out-of-the-box and in my opinion that's what those DB locks are for.