Object saving best practices and the DB connection pool

The Rails guide says this about the database connection pool

Any one request will check out a connection the first time it requires access to the database. At the end of the request it will check the connection back in. This means that the additional connection slot will be available again for the next request in the queue.

I take this to mean that it is best practice within a controller action to push DB queries and saves to the end of the action so the connection is held for a shorter period of time.

For example, if I have an action that uploads some images sent from the client to another server and then saves the location of those images and some other data to the DB then it’d be better to do all the image uploads first before making any DB queries. Is this generally right?

Furthermore, is it generally best practice to have more complicated model methods avoid calling save or any other DB mutating methods so that they can be composed together in a single or small number of save calls at that end?

You need to ensure there are enough connections available for all your application server and worker instances in the first place. If you undersize it, you’re going to get a lot of ActiveRecord::ConnectionTimeoutError exceptions when your current server parallel capacity maxes out.

This applies more towards limiting the amount of time spent in a database transaction (and holding locks other DB operations depend on)

Not necessary I believe. Rails will commit / rollback them atomically in a single database transaction.

Thank you for the reply!

These transactions are not created automatically for every Action, right?

If I have this


then a failure in obj2.save! will not rollback obj1.save! unless I explicitly put it in a transaction somewhere, right?

My bad, transactions aren’t created atomically per save

I was thinking about multiple saves triggered by AR callbacks which I believe are wrapped in a transaction.