Tools such as MySQLTuner add up globally allocated memory and add it to the product of max connections and per connection memory requirement. I formulated the following query to better estimate how much max memory would be required, if 100% of the max_connections are used.
Can someone verify whether it looks correct and whether any adjustments can be done?
I realise it excludes many other RAM requirements by MySQL and the server, but the idea is to estimate better.
SELECT
sys.FORMAT_BYTES(
@@key_buffer_size + @@query_cache_size + @@innodb_buffer_pool_size + @@innodb_log_buffer_size +
(
@@max_connections
* (
((select_scans / queries) * @@read_buffer_size)
+ ((sort_operations / queries) * (@@read_rnd_buffer_size + @@sort_buffer_size))
+ ((join_operations / queries) * @@join_buffer_size)
+ @@binlog_cache_size + @@thread_stack
+ ((temp_tables / queries) * LEAST(@@tmp_table_size, @@max_heap_table_size))
#need a better way to determine average packet size
+ (@@max_allowed_packet * 0.5) + @@net_buffer_length
)
)
) AS MAX_MEMORY
FROM (
SELECT
SUM(COUNT_STAR) AS queries,
SUM(SUM_SELECT_SCAN) AS select_scans,
SUM(
GREATEST(
(CASE WHEN UPPER(DIGEST_TEXT) LIKE '%ORDER BY%' THEN COUNT_STAR ELSE 0 END),
(CASE WHEN SUM_SORT_MERGE_PASSES > 0 OR SUM_SORT_RANGE > 0 OR SUM_SORT_ROWS > 0 OR SUM_SORT_SCAN > 0 THEN COUNT_STAR ELSE 0 END)
)
) AS sort_operations,
SUM(CASE WHEN UPPER(DIGEST_TEXT) LIKE '%JOIN%' THEN COUNT_STAR ELSE 0 END) AS join_operations,
SUM(SUM_CREATED_TMP_TABLES) AS temp_tables
FROM performance_schema.events_statements_summary_by_digest
) t;