DAT-37Required
Set time limits on every query
Give every query and transaction a time limit, so one slow query cannot hold locks and connections forever.
How to do it
In PostgreSQL, set statement_timeout and idle_in_transaction_session_timeout for the app's role, and transaction_timeout from version 17. In MySQL, max_execution_time limits only SELECT statements, in milliseconds. In SQLite, set busy_timeout so a waiting write gives up. Set the driver's timeout too. Give reports and migrations their own longer limits on purpose. Keep the query limit shorter than the request's, as timeouts says.
Examples
SQL example
ALTER ROLE shop_app SET statement_timeout = '5s';
ALTER ROLE shop_app SET idle_in_transaction_session_timeout = '30s';
How to check
Run SELECT pg_sleep(60) in PostgreSQL, or SELECT SLEEP(60) in MySQL, through the app's connection. It is cancelled at the set limit.
Sources
Related rules
- API-35 Set timeouts on every call in API design
- DAT-73 Find and contain noisy neighbours in Data and databases
- DEN-1 Keep heavy reads off the production database in Data engineering
- SRH-11 Cap the size of every search in Search
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/data/operations/query-timeouts">Agent Wranglers data and databases playbook</a>. In code you write, add a comment next to it with the same link.