# Add Query Timeouts to a Flask and SQLAlchemy App

Yes. An agent sets a statement timeout per database through SQLAlchemy connect_args, keeps SQLite on its busy timeout, and maps a cancelled query to a 503.

[Run this on Rush](https://cloud.getrush.ai/run/add-query-timeouts/sqlalchemy/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

In a Flask app laid out like miguelgrinberg/microblog, `config.py` builds `SQLALCHEMY_DATABASE_URI` from `DATABASE_URL` or falls back to `sqlite:///app.db`, with no `SQLALCHEMY_ENGINE_OPTIONS`, so no query has a time limit anywhere. The drivers are `psycopg2-binary==2.9.9` from `requirements.txt` for PostgreSQL and `pymysql`, which the `Dockerfile` installs with `pip` beside `gunicorn`, for MySQL. `app/errors/handlers.py` registers a 500 handler that calls `db.session.rollback()` and answers JSON or HTML by `wants_json_response()`, and `app/api/errors.py` has `error_response(status_code, message)` for the API blueprint. The queries most likely to run long are the paginated feeds in `app/main/routes.py` and the `User.following_posts` join over the `followers` table in `app/models.py`; the RQ worker in `app/tasks.py` runs `export_posts` against the same database with the same `Config`.

A statement timeout is a driver and server setting, not an ORM one, so the agent sets it through `connect_args` in `SQLALCHEMY_ENGINE_OPTIONS`, chosen by the URI's scheme. For `postgresql` with psycopg2, `connect_args={'options': '-c statement_timeout=<ms>'}` makes the server cancel any statement that runs past the limit on that connection; for `mysql+pymysql`, `connect_args={'init_command': 'SET SESSION MAX_EXECUTION_TIME=<ms>'}` does the same for `SELECT` statements, which is what MySQL's limit covers; for `sqlite`, `connect_args={'timeout': <seconds>}` is the busy timeout, how long a connection waits for a lock, which is the only kind of waiting SQLite has. The milliseconds come from a `DB_STATEMENT_TIMEOUT_MS` variable, and the option is set only when the variable is: with it unset, the engine is built exactly as today. `tests.py` runs on in-memory `sqlite://` through `TestConfig` and sees no change.

A cancelled statement surfaces as `sqlalchemy.exc.OperationalError` wrapping the driver's error (psycopg2's `QueryCanceled`, SQLSTATE `57014`, with `canceling statement due to statement timeout`), and today that is an unhandled exception that becomes the 500 page. The agent registers a handler for `OperationalError` in `app/errors/handlers.py` that rolls the session back, logs the statement's first line through `app.logger`, and answers 503 with a one-line message, JSON through `error_response` for API callers or a template for the browser, so a slow page fails fast with a reason instead of a generic error. Any other `OperationalError` keeps the existing 500 path, since a lost connection is not a timeout.

Proof runs against PostgreSQL in the sandbox: the agent installs it with `apt-get`, creates a database, sets `DATABASE_URL` and `DB_STATEMENT_TIMEOUT_MS`, runs `flask db upgrade` over the nine migrations, and in `flask shell` runs `db.session.execute(sa.text('select pg_sleep(3)'))` with a limit below that, quoting the `QueryCanceled` error, then runs a normal query on the same session to show the rollback left it usable. It starts the app, requests a page after forcing the same cancellation inside a request to show the 503 and its log line, then runs `python tests.py` to show the SQLite path is unchanged. The worker reads the same `Config`, so the pull request notes that a long maintenance query in a task needs a higher value in that process's environment.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add query timeouts to this Flask and SQLAlchemy app. Read config.py, app/__init__.py, app/errors/handlers.py, app/api/errors.py, app/models.py, app/main/routes.py, app/tasks.py, requirements.txt, Dockerfile and tests.py first. Add SQLALCHEMY_ENGINE_OPTIONS with connect_args chosen by the URI scheme and a DB_STATEMENT_TIMEOUT_MS variable: statement_timeout through psycopg2's options for postgresql, MAX_EXECUTION_TIME through pymysql's init_command for mysql, and the busy timeout for sqlite; set nothing when the variable is unset. Register an OperationalError handler that rolls back, logs, and answers 503 for a cancelled statement, JSON or HTML by wants_json_response, and leaves other OperationalErrors on the 500 path. Install PostgreSQL in the sandbox, run flask db upgrade, show pg_sleep being cancelled in flask shell and the session still usable, show the 503 from a request, and run python tests.py. Quote all of it. Open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that changes `config.py` and `app/errors/handlers.py` and adds one error template under `app/templates/errors/`. The description quotes the `QueryCanceled` line from `flask shell`, the query that succeeded on the same session afterwards, the 503 response and its log line, and the `python tests.py` result, and gives the three `connect_args` forms side by side with which database each applies to.

The run's record keeps the PostgreSQL setup, the shell session and the request, so a reviewer can see the cancellation and the recovery as they happened rather than as a summary.

Before merging, a reviewer picks the value of `DB_STATEMENT_TIMEOUT_MS` for the web process from their slowest acceptable page, sets a higher one or none for the RQ worker, and decides whether the API's 503 should carry a `Retry-After` header, which is one line in the handler.

## Run it on every slow request alert

The timeout turns a hung page into a logged 503, and the log line is the trigger for the next job. A Grafana alert on the count of those lines posts to an automation's `webhook` trigger URL with the `Authorization: Bearer <its secret>` header Grafana's contact point can send; the automation's prompt asks the agent to read the statement named in the alert, find it in `app/models.py` or `app/main/routes.py`, run `EXPLAIN ANALYZE` on it against a database seeded from the migrations, and open a pull request with an index or a rewritten query and the plans quoted. The webhook's body reaches the agent after the prompt as event text, and `max_runs_per_hour` keeps a noisy alert from opening a pull request a minute.

A monitoring service that cannot send that header calls a handler on the reader's server, and the handler calls `POST /o/{org}/sessions` with a `request_id` that is a UUID v5 of the alert id, so a repeated notification returns the run already started.

## Why run it on Rush?

A query timeout is three different settings on three databases plus an error path, and the only way to know the error path is right is to cancel a real statement and watch what the app does next. In a Rush sandbox the agent has a PostgreSQL of its own, cancels a `pg_sleep` on purpose, and shows the session recovering and the 503 rendering, so the pull request proves the whole path from server to browser.

The shell session, the request and the test run stay in the run's record and the pull request quotes them, so review is reading two files against evidence rather than reasoning about driver options. A team with several Flask services runs the job on each at once, one sandbox and one pull request each, each with the `connect_args` its own driver takes.

## Frequently asked questions

### Why connect_args rather than a SQLAlchemy option?

Because the timeout is enforced by the database server, and each driver has its own way to ask for it: psycopg2 passes `options` to PostgreSQL at connect, pymysql runs an `init_command`, and sqlite3 takes a `timeout` for locks. SQLAlchemy only forwards `connect_args` to the driver, which is why the options are chosen by the URI's scheme in `config.py`.

### Does this limit the RQ worker's queries too?

Yes, by default, since `app/tasks.py` builds its app from the same `Config`. The value comes from the environment, so the worker process can be given a higher `DB_STATEMENT_TIMEOUT_MS` or none in its supervisor configuration; the pull request says so rather than special-casing the worker in code.

### What does the user see when a query is cancelled?

A 503 with a one-line message, as JSON for an API caller or a page for the browser, after the session has been rolled back so the next request on that connection works. Before this change the same cancellation would have been an unhandled exception and the generic 500 page.

### Why is SQLite handled differently?

SQLite has no statement timeout; its `timeout` is how long a connection waits for a lock held by another writer. Setting it is still useful, since a locked database is the way SQLite stalls, and leaving the statement timeout to the server databases keeps `tests.py`, which runs on in-memory SQLite, exactly as it is.

## More SQLAlchemy jobs

- [Add Slow Query Logging to a Flask + SQLAlchemy App](https://getrush.ai/run/add-slow-query-logging/sqlalchemy/)
- [Add Soft Delete to SQLAlchemy Models](https://getrush.ai/run/add-soft-delete/sqlalchemy/)
- [Fix "Can't load plugin: sqlalchemy.dialects:postgres" in a Flask App](https://getrush.ai/run/fix-cant-load-plugin-sqlalchemy-dialects-postgres/sqlalchemy/)

## The same job on other stacks

- [Add Query Timeouts to a sqlc Project](https://getrush.ai/run/add-query-timeouts/sqlc/)
- [Add Query Timeouts to a TypeORM + NestJS App](https://getrush.ai/run/add-query-timeouts/typeorm/)
- [Add Query Timeouts to a Drizzle and postgres.js Setup in Next.js](https://getrush.ai/run/add-query-timeouts/drizzle/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
