🤖 Ai回答: In MySQL, the `wait_timeout` system variable controls how long a connection to the MySQL server can remain idle (i.e., without any activity) before it is automatically closed by the server.
✅ What is `wait_timeout`?
Default value: Usually 8 hours (28,800 seconds), but may vary depending on MySQL version and configuration.
Applies to: All client connections that are idle (no queries, no data transfer).
Does NOT apply to: Active connections performing queries or transactions.
Scope: Global and Session level — can be set globally for all connections or per session.
Then restart MySQL service for changes to take effect.
🔄 Related Variable: `interactive_timeout`
Similar to `wait_timeout`, but applies to interactive clients (like mysql CLI) instead of non-interactive ones (like PHP, Python scripts, etc.).
Often set higher for interactive sessions (e.g., 28800).
❗ Important Notes
Connection loss: If a client is idle longer than `wait_timeout`, it will lose its connection、The client must reconnect if needed.
Application impact: Long-running applications may need to handle reconnection logic if they’re affected.
Security: Shorter timeouts help reduce resource usage and potential security risks from idle connections.
Performance: Too short a timeout may cause legitimate long-running operations to disconnect prematurely.
🔍 Example Scenario
You have an application that connects to MySQL via a script that runs every 5 minutes、If `wait_timeout` is 28800 (8 hours), your script won’t be affected、But if you set it to 300 (5 minutes), the connection might close between script runs — so your app needs to handle reconnecting.
✅ Best Practices
Set `wait_timeout` based on your application’s behavior (e.g., 60–300 seconds for web apps).
Use `interactive_timeout` for interactive sessions if different behavior is needed.
Always test changes in staging before production.
Consider using connection pooling (e.g., with libraries like `mysql-connector-python`, `Druid`, or `HikariCP`) to manage connections efficiently.
🧪 Test Connection Timeout
You can simulate an idle connection by running this:
sql
Connect to MySQL
Do nothing for 10 minutes
Then check if connection still alive
SELECT CONNECTION_ID();
If connection was closed, you’ll get an error when trying to query.
Let me know if you want to configure `wait_timeout` for specific users, or troubleshoot connection drops!