> For the complete documentation index, see [llms.txt](https://ploegert.gitbook.io/til/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ploegert.gitbook.io/til/programmy/rails/set-statement-timeout-for-all-postgres-connections.md).

# Set Statement Timeout For All Postgres Connections

The [`statement_timeout`](https://github.com/ploegert/til/blob/master/programmy/rails/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-)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ploegert.gitbook.io/til/programmy/rails/set-statement-timeout-for-all-postgres-connections.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
