CppNoob
CppNoob

Reputation: 2390

Rails 4: Using ActiveRecord object from one thread in another

I have two threads. In one thread I fetch a record from the database as an ActiveRecord object. I then access this object from another thread.

Is there a problem with this usage? If the two threads use separate connections to the DB, which connection will be used if needed to access the AR object's associations, etc?

I have seen some questions on StackOverflow that speak about the pitfalls of connecting to the DB via ActiveRecord from different threads and the need for manually checking-in such connections. Does that have an impact on this issue?

Upvotes: 0

Views: 675

Answers (1)

Glyoko
Glyoko

Reputation: 2090

You've heard correctly. When using AR, you may find that you'll need to tiptoe around threads in weird ways to keep things stable... If you have a guarantee that you'll only ever have 2 threads, then you're probably safe at least as far as AR is concerned. (Of course, all the other pitfalls of concurrency–e.g. deadlocks, thread starvation, etc–still apply, so make sure to account for these.)

One thing to keep in mind is that each thread will use it's AR connection, so the pool field in database.yml must be high enough to accommodate all threads. If you're using a thread based webserver like Puma, then this can get even more complicated... If you're newer to rails, I would urge caution when dealing with threads and AR. It can be quite a rabbit-hole.

What's the purpose of having one thread fetch the object, and another access it? If you expect real speed benefits then it may be worth it, but since the activity of the second thread (operations on the AR record) is contingent on the result of the first thread, (loading of the AR record) then you may not see speed improvements since you'll need to wait for the first thread to finish to even begin using the second one. If your scenario doesn't do anything with the first thread after it's loaded up the object, I would absolutely recommend against this since you wouldn't see any speed improvements, but I don't know the whole scenario, and using threads may still make sense for your situation.

So in short, there's nothing stopping you from using threads with AR, but it is risky, and you can expect bugs to crop up in weird places unless your thread usage is conservative. It may still make sense for your app, but look into other solutions first and proceed with caution if you do go with threads.

Re "If the two threads use separate connections to the DB, which connection will be used if needed to access the AR object's associations": Each thread acquires its own AR connection, so the thread accessing the AR associations will use its own connection, irrespective of the thread that originally loaded the AR record.

What's the motivation for using threads in your app? There may be a better way of handling things.

Upvotes: 1

Related Questions