MySQL Connections, Cursors, and SQL Cache

On this topic, MySQL is the simplest. One connection is one thread, and each time a statement arrives it is parsed, optimized, and executed. There is no execution plan cache, and the query cache that stored the result of the same SELECT was removed in 8.0. The only things the server keeps across sessions are table definitions, open table handles, and pages in the InnoDB buffer pool. This structure works because the optimizer is relatively light, and in exchange a complex statement pays the optimization cost on every execution.

Key Specs

ItemValue
ProtocolMySQL client/server protocol. Default TCP port 3306, Unix socket. The X protocol uses 33060
One connectionOne thread (Memory and Thread Architecture)
Maximum connectionsmax_connections (151) + 1 for an administrator. Per account max_user_connections (0 = unlimited)
AuthenticationAuthentication plugins. Default caching_sha2_password since 8.0
Idle connection timeoutwait_timeout and interactive_timeout, both 28,800 seconds (8 hours) by default
Connect timeoutconnect_timeout, default 10 seconds
Query modesText protocol (COM_QUERY), binary protocol (COM_STMT_PREPARE, COM_STMT_EXECUTE)
Execution plan cacheNone. Optimizes on every execution
Query (result) cacheNone. Removed in 8.0
Prepared statementsSeparate per session. Server-wide total limit max_prepared_stmt_count (16,382)
CursorsDECLARE … CURSOR in stored programs (read-only, forward-only), protocol cursors (COM_STMT_FETCH)
Default result deliverySends the entire result to the client
Table cachetable_open_cache (4,000), table_definition_cache (automatic)
Statement execution time limitmax_execution_time (milliseconds, default 0). Applies only to read-only SELECT

Connections

Figure. From connect to the first query

sequenceDiagram
  participant C as Client
  participant L as Connection manager thread
  participant T as Connection thread
  C->>L: TCP connection
  L->>T: Assign a thread (reuse one from the thread cache if available)
  T->>C: Initial handshake (server version, connection ID, authentication plugin, nonce)
  C->>T: Handshake response (user, authentication value, default schema), switch to TLS first if needed
  T->>C: Extra exchange depending on the authentication plugin
  T->>C: OK
  C->>T: COM_QUERY (SQL text)
  T->>C: Column definitions, rows, OK
  C->>T: COM_QUIT
  T->>L: Return the thread to the cache or terminate

Diagram notes: Time flows from top to bottom.

  1. The Connection manager thread accepts the TCP connection and assigns a Connection thread. The assigned connection thread performs authentication.
  2. Unlike PostgreSQL, the server speaks first. It sends an initial handshake containing the server version, connection ID, the authentication plugin to use, and a nonce, and the client returns the user name and an authentication value built from that nonce. For caching_sha2_password, the server caches the account's authentication result in memory; if it is cached, one exchange is enough, and if not, a full authentication using TLS or an RSA key takes place.
  3. After receiving OK, the client sends commands. A command starts with a type byte such as COM_QUERY (SQL text) or COM_STMT_PREPARE.
  4. When the connection ends, the thread returns to the thread cache (thread_cache_size) if there is room and waits for the next connection.

One command at a time. The client cannot send the next command on the same connection before it has received the whole response. To stop a running statement, run KILL QUERY <connection ID> from another connection. KILL CONNECTION (or KILL) also drops the connection.

Connection pools and session state. The server has no connection pool, so you use an application-side pool or a proxy (ProxySQL, MySQL Router). To make sure the previous user's session variables, temporary tables, prepared statements, and open transactions do not remain when a pool reuses a connection, send COM_RESET_CONNECTION. It resets only the session state without authenticating again.

LimitSetting (default)Description
Idle connectionwait_timeout (28,800 seconds)The server drops the connection if there is no command for this long. Keep the pool's connection lifetime shorter than this
Read and write waitnet_read_timeout (30 seconds), net_write_timeout (60 seconds)When the client stalls while sending or does not read the result
Connect errorsmax_connect_errors (100)Blocks a host when this many consecutive connection failures accumulate from it
Wait queueback_logNumber of connection requests before a connection thread is assigned
Per accountCREATE USER … WITH MAX_USER_CONNECTIONS nLimits the number of concurrent connections per account

Statement Processing

Figure. Text protocol and prepared statements

flowchart LR
  Q["COM_QUERY<br/>SQL text"] --> P["Parse"]
  SP["COM_STMT_PREPARE<br/>SQL text with question marks"] --> P
  P --> R["Resolve names, prepare<br/>tables, columns, privileges"]
  R --> PS["Prepared statement<br/>session memory, statement ID"]
  SE["COM_STMT_EXECUTE<br/>statement ID and parameter values"] --> PS
  PS --> O["Optimize<br/>on every execution"]
  R -->|"COM_QUERY goes directly"| O
  O --> E["Execute"]
  E --> RS["Result"]

Diagram notes: It proceeds from left to right.

  • COM_QUERY takes SQL text and performs Parse, Resolve names, prepare, Optimize, and Execute every time. Nothing remains after execution.
  • COM_STMT_PREPARE parses text containing ? placeholders, keeps the parsed and prepared result as a Prepared statement in that session's memory, and returns a statement ID. COM_STMT_EXECUTE sends only that ID and the parameter values, so it skips parsing.
  • On either path, Optimize runs on every execution. A prepared statement also does not store an execution plan; it re-chooses the join order and indexes using the parameter values and statistics at that time. So there is no problem like other DBMSs' parameter sniffing, but the only things a prepared statement saves are parsing and preparation.

You can also use prepared statements from SQL.

PREPARE ord_by_cust FROM 'SELECT * FROM orders WHERE cust_id = ?';
SET @id = 101;
EXECUTE ord_by_cust USING @id;
DEALLOCATE PREPARE ord_by_cust;
TopicDescription
ScopeA prepared statement is visible only to the session that created it and disappears when the connection ends
LimitPREPARE fails when the total across all sessions exceeds max_prepared_stmt_count. You hit it if an application does not close statements
Client-side emulationMany drivers by default do not have the server prepare statements; they embed values in the text and send it with COM_QUERY (Connector/J's useServerPrepStmts defaults to false, and PHP PDO's emulation is on by default)
Value passingThe binary protocol sends values as typed binary and receives results as binary. Values are not mixed into the text, which prevents SQL injection
Stored programsProcedures and functions cache the parsed form in that session the first time the session calls them (stored_program_cache, 256 per connection)

What the Server Caches

Figure. What is cached and what is not

block-beta
  columns 6
  t1["Caches shared server-wide"]:6
  bp["InnoDB buffer pool<br/>data and index pages"]:2 tc["Table cache<br/>open table handles"] td["Table definition cache<br/>dictionary object cache"] ac["Privilege cache<br/>authentication cache"] hc["Host cache"]
  t2["Per session"]:6
  ps["Prepared statements<br/>parse and prepare result"]:2 sp["Stored program cache"]:2 sv["Session variables<br/>temporary tables"]:2
  t3["Not cached"]:6
  n1["Execution plans"]:3 n2["Query results (removed in 8.0)"]:3
  class t1,t2,t3 plain
  class bp data
  class tc,td,ac,hc meta
  class ps,sp,sv slot
  class n1,n2 warn

Diagram notes: From top to bottom the sharing scope narrows, and the last row is what does not exist.

  • The Table cache holds the open handles a connection thread needs when it uses a table. Since a handle is needed for each session using the same table at once, many tables and many concurrent connections make table_open_cache too small, and tables get opened and closed repeatedly.
  • The Table definition cache and the dictionary object cache hold table structure. Since 8.0 the data dictionary lives in InnoDB tables, and this cache reduces reads of those tables.
  • The Privilege cache holds accounts and privileges in memory, and the Host cache holds the name resolution results for client IPs and connect error counts.
  • Execution plans are not cached. The query cache, which stored query results by text, had to discard all results of a table whenever the table changed and was protected by a single lock, so it became a bottleneck as core counts grew; it was deprecated in 5.7 and removed in 8.0. To cache results, do it in the application or a proxy.

performance_schema.events_statements_summary_by_digest holds execution statistics per statement shape (digest) with literals removed. It is statistics, not a cache, and you use it to see how often and for how long each shape of statement runs.

Result Sets and Cursors

ModeHow to openBehavior
Buffered (default)mysql_store_result in the C API, default in most driversThe server sends the whole result, and the client receives all of it in memory before returning. A large result uses up client memory
Streamingmysql_use_result, setFetchSize(Integer.MIN_VALUE) in Connector/JThe client reads rows one at a time. Other commands cannot be sent on that connection until all rows are read. The server drops the connection if reading stalls longer than net_write_timeout
Protocol cursorRun a prepared statement with the cursor flag, then COM_STMT_FETCH (Connector/J's useCursorFetch=true and a fetch size)The server builds the result in an internal temporary table and sends the requested number of rows at a time
Stored program cursorDECLARE … CURSOR inside a procedure or functionReceives one row at a time into variables and processes it

Stored program cursors are fixed by the following three properties.

PropertyMeaning
Read-onlyRows read through the cursor cannot be updated with WHERE CURRENT OF
Forward-onlyOne row at a time in one direction. You cannot skip or go back
AsensitiveThe server may make a copy of the result or read the original directly. Whether changes after opening are visible is not defined
CREATE PROCEDURE sum_by_cust(IN p_cust INT, OUT p_total BIGINT)
BEGIN
  DECLARE v_amt INT;
  DECLARE done INT DEFAULT 0;
  DECLARE c CURSOR FOR SELECT amt FROM orders WHERE cust_id = p_cust;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
  SET p_total = 0;
  OPEN c;
  read_loop: LOOP
    FETCH c INTO v_amt;
    IF done = 1 THEN LEAVE read_loop; END IF;
    SET p_total = p_total + v_amt;
  END LOOP;
  CLOSE c;
END
  • A cursor is closed when the BEGIN … END block where it was declared ends. There is no DECLARE CURSOR for SQL outside stored programs.
  • To read a large result in pieces, key-based pagination (WHERE id > last value read ORDER BY id LIMIT n) is more common than a cursor. It does not hold the connection and does not build a temporary table on the server.

Configuration and Checks

-- Connections and running statements
SHOW FULL PROCESSLIST;
SELECT id, user, host, db, command, time, state, info FROM performance_schema.processlist;

-- Connection counts and connect failures
SHOW GLOBAL STATUS WHERE Variable_name IN
  ('Threads_connected', 'Threads_running', 'Max_used_connections', 'Connections',
   'Aborted_connects', 'Aborted_clients', 'Connection_errors_max_connections');

-- Prepared statements: count and per-session contents
SHOW GLOBAL STATUS LIKE 'Prepared_stmt_count';
SELECT statement_name, sql_text, owner_thread_id, count_execute, count_reprepare
FROM performance_schema.prepared_statements_instances;

-- Is the table cache sufficient? (if Opened_tables keeps growing, it is too small)
SHOW GLOBAL STATUS LIKE 'Open%tables';
SHOW GLOBAL STATUS LIKE 'Table_open_cache%';

-- Statistics per statement shape
SELECT digest_text, count_star, sum_timer_wait / 1e12 AS total_s, sum_rows_examined
FROM performance_schema.events_statements_summary_by_digest
ORDER BY sum_timer_wait DESC LIMIT 10;

-- Stop a running statement
KILL QUERY 1234;
  • If Aborted_clients grows, clients disappeared without closing the connection or hit wait_timeout; if Aborted_connects grows, authentication failed or the connection dropped during connect.
  • If the ratio of Com_stmt_prepare to Com_stmt_execute is close to 1, statements are prepared, executed once, and discarded. This only adds round trips, so client-side emulation is better.

Comparison with Other DBMSs

MySQLPostgreSQLOracleSQL ServerKDBS
Execution plan cacheNoneSession-local, prepared statements onlyShared pool (all sessions)Plan cache (all sessions)None. Remembers only the join order
What a prepared statement savesParsing, preparationParsing, analysis, (if a generic plan) planningThe whole parseThe whole compileParsing
Stopping executionKILL QUERY from another connectionCancel request on a new connectionALTER SYSTEM CANCEL SQL from another sessionAttention on the same connectionCancel request on a new connection
SQL-level cursorsOnly inside stored programsDECLARE, FETCHPL/SQL, every statement is a cursorT-SQL cursorsNone
Result cacheNone (removed in 8.0)NoneServer result cacheNoneNone

The full comparison is in DBMS Architecture at a Glance.

NOTE Defaults are for MySQL 8.0 and 8.4 and can vary with the version. This site has no MySQL sandbox, so the values in this document were not measured. For a driver's default behavior, check the driver version.

Related pages