A
A
Anton Ivanov2017-11-13 06:28:54
Ruby on Rails
Anton Ivanov, 2017-11-13 06:28:54

How safe is it to keep the model in a separate thread?

Hello.
There is a model that can persist for quite a long time. About a second, but for a web application this is critical.
How justified is this approach?

Thread.new do
  model_instance.save
end

the fact that the model survived is not particularly important. In 99.99% of cases, it will be saved, errors will still get into the log.
The question is, will I not step on some kind of rake if the request is already completed, and the model has not yet been saved? Since the model is saved almost before the response is sent to the user.
Server - puma
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Viktor, 2017-11-13
@Fly3110

It is likely that here you can already think about some tools for working with background tasks and give something "long-playing" there.
But, if it’s specific to the case, then you need to keep in mind that each thread will be opened with its own connection to the database, which then will need to be closed by hand inside the block after saving:

Thread.new do
  model_instance.save
  ActiveRecord::Base.connection.close
end

Or perform actions inside the thread using an existing connection from the pool:
Thread.new do
  ActiveRecord::Base.connection_pool.with_connection do
    model_instance.save
  end
end

E
Evgeny Kozlov, 2017-11-13
@lebron32rus

I would start with the db. Analyzed the query plan, optimized the query. Finding out the reason why the database takes a long time to execute a query is paramount.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question