Single Table Queries Very Slow With Indexes MariaDB - mysql

I am trying to tune some slow running queries on MariaDB and have hit a brick wall. I mainly work with Postgres / Oracle and these queries times seem extremely slow to me, but I can't figure out what I'm missing.
The queries in question (see below for examples) are mostly single table queries or with one join / subquery. The table in question has around 19million rows (26.5gb) and has fairly frequent writes.
Table structure and indexes below:
CREATE TABLE products_reviews (
id bigint(20) NOT NULL AUTO_INCREMENT
,  product_id int(11) NOT NULL DEFAULT 0
,  name varchar(255) NOT NULL DEFAULT ''
,  rate tinyint(4) NOT NULL DEFAULT 0
,  created_at datetime NOT NULL
,  posted_at date NOT NULL
,  site varchar(50) NOT NULL
,  review text NOT NULL
,  details text DEFAULT NULL
,  type smallint(6) NOT NULL DEFAULT 0
,  notify smallint(6) NOT NULL DEFAULT 1
,  notify_daily int(11) NOT NULL DEFAULT 1
,  user_id int(11) DEFAULT NULL
,  updated_at datetime NOT NULL
,  admin_id int(11) DEFAULT NULL
,  status smallint(6) NOT NULL DEFAULT 0
,  comment text NOT NULL
,  notified_at datetime NOT NULL
,  reply tinyint(4) NOT NULL DEFAULT 0
,  syndicate varchar(100) NOT NULL
,  status_user tinyint(4) NOT NULL
,  reviewer_id varchar(100) NOT NULL DEFAULT ''
,  sentiment text DEFAULT NULL
,  sentiment_score float(5,2) NOT NULL DEFAULT 0.00
,  ai text DEFAULT NULL
,  active tinyint(4) NOT NULL DEFAULT 1
,  active_updated_at datetime NOT NULL DEFAULT current_timestamp()
,  review_translate text NOT NULL
,  price float(6,2) NOT NULL
,  tagging text NOT NULL
,  site_id int(11) NOT NULL
,  hash varchar(255) NOT NULL
,  PRIMARY KEY (id)
,  KEY created_at (created_at)
,  KEY posted_at (posted_at)
,  KEY site (site)
,  KEY product_id (product_id)
,  KEY admin_id (admin_id)
,  KEY type (type)
,  KEY notify (notify)
,  KEY active (active)
,  KEY admin_posted (admin_id,posted_at)
,  KEY reviewer_id (reviewer_id)
,  KEY idx_products_reviews_pspth (product_id,site,posted_at,type,hash)
,  KEY idx_products_reviews_pa (product_id,active)
,  KEY idx_products_reviews_product_posted (product_id,posted_at)
,  KEY idx_products_reviews_product_adminid_postedid (product_id,admin_id,posted_at)
,  KEY product_id_2 (product_id,site,active)
) ENGINE=InnoDB AUTO_INCREMENT=27316062 DEFAULT CHARSET=utf8
Mariadb settings below:
alter_algorithm DEFAULT
aria_block_size 8192
aria_checkpoint_interval 30
aria_checkpoint_log_activity 1048576
aria_encrypt_tables OFF
aria_force_start_after_recovery_failures 0
aria_group_commit none
aria_group_commit_interval 0
aria_log_file_size 1073741824
aria_log_purge_type immediate
aria_max_sort_file_size 9223372036853727232
aria_page_checksum ON
aria_pagecache_age_threshold 300
aria_pagecache_buffer_size 134217728
aria_pagecache_division_limit 100
aria_pagecache_file_hash_size 512
aria_recover_options BACKUP,QUICK
aria_repair_threads 1
aria_sort_buffer_size 268434432
aria_stats_method nulls_unequal
aria_sync_log_dir NEWFILE
aria_used_for_temp_tables ON
auto_increment_increment 1
auto_increment_offset 1
autocommit ON
automatic_sp_privileges ON
back_log 100
basedir /usr
big_tables OFF
binlog_annotate_row_events ON
binlog_cache_size 32768
binlog_checksum CRC32
binlog_commit_wait_count 0
binlog_commit_wait_usec 100000
binlog_direct_non_transactional_updates OFF
binlog_file_cache_size 16384
binlog_format MIXED
binlog_optimize_thread_scheduling ON
binlog_row_image FULL
binlog_stmt_cache_size 32768
bulk_insert_buffer_size 8388608
check_constraint_checks ON
column_compression_threshold 100
column_compression_zlib_level 6
column_compression_zlib_strategy DEFAULT_STRATEGY
column_compression_zlib_wrap OFF
completion_type NO_CHAIN
concurrent_insert AUTO
connect_timeout 10
core_file OFF
date_format %Y-%m-%d
datetime_format %Y-%m-%d %H:%i:%s
deadlock_search_depth_long 15
deadlock_search_depth_short 4
deadlock_timeout_long 50000000
deadlock_timeout_short 10000
debug_no_thread_alarm OFF
default_master_connection
default_regex_flags
default_storage_engine InnoDB
default_tmp_storage_engine MyISAM
default_week_format 0
delay_key_write ON
delayed_insert_limit 100
delayed_insert_timeout 300
delayed_queue_size 1000
div_precision_increment 4
encrypt_binlog OFF
encrypt_tmp_disk_tables OFF
encrypt_tmp_files OFF
enforce_storage_engine
eq_range_index_dive_limit 0
error_count 0
event_scheduler OFF
expensive_subquery_limit 100
expire_logs_days 7
explicit_defaults_for_timestamp OFF
external_user
extra_max_connections 1
extra_port 0
flush OFF
flush_time 0
foreign_key_checks ON
ft_boolean_syntax + -><()~*:""&|
ft_max_word_len 84
ft_min_word_len 4
ft_query_expansion_limit 20
ft_stopword_file (built-in)
general_log OFF
group_concat_max_len 1048576
gtid_binlog_pos
gtid_binlog_state
gtid_current_pos
gtid_domain_id 0
gtid_ignore_duplicates OFF
gtid_pos_auto_engines
gtid_seq_no 0
gtid_slave_pos
gtid_strict_mode OFF
have_compress YES
have_crypt YES
have_dynamic_loading YES
have_geometry YES
have_openssl YES
have_profiling YES
have_query_cache YES
have_rtree_keys YES
have_ssl DISABLED
have_symlink YES
histogram_size 0
histogram_type SINGLE_PREC_HB
host_cache_size 633
identity 0
idle_readonly_transaction_timeout 0
idle_transaction_timeout 0
idle_write_transaction_timeout 0
ignore_builtin_innodb OFF
ignore_db_dirs
in_predicate_conversion_threshold 1000
in_transaction 0
init_connect
init_file
init_slave
innodb_adaptive_flushing ON
innodb_adaptive_flushing_lwm 10.000000
innodb_adaptive_hash_index ON
innodb_adaptive_hash_index_parts 8
innodb_adaptive_max_sleep_delay 150000
innodb_autoextend_increment 64
innodb_autoinc_lock_mode 1
innodb_background_scrub_data_check_interval 3600
innodb_background_scrub_data_compressed OFF
innodb_background_scrub_data_interval 604800
innodb_background_scrub_data_uncompressed OFF
innodb_buf_dump_status_frequency 0
innodb_buffer_pool_chunk_size 134217728
innodb_buffer_pool_dump_at_shutdown ON
innodb_buffer_pool_dump_now OFF
innodb_buffer_pool_dump_pct 25
innodb_buffer_pool_filename ib_buffer_pool
innodb_buffer_pool_instances 8
innodb_buffer_pool_load_abort OFF
innodb_buffer_pool_load_at_startup ON
innodb_buffer_pool_load_now OFF
innodb_buffer_pool_size 68719476736
innodb_change_buffer_max_size 25
innodb_change_buffering all
innodb_checksum_algorithm crc32
innodb_checksums ON
innodb_cmp_per_index_enabled OFF
innodb_commit_concurrency 0
innodb_compression_algorithm zlib
innodb_compression_default OFF
innodb_compression_failure_threshold_pct 5
innodb_compression_level 6
innodb_compression_pad_pct_max 50
innodb_concurrency_tickets 5000
innodb_data_file_path ibdata1:12M:autoextend
innodb_data_home_dir
innodb_deadlock_detect ON
innodb_default_encryption_key_id 1
innodb_default_row_format dynamic
innodb_disable_sort_file_cache OFF
innodb_disallow_writes OFF
innodb_doublewrite ON
innodb_encrypt_log OFF
innodb_encrypt_tables OFF
innodb_encrypt_temporary_tables OFF
innodb_encryption_rotate_key_age 1
innodb_encryption_rotation_iops 100
innodb_encryption_threads 0
innodb_fast_shutdown 1
innodb_fatal_semaphore_wait_threshold 600
innodb_file_format
innodb_file_per_table ON
innodb_fill_factor 100
innodb_flush_log_at_timeout 1
innodb_flush_log_at_trx_commit 1
innodb_flush_method fsync
innodb_flush_neighbors 1
innodb_flush_sync ON
innodb_flushing_avg_loops 30
innodb_force_load_corrupted OFF
innodb_force_primary_key OFF
innodb_force_recovery 0
innodb_ft_aux_table
innodb_ft_cache_size 8000000
innodb_ft_enable_diag_print OFF
innodb_ft_enable_stopword ON
innodb_ft_max_token_size 84
innodb_ft_min_token_size 3
innodb_ft_num_word_optimize 2000
innodb_ft_result_cache_limit 2000000000
innodb_ft_server_stopword_table
innodb_ft_sort_pll_degree 2
innodb_ft_total_cache_size 640000000
innodb_ft_user_stopword_table
innodb_idle_flush_pct 100
innodb_immediate_scrub_data_uncompressed OFF
innodb_io_capacity 1000
innodb_io_capacity_max 2000
innodb_large_prefix
innodb_lock_schedule_algorithm fcfs
innodb_lock_wait_timeout 50
innodb_locks_unsafe_for_binlog OFF
innodb_log_buffer_size 16777216
innodb_log_checksums ON
innodb_log_compressed_pages ON
innodb_log_file_size 50331648
innodb_log_files_in_group 2
innodb_log_group_home_dir ./
innodb_log_optimize_ddl ON
innodb_log_write_ahead_size 8192
innodb_lru_scan_depth 1024
innodb_max_dirty_pages_pct 75.000000
innodb_max_dirty_pages_pct_lwm 0.000000
innodb_max_purge_lag 0
innodb_max_purge_lag_delay 0
innodb_max_undo_log_size 10485760
innodb_monitor_disable
innodb_monitor_enable
innodb_monitor_reset
innodb_monitor_reset_all
innodb_old_blocks_pct 37
innodb_old_blocks_time 1000
innodb_online_alter_log_max_size 134217728
innodb_open_files 4096
innodb_optimize_fulltext_only OFF
innodb_page_cleaners 4
innodb_page_size 16384
innodb_prefix_index_cluster_optimization OFF
innodb_print_all_deadlocks OFF
innodb_purge_batch_size 300
innodb_purge_rseg_truncate_frequency 128
innodb_purge_threads 4
innodb_random_read_ahead OFF
innodb_read_ahead_threshold 56
innodb_read_io_threads 4
innodb_read_only OFF
innodb_replication_delay 0
innodb_rollback_on_timeout OFF
innodb_rollback_segments 128
innodb_scrub_log OFF
innodb_scrub_log_speed 256
innodb_sort_buffer_size 1048576
innodb_spin_wait_delay 4
innodb_stats_auto_recalc ON
innodb_stats_include_delete_marked OFF
innodb_stats_method nulls_equal
innodb_stats_modified_counter 0
innodb_stats_on_metadata OFF
innodb_stats_persistent ON
innodb_stats_persistent_sample_pages 20
innodb_stats_sample_pages 8
innodb_stats_traditional ON
innodb_stats_transient_sample_pages 8
innodb_status_output OFF
innodb_status_output_locks OFF
innodb_strict_mode OFF
innodb_sync_array_size 1
innodb_sync_spin_loops 30
innodb_table_locks ON
innodb_temp_data_file_path ibtmp1:12M:autoextend
innodb_thread_concurrency 0
innodb_thread_sleep_delay 10000
innodb_tmpdir
innodb_undo_directory ./
innodb_undo_log_truncate OFF
innodb_undo_logs 128
innodb_undo_tablespaces 0
innodb_use_atomic_writes ON
innodb_use_native_aio ON
innodb_version 10.3.21
innodb_write_io_threads 4
insert_id 0
interactive_timeout 3600
join_buffer_size 1048576
join_buffer_space_limit 2097152
join_cache_level 2
keep_files_on_create OFF
key_buffer_size 67108864
key_cache_age_threshold 300
key_cache_block_size 1024
key_cache_division_limit 100
key_cache_file_hash_size 512
key_cache_segments 0
large_files_support ON
large_page_size 0
large_pages OFF
last_gtid
last_insert_id 0
lc_messages en_US
lc_messages_dir
lc_time_names en_US
license GPL
local_infile ON
lock_wait_timeout 86400
locked_in_memory OFF
log_bin OFF
log_bin_basename
log_bin_compress OFF
log_bin_compress_min_len 256
log_bin_index
log_bin_trust_function_creators OFF
log_disabled_statements sp
log_error /var/log/mariadb/mariadb.log
log_output FILE
log_queries_not_using_indexes OFF
log_slave_updates OFF
log_slow_admin_statements ON
log_slow_disabled_statements sp
log_slow_filter admin,filesort,filesort_on_disk,filesort_priority_queue,full_join,full_scan,query_cache,query_cache_miss,tmp_table,tmp_table_on_disk
log_slow_rate_limit 1
log_slow_slave_statements ON
log_slow_verbosity
log_tc_size 24576
log_warnings 2
long_query_time 1.000000
low_priority_updates OFF
lower_case_file_system OFF
lower_case_table_names 0
master_verify_checksum OFF
max_allowed_packet 67108864
max_binlog_cache_size 18446744073709547520
max_binlog_size 1073741824
max_binlog_stmt_cache_size 18446744073709547520
max_connect_errors 10000
max_connections 600
max_delayed_threads 20
max_digest_length 1024
max_error_count 64
max_heap_table_size 67108864
max_insert_delayed_threads 20
max_join_size 18446744073709551615
max_length_for_sort_data 1024
max_long_data_size 67108864
max_prepared_stmt_count 16382
max_recursive_iterations 4294967295
max_relay_log_size 1073741824
max_seeks_for_key 4294967295
max_session_mem_used 9223372036854775807
max_sort_length 1024
max_sp_recursion_depth 0
max_statement_time 0.000000
max_tmp_tables 32
max_user_connections 0
max_write_lock_count 4294967295
metadata_locks_cache_size 1024
metadata_locks_hash_instances 8
min_examined_row_limit 0
mrr_buffer_size 262144
multi_range_count 256
myisam_block_size 1024
myisam_data_pointer_size 6
myisam_max_sort_file_size 9223372036853727232
myisam_mmap_size 18446744073709551615
myisam_recover_options BACKUP,QUICK
myisam_repair_threads 1
myisam_sort_buffer_size 134217728
myisam_stats_method NULLS_UNEQUAL
myisam_use_mmap OFF
mysql56_temporal_format ON
net_buffer_length 16384
net_read_timeout 30
net_retry_count 10
net_write_timeout 60
open_files_limit 65535
optimizer_prune_level 1
optimizer_search_depth 62
optimizer_selectivity_sampling_limit 100
optimizer_switch index_merge=off,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on,index_merge_sort_intersection=off,engine_condition_pushdown=off,index_condition_pushdown=on,derived_merge=on,derived_with_keys=on,firstmatch=on,loosescan=on,materialization=on,in_to_exists=on,semijoin=on,partial_match_rowid_merge=on,partial_match_table_scan=on,subquery_cache=on,mrr=off,mrr_cost_based=off,mrr_sort_keys=off,outer_join_with_cache=on,semijoin_with_cache=on,join_cache_incremental=on,join_cache_hashed=on,join_cache_bka=on,optimize_join_buffer_size=off,table_elimination=on,extended_keys=on,exists_to_in=on,orderby_uses_equalities=on,condition_pushdown_for_derived=on,split_materialized=on
optimizer_use_condition_selectivity 1
performance_schema OFF
performance_schema_accounts_size -1
performance_schema_digests_size -1
performance_schema_events_stages_history_long_size -1
performance_schema_events_stages_history_size -1
performance_schema_events_statements_history_long_size -1
performance_schema_events_statements_history_size -1
performance_schema_events_waits_history_long_size -1
performance_schema_events_waits_history_size -1
performance_schema_hosts_size -1
performance_schema_max_cond_classes 80
performance_schema_max_cond_instances -1
performance_schema_max_digest_length 1024
performance_schema_max_file_classes 50
performance_schema_max_file_handles 32768
performance_schema_max_file_instances -1
performance_schema_max_mutex_classes 200
performance_schema_max_mutex_instances -1
performance_schema_max_rwlock_classes 40
performance_schema_max_rwlock_instances -1
performance_schema_max_socket_classes 10
performance_schema_max_socket_instances -1
performance_schema_max_stage_classes 160
performance_schema_max_statement_classes 200
performance_schema_max_table_handles -1
performance_schema_max_table_instances -1
performance_schema_max_thread_classes 50
performance_schema_max_thread_instances -1
performance_schema_session_connect_attrs_size -1
performance_schema_setup_actors_size 100
performance_schema_setup_objects_size 100
performance_schema_users_size -1
pid_file /var/run/mariadb/mariadb.pid
plugin_dir /usr/lib64/mysql/plugin/
plugin_maturity gamma
port 3306
preload_buffer_size 32768
profiling OFF
profiling_history_size 15
progress_report_time 5
protocol_version 10
proxy_protocol_networks
proxy_user
pseudo_slave_mode OFF
pseudo_thread_id 1852681
query_alloc_block_size 16384
query_cache_limit 1048576
query_cache_min_res_unit 4096
query_cache_size 1048576
query_cache_strip_comments OFF
query_cache_type OFF
query_cache_wlock_invalidate OFF
query_prealloc_size 24576
rand_seed1 93838501
rand_seed2 36662033
range_alloc_block_size 4096
read_binlog_speed_limit 0
read_buffer_size 1048576
read_only OFF
read_rnd_buffer_size 1048576
relay_log
relay_log_basename
relay_log_index
relay_log_info_file relay-log.info
relay_log_purge ON
relay_log_recovery OFF
relay_log_space_limit 17179869184
replicate_annotate_row_events ON
replicate_do_db
replicate_do_table
replicate_events_marked_for_skip REPLICATE
replicate_ignore_db
replicate_ignore_table
replicate_wild_do_table
replicate_wild_ignore_table
report_host
report_password
report_port 3306
report_user
rowid_merge_buff_size 8388608
secure_auth ON
secure_file_priv
secure_timestamp NO
server_id 1
session_track_schema ON
session_track_state_change OFF
session_track_system_variables autocommit,character_set_client,character_set_connection,character_set_results,time_zone
session_track_transaction_info OFF
skip_external_locking ON
skip_name_resolve ON
skip_networking OFF
skip_parallel_replication OFF
skip_replication OFF
skip_show_database OFF
slave_compressed_protocol OFF
slave_ddl_exec_mode IDEMPOTENT
slave_domain_parallel_threads 0
slave_exec_mode STRICT
slave_load_tmpdir /san/svc-fs/mysqltmp
slave_max_allowed_packet 1073741824
slave_net_timeout 60
slave_parallel_max_queued 131072
slave_parallel_mode conservative
slave_parallel_threads 0
slave_parallel_workers 0
slave_run_triggers_for_rbr NO
slave_skip_errors OFF
slave_sql_verify_checksum ON
slave_transaction_retries 10
slave_transaction_retry_errors 1213,1205
slave_transaction_retry_interval 0
slave_type_conversions
slow_launch_time 2
slow_query_log ON
slow_query_log_file /san/svc-fs/mysqllogs/slow-log
socket /san/svc-fs/mysql/mysql.sock
sort_buffer_size 1048576
sql_auto_is_null OFF
sql_big_selects ON
sql_buffer_result OFF
sql_log_bin ON
sql_log_off OFF
sql_mode NO_ENGINE_SUBSTITUTION
sql_notes ON
sql_quote_show_create ON
sql_safe_updates OFF
sql_select_limit 18446744073709551615
sql_slave_skip_counter 0
sql_warnings OFF
ssl_ca
ssl_capath
ssl_cert
ssl_cipher
ssl_crl
ssl_crlpath
ssl_key
standard_compliant_cte ON
storage_engine InnoDB
stored_program_cache 256
strict_password_validation ON
sync_binlog 0
sync_frm ON
sync_master_info 10000
sync_relay_log 10000
sync_relay_log_info 10000
system_time_zone CST
system_versioning_alter_history ERROR
system_versioning_asof DEFAULT
table_definition_cache 4096
table_open_cache 4096
table_open_cache_instances 8
tcp_keepalive_interval 0
tcp_keepalive_probes 0
tcp_keepalive_time 0
thread_cache_size 16
thread_concurrency 10
thread_handling one-thread-per-connection
thread_pool_idle_timeout 60
thread_pool_max_threads 65536
thread_pool_oversubscribe 3
thread_pool_prio_kickup_timer 1000
thread_pool_priority auto
thread_pool_size 16
thread_pool_stall_limit 500
thread_stack 299008
time_format %H:%i:%s
time_zone SYSTEM
timed_mutexes OFF
timestamp 1644789513.087889
tmp_disk_table_size 18446744073709551615
tmp_memory_table_size 33554432
tmp_table_size 33554432
tmpdir /san/svc-fs/mysqltmp
transaction_alloc_block_size 8192
transaction_prealloc_size 4096
tx_isolation REPEATABLE-READ
tx_read_only OFF
unique_checks ON
updatable_views_with_limit YES
use_stat_tables NEVER
userstat OFF
version 10.3.21-MariaDB-log
version_comment MariaDB Server
version_compile_machine x86_64
version_compile_os Linux
version_malloc_library jemalloc 3.6.0-0-g46c0af68bd248b04df75e4f92d5fb804c3d75340
version_source_revision e5e5877740f248de848219ee3a1d2881cd5c5b82
version_ssl_library OpenSSL 1.0.2k-fips  26 Jan 2017
wait_timeout 600
warning_count 0
wsrep_osu_method TOI
wsrep_auto_increment_control ON
wsrep_causal_reads OFF
wsrep_certification_rules strict
wsrep_certify_nonpk ON
wsrep_cluster_address
wsrep_cluster_name my_wsrep_cluster
wsrep_convert_lock_to_trx OFF
wsrep_data_home_dir /san/svc-fs/mysql/
wsrep_dbug_option
wsrep_debug OFF
wsrep_desync OFF
wsrep_dirty_reads OFF
wsrep_drupal_282555_workaround OFF
wsrep_forced_binlog_format NONE
wsrep_gtid_domain_id 0
wsrep_gtid_mode OFF
wsrep_load_data_splitting ON
wsrep_log_conflicts OFF
wsrep_max_ws_rows 0
wsrep_max_ws_size 2147483647
wsrep_mysql_replication_bundle 0
wsrep_node_address
wsrep_node_incoming_address AUTO
wsrep_notify_cmd
wsrep_on OFF
wsrep_patch_version wsrep_25.24
wsrep_provider none
wsrep_provider_options
wsrep_recover OFF
wsrep_reject_queries NONE
wsrep_replicate_myisam OFF
wsrep_restart_slave OFF
wsrep_retry_autocommit 1
wsrep_slave_fk_checks ON
wsrep_slave_uk_checks OFF
wsrep_slave_threads 1
wsrep_sst_auth
wsrep_sst_donor
wsrep_sst_donor_rejects_queries OFF
wsrep_sst_method rsync
wsrep_sst_receive_address AUTO
wsrep_start_position 00000000-0000-0000-0000-000000000000:-1
wsrep_sync_wait 0
The queries filters can be selected on the front end by a user so the where clause can vary a bit. They will all contain a product_id at least. The speed to read from disk seems absurdly slow for the number of rows being fetched.
Example queries:
This one takes 400seconds to return
Edit - Below query is in an incorrect format which must have happened when creating the post. Original is below
SELECT SQL_NO_CACHE
pr.rate as star, pr.product_id, pr.site, COUNT(pr.id) AS count
FROM products_reviews pr
JOIN products p ON p.id = pr.product_id
AND pr.active > 0
AND pr.posted_at >= '2020-10-26'
AND pr.posted_at <= '2022-01-24 23:59'
AND pr.admin_id = 3598
GROUP BY pr.rate, pr.product_id, pr.site;
SELECT rate as star, product_id, site, COUNT(id) AS count
FROM products_reviews
WHERE product_id IN (SELECT id FROM products WHERE admin_id = 3598)
AND active >0 AND posted_at >= '2020-10-26'
AND posted_at <= '2022-01-24 23:59'
AND admin_id = 3598
GROUP BY rate, product_id, site
Explain plan
{
"query_block": {
"select_id": 1,
"filesort": {
"sort_key": "products_reviews.rate, products_reviews.product_id, products_reviews.site",
"temporary_table": {
"table": {
"table_name": "products_reviews",
"access_type": "range",
"possible_keys": [
"posted_at",
"product_id",
"admin_id",
"active",
"admin_posted",
"idx_products_reviews_pspth",
"idx_products_reviews_pa",
"idx_products_reviews_product_posted",
"idx_products_reviews_product_adminid_postedid",
"product_id_2",
"idx_products_aaprps_covering",
"idx_products_aprps_covering_t"
],
"key": "idx_products_aaprps_covering",
"key_length": "6",
"used_key_parts": ["admin_id", "active"],
"rows": 1826162,
"filtered": 100,
"attached_condition": "products_reviews.admin_id = 3598 and products_reviews.active > 0 and products_reviews.posted_at >= '2020-10-26' and products_reviews.posted_at <= '2022-01-24 23:59'",
"using_index": true
},
"table": {
"table_name": "products",
"access_type": "eq_ref",
"possible_keys": ["PRIMARY", "id", "admin_id"],
"key": "PRIMARY",
"key_length": "8",
"used_key_parts": ["id"],
"ref": ["metabase.products_reviews.product_id"],
"rows": 1,
"filtered": 100,
"attached_condition": "products.admin_id = 3598 and products_reviews.product_id = products.`id`"
}
}
}
}
}
I ran profiling on the transaction and the whole time is spent on "Sending Data".
Here is a second query, this one takes around 32 seconds.
SELECT site, MIN(posted_at) as posted_at, AVG(IF(rate>0, rate, NULL)) as rate, COUNT(IF(type=0, 1, NULL)) as count, COUNT(IF(type=0 AND syndicate='', 1, NULL)) as count_ns, AVG(IF(rate>0 AND syndicate='', rate, NULL)) as rate_ns, COUNT(IF(type=1, 1, NULL)) as count_qe
FROM products_reviews
WHERE product_id = '24828'
AND active >0
GROUP BY site
Explain Plan
{
"query_block": {
"select_id": 1,
"table": {
"table_name": "products_reviews",
"access_type": "ref",
"possible_keys": [
"product_id",
"active",
"idx_products_reviews_pspth",
"idx_products_reviews_pa",
"idx_products_reviews_product_posted",
"idx_products_reviews_product_adminid_postedid",
"product_id_2"
],
"key": "product_id_2",
"key_length": "4",
"used_key_parts": ["product_id"],
"ref": ["const"],
"rows": 6575,
"filtered": 100,
"attached_condition": "products_reviews.product_id <=> '24828' and products_reviews.active > 0"
}
}
{
"query_block": {
"select_id": 1,
"table": {
"table_name": "products_reviews",
"access_type": "ref",
"possible_keys": [
"product_id",
"active",
"idx_products_reviews_pspth",
"idx_products_reviews_pa",
"idx_products_reviews_product_posted",
"idx_products_reviews_product_adminid_postedid",
"product_id_2"
],
"key": "product_id_2",
"key_length": "4",
"used_key_parts": ["product_id"],
"ref": ["const"],
"rows": 6575,
"filtered": 100,
"attached_condition": "products_reviews.product_id <=> '24828' and products_reviews.active > 0"
}
}
}
Possibly partially related to cardinality. Here's a count of rows, distinct product_id and distinct posted_at.
count(*) 19128090
count(distinct(product_id)) 28821
count(distinct(posted_at)) 7551
The server has 96gb RAM and a 480GB SATA SSD. The buffer pool settings look well optimized to me. I tried increasing innodb_io_capacity but that had a negative impact.
If there is nothing I can do to speed up the queries with regards query tuning or parameter tuning, I wondered about keeping the table in memory at all times. They seem to get flushed at least once a day (probably around the time backups are taken). Would it be sensible to have a job that runs once every couple of hours to select * from the table?
Many thanks.

It's a good question you ask. My answer has a few dimensions.
Server provisioning: Your machine is adequate, and possibly overprovisioned. You have allocated 2/3 of your server's RAM to your 64GiB InnoDB buffer pool (innodb_buffer_pool_size) and that's probably enough to hold your tables. You could allocate another 8 - 12 GiB to it and still have RAM left over for your server's other functions. But buffer pool size is almost certainly not your issue.
Many indexes: You have quite a few single-column indexes. Are you sure they are all needed? Generally speaking, we create indexes to support particular query patterns, not because they might be helpful someday. If you can drop some of your indexes, do so. And, indexes slow down INSERTs and UPDATEs because both the table data and indexes are affected. Which brings us to ...
Frequent updates: It's possible that your update operations slow down the reporting-style queries you showed us in your question because the server is struggling to give consistent results (using locks) as updates happen. Try giving this SQL statement right before your too-slow query.
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
This causes a "dirty read". It cuts down on locking, but gives you the chance you'll get an older version of rows that are being actively updated. That's usually no problem for reporting-style queries. Try it and see how much it helps.
Equality and range filters, covering BTREE indexes. Consider your first query, repeated here:
SELECT SQL_NO_CACHE
pr.rate as star, pr.product_id, pr.site, COUNT(pr.id) AS count
FROM products_reviews pr
JOIN products p ON p.id = pr.product_id
AND pr.active > 0
AND pr.posted_at >= '2020-10-26'
AND pr.posted_at <= '2022-01-24 23:59'
AND pr.admin_id = 3598
GROUP BY pr.rate, pr.product_id, pr.site;
You filter product_reviews on admin_id for equality, then active and posted at for ranges, then you look up rows in products, then group by rate, product_id, and site.
Try using this so-called covering index.
CREATE INDEX rate_product_site_rollup ON products_review
(admin_id, posted_at, active, rate, product_id, site);
It contains the data your query needs from the products_review table. To satisfy the query, the database can random-access the index to the first eligible row (admin_id = nnnn and the first eligible posted_at row. It can then scan the index sequentially to filter out active <= 0 rows. Finally, your GROUP BY columns are there already sorted in an order suitable for quick grouping.
You might consider a similar covering index for your second query.
(Some makes and versions of database servers allow INCLUDE(col, col, col) clauses in index declarations, but not MariaDB / MySQL. INCLUDE is very useful for covering indexes, but including the columns in the index works too.)
More than one range filter: BTREE indexes do their fastest work when you only have one range filter in your query. If your business rules allowed you to filter on pr.active = 1 then this index would satisfy your query even faster.
CREATE INDEX rate_product_site_rollup ON products_review
(admin_id, active, posted_at, rate, product_id, site);
Extraneous JOIN: You JOIN to your products table, but don't use any columns from it. So the JOIN serves only one purpose: to exclude reviews that have no matching product. Is this step necessary?
Note: pr.posted_at < '2022-01-24' + INTERVAL 1 DAY, with <, is a bit more reliable on the almost-midnight edge case than pr.posted_at <= '2022-01-24 23:59'

`products is only sort of used. If you don't really need it, get rid of it. I see two things that can matter:
If there is no matching row from products the JOIN will avoid including it.
If there are multiple rows in products, then the COUNT will increase.
Replace
JOIN products p ON p.id = pr.product_id
AND
with
WHERE
As a rule:
Use ON to specify how the tables are related.
Use WHERE to specify which rows to keep.
Another INDEX tip: When you need INDEX(a,b), you can do without INDEX(a). I am thinking of (admin_id, posted_at)
If active is only "0" or "1", then use AND active = 1, plus change to INDEX(admin_id, active, posted_at)
"indexes could only contain one equality operator" -- The rule is more like "Indexes should contain only one range operator, and it needs to be last". (Note: "covering" is a deliberate exception.)
(I agree that the 'covering' index may help, but I generally avoid indexes with lots of columns.)
I have the master of that MariaDB link (that RLOG mentioned); it has been updated a few times here: http://mysql.rjweb.org/doc.php/index_cookbook_mysql

Related

Mysql memory usage growing until OOM and system kills / restarts

I have MySQL 5.7.27 under Ubuntu 16.04.4, 64 bit, 4GB RAM and SSDs (it's a virtual machine). I am observing resident memory growth in mysqld until no more resources are available and the OS kills / restarts mysqld.
Some background - The system is used to collect information from remote locations, with 1 entity being collected from each location. Each entity might have many hundreds of data points. For each remote location, there are two databases, which supports two situations: each location is per customer (but one customer might have many - thousands - of such locations) and in some situations, it might be many thousands of entities being collected from each remote location. The two DBs correspond to raw data collected and "processed" summaries. In addition, there is one additional DB per customer recording admin and other data about each remote location. So, total DB count is C * ( 1 + 2L ) - C for customer, L for location. The first DB of 2L has 32 tables and a minimum size of 2MB (but I have at least one example which it 5.9GB - not in this current sample set) - it is "cleared" at the start of each collection event; the second has 12 tables and typical size in the current sample set is 1MB (although this accumulates for each collection event).
A remote collection is performed periodically, say once a week or once a month, per remote location. After each collection, a process is run to summarise data from the ALL of the 2L databases into the one unifying one.
In the system with the issue, there are C ( 1 + 2L ) equaling just over 5000. When the summarisation process is run, mysqld resident memory (viewed using top) grows from around 800MB to just under 3GB. The summarisation process completes and might then run again a short time afterwards. That process completes cleanly and correctly releases query results and closes DB connections. The application is PHP 7.2.24 CLI running locally (so, using sockets, not TCP).
I have tried "tuning":
open_files_limit = 11000
table_open_cache = 5200
innodb_lru_scan_depth = 128
innodb_flush_log_at_trx_commit = 2
innodb_buffer_pool_size = 1073741824
(see open_files_limit, table_open_cache, innodb_lru_scan_depth, innodb_flush_log_at_trx_commit, innodb_buffer_pool_size)
These either made no apparent change or worsened the rate of growth of memory usage. I also ran show engine performance_schema status; at three instances: when resident memory was at 2459MB, 2478MB and 2910MB. Between those three samples, I saw differences only in the following metrics:
2459MB 2478MB 2910MB
(digest_hash).count 4676 -> 4837 -> 4958
(filename_hash).count 121118 -> 121139 -> 121214
(table_share_hash).count 27229 -> 27247 -> 27276
mutex_instances.count 29696 -> 30720 -> 31744
mutex_instances.memory 3801088 -> 3932160 -> 4063232
performance_scheme.memory 426293432 -> 426424504 -> 4266886648
rwlock_instances.count 400384 -> 400384 -> 401408
rwlock_instances.memory 51249152 -> 51249152 -> 51380224
My expectation is that at the end of each summarisation run, either "temporary" buffer space in mysqld would be freed up, or would simply be reused at the next run of that process, given that it effectively is making the same sequence of queries (and very similar updates) across the same set of databases / tables. The fact that the memory footprint grows suggest to me that either there is a memory leak in mysqld, or that an intentional "buffer" related to some failure condition (connections, locks, mutexes?) is at least part of the cause of the memory growth. I suggest the latter, because I would look at what would persist in mysqld between subsequent runs of that summarisation process.
I have also tried running mysqltuner.pl (see http://mysqltuner.com), but this also causes the memory growth problem, which is undoubtedly related to the number of databases. However, if I might refer to https://dev.mysql.com/doc/refman/5.7/en/database-count-limit.html, whatever limit MySQL might or might not have to the number of databases and tables, the numbers here are not significant to mysqld itself, even if they might be to the underlying OS. I confess I was impressed that the server was apparently handling over 1000 SELECTS per second on a not very highly spec'd system.
So, What "monitoring" parameters should I be looking at to assist with tuning mysql, the OS or platform and what (mysql / OS) tuning parameters would be most helpful in this situation? I could just take the Jaws approach ("We're going to need a bigger boat"), but if the issue I'm experiencing is a memory leak, then just adding more RAM is only just postponing the inevitable.
------------ EDIT following answer by Rick James (2020/01/13) -
RAM - 4GB
SHOW VARIABLES; (less SSL related info) output:
auto_generate_certs ON
auto_increment_increment 1
auto_increment_offset 1
autocommit ON
automatic_sp_privileges ON
avoid_temporal_upgrade OFF
back_log 80
basedir /usr/
big_tables OFF
bind_address *
binlog_cache_size 32768
binlog_checksum CRC32
binlog_direct_non_transactional_updates OFF
binlog_error_action ABORT_SERVER
binlog_format ROW
binlog_group_commit_sync_delay 0
binlog_group_commit_sync_no_delay_count 0
binlog_gtid_simple_recovery ON
binlog_max_flush_queue_time 0
binlog_order_commits ON
binlog_row_image FULL
binlog_rows_query_log_events OFF
binlog_stmt_cache_size 32768
binlog_transaction_dependency_history_size 25000
binlog_transaction_dependency_tracking COMMIT_ORDER
block_encryption_mode aes-128-ecb
bulk_insert_buffer_size 8388608
character_set_client utf8mb4
character_set_connection utf8mb4
character_set_database utf8
character_set_filesystem binary
character_set_results utf8mb4
character_set_server utf8
character_set_system utf8
character_sets_dir /usr/share/mysql/charsets/
check_proxy_users OFF
collation_connection utf8mb4_general_ci
collation_database utf8_unicode_ci
collation_server utf8_unicode_ci
completion_type NO_CHAIN
concurrent_insert AUTO
connect_timeout 10
core_file OFF
datadir /var/lib/mysql/
date_format %Y-%m-%d
datetime_format %Y-%m-%d %H:%i:%s
default_authentication_plugin mysql_native_password
default_password_lifetime 0
default_storage_engine InnoDB
default_tmp_storage_engine InnoDB
default_week_format 0
delay_key_write ON
delayed_insert_limit 100
delayed_insert_timeout 300
delayed_queue_size 1000
disabled_storage_engines
disconnect_on_expired_password ON
div_precision_increment 4
end_markers_in_json OFF
enforce_gtid_consistency OFF
eq_range_index_dive_limit 200
error_count 0
event_scheduler OFF
expire_logs_days 10
explicit_defaults_for_timestamp OFF
external_user
flush OFF
flush_time 0
foreign_key_checks ON
ft_boolean_syntax + -><()~*:""&|
ft_max_word_len 84
ft_min_word_len 4
ft_query_expansion_limit 20
ft_stopword_file (built-in)
general_log OFF
general_log_file /var/lib/mysql/demo.log
group_concat_max_len 1024
gtid_executed_compression_period 1000
gtid_mode OFF
gtid_next AUTOMATIC
gtid_owned
gtid_purged
have_compress YES
have_crypt YES
have_dynamic_loading YES
have_geometry YES
have_openssl YES
have_profiling YES
have_query_cache YES
have_rtree_keys YES
have_ssl YES
have_statement_timeout YES
have_symlink YES
host_cache_size 279
hostname <hidden>
identity 0
ignore_builtin_innodb OFF
ignore_db_dirs
init_connect
init_file
init_slave
innodb_adaptive_flushing ON
innodb_adaptive_flushing_lwm 10
innodb_adaptive_hash_index ON
innodb_adaptive_hash_index_parts 8
innodb_adaptive_max_sleep_delay 150000
innodb_api_bk_commit_interval 5
innodb_api_disable_rowlock OFF
innodb_api_enable_binlog OFF
innodb_api_enable_mdl OFF
innodb_api_trx_level 0
innodb_autoextend_increment 64
innodb_autoinc_lock_mode 1
innodb_buffer_pool_chunk_size 134217728
innodb_buffer_pool_dump_at_shutdown ON
innodb_buffer_pool_dump_now OFF
innodb_buffer_pool_dump_pct 25
innodb_buffer_pool_filename ib_buffer_pool
innodb_buffer_pool_instances 1
innodb_buffer_pool_load_abort OFF
innodb_buffer_pool_load_at_startup ON
innodb_buffer_pool_load_now OFF
innodb_buffer_pool_size 134217728
innodb_change_buffer_max_size 25
innodb_change_buffering all
innodb_checksum_algorithm crc32
innodb_checksums ON
innodb_cmp_per_index_enabled OFF
innodb_commit_concurrency 0
innodb_compression_failure_threshold_pct 5
innodb_compression_level 6
innodb_compression_pad_pct_max 50
innodb_concurrency_tickets 5000
innodb_data_file_path ibdata1:12M:autoextend
innodb_data_home_dir
innodb_deadlock_detect ON
innodb_default_row_format dynamic
innodb_disable_sort_file_cache OFF
innodb_doublewrite ON
innodb_fast_shutdown 1
innodb_file_format Barracuda
innodb_file_format_check ON
innodb_file_format_max Barracuda
innodb_file_per_table ON
innodb_fill_factor 100
innodb_flush_log_at_timeout 1
innodb_flush_log_at_trx_commit 2
innodb_flush_method
innodb_flush_neighbors 1
innodb_flush_sync ON
innodb_flushing_avg_loops 30
innodb_force_load_corrupted OFF
innodb_force_recovery 0
innodb_ft_aux_table
innodb_ft_cache_size 8000000
innodb_ft_enable_diag_print OFF
innodb_ft_enable_stopword ON
innodb_ft_max_token_size 84
innodb_ft_min_token_size 3
innodb_ft_num_word_optimize 2000
innodb_ft_result_cache_limit 2000000000
innodb_ft_server_stopword_table
innodb_ft_sort_pll_degree 2
innodb_ft_total_cache_size 640000000
innodb_ft_user_stopword_table
innodb_io_capacity 200
innodb_io_capacity_max 2000
innodb_large_prefix ON
innodb_lock_wait_timeout 50
innodb_locks_unsafe_for_binlog OFF
innodb_log_buffer_size 16777216
innodb_log_checksums ON
innodb_log_compressed_pages ON
innodb_log_file_size 50331648
innodb_log_files_in_group 2
innodb_log_group_home_dir ./
innodb_log_write_ahead_size 8192
innodb_lru_scan_depth 128
innodb_max_dirty_pages_pct 75
innodb_max_dirty_pages_pct_lwm 0
innodb_max_purge_lag 0
innodb_max_purge_lag_delay 0
innodb_max_undo_log_size 1073741824
innodb_monitor_disable
innodb_monitor_enable
innodb_monitor_reset
innodb_monitor_reset_all
innodb_numa_interleave OFF
innodb_old_blocks_pct 37
innodb_old_blocks_time 1000
innodb_online_alter_log_max_size 134217728
innodb_open_files 5200
innodb_optimize_fulltext_only OFF
innodb_page_cleaners 1
innodb_page_size 16384
innodb_print_all_deadlocks OFF
innodb_purge_batch_size 300
innodb_purge_rseg_truncate_frequency 128
innodb_purge_threads 4
innodb_random_read_ahead OFF
innodb_read_ahead_threshold 56
innodb_read_io_threads 4
innodb_read_only OFF
innodb_replication_delay 0
innodb_rollback_on_timeout OFF
innodb_rollback_segments 128
innodb_sort_buffer_size 1048576
innodb_spin_wait_delay 6
innodb_stats_auto_recalc ON
innodb_stats_include_delete_marked OFF
innodb_stats_method nulls_equal
innodb_stats_on_metadata OFF
innodb_stats_persistent ON
innodb_stats_persistent_sample_pages 20
innodb_stats_sample_pages 8
innodb_stats_transient_sample_pages 8
innodb_status_output OFF
innodb_status_output_locks OFF
innodb_strict_mode ON
innodb_support_xa ON
innodb_sync_array_size 1
innodb_sync_spin_loops 30
innodb_table_locks ON
innodb_temp_data_file_path ibtmp1:12M:autoextend
innodb_thread_concurrency 0
innodb_thread_sleep_delay 10000
innodb_tmpdir
innodb_undo_directory ./
innodb_undo_log_truncate OFF
innodb_undo_logs 128
innodb_undo_tablespaces 0
innodb_use_native_aio ON
innodb_version 5.7.28
innodb_write_io_threads 4
insert_id 0
interactive_timeout 28800
internal_tmp_disk_storage_engine InnoDB
join_buffer_size 262144
keep_files_on_create OFF
key_buffer_size 16777216
key_cache_age_threshold 300
key_cache_block_size 1024
key_cache_division_limit 100
keyring_operations ON
large_files_support ON
large_page_size 0
large_pages OFF
last_insert_id 0
lc_messages en_US
lc_messages_dir /usr/share/mysql/
lc_time_names en_US
license GPL
local_infile ON
lock_wait_timeout 31536000
locked_in_memory OFF
log_bin OFF
log_bin_basename
log_bin_index
log_bin_trust_function_creators OFF
log_bin_use_v1_row_events OFF
log_builtin_as_identified_by_password OFF
log_error /var/log/mysql/error.log
log_error_verbosity 3
log_output FILE
log_queries_not_using_indexes OFF
log_slave_updates OFF
log_slow_admin_statements OFF
log_slow_slave_statements OFF
log_statements_unsafe_for_binlog ON
log_syslog OFF
log_syslog_facility daemon
log_syslog_include_pid ON
log_syslog_tag
log_throttle_queries_not_using_indexes 0
log_timestamps UTC
log_warnings 2
long_query_time 10
low_priority_updates OFF
lower_case_file_system OFF
lower_case_table_names 0
master_info_repository FILE
master_verify_checksum OFF
max_allowed_packet 16777216
max_binlog_cache_size 1.84467440737095E+019
max_binlog_size 104857600
max_binlog_stmt_cache_size 1.84467440737095E+019
max_connect_errors 100
max_connections 151
max_delayed_threads 20
max_digest_length 1024
max_error_count 64
max_execution_time 0
max_heap_table_size 16777216
max_insert_delayed_threads 20
max_join_size 1.84467440737096E+019
max_length_for_sort_data 1024
max_points_in_geometry 65536
max_prepared_stmt_count 16382
max_relay_log_size 0
max_seeks_for_key 1.84467440737096E+019
max_sort_length 1024
max_sp_recursion_depth 0
max_tmp_tables 32
max_user_connections 0
max_write_lock_count 1.84467440737096E+019
metadata_locks_cache_size 1024
metadata_locks_hash_instances 8
min_examined_row_limit 0
multi_range_count 256
myisam_data_pointer_size 6
myisam_max_sort_file_size 9.22337203685373E+018
myisam_mmap_size 1.84467440737096E+019
myisam_recover_options BACKUP
myisam_repair_threads 1
myisam_sort_buffer_size 8388608
myisam_stats_method nulls_unequal
myisam_use_mmap OFF
mysql_native_password_proxy_users OFF
net_buffer_length 16384
net_read_timeout 30
net_retry_count 10
net_write_timeout 60
new OFF
ngram_token_size 2
offline_mode OFF
old OFF
old_alter_table OFF
old_passwords 0
open_files_limit 11000
optimizer_prune_level 1
optimizer_search_depth 62
optimizer_switch index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on,engine_condition_pushdown=on,index_condition_pushdown=on,mrr=on,mrr_cost_based=on,block_nested_loop=on,batched_key_access=off,materialization=on,semijoin=on,loosescan=on,firstmatch=on,duplicateweedout=on,subquery_materialization_cost_based=on,use_index_extensions=on,condition_fanout_filter=on,derived_merge=on
optimizer_trace enabled=off,one_line=off
optimizer_trace_features greedy_search=on,range_optimizer=on,dynamic_range=on,repeated_subselect=on
optimizer_trace_limit 1
optimizer_trace_max_mem_size 16384
optimizer_trace_offset -1
parser_max_mem_size 1.84467440737096E+019
performance_schema ON
performance_schema_accounts_size -1
performance_schema_digests_size 10000
performance_schema_events_stages_history_long_size 10000
performance_schema_events_stages_history_size 10
performance_schema_events_statements_history_long_size 10000
performance_schema_events_statements_history_size 10
performance_schema_events_transactions_history_long_size 10000
performance_schema_events_transactions_history_size 10
performance_schema_events_waits_history_long_size 10000
performance_schema_events_waits_history_size 10
performance_schema_hosts_size -1
performance_schema_max_cond_classes 80
performance_schema_max_cond_instances -1
performance_schema_max_digest_length 1024
performance_schema_max_file_classes 80
performance_schema_max_file_handles 32768
performance_schema_max_file_instances -1
performance_schema_max_index_stat -1
performance_schema_max_memory_classes 320
performance_schema_max_metadata_locks -1
performance_schema_max_mutex_classes 210
performance_schema_max_mutex_instances -1
performance_schema_max_prepared_statements_instances -1
performance_schema_max_program_instances -1
performance_schema_max_rwlock_classes 50
performance_schema_max_rwlock_instances -1
performance_schema_max_socket_classes 10
performance_schema_max_socket_instances -1
performance_schema_max_sql_text_length 1024
performance_schema_max_stage_classes 150
performance_schema_max_statement_classes 193
performance_schema_max_statement_stack 10
performance_schema_max_table_handles -1
performance_schema_max_table_instances -1
performance_schema_max_table_lock_stat -1
performance_schema_max_thread_classes 50
performance_schema_max_thread_instances -1
performance_schema_session_connect_attrs_size 512
performance_schema_setup_actors_size -1
performance_schema_setup_objects_size -1
performance_schema_users_size -1
pid_file /var/run/mysqld/mysqld.pid
plugin_dir /usr/lib/mysql/plugin/
port 3306
preload_buffer_size 32768
profiling OFF
profiling_history_size 15
protocol_version 10
proxy_user
pseudo_slave_mode OFF
pseudo_thread_id 8224
query_alloc_block_size 8192
query_cache_limit 1048576
query_cache_min_res_unit 4096
query_cache_size 16777216
query_cache_type OFF
query_cache_wlock_invalidate OFF
query_prealloc_size 8192
rand_seed1 0
rand_seed2 0
range_alloc_block_size 4096
range_optimizer_max_mem_size 8388608
rbr_exec_mode STRICT
read_buffer_size 131072
read_only OFF
read_rnd_buffer_size 262144
relay_log
relay_log_basename /var/lib/mysql/demo-relay-bin
relay_log_index /var/lib/mysql/demo-relay-bin.index
relay_log_info_file relay-log.info
relay_log_info_repository FILE
relay_log_purge ON
relay_log_recovery OFF
relay_log_space_limit 0
report_host
report_password
report_port 3306
report_user
require_secure_transport ON
rpl_stop_slave_timeout 31536000
secure_auth ON
secure_file_priv /var/lib/mysql-files/
server_id 0
server_id_bits 32
server_uuid <hidden>
session_track_gtids OFF
session_track_schema ON
session_track_state_change OFF
session_track_system_variables time_zone,autocommit,character_set_client,character_set_results,character_set_connection
session_track_transaction_info OFF
sha256_password_auto_generate_rsa_keys ON
sha256_password_private_key_path private_key.pem
sha256_password_proxy_users OFF
sha256_password_public_key_path public_key.pem
show_compatibility_56 OFF
show_create_table_verbosity OFF
show_old_temporals OFF
skip_external_locking ON
skip_name_resolve OFF
skip_networking OFF
skip_show_database OFF
slave_allow_batching OFF
slave_checkpoint_group 512
slave_checkpoint_period 300
slave_compressed_protocol OFF
slave_exec_mode STRICT
slave_load_tmpdir /tmp
slave_max_allowed_packet 1073741824
slave_net_timeout 60
slave_parallel_type DATABASE
slave_parallel_workers 0
slave_pending_jobs_size_max 16777216
slave_preserve_commit_order OFF
slave_rows_search_algorithms TABLE_SCAN,INDEX_SCAN
slave_skip_errors OFF
slave_sql_verify_checksum ON
slave_transaction_retries 10
slave_type_conversions
slow_launch_time 2
slow_query_log OFF
slow_query_log_file /var/lib/mysql/demo-slow.log
socket /var/run/mysqld/mysqld.sock
sort_buffer_size 262144
sql_auto_is_null OFF
sql_big_selects ON
sql_buffer_result OFF
sql_log_bin ON
sql_log_off OFF
sql_mode ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
sql_notes ON
sql_quote_show_create ON
sql_safe_updates OFF
sql_select_limit 1.84467440737096E+019
sql_slave_skip_counter 0
sql_warnings OFF
stored_program_cache 256
super_read_only OFF
sync_binlog 1
sync_frm ON
sync_master_info 10000
sync_relay_log 10000
sync_relay_log_info 10000
system_time_zone GMT
table_definition_cache 2000
table_open_cache 5200
table_open_cache_instances 16
thread_cache_size 8
thread_handling one-thread-per-connection
thread_stack 262144
time_format %H:%i:%s
time_zone SYSTEM
timestamp 1579095336.07864
tls_version TLSv1,TLSv1.1,TLSv1.2
tmp_table_size 16777216
tmpdir /tmp
transaction_alloc_block_size 8192
transaction_allow_batching OFF
transaction_isolation REPEATABLE-READ
transaction_prealloc_size 4096
transaction_read_only OFF
transaction_write_set_extraction OFF
tx_isolation REPEATABLE-READ
tx_read_only OFF
unique_checks ON
updatable_views_with_limit YES
version 5.7.28-0ubuntu0.16.04.2
version_comment (Ubuntu)
version_compile_machine x86_64
version_compile_os Linux
wait_timeout 28800
warning_count 0
SHOW GLOBAL STATUS; (less SSL related info and any com_*=0 values) output:
Aborted_clients 0
Aborted_connects 4
Binlog_cache_disk_use 0
Binlog_cache_use 0
Binlog_stmt_cache_disk_use 0
Binlog_stmt_cache_use 0
Bytes_received 120596117
Bytes_sent 423055987
Com_admin_commands 1422
Com_change_db 1969
Com_delete 26
Com_delete_multi 5
Com_flush 5
Com_insert 543
Com_lock_tables 106103
Com_select 290121
Com_set_option 3952
Com_show_charsets 4
Com_show_fields 1756
Com_show_keys 3
Com_show_plugins 1
Com_show_status 2317
Com_show_tables 4
Com_show_variables 10
Com_unlock_tables 106103
Com_update 119462
Connection_errors_accept 0
Connection_errors_internal 0
Connection_errors_max_connections 0
Connection_errors_peer_address 0
Connection_errors_select 0
Connection_errors_tcpwrap 0
Connections 53918
Created_tmp_disk_tables 7205
Created_tmp_files 6
Created_tmp_tables 26682
Delayed_errors 0
Delayed_insert_threads 0
Delayed_writes 0
Flush_commands 1
Handler_commit 516258
Handler_delete 605
Handler_discover 0
Handler_external_lock 1131715
Handler_mrr_init 0
Handler_prepare 0
Handler_read_first 251891
Handler_read_key 1450835
Handler_read_last 0
Handler_read_next 46912240
Handler_read_prev 0
Handler_read_rnd 333804
Handler_read_rnd_next 77706400
Handler_rollback 0
Handler_savepoint 0
Handler_savepoint_rollback 0
Handler_update 20612
Handler_write 139820
Innodb_buffer_pool_dump_status Dumping of buffer pool not started
Innodb_buffer_pool_load_status Buffer pool(s) load completed at 200110 15:44:11
Innodb_buffer_pool_resize_status
Innodb_buffer_pool_pages_data 7744
Innodb_buffer_pool_bytes_data 126877696
Innodb_buffer_pool_pages_dirty 0
Innodb_buffer_pool_bytes_dirty 0
Innodb_buffer_pool_pages_flushed 10525
Innodb_buffer_pool_pages_free 128
Innodb_buffer_pool_pages_misc 319
Innodb_buffer_pool_pages_total 8191
Innodb_buffer_pool_read_ahead_rnd 0
Innodb_buffer_pool_read_ahead 2174
Innodb_buffer_pool_read_ahead_evicted 552
Innodb_buffer_pool_read_requests 92861248
Innodb_buffer_pool_reads 230500
Innodb_buffer_pool_wait_free 0
Innodb_buffer_pool_write_requests 490867
Innodb_data_fsyncs 6682
Innodb_data_pending_fsyncs 0
Innodb_data_pending_reads 0
Innodb_data_pending_writes 0
Innodb_data_read 3812250112
Innodb_data_reads 257019
Innodb_data_writes 36166
Innodb_data_written 301705728
Innodb_dblwr_pages_written 5776
Innodb_dblwr_writes 1121
Innodb_log_waits 0
Innodb_log_write_requests 24009
Innodb_log_writes 23298
Innodb_os_log_fsyncs 3651
Innodb_os_log_pending_fsyncs 0
Innodb_os_log_pending_writes 0
Innodb_os_log_written 34017280
Innodb_page_size 16384
Innodb_pages_created 388
Innodb_pages_read 232676
Innodb_pages_written 10525
Innodb_row_lock_current_waits 0
Innodb_row_lock_time 0
Innodb_row_lock_time_avg 0
Innodb_row_lock_time_max 0
Innodb_row_lock_waits 0
Innodb_rows_deleted 605
Innodb_rows_inserted 33914
Innodb_rows_read 125144394
Innodb_rows_updated 20612
Innodb_num_open_files 5200
Innodb_truncated_status_writes 0
Innodb_available_undo_logs 128
Key_blocks_not_flushed 0
Key_blocks_unused 13396
Key_blocks_used 3
Key_read_requests 6
Key_reads 3
Key_write_requests 0
Key_writes 0
Locked_connects 0
Max_execution_time_exceeded 0
Max_execution_time_set 0
Max_execution_time_set_failed 0
Max_used_connections 14
Max_used_connections_time 10/01/20 15:50
Not_flushed_delayed_rows 0
Ongoing_anonymous_transaction_count 0
Open_files 0
Open_streams 0
Open_table_definitions 3464
Open_tables 5200
Opened_files 337104
Opened_table_definitions 140571
Opened_tables 76095
Performance_schema_accounts_lost 0
Performance_schema_cond_classes_lost 0
Performance_schema_cond_instances_lost 0
Performance_schema_digest_lost 0
Performance_schema_file_classes_lost 0
Performance_schema_file_handles_lost 0
Performance_schema_file_instances_lost 0
Performance_schema_hosts_lost 0
Performance_schema_index_stat_lost 0
Performance_schema_locker_lost 0
Performance_schema_memory_classes_lost 0
Performance_schema_metadata_lock_lost 0
Performance_schema_mutex_classes_lost 0
Performance_schema_mutex_instances_lost 0
Performance_schema_nested_statement_lost 0
Performance_schema_prepared_statements_lost 0
Performance_schema_program_lost 0
Performance_schema_rwlock_classes_lost 0
Performance_schema_rwlock_instances_lost 0
Performance_schema_session_connect_attrs_lost 0
Performance_schema_socket_classes_lost 0
Performance_schema_socket_instances_lost 0
Performance_schema_stage_classes_lost 0
Performance_schema_statement_classes_lost 0
Performance_schema_table_handles_lost 0
Performance_schema_table_instances_lost 0
Performance_schema_table_lock_stat_lost 0
Performance_schema_thread_classes_lost 0
Performance_schema_thread_instances_lost 0
Performance_schema_users_lost 0
Prepared_stmt_count 0
Qcache_free_blocks 1
Qcache_free_memory 16760152
Qcache_hits 0
Qcache_inserts 0
Qcache_lowmem_prunes 0
Qcache_not_cached 184049
Qcache_queries_in_cache 0
Qcache_total_blocks 1
Queries 687716
Questions 684326
Rsa_public_key <removed>
Select_full_join 2827
Select_full_range_join 319
Select_range 56255
Select_range_check 1525
Select_scan 156904
Slave_open_temp_tables 0
Slow_launch_threads 0
Slow_queries 0
Sort_merge_passes 0
Sort_range 61935
Sort_rows 116417
Sort_scan 99600
Table_locks_immediate 458
Table_locks_waited 0
Table_open_cache_hits 381570
Table_open_cache_misses 76095
Table_open_cache_overflows 70888
Tc_log_max_pages_used 0
Tc_log_page_size 0
Tc_log_page_waits 0
Threads_cached 7
Threads_connected 3
Threads_created 14
Threads_running 1
Uptime 424288
Uptime_since_flush_status 424288
Short answer: If you are not swapping and not crashing, there is nothing to worry about. But, since OOM is killing it, then something needs to be tuned lower.
Long answer...
Change swappiness to 1. (It may be defaulted to 60.)
For only 4GB of RAM, do not set innodb_buffer_pool_size to 75-80% of RAM as someone else suggested. You will run out of RAM. Swapping is terrible for performance. Leave it at 1G for now. And this assumes you do not have any other applications running on the machine.
The buffer_pool grows but does not shrink. It is reused. It is a "cache" for blocks of data and indexes of the various tables you are working on.
It sounds like 400MB is chewed up by performance_schema. If you are not using that, turn it off. If you are using it, then lower the buffer_pool to 1000M to make room for PS.
table_open_cache = 5200 -- Do you have thousands of tables? Perhaps 1000 would be safer.
Dozens, even hundreds, of databases is not a problem. table_open_cache is a cache, so it does not need to be as large as the number of tables you have. But, since there are multiple entries for one table when multiple connections are looking at that table, it can be too small.
For further analysis, please provide the info discussed here: http://mysql.rjweb.org/doc.php/mysql_analysis#tuning I will see if there are further clues in the VARIABLES and GLOBAL STATUS.
1K qps is moderately busy (~70th percentile); 10K gets more exciting. Since you seem to have bursts of activity, perhaps you are hitting 10K?
I am not a fan of "throwing hardware at a problem".
An analysis of the settings
Observations:
* Version: 5.7.28-0ubuntu0.16.04.2
* 4 GB of RAM
* Uptime = 4d 21:51:28
* Are you sure this was a SHOW GLOBAL STATUS ?
* You are not running on Windows.
* Running 64-bit version
* You appear to be running entirely (or mostly) InnoDB.
The More Important Issues:
Do not use LOCK TABLES / UNLOCK TABLES with InnoDB. Use transactions. (Or, let's discuss why you are using them.)
innodb_buffer_pool_size = 1G -- or lower if you have a lot of other apps running -- Caution: 1G would make the OOM issue worse, so don't do this until figuring out the OOM problem.
Your system seems to be rather lightly loaded -- except for the number of tables that are open. Can you elaborate on what the app does?
Possibly a lot of inefficient queries. Set long_query_time = 1 and turn on the slowlog.
Details and other observations:
( (key_buffer_size / 0.20 + innodb_buffer_pool_size / 0.70) ) = ((16M / 0.20 + 128M / 0.70)) / 4096M = 6.4% -- Most of available ram should be made available for caching.
-- http://mysql.rjweb.org/doc.php/memory
( table_open_cache ) = 5,200 -- Number of table descriptors to cache
-- Several hundred is usually good.
( Table_open_cache_misses / (Table_open_cache_hits + Table_open_cache_misses) ) = 76,095 / (381570 + 76095) = 16.6% -- Effectiveness of table_open_cache.
-- Increase table_open_cache (now 5200) and check table_open_cache_instances (now 16).
( innodb_buffer_pool_size ) = 128M -- InnoDB Data + Index cache
-- 128M (an old default) is woefully small.
( Innodb_buffer_pool_read_ahead_evicted / Innodb_buffer_pool_read_ahead ) = 552 / 2174 = 25.4% -- Utility of read_ahead.
-- Turn off innodb_random_read_ahead (now OFF).
( Innodb_dblwr_pages_written/Innodb_pages_written ) = 5,776/10525 = 54.9% -- Seems like these values should be equal?
( Innodb_os_log_written / (Uptime / 3600) / innodb_log_files_in_group / innodb_log_file_size ) = 34,017,280 / (424288 / 3600) / 2 / 48M = 0.00287 -- Ratio
-- (see minutes)
( Uptime / 60 * innodb_log_file_size / Innodb_os_log_written ) = 424,288 / 60 * 48M / 34017280 = 10,462 -- Minutes between InnoDB log rotations Beginning with 5.6.8, this can be changed dynamically; be sure to also change my.cnf.
-- (The recommendation of 60 minutes between rotations is somewhat arbitrary.) Adjust innodb_log_file_size (now 50331648). (Cannot change in AWS.)
( innodb_flush_method ) = innodb_flush_method = -- How InnoDB should ask the OS to write blocks. Suggest O_DIRECT or O_ALL_DIRECT (Percona) to avoid double buffering. (At least for Unix.) See chrischandler for caveat about O_ALL_DIRECT
( innodb_flush_neighbors ) = 1 -- A minor optimization when writing blocks to disk.
-- Use 0 for SSD drives; 1 for HDD.
( innodb_io_capacity ) = 200 -- I/O ops per second capable on disk . 100 for slow drives; 200 for spinning drives; 1000-2000 for SSDs; multiply by RAID factor.
( innodb_print_all_deadlocks ) = innodb_print_all_deadlocks = OFF -- Whether to log all Deadlocks.
-- If you are plagued with Deadlocks, turn this on. Caution: If you have lots of deadlocks, this may write a lot to disk.
( character_set_server ) = character_set_server = utf8
-- Charset problems may be helped by setting character_set_server (now utf8) to utf8mb4. That is the future default.
( net_buffer_length / max_allowed_packet ) = 16,384 / 16M = 0.10%
( local_infile ) = local_infile = ON
-- local_infile (now ON) = ON is a potential security issue
( Select_scan / Com_select ) = 156,904 / 290121 = 54.1% -- % of selects doing full table scan. (May be fooled by Stored Routines.)
-- Add indexes / optimize queries
( innodb_autoinc_lock_mode ) = 1 -- Galera: desires 2 -- 2 = "interleaved"; 1 = "consecutive" is typical; 0 = "traditional".
-- Galera desires 2; 2 requires BINLOG_FORMAT=ROW or MIXED
( slow_query_log ) = slow_query_log = OFF -- Whether to log slow queries. (5.1.12)
( long_query_time ) = 10 -- Cutoff (Seconds) for defining a "slow" query.
-- Suggest 2
( log_slow_slave_statements ) = log_slow_slave_statements = OFF -- (5.6.11, 5.7.1) By default, replicated statements won't show up in the slowlog; this causes them to show.
-- It can be helpful in the slowlog to see writes that could be interfering with Slave reads.
( back_log ) = 80 -- (Autosized as of 5.6.6; based on max_connections)
-- Raising to min(150, max_connections (now 151)) may help when doing lots of connections.
You have the Query Cache half-off. You should set both query_cache_type = OFF and query_cache_size = 0 . There is (according to a rumor) a 'bug' in the QC code that leaves some code on unless you turn off both of those settings.
Abnormally small:
Com_insert = 4.6 /HR
Created_tmp_files = 0.051 /HR
Handler_write = 0.33 /sec
Innodb_buffer_pool_bytes_data = 299 /sec
Key_read_requests = 0.051 /HR
Key_reads+Key_writes + Innodb_pages_read+Innodb_pages_written+Innodb_dblwr_writes+Innodb_buffer_pool_pages_flushed = 0.6 /sec
Open_files = 0
Table_locks_immediate = 3.9 /HR
Abnormally large:
Com_unlock_tables = 0.25 /sec
Innodb_num_open_files = 5,200
Open_table_definitions = 3,464
Open_tables = 5,200
performance_schema_max_rwlock_classes = 50
Abnormal strings:
innodb_fast_shutdown = 1
optimizer_trace = enabled=off,one_line=off
optimizer_trace_features = greedy_search=on, range_optimizer=on, dynamic_range=on, repeated_subselect=on
require_secure_transport = ON
slave_rows_search_algorithms = TABLE_SCAN,INDEX_SCAN

MySQL TokuDB engine using too much CPU

I have converted tables of a database from InnoDB to TokuDB and i noticed that with TokuDB, reads are using way too much CPU. Why is this?
To be more specific, the server with TokuDB tables is a slave of a server with InnoDB which is part of the PXC. The slave just used regular percona server and not PXC. But the slave seems to be using way too much CPU and i do not know why?
Below is my my.cnf config:
[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock
[mysqld_safe]
thp-setting=never
socket = /var/run/mysqld/mysqld.sock
nice = 0
flush_caches
numa_interleave
core-file-size = unlimited
open_files_limit = 1024
[mysqld]
back_log = 65535
bind-address = 0.0.0.0
binlog_format = ROW
character_set_server = utf8
collation_server = utf8_general_ci
core_file
basedir = /usr
datadir = /var/lib/mysql
#default_storage_engine = InnoDB
enforce-gtid-consistency = 1
expand_fast_index_creation = 1
expire_logs_days = 7
gtid_mode = ON
innodb_autoinc_lock_mode = 2
innodb_buffer_pool_instances = 1
innodb_buffer_pool_populate = 1
innodb_buffer_pool_size = 512M
innodb_data_file_path = ibdata1:64M;ibdata2:64M:autoextend
innodb_file_format = Barracuda
innodb_file_per_table
innodb_force_recovery = 1
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT
innodb_io_capacity = 1600
innodb_large_prefix
innodb_locks_unsafe_for_binlog = 1
innodb_log_file_size = 64M
innodb_print_all_deadlocks = 1
innodb_read_io_threads = 64
innodb_stats_on_metadata = FALSE
innodb_support_xa = FALSE
innodb_write_io_threads = 64
lc-messages-dir = /usr/share/mysql
log-bin = mysqld-bin
log-queries-not-using-indexes
log-slave-updates
long_query_time = 1
master_info_repository = TABLE
max_allowed_packet = 64M
max_connect_errors = 4294967295
max_connections = 2500
max_user_connections = 2550
min_examined_row_limit = 1000
open_files_limit = 1024
port = 3306
relay_log_info_repository = TABLE
relay-log-recovery = TRUE
relay-log-recovery = 1
skip-external-locking
skip-name-resolve
slave_parallel_workers = 8
slow_query_log = 1
slow_query_log_timestamp_always = 1
socket = /var/run/mysqld/mysqld.sock
table_open_cache = 4096
thread_cache = 1024
tmpdir = /srv/tmp
transaction_isolation = REPEATABLE-READ
updatable_views_with_limit = 0
user = mysql
wait_timeout = 60
server-id = 2
# TokuDB fine tuning
default_storage_engine = TokuDB
tokudb_analyze_time = 5
#tokudb_cache_size = 6G
tokudb_directio = 1
tokudb_commit_sync = 0
tokudb_fsync_log_period = 1000
tokudb_load_save_space =1
tokudb_alter_print_error=0
tokudb_block_size = 4MB
tokudb_bulk_fetch = 1
tokudb_disable_slow_alter = 1
tokudb_last_lock_timeout = empty
tokudb_row_format = tokudb_quicklz
#tokudb_data_dir = /var/lib/tokudb
[mysqldump]
quick
quote-names
max_allowed_packet = 16M
[mysql]
#no-auto-rehash # faster start of mysql but no tab completition
[isamchk]
key_buffer = 16M
!includedir /etc/mysql/conf.d/
The following replication message was being reported by our monitoring system xymon when tokudb_cache_size when initially set to 80% of total RAM.
2016-02-25 16:42:04 9604 [Warning] Neither --relay-log nor --relay-log-index were used; so replication may break when this MySQL server acts as a slave and has his hostname changed!! Please use '--relay-log=db-kdb-slave-6-relay-bin' to avoid this problem.
2016-02-25 16:42:05 9604 [Warning] Recovery from master pos 552554502 and file mysqld-bin.001163. Previous relay log pos and relay log file had been set to 552554714, ./db-kdb-slave-6-relay-bin.002933 respectively.
2016-02-25 16:42:05 9604 [Warning] Storing MySQL user name or password information in the master info repository is not secure and is therefore not recommended. Please consider using the USER and PASSWORD connection options for START SLAVE; see the 'START SLAVE Syntax' in the MySQL Manual for more information.
------More info about the Master server running InnoDB and part of PXC-----------
## Results from top
top - 10:05:12 up 14 days, 7:56, 2 users, load average: 2.16, 2.31, 2.39
Tasks: 413 total, 1 running, 412 sleeping, 0 stopped, 0 zombie
%Cpu(s): 8.9 us, 0.6 sy, 0.0 ni, 89.9 id, 0.3 wa, 0.0 hi, 0.2 si, 0.0 st
KiB Mem: 65704012 total, 63553216 used, 2150796 free, 169832 buffers
KiB Swap: 975868 total, 809892 used, 165976 free. 16304268 cached Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
2485 mysql 20 0 60.146g 0.045t 2.612g S 314.9 73.3 27762:43 mysqld
## disk info
george#db-erp-3:~$ df -h
Filesystem Size Used Avail Use% Mounted on
udev 32G 8.0K 32G 1% /dev
tmpfs 6.3G 1.2M 6.3G 1% /run
/dev/sda2 274G 2.1G 258G 1% /
none 4.0K 0 4.0K 0% /sys/fs/cgroup
none 5.0M 0 5.0M 0% /run/lock
none 32G 0 32G 0% /run/shm
none 100M 0 100M 0% /run/user
/dev/nvme0n1p1 1.1T 542G 503G 52% /srv
na1:/vol/yphome 4.5T 3.7T 875G 82% /net/account
## Memory info
george#db-erp-3:~$ free -g
total used free shared buffers cached
Mem: 62 60 2 0 0 15
-/+ buffers/cache: 44 17
Swap: 0 0 0
george#db-erp-3:~$
## Database info
+--------------------+----------------------+
| Data Base Name | Data Base Size in MB |
+--------------------+----------------------+
| information_schema | 0.00976563 |
| dberp | 347143.32031250 |
| mysql | 2.11562061 |
| performance_schema | 0.00000000 |
+--------------------+----------------------+
4 rows in set (0.13 sec)
+--------------------+----------------------+------------------+
| Data Base Name | Data Base Size in MB | Free Space in MB |
+--------------------+----------------------+------------------+
| information_schema | 0.00976563 | 0.00000000 |
| dberp | 347143.32031250 | 6270.00000000 |
| mysql | 2.11562061 | 4.00199127 |
| performance_schema | 0.00000000 | 0.00000000 |
+--------------------+----------------------+------------------+
4 rows in set (0.03 sec)
Your CPU will be higher for reads because TokuDB data needs to be decompressed to be used. Also, if this slave is processing any activity from the master than it's also doing compression for the insert/update/delete activity.
Couple of ideas.
1. Reduce the value of tokudb_block_size. While 4MB is great for compression it means that your point queries need to decompress a lot more data than they have to. Try using 256KB and see how CPU and performance changes. You might have to rebuild your slave to accomplish this easily (I'm now over a year away from working at TokuDB).
2. Look at your tokudb_cache_size. It defaults to 50% of RAM, but if nothing else is on this server you should up it to somewhere between 75% and 80%. This will mean less reads and decompression since more data will be in your cache.

MySQL query performance issue with MyISAM table

Folks
I have a table( billing_data) with about 60 million records. The table engine is MyISAM. We have a stored procedure that will read csv file and dump in temp table every 10-15 mins and then it will be inserted in this table( billing_data). There are lot of records being inserted in this table.
we are trying to run the query as below on the same table( plus the other tables in join) to generate the report.
"select b.destination,b.release_cause_protocol_stack,b.binary_value_protocol_stack,b.release_cause from billing_datas b inner join (select id from carriermasters where id in (99, 100, 101) ) c1 on b.carrierid_customer=c1.idinner join (select id from technicalprofiles where id in (83, 274, 84, 416)) t1 on b.technical_profileid_customer=t1.id inner join (select trunk from trunks where trunk in (90409, 90310, 30230, 30313) ) tr1 on b.origination_trunkid=tr1.trunk inner join (select id from carriermasters where id in (214, 215, 59, 60, 62, 292, 63, 216, 64, 61, 217, 274, 58) ) c2 on b.carrierid_supplier=c2.id inner join (select id from technicalprofiles where id in (223, 55, 224, 56, 225, 57, 226, 58, 227, 228, 229, 230, 393, 394, 395, 59, 231, 232, 233, 460, 234)) t2 on b.technical_profileid_supplier=t2.id inner join (select trunk from trunks where trunk in (90106, 30249, 90249, 30250, 90250, 90445, 30409, 90446, 30410, 30294, 90363, 30293, 90293, 30175, 30146, 90146, 90435, 90049, 30177, 90294, 90130, 30130, 90189, 30145, 90145, 90389, 30400, 90429, 90121, 90159)) tr2 on b.supplierid=tr2.trunk where b.start_time_date between '2013-08-02 00:00:00' and '2013-08-02 23:59:59' order by b.start_time_date asc"
NOw the scenario is
a) if we stop the cron job to insert the data in the billing_datas table, then the above query takes about more than 40 mins.
b) if the cron job is running ( inserting the data from the file) to the temp table and then to billing_data. At that time the above query will run forever.
I m not sure where i m getting wrong.
we also checked the indexes and its fine.
Mysql query : show variables
automatic_sp_privileges ON
back_log 50
big_tables OFF
binlog_cache_size 32768
binlog_direct_non_transactional_updates OFF
binlog_format STATEMENT
bulk_insert_buffer_size 8388608
completion_type 0
concurrent_insert 1
connect_timeout 10
default_week_format 0
delay_key_write ON
delayed_insert_limit 100
delayed_insert_timeout 300
delayed_queue_size 1000
div_precision_increment 4
engine_condition_pushdown ON
event_scheduler OFF
flush OFF
flush_time 0
foreign_key_checks ON
ft_query_expansion_limit 20
ignore_builtin_innodb OFF
innodb_adaptive_hash_index ON
innodb_additional_mem_pool_size 1048576
innodb_autoextend_increment 8
innodb_autoinc_lock_mode 1
innodb_buffer_pool_size 8388608
innodb_checksums ON
innodb_commit_concurrency 0
innodb_concurrency_tickets 500
innodb_data_file_path ibdata1:10M:autoextend
innodb_data_home_dir
innodb_doublewrite ON
innodb_fast_shutdown 1
innodb_file_io_threads 4
innodb_file_per_table OFF
innodb_flush_log_at_trx_commit 1
innodb_flush_method
innodb_force_recovery 0
innodb_lock_wait_timeout 50
innodb_locks_unsafe_for_binlog OFF
innodb_log_buffer_size 1048576
innodb_log_file_size 5242880
innodb_log_files_in_group 2
innodb_max_dirty_pages_pct 90
innodb_max_purge_lag 0
innodb_mirrored_log_groups 1
innodb_open_files 300
innodb_rollback_on_timeout OFF
innodb_stats_method nulls_equal
innodb_stats_on_metadata ON
innodb_support_xa ON
innodb_sync_spin_loops 20
innodb_table_locks ON
innodb_thread_concurrency 8
innodb_thread_sleep_delay 10000
innodb_use_legacy_cardinality_algorithm ON
insert_id 0
interactive_timeout 28800
join_buffer_size 131072
keep_files_on_create OFF
key_buffer_size 8384512
key_cache_age_threshold 300
key_cache_block_size 1024
key_cache_division_limit 100
large_files_support ON
large_page_size 0
large_pages OFF
last_insert_id 0
local_infile ON
locked_in_memory OFF
log OFF
log_bin OFF
log_bin_trust_function_creators OFF
log_bin_trust_routine_creators OFF
long_query_time 10
low_priority_updates OFF
max_allowed_packet 1048576
max_binlog_cache_size 1.84467E+19
max_binlog_size 1073741824
max_connect_errors 10
max_connections 151
max_delayed_threads 20
max_error_count 64
max_heap_table_size 16777216
max_insert_delayed_threads 20
max_join_size 1.84467E+19
max_length_for_sort_data 1024
max_long_data_size 1048576
max_prepared_stmt_count 16382
max_relay_log_size 0
max_seeks_for_key 1.84467E+19
max_sort_length 1024
max_sp_recursion_depth 0
max_tmp_tables 32
max_user_connections 0
max_write_lock_count 1.84467E+19
min_examined_row_limit 0
multi_range_count 256
myisam_data_pointer_size 6
myisam_max_sort_file_size 9.22337E+18
myisam_mmap_size 1.84467E+19
myisam_recover_options OFF
myisam_repair_threads 1
myisam_sort_buffer_size 8388608
myisam_stats_method nulls_unequal
myisam_use_mmap OFF
net_buffer_length 16384
net_read_timeout 30
net_retry_count 10
net_write_timeout 60
open_files_limit 1024
optimizer_prune_level 1
optimizer_search_depth 62
optimizer_switch index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on
preload_buffer_size 32768
pseudo_thread_id 7256
query_alloc_block_size 8192
query_cache_limit 1048576
query_cache_min_res_unit 4096
query_cache_size 0
query_cache_type ON
query_cache_wlock_invalidate OFF
query_prealloc_size 8192
range_alloc_block_size 4096
read_buffer_size 131072
read_only OFF
read_rnd_buffer_size 262144
skip_external_locking ON
slow_launch_time 2
sort_buffer_size 2097144
sql_auto_is_null ON
sql_big_selects ON
sql_big_tables OFF
sql_buffer_result OFF
sql_log_bin ON
sql_log_off OFF
sql_log_update ON
sql_low_priority_updates OFF
sql_max_join_size 1.84467E+19
sql_quote_show_create ON
sql_safe_updates OFF
sql_select_limit 1.84467E+19
storage_engine MyISAM
sync_binlog 0
sync_frm ON
table_definition_cache 256
table_lock_wait_timeout 50
table_open_cache 64
table_type MyISAM
thread_cache_size 0
thread_handling one-thread-per-connection
thread_stack 262144
timed_mutexes OFF
tmp_table_size 16777216
transaction_alloc_block_size 8192
transaction_prealloc_size 4096
unique_checks ON
updatable_views_with_limit YES
version 05/01/69
version_compile_os redhat-linux-gnu
wait_timeout 28800
SELECT b.destination
, b.release_cause_protocol_stack
, b.binary_value_protocol_stack
, b.release_cause
FROM billing_datas b
JOIN carriermasters customer
ON b.carrierid_customer = customer.id
JOIN technicalprofiles tpc
ON b.technical_profileid_customer = tpc.id
JOIN trunks kc
ON b.origination_trunkid = kc.trunk
JOIN carriermasters supplier
ON b.carrierid_supplier = supplier.id
JOIN technicalprofiles tps
ON b.technical_profileid_supplier = tps.id
JOIN trunks ks
ON b.supplierid = ks.trunk
WHERE b.start_time_date BETWEEN '2013-08-02 00:00:00' AND '2013-08-02 23:59:59'
AND customer.id IN (99, 100, 101)
AND tpc.id IN (83, 274, 84, 416)
AND kc.trunk IN (90409, 90310, 30230, 30313)
AND supplier.id IN (214, 215, 59, 60, 62, 292, 63, 216, 64, 61, 217, 274, 58)
AND tps.id IN (223, 55, 224, 56, 225, 57, 226, 58, 227, 228, 229, 230, 393, 394, 395, 59, 231, 232, 233, 460, 234)
AND ks.trunk IN (90106, 30249, 90249, 30250, 90250, 90445, 30409, 90446, 30410, 30294, 90363, 30293, 90293, 30175, 30146, 90146, 90435, 90049, 30177, 90294, 90130, 30130, 90189, 30145, 90145, 90389, 30400, 90429, 90121, 90159)
ORDER
BY b.start_time_date ASC;

InnoDB insert count slow down

I batch insert to mysql innoDB table continuously, insert per second ratio is slow down.
Some behaviour are
- If shutdown data inserter (java) application, mysql do some i/o operation for a while.
- Add some insert then shutdown mysql server, shutdown operation duration is too long. If start and stop mysql without any insertion, start and stop operation so fast.
- Insert speed is not (so much) depend on data amount on table. If restart mysql server, insert per second is similar to last restart insert per second value.
I read some comment on forum, do not add continuosly, have gap between 2 insertions. Is it meaningful? Why sql is slow down?
query SHOW VARIABLES LIKE 'inno%' result is below
innodb_adaptive_flushing = ON
innodb_adaptive_hash_index = ON
innodb_additional_mem_pool_size = 20971520
innodb_autoextend_increment = 8
innodb_autoinc_lock_mode = 1
innodb_buffer_pool_instances = 1
innodb_buffer_pool_size = 268435456
innodb_change_buffering = all
innodb_checksums = ON
innodb_commit_concurrency = 0
innodb_concurrency_tickets = 500
innodb_data_file_path = ibdata1:50M:autoextend
innodb_data_home_dir =
innodb_doublewrite = ON
innodb_fast_shutdown = 1
innodb_file_format = Barracuda
innodb_file_format_check = ON
innodb_file_format_max = Antelope
innodb_file_per_table = ON
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DSYNC
innodb_force_recovery = 0
innodb_io_capacity = 200
innodb_lock_wait_timeout = 50
innodb_locks_unsafe_for_binlog = OFF
innodb_log_buffer_size = 8388608
innodb_log_file_size = 268435456
innodb_log_files_in_group = 2
innodb_log_group_home_dir = ./
innodb_max_dirty_pages_pct = 75
innodb_max_purge_lag = 0
innodb_mirrored_log_groups = 1
innodb_old_blocks_pct = 37
innodb_old_blocks_time = 0
innodb_open_files = 300
innodb_purge_batch_size = 20
innodb_purge_threads = 0
innodb_read_ahead_threshold = 56
innodb_read_io_threads = 4
innodb_replication_delay = 0
innodb_rollback_on_timeout = OFF
innodb_spin_wait_delay = 6
innodb_stats_on_metadata = ON
innodb_stats_sample_pages = 8
innodb_strict_mode = ON
innodb_support_xa = ON
innodb_sync_spin_loops = 30
innodb_table_locks = ON
innodb_thread_concurrency = 0
innodb_thread_sleep_delay = 10000
innodb_use_native_aio = OFF
innodb_use_sys_malloc = ON
innodb_version = 1.1.1
innodb_write_io_threads = 4
Thanks
InnoDB works by default in autocommit mode, which means every insert requires writing to disk twice. Using extended inserts (a.k.a. multi-row inserts) and enclosing several consecutive inserts into a transaction increases performance.
Slow down reason is insert operation stored on to cache (dirty page) and periodically written hard-drive. Until dirty page memory is full insert operations are fast then cache is full and insert speed bottleneck disc written (I/O).
You can use below sql to show dirty page size "Modified db pages"
show engine innodb status

Mysql query staying in 'SENDING DATA' state for long time when using LEFT JOIN

I have query which is going in the SENDING DATA state for very long period of time.
Can someone please help me with this : below are details
Mysql Query:
select a.msgId,a.senderId,a.destination,a.inTime,a.status as InStatus,b.status as SubStatus,c.deliverTime,substr(c.receipt,82,7) as DlvStatus
from inserted_history a left join submitted_history b on b.msgId = a.msgId left join delivered_history c on a.msgId = c.msgId
where a.inTime between '2010-08-10 00:00:00' and '2010-08-010 23:59:59' and a.systemId='ND_arber'
Total records in delivered_history : 223870168
Total records in inserted_history : 264817239
Total records in submitted_history : 226637058
Explain query returns:
id , select_type , table , type , possible_keys , key , key_len , ref , rows , Extra
1 , SIMPLE , a , ref , systemId,idx_time , systemId , 14 , const , 735310 , Using where
1 , SIMPLE , b , ref , PRIMARY , PRIMARY , 66 , gwreports2.a.msgId , 2270405 ,
1 , SIMPLE , c , ref , PRIMARY , PRIMARY , 66 , gwreports2.a.msgId , 2238701 ,
CREATE TABLE for delivered_history
CREATE TABLE `delivered_history` (
`msgId` VARCHAR(64) NOT NULL,
`systemId` VARCHAR(12) NOT NULL,
`deliverTime` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
`smscId` VARCHAR(64) NOT NULL,
`smsc` VARCHAR(20) NOT NULL,
`receipt` BLOB NULL,
`errcode` INT(11) NULL DEFAULT NULL,
PRIMARY KEY (`msgId`, `deliverTime`),
INDEX `systemId` (`systemId`),
INDEX `smsc` (`smsc`),
INDEX `idx_time` (`deliverTime`)
)
ROW_FORMAT=DEFAULT
CREATE TABLE for inserted_history
CREATE TABLE `inserted_history` (
`msgId` VARCHAR(64) NOT NULL,
`systemId` VARCHAR(12) NOT NULL,
`senderId` VARCHAR(15) NOT NULL,
`destination` VARCHAR(15) NOT NULL,
`inTime` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
`status` VARCHAR(20) NOT NULL,
`msgText` BLOB NULL,
`msgType` VARCHAR(15) NULL DEFAULT NULL,
PRIMARY KEY (`msgId`, `inTime`),
INDEX `systemId` (`systemId`),
INDEX `senderId` (`senderId`),
INDEX `destination` (`destination`),
INDEX `status` (`status`),
INDEX `idx_time` (`inTime`)
)
ROW_FORMAT=DEFAULT
CREATE TABLE for submitted_history
CREATE TABLE `submitted_history` (
`msgId` VARCHAR(64) NOT NULL,
`systemId` VARCHAR(12) NOT NULL,
`submitTime` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
`status` VARCHAR(20) NOT NULL,
`smscId` VARCHAR(64) NOT NULL,
`smsc` VARCHAR(16) NOT NULL,
`errcode` INT(6) NULL DEFAULT '0',
PRIMARY KEY (`msgId`, `submitTime`),
INDEX `systemId` (`systemId`),
INDEX `smsc` (`smsc`),
INDEX `status` (`status`),
INDEX `idx_time` (`submitTime`)
)
ROW_FORMAT=DEFAULT
ALL TABLES ARE DATE PARTIONED on the timestamp fields
List of the global variables in Mysql Server
Variable_name , Value
auto_increment_increment , 1
auto_increment_offset , 1
autocommit , ON
automatic_sp_privileges , ON
back_log , 50
basedir , /usr/
big_tables , OFF
binlog_cache_size , 32768
binlog_format , STATEMENT
bulk_insert_buffer_size , 8388608
character_set_client , latin1
character_set_connection , latin1
character_set_database , latin1
character_set_filesystem , binary
character_set_results , latin1
character_set_server , latin1
character_set_system , utf8
character_sets_dir , /usr/share/mysql/charsets/
collation_connection , latin1_swedish_ci
collation_database , latin1_swedish_ci
collation_server , latin1_swedish_ci
completion_type , 0
concurrent_insert , 1
connect_timeout , 10
datadir , /var/lib/mysql/
date_format , %Y-%m-%d
datetime_format , %Y-%m-%d %H:%i:%s
default_week_format , 0
delay_key_write , ON
delayed_insert_limit , 100
delayed_insert_timeout , 300
delayed_queue_size , 1000
div_precision_increment , 4
engine_condition_pushdown , ON
error_count , 0
event_scheduler , OFF
expire_logs_days , 10
flush , OFF
flush_time , 0
foreign_key_checks , ON
ft_boolean_syntax , + -><()~*: &|
ft_max_word_len , 84
ft_min_word_len , 4
ft_query_expansion_limit , 20
ft_stopword_file , (built-in)
general_log , OFF
general_log_file , /var/run/mysqld/mysqld.log
group_concat_max_len , 1024
have_community_features , YES
have_compress , YES
have_crypt , YES
have_csv , YES
have_dynamic_loading , YES
have_geometry , YES
have_innodb , YES
have_ndbcluster , NO
have_openssl , DISABLED
have_partitioning , YES
have_query_cache , YES
have_rtree_keys , YES
have_ssl , DISABLED
have_symlink , YES
hostname , smscdb
identity , 0
ignore_builtin_innodb , OFF
init_connect ,
init_file ,
init_slave ,
innodb_adaptive_hash_index , ON
innodb_additional_mem_pool_size , 1048576
innodb_autoextend_increment , 8
innodb_autoinc_lock_mode , 1
innodb_buffer_pool_size , 8388608
innodb_checksums , ON
innodb_commit_concurrency , 0
innodb_concurrency_tickets , 500
innodb_data_file_path , ibdata1:10M:autoextend
innodb_data_home_dir ,
innodb_doublewrite , ON
innodb_fast_shutdown , 1
innodb_file_io_threads , 4
innodb_file_per_table , OFF
innodb_flush_log_at_trx_commit , 1
innodb_flush_method ,
innodb_force_recovery , 0
innodb_lock_wait_timeout , 50
innodb_locks_unsafe_for_binlog , OFF
innodb_log_buffer_size , 1048576
innodb_log_file_size , 5242880
innodb_log_files_in_group , 2
innodb_log_group_home_dir , ./
innodb_max_dirty_pages_pct , 90
innodb_max_purge_lag , 0
innodb_mirrored_log_groups , 1
innodb_open_files , 300
innodb_rollback_on_timeout , OFF
innodb_stats_on_metadata , ON
innodb_support_xa , ON
innodb_sync_spin_loops , 20
innodb_table_locks , ON
innodb_thread_concurrency , 8
innodb_thread_sleep_delay , 10000
innodb_use_legacy_cardinality_algorithm , ON
insert_id , 0
interactive_timeout , 28800
join_buffer_size , 131072
keep_files_on_create , OFF
key_buffer_size , 1073741824
key_cache_age_threshold , 300
key_cache_block_size , 1024
key_cache_division_limit , 100
language , /usr/share/mysql/english/
large_files_support , ON
large_page_size , 0
large_pages , OFF
last_insert_id , 0
lc_time_names , en_US
license , GPL
local_infile , ON
locked_in_memory , OFF
log , OFF
log_bin , ON
log_bin_trust_function_creators , OFF
log_bin_trust_routine_creators , OFF
log_error ,
log_output , FILE
log_queries_not_using_indexes , OFF
log_slave_updates , OFF
log_slow_queries , OFF
log_warnings , 1
long_query_time , 10.000000
low_priority_updates , OFF
lower_case_file_system , OFF
lower_case_table_names , 0
max_allowed_packet , 536870912
max_binlog_cache_size , 4294963200
max_binlog_size , 104857600
max_connect_errors , 10
max_connections , 151
max_delayed_threads , 20
max_error_count , 64
max_heap_table_size , 16777216
max_insert_delayed_threads , 20
max_join_size , 18446744073709551615
max_length_for_sort_data , 1024
max_prepared_stmt_count , 16382
max_relay_log_size , 0
max_seeks_for_key , 4294967295
max_sort_length , 1024
max_sp_recursion_depth , 0
max_tmp_tables , 32
max_user_connections , 0
max_write_lock_count , 4294967295
min_examined_row_limit , 0
multi_range_count , 256
myisam_data_pointer_size , 6
myisam_max_sort_file_size , 2146435072
myisam_recover_options , BACKUP
myisam_repair_threads , 1
myisam_sort_buffer_size , 8388608
myisam_stats_method , nulls_unequal
myisam_use_mmap , OFF
net_buffer_length , 16384
net_read_timeout , 30
net_retry_count , 10
net_write_timeout , 60
new , OFF
old , OFF
old_alter_table , OFF
old_passwords , OFF
open_files_limit , 20000
optimizer_prune_level , 1
optimizer_search_depth , 62
optimizer_switch , index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on
pid_file , /var/run/mysqld/mysqld.pid
plugin_dir , /usr/lib/mysql/plugin
port , 3306
preload_buffer_size , 32768
profiling , OFF
profiling_history_size , 15
protocol_version , 10
pseudo_thread_id , 0
query_alloc_block_size , 8192
query_cache_limit , 1073741824
query_cache_min_res_unit , 4096
query_cache_size , 536870912
query_cache_type , ON
query_cache_wlock_invalidate , OFF
query_prealloc_size , 8192
rand_seed1 ,
rand_seed2 ,
range_alloc_block_size , 4096
read_buffer_size , 131072
read_only , OFF
read_rnd_buffer_size , 33554432
relay_log ,
relay_log_index ,
relay_log_info_file , relay-log.info
relay_log_purge , ON
relay_log_space_limit , 0
report_host ,
report_password ,
report_port , 3306
report_user ,
rpl_recovery_rank , 0
secure_auth , OFF
secure_file_priv ,
server_id , 3
skip_external_locking , ON
skip_networking , OFF
skip_show_database , OFF
slave_compressed_protocol , OFF
slave_exec_mode , STRICT
slave_load_tmpdir , /tmp
slave_net_timeout , 3600
slave_skip_errors , OFF
slave_transaction_retries , 10
slow_launch_time , 2
slow_query_log , OFF
slow_query_log_file , /var/run/mysqld/mysqld-slow.log
socket , /var/run/mysqld/mysqld.sock
sort_buffer_size , 67108864
sql_auto_is_null , ON
sql_big_selects , ON
sql_big_tables , OFF
sql_buffer_result , OFF
sql_log_bin , ON
sql_log_off , OFF
sql_log_update , ON
sql_low_priority_updates , OFF
sql_max_join_size , 18446744073709551615
sql_mode ,
sql_notes , ON
sql_quote_show_create , ON
sql_safe_updates , OFF
sql_select_limit , 18446744073709551615
sql_slave_skip_counter ,
sql_warnings , OFF
ssl_ca ,
ssl_capath ,
ssl_cert ,
ssl_cipher ,
ssl_key ,
storage_engine , MyISAM
sync_binlog , 0
sync_frm , ON
system_time_zone , IST
table_definition_cache , 256
table_lock_wait_timeout , 50
table_open_cache , 500
table_type , MyISAM
thread_cache_size , 8
thread_handling , one-thread-per-connection
thread_stack , 196608
time_format , %H:%i:%s
time_zone , SYSTEM
timed_mutexes , OFF
timestamp , 1282125419
tmp_table_size , 16777216
tmpdir , /tmp
transaction_alloc_block_size , 8192
transaction_prealloc_size , 4096
tx_isolation , REPEATABLE-READ
unique_checks , ON
updatable_views_with_limit , YES
version , 5.1.37-1ubuntu5-log
version_comment , (Ubuntu)
version_compile_machine , i486
version_compile_os , debian-linux-gnu
wait_timeout , 28800
warning_count , 0
Your explain plan that you gave:
id , select_type , table , type , possible_keys , key , key_len , ref , rows , Extra
1 , SIMPLE , a , ref , systemId idx_time) , systemId , 14 , const , 735310 , Using where
1 , SIMPLE , b , ref , PRIMARY , PRIMARY , 66 , gwreports2.a.msgId , 2270405 ,
1 , SIMPLE , c , ref , PRIMARY , PRIMARY , 66 , gwreports2.a.msgId , 2238701 ,
shows that you are hitting: 735310 * 2270405 * 2238701 = 3T rows!!!!!!
Effectively your not using your indexes to their fullest potential.
How to interpret your 'explain plan':
For every row in table 'a' (735310 ), you hit table 'b' 2270405 times.
For every row you hit in table 'b', you hit table 'c' 2238701 times.
As you can see, this is an exponential problem.
Yes, the 8MB of InnoDb Buffer space is small, but getting your explain plan down to xxxx * 1 * 1 will result in incredible speeds, even for 8MB of Buffer Space.
Given your Query:
SELECT a.msgId,a.senderId,a.destination,a.inTime,a.status as InStatus,b.status as SubStatus,c.deliverTime,substr(c.receipt,82,7) as DlvStatus
FROM inserted_history a
LEFT JOIN submitted_history b ON b.msgId = a.msgId -- USES 1 column of PK
LEFT JOIN delivered_history c ON a.msgId = c.msgId -- USES 1 column of PK
WHERE a.inTime BETWEEN '2010-08-10 00:00:00' AND '2010-08-010 23:59:59' -- NO key
AND a.systemId='ND_arber' -- Uses non-unique PK
Here are the problems I see:
A) Your _history tables are partitioned on the columns with 'Timestamp' datatype, YET you are NOT those columns in your JOIN/WHERE criteria. The engine must hit EVERY partition without that information.
B) Access to submitted_history and delivered_history is using only 1 column of a 2-column PK. You are only getting partial benefit of the PK. Can you get more columns to be part of the JOIN? You must get the # of rows found for this table as close to '1' as possible.
C) msgID = varchar(64) and this is the 1st column of the PK for each table. Your Keys on each table are ** HUGE **!!
- Try to reduce the size of columns for the PK, or use different columns.
Your data patterns of the other keys shows that you have LOTS of disk/ram space tied up in non-PK keys.
Question 1) What does "Show Indexes FROM " (Link) for each of the tables report?? The column 'Cardinality' will show you how effective each of your keys really are. The smaller the cardinality is, the WORST/Less effective that index is. You want cardinality as close to "total rows" as possible for ideal performance.
Question 2) Can you re-factor the SQL such that the JOIN'd columns of each table are those with the highest cardinality for that table?
Question 3) Is the columns of 'timestamp' datatype really the best column for the partitioning? If your access patterns always use 'msgId', and msgId is the 1st column of the PK, then .
Question 4) Is msgId unique? My guess is yes, and the 2nd column of the PK is not really necessary.
Read up on Optimizing SQL (Link) and have the index cardinality reports of your tables. This is the path to figure out how to optimize an query. You want the 'rows' of the explain plan to be N * 1 * 1.
SIDE NOTE:InnoDb & MyISAM engines does NOT automatically update table cardinality for non-unique columns, the DBA needs to manually run 'Analyze Table' periodically to ensure its accuracy.
Good Luck.
Would it be possible to alter the index of inserted_history,
systemId (systemId)
to be
systemId (systemId, inTime). Or add an additional index
My logic being that this should help to speed up the selection of the inserted_history (a) rows which forms the basis of the join.
The where clause "where a.inTime between '2010-08-10 00:00:00' and '2010-08-010 23:59:59' and a.systemId='ND_arber'" would all be selectable by index. At present, rows are selectable by systemId but then all those rows need to be scanned for the time.
Just as a matter of interest, how many records would there be (on average) for each system id. Also as msgid is not unique on its own, how many records (on average) in the other tables will have teh same msgid.
Main Idea
Are you using InnoDB? It looks like your buffer pool is only 8MB. That could easily be the problem, you're dealing with a lot of data and InnoDB doesn't have much memory. Can you bump the innodb_buffer_pool_size up? You'll have to restart MySQL, but I'm betting that would make a HUGE difference, even if you only give it 256 or 512MB.
Update: I see your storage engine and table format seem to default to MyISAM, so unless you specified otherwise this wouldn't apply. I wonder if the myisam_sort_buffer_size would help? We don't use MyISAM so I'm not familiar with tuning it.
Random Thought
I wonder if having having the primary key be alphanumeric (especially VARCHAR) has anything to do with it. I remember we had problems with performance on non-numeric primary keys, but that database dated from 4.0 or 4.1, so that may not apply (or ever have been true).
Secondary Idea
After the memory thing above, my best guess would be to give MySQL more hints. When I have a query that's running slow, I often find giving it more information helps it out. You have messageId/time indexes on each table. Maybe something more like this would work better:
select a.msgId,a.senderId,a.destination,a.inTime,a.status as InStatus,
b.status as SubStatus,c.deliverTime,substr(c.receipt,82,7) as DlvStatus
from inserted_history a left join submitted_history b on b.msgId = a.msgId
left join delivered_history c on a.msgId = c.msgId
where a.inTime between '2010-08-10 00:00:00' and '2010-08-010 23:59:59'
and a.systemId='ND_arber' AND c.inTime between b.inTime >= a.inTime
and c.inTime >= b.inTime
I'm guessing things get inserted into A, then B, then C. If you have better limits (say when something goes in A, it's always sent out and submitted within one day) add that information could help.
I wonder about this both because I've seen it help my query performance in some situations, but also because you have the data partitioned on the datetime. That may help the optimizer.
My other suggestion would be to run your query for a short amount of time, say 10 minutes instead of a full day, and make sure the results are right. Then try 30. Increase it and see when it falls off into "come back tomorrow" territory. That may tell you something.