From 9f766c5dc2017e57da9ff6f0b7fca6551185c69a Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 16 Mar 2021 16:22:12 -0500 Subject: [PATCH] Add Set Statement Timeout For All Postgres Connections as a rails til --- README.md | 3 +- ...nt-timeout-for-all-postgres-connections.md | 39 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 rails/set-statement-timeout-for-all-postgres-connections.md diff --git a/README.md b/README.md index f7e9aa7..5b12af6 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1087 TILs and counting..._ +_1088 TILs and counting..._ --- @@ -711,6 +711,7 @@ _1087 TILs and counting..._ - [Set A Timestamp Field To The Current Time](rails/set-a-timestamp-field-to-the-current-time.md) - [Set default_url_options For Entire Application](rails/set-default-url-options-for-entire-application.md) - [Set Schema Search Path](rails/set-schema-search-path.md) +- [Set Statement Timeout For All Postgres Connections](rails/set-statement-timeout-for-all-postgres-connections.md) - [Set The Default Development Port](rails/set-the-default-development-port.md) - [Show Pending Migrations](rails/show-pending-migrations.md) - [Show Rails Models With Pry](rails/show-rails-models-with-pry.md) diff --git a/rails/set-statement-timeout-for-all-postgres-connections.md b/rails/set-statement-timeout-for-all-postgres-connections.md new file mode 100644 index 0000000..50eccaa --- /dev/null +++ b/rails/set-statement-timeout-for-all-postgres-connections.md @@ -0,0 +1,39 @@ +# Set Statement Timeout For All Postgres Connections + +The +[`statement_timeout`](postgres/set-a-statement-timeout-threshold-for-a-session.md) +setting in PostgreSQL allows you to head off long running queries and +migrations that could break your deploys and lock up your production tables. + +This value can be set to a sensible default across all the connections your +Rails app makes to PostgreSQL. To set it, open up your `config/database.yml` +file and add a `variables` element to the default section. + +```yaml +default: &default + adapter: postgresql + encoding: unicode + # For details on connection pooling, see Rails configuration guide + # https://guides.rubyonrails.org/configuring.html#database-pooling + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + variables: + statement_timeout: 60000 +``` + +That's 60 seconds in milliseconds. You can avoid the mental math by using a +string argument with a unit such as `s` for seconds. + +```yaml + variables: + statement_timeout: '60s' +``` + +If you then execute a long running query, such as: + +```ruby +ActiveRecord::Base.connection.execute('select pg_sleep(62)') +``` + +It will terminate 2 seconds early because of the statement timeout. + +[source](https://til.hashrocket.com/posts/b44baf657d-railspg-statement-timeout-)