A database timeout means something waited longer than its limit: either a query took too long to run, or the app couldn't get a connection in time. The usual cause is one slow query, often on a table that has grown, or one missing an index, or rows locked by another long operation. Turn on slow-query logging to find it, then fix the query or add the index.
What's the problem
Pages are slow and then fail with "query timeout", "statement timeout", "Lock wait timeout exceeded", "MySQL server has gone away" or a 504. Often only some pages, or only at busy times.
Why it happens
- A slow query: scanning a whole large table because there's no index for it.
- Lock waits: one long operation (an import, a report, a migration) holds locks other queries need.
- An overloaded database: CPU or disk at its limit.
- Idle connections closed by the server, then reused by the app ("gone away").
- Network problems between app and database.
How to fix it
- Turn on slow-query logging. PostgreSQL:
log_min_duration_statement. MySQL: the slow query log. - Find the slowest and most frequent queries, and run them with
EXPLAINto see whether they use an index. - Add the missing index, or rewrite the query to fetch less.
- Move long jobs off busy times or into background workers.
- Check database CPU, memory and disk in your provider's dashboard.
- Configure your app's pool to check connections before reusing them.
What Preventionlabs checks
One click runs the full report on your domain. For this problem it shows whether your site loads, how fast, and where its redirects go; uptime checked every 5 minutes, with an email when the site goes down and when it is back. With Cloudflare connected, it also shows which pages returned server errors (5xx) to visitors, and when; recent deploys and account changes, with their times. It can't connect to your database, so the database error itself is in your host's or database provider's logs.
Run your free reportYour first report is free, no card needed. Then A$50 a month, up to 10 domains. Read-only: it never changes anything.
Sources
- PostgreSQL: Client Connection Defaultsofficial docs
Abort any statement that takes more than the specified amount of time.
- PostgreSQL: Error Reporting and Loggingofficial docs
Causes the duration of each completed statement to be logged if the statement ran for at least the specified amount of time.
- MySQL: MySQL server has gone awayofficial docs
The most common reason for the MySQL server has gone away error is that the server timed out and closed the connection.