Eu tenho um servidor MySQL (versão 5.6) que está bem equipado com hardware (Linux, na AWS, 32 GB de RAM, 56 CPUs), e de acordo com top e iotop, nem está quente; ainda esta consulta leva algo como 2 horas (a consulta real, não a explicação):
mysql> explain
-> SELECT
-> DATE_FORMAT(DATE('2020-04-14'), '%m/%d/%Y') AS "Gaming Day",
-> g.name AS "Game name",
-> u.username AS "User Id",
-> ga.game_instance_id AS "Game Round Id",
-> gt.user_transaction_id AS "Transaction Id",
-> ga.type AS "Transaction Type",
-> ga.amount AS "Transaction Amount",
-> CONVERT_TZ(ga.created_timestamp, 'UTC', 'SYSTEM') AS "Transaction Date Time (EST)"
-> FROM spin.game_action ga
-> INNER JOIN spin.game_instance gi
-> ON gi.game_instance_id = ga.game_instance_id
-> INNER JOIN spin.game_transaction gt
-> ON gt.game_action_id = ga.game_action_id
-> INNER JOIN spin.user u
-> ON ga.user_id = u.user_id
-> INNER JOIN spin.organisation_site os
-> ON u.organisation_site_id = os.organisation_site_id
-> INNER JOIN spin.game g
-> ON g.game_id = ga.game_id
-> WHERE os.hostname = 'nyx'
-> AND gi.end_datetime BETWEEN CONVERT_TZ('2020-04-14 00:00:00', 'SYSTEM', 'UTC') AND CONVERT_TZ('2020-04-21 23:59:59', 'SYSTEM', 'UTC')
-> AND gi.status IN ('RESOLVED', 'AUTO_COMPLETED');
+----+-------------+-------+--------+---------------------------------+---------+---------+-----------------------------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+---------------------------------+---------+---------+-----------------------------+------+-------------+
| 1 | SIMPLE | g | index | PRIMARY | BG_UK1 | 202 | NULL | 60 | Using index |
| 1 | SIMPLE | ga | ref | PRIMARY,GA_IX01,GA_IX02,GA_IX03 | GA_IX01 | 4 | spin.g.game_id | 674 | Using where |
| 1 | SIMPLE | u | eq_ref | PRIMARY,U_UK01,U_IX_04 | PRIMARY | 4 | spin.ga.user_id | 1 | NULL |
| 1 | SIMPLE | os | eq_ref | PRIMARY | PRIMARY | 4 | spin.u.organisation_site_id | 1 | Using where |
| 1 | SIMPLE | gi | ref | PRIMARY | PRIMARY | 8 | spin.ga.game_instance_id | 1 | Using where |
| 1 | SIMPLE | gt | ref | GT_IX03 | GT_IX03 | 9 | spin.ga.game_action_id | 1 | Using index |
+----+-------------+-------+--------+---------------------------------+---------+---------+-----------------------------+------+-------------+
6 rows in set (0.01 sec)
Eu tentei executá-lo em perfil, mas isso é basicamente inútil:
mysql> show profile for query 2;
+----------------------+------------+
| Status | Duration |
+----------------------+------------+
| starting | 0.000160 |
| checking permissions | 0.000005 |
| checking permissions | 0.000002 |
| checking permissions | 0.000003 |
| checking permissions | 0.000003 |
| checking permissions | 0.000003 |
| checking permissions | 0.000005 |
| Opening tables | 0.000067 |
| init | 0.000133 |
| System lock | 0.000201 |
| optimizing | 0.000049 |
| statistics | 0.000416 |
| preparing | 0.000050 |
| executing | 0.000005 |
| Sending data | 999.999999 |
| end | 0.000010 |
| query end | 0.000008 |
| closing tables | 0.010543 |
| freeing items | 0.000062 |
| logging slow query | 0.000002 |
| logging slow query | 0.110968 |
| cleaning up | 0.003693 |
+----------------------+------------+
22 rows in set, 1 warning (0.01 sec)
Pelo que entendi, Sending data
abrange tanto a transmissão real dos resultados ao cliente quanto uma parte importante do processamento. Agora estou considerando como analisar isso ainda mais com o performance_schema; é provável que revele detalhes mais úteis?
Editar
Saída de SHOW GLOBAL STATUS\G
: https://pastebin.com/QejRk9RA
Saída de SHOW GLOBAL VARIABLES\G
: https://pastebin.com/b3B76v21
Saída de SHOW FULL PROCESSLIST\G
: https://pastebin.com/N85YUwFj
Relatório do MySQLtuner: https://pastebin.com/HJJsCCzL
Editar 2
$ ulimit -a
time(seconds) unlimited
file(blocks) unlimited
data(kbytes) unlimited
stack(kbytes) 8192
coredump(blocks) 0
memory(kbytes) unlimited
locked memory(kbytes) 64
process 128223
nofiles 1024
vmemory(kbytes) unlimited
locks unlimited
rtprio 0
db3 root = iostat -xm 5 3
Linux 4.9.0-11-amd64 (db3.spin-production.gamingrealms.org) 05/27/2020 _x86_64_ (56 CPU)
avg-cpu: %user %nice %system %iowait %steal %idle
0.72 0.00 0.07 0.04 0.00 99.17
Device: rrqm/s wrqm/s r/s w/s rMB/s wMB/s avgrq-sz avgqu-sz await r_await w_await svctm %util
sda 0.11 11.30 20.83 17.03 3.66 0.66 233.37 0.05 1.24 1.41 1.04 0.51 1.94
dm-0 0.00 0.00 0.04 0.04 0.00 0.00 8.13 0.01 99.38 3.62 184.79 1.05 0.01
dm-1 0.00 0.00 20.88 27.29 3.66 0.66 183.42 0.05 1.05 1.42 0.76 0.40 1.94
avg-cpu: %user %nice %system %iowait %steal %idle
3.60 0.00 0.16 0.08 0.00 96.16
Device: rrqm/s wrqm/s r/s w/s rMB/s wMB/s avgrq-sz avgqu-sz await r_await w_await svctm %util
sda 0.00 18.60 121.40 13.80 30.00 0.27 458.59 0.13 0.93 0.92 1.10 0.49 6.64
dm-0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
dm-1 0.00 0.00 121.40 32.40 30.00 0.27 403.13 0.13 0.82 0.91 0.47 0.43 6.64
avg-cpu: %user %nice %system %iowait %steal %idle
1.59 0.00 0.16 0.03 0.00 98.23
Device: rrqm/s wrqm/s r/s w/s rMB/s wMB/s avgrq-sz avgqu-sz await r_await w_await svctm %util
sda 0.00 15.00 49.00 17.60 12.02 0.21 375.95 0.04 0.64 0.87 0.00 0.37 2.48
dm-0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
dm-1 0.00 0.00 49.00 32.60 12.02 0.21 306.84 0.04 0.52 0.87 0.00 0.30 2.48
db3 root = top -c
top - 04:36:25 up 167 days, 21:28, 1 user, load average: 1.97, 2.28, 2.18
Tasks: 584 total, 2 running, 582 sleeping, 0 stopped, 0 zombie
%Cpu(s): 3.4 us, 0.2 sy, 0.0 ni, 96.4 id, 0.1 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem : 32848684 total, 5421432 free, 19970372 used, 7456880 buff/cache
KiB Swap: 66916348 total, 66844172 free, 72176 used. 12286984 avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
43108 root 20 0 4440 1312 1044 R 89.2 0.0 243:45.28 /bin/gzip -
18933 root 20 0 4440 1332 1048 S 61.0 0.0 107:19.61 /bin/gzip -
43107 root 20 0 249232 40072 11788 S 9.8 0.1 24:21.13 /usr/bin/innobackupex --stream=tar --user=backupuser --password=x xxxxxx --safe-slave-backup --slave-info --databa+
18932 root 20 0 249232 40024 11740 S 7.2 0.1 10:17.08 /usr/bin/innobackupex --stream=tar --user=backupuser --password=x xxxxxx --safe-slave-backup --slave-info --databa+
18934 root 20 0 1058508 147260 9648 S 4.3 0.4 6:46.18 /usr/bin/python3 /usr/bin/aws s3 cp - s3://spin.db.backup/2020-05-27-spin.tar.gz --region us-east-1
43109 root 20 0 1069768 174488 9404 S 3.6 0.5 14:16.26 /usr/bin/python3 /usr/bin/aws s3 cp - s3://spin.db.backup/2020-05-26-spin.tar.gz --region us-east-1
54915 root 20 0 45472 4396 3240 R 1.6 0.0 0:00.29 top -c
39686 mysql 20 0 21.178g 0.018t 8980 S 1.3 58.2 2979:59 /usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib/mysql/plugin --user=mysql --log-err+
41601 root 20 0 33196 11696 5100 S 0.7 0.0 70:42.86 /usr/share/filebeat/bin/filebeat -c /etc/filebeat/filebeat.yml -path.home /usr/share/filebeat -path.config /etc/fi+
312 root 20 0 0 0 0 S 0.3 0.0 0:36.25 [ksoftirqd/50]
1661 sensu 20 0 1594004 28004 5676 S 0.3 0.1 127:00.25 /opt/sensu/embedded/bin/ruby /opt/sensu/bin/sensu-client -c /etc/sensu/config.json -d /etc/sensu/conf.d -e /etc/se+
11120 root 20 0 109512 684 660 S 0.3 0.0 132:39.67 /var/ossec/bin/wazuh-modulesd
24552 sensu 20 0 135144 24696 0 S 0.3 0.1 217:07.55 /usr/sbin/sensu-agent start
1 root 20 0 57396 5144 3668 S 0.0 0.0 11:17.41 /sbin/init
...
Eu executei essa consulta quando o servidor parece estar sem carga (de acordo com top e show processlist) e quando alguns trabalhos SQL pesados o empurram para cerca de 1000% da CPU, e parece não fazer muita diferença, acredite ou não. As ~ 2 horas é o que é preciso com nada acontecendo.
Editar3
MOSTRAR STATUS GLOBAL: https://pastebin.com/5PeBEkz7
MOSTRAR VARIÁVEIS GLOBAIS: https://pastebin.com/SnGS28rD
MOSTRAR LISTA DE PROCESSOS COMPLETA: https://pastebin.com/AR2WZbnM
Editar4
db3 root = hdparm -I /dev/sda
/dev/sda:
SG_IO: bad/missing sense data, sb[]: 70 00 05 00 00 00 00 0d 00 00 00 00 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
ATA device, with non-removable media
Standards:
Likely used: 1
Configuration:
Logical max current
cylinders 0 0
heads 0 0
sectors/track 0 0
--
Logical/Physical Sector size: 512 bytes
device size with M = 1024*1024: 0 MBytes
device size with M = 1000*1000: 0 MBytes
cache/buffer size = unknown
Capabilities:
IORDY not likely
Cannot perform double-word IO
R/W multiple sector transfer: not supported
DMA: not supported
PIO: pio0
Editar
show create table e mostre o status da tabela: https://pastebin.com/s9Y61GTb
Análise de VARIÁVEIS e STATUS GLOBAL:
Observações:
As questões mais importantes:
A menos que você tenha um pequeno conjunto de dados ou muitos outros aplicativos no mesmo servidor,
innodb_buffer_pool_size
(agora 5G) deve ser maior - digamos, 22Ginnodb_log_file_size
(256M) é bastante baixo para a atividade que você está experimentando. 1G seria melhor.Supondo que você tenha unidades SSD,
innodb_io_capacity
deve ser maior que 200. Digamos, 1000.O "cache de consulta" parece estar ativado, mas não é usado. Recomendar
Parece haver muitas consultas lentas. Vamos investigá-los (em uma pergunta diferente). http://mysql.rjweb.org/doc.php/mysql_analysis#slow_queries_and_slowlog
Há muitas gravações por segundo. Vamos discuti-los. Pode haver truques para acelerar inserções/exclusões/atualizações -- em alguns casos em 10x.
Seu tipo de consulta mais movimentado é
UPDATE
. Vamos discutir o que está fazendo.Como você não usa muitas conexões (cf
Max_used_connections
= 6), sugira diminuirmax_connections
de 1000 para, digamos, 30.CREATE INDEX
ocorre a cada 15 minutos. Isso é bastante frequente; porque?Eu não sou fã de
autocommit=0
. Podemos discutir, se quiser. Enquanto isso, note queinit_connect
é ignorado por 'root' e outros usuários 'SUPER'.Detalhes e outras observações:
( innodb_buffer_pool_size / innodb_buffer_pool_instances ) = 5120M / 1 = 5120MB
-- Tamanho de cada instância buffer_pool. -- Uma instância deve ter pelo menos 1 GB. Em RAM muito grande, tenha 16 instâncias.( Innodb_os_log_written ) = 257,579,082,240 / 683360 = 376930 /sec
-- Este é um indicador de quão ocupado o InnoDB está. -- InnoDB muito ocioso ou muito ocupado.( Innodb_log_writes ) = 179,367,526 / 683360 = 262 /sec
( Innodb_os_log_written / (Uptime / 3600) / innodb_log_files_in_group / innodb_log_file_size ) = 257,579,082,240 / (683360 / 3600) / 2 / 256M = 2.53
-- Proporção -- (ver minutos)( Uptime / 60 * innodb_log_file_size / Innodb_os_log_written ) = 683,360 / 60 * 256M / 257579082240 = 11.9
-- Minutos entre rotações de log do InnoDB A partir do 5.6.8, isso pode ser alterado dinamicamente; certifique-se de alterar também my.cnf. -- (A recomendação de 60 minutos entre as rotações é um tanto arbitrária.) Ajuste innodb_log_file_size (agora 268435456). (Não é possível alterar na AWS.)( innodb_flush_method ) = innodb_flush_method =
-- Como o InnoDB deve pedir ao SO para escrever blocos. Sugira O_DIRECT ou O_ALL_DIRECT (Percona) para evitar buffer duplo. (Pelo menos para Unix.) Veja chrischandler para advertência sobre O_ALL_DIRECT( innodb_io_capacity ) = 200
-- Capacidade de operações de E/S por segundo no disco . 100 para unidades lentas; 200 para acionamentos giratórios; 1000-2000 para SSDs; multiplicar pelo fator RAID.( innodb_stats_on_metadata ) = innodb_stats_on_metadata = ON
-- Reanalisar a tabela ao tocar nas estatísticas. -- ON provavelmente retardará certos acessos de SHOWs e information_schema.( expand_fast_index_creation ) = expand_fast_index_creation = OFF
-- ALTER e OPTIMIZE podem ser bastante acelerados usando ON. -- Provavelmente é melhor estar ligado.( innodb_recovery_update_relay_log ) = innodb_recovery_update_relay_log = OFF
-- Ajuda a evitar erros de replicação após uma falha.( innodb_import_table_from_xtrabackup ) = 0
-- Útil para tablespaces transportáveis( sync_binlog ) = 0
-- Use 1 para maior segurança, com algum custo de I/O =1 pode levar a muitas "query end"; =0 pode levar a "binlog em posição impossível" e perder transações em uma falha, mas é mais rápido.( innodb_print_all_deadlocks ) = innodb_print_all_deadlocks = OFF
-- Se deve registrar todos os Deadlocks. -- Se você está atormentado com Deadlocks, ative isso. Cuidado: Se você tiver muitos deadlocks, isso pode gravar muito no disco.( character_set_server ) = character_set_server = latin1
-- Problemas de charset podem ser ajudados configurando character_set_server (agora latin1) para utf8mb4. Esse é o padrão futuro.( local_infile ) = local_infile = ON
-- local_infile (agora ATIVADO) = ATIVADO é um possível problema de segurança( Qcache_free_memory / query_cache_size ) = 54,508,208 / 52M = 100.0%
-- Pct Query Cache free -- menor query_cache_size (agora 54525952) Abaixar libera RAM para outros usos, mas como o espaço livre varia com o tempo, essa leitura pode enganá-lo.( Qcache_not_cached / (Qcache_hits + Com_select + Qcache_not_cached) ) = 252,613 / (0 + 253801 + 252613) = 49.9%
-- Porcentagem de SELECTs que não foram armazenados em cache no QC. -- QC não é muito útil.( Qcache_hits / Qcache_inserts ) = 0 / 3 = 0
-- Taxa de acerto para inserção -- alto é bom -- Considere desativar o cache de consulta.( Qcache_hits / (Qcache_hits + Com_select) ) = 0 / (0 + 253801) = 0
-- Taxa de acertos -- SELECTs que usaram QC -- Considere desativar o cache de consulta.( Qcache_hits / (Qcache_hits + Qcache_inserts + Qcache_not_cached) ) = 0 / (0 + 3 + 252613) = 0
-- Query cache hit rate -- Provavelmente é melhor desligar o QC.( Qcache_free_blocks / Qcache_total_blocks ) = 1 / 1 = 100.0%
-- Fragmentação no Cache de Consulta. -- Várias coisas.( (query_cache_size - Qcache_free_memory) / Qcache_queries_in_cache / query_alloc_block_size ) = (52M - 54508208) / 0 / 8192 = INF
-- query_alloc_block_size vs formula -- Ajusta query_alloc_block_size (agora 8192)( (Queries-Questions)/Queries ) = (568240759-827878)/568240759 = 99.9%
-- Fração de consultas que estão dentro de rotinas armazenadas. -- (Não é ruim se alto; mas afeta a validade de algumas outras conclusões.)( Created_tmp_disk_tables / Questions ) = 50,164 / 827878 = 6.1%
-- Porcentagem de consultas que precisavam da tabela tmp no disco. -- Melhores índices / Sem blobs / etc.( Handler_read_rnd_next / Com_select ) = 10,856,649,505 / 253801 = 42,776
-- Média de linhas verificadas por SELECT. (aprox) -- Considere aumentar read_buffer_size (agora 131072)( (Com_insert + Com_update + Com_delete + Com_replace) / Com_commit ) = (170092830 + 199370523 + 19280137 + 0) / 178617506 = 2.18
-- Declarações por Commit (assumindo todo InnoDB) -- Baixa: Pode ajudar a agrupar consultas em transações; Alta: transações longas sobrecarregam várias coisas.( Select_scan / Com_select ) = 280,730 / 253801 = 110.6%
-- % de seleções fazendo varredura completa da tabela. (Pode ser enganado por rotinas armazenadas.) -- Adicionar índices/otimizar consultas( Com_insert + Com_delete + Com_delete_multi + Com_replace + Com_update + Com_update_multi ) = (170092830 + 19280137 + 0 + 0 + 199370523 + 0) / 683360 = 568 /sec
-- writes/sec -- 50 writes/s + log flushes provavelmente irão maximizar a capacidade de gravação de E/S de unidades normais( Com__biggest ) = Com__biggest = Com_update
-- Qual das métricas "Com_" é a maior. -- Normalmente é Com_select (agora 253801). Se for outra coisa, pode ser uma plataforma desleixada ou pode ser outra coisa.( back_log ) = 50
-- (Autodimensionado a partir de 5.6.6; baseado em max_connections) -- Aumentar para min(150, max_connections (agora 1000)) pode ajudar ao fazer muitas conexões.( thread_cache_size / Max_used_connections ) = 8 / 6 = 133.3%
-- Não há vantagem em ter o cache de threads maior que o número provável de conexões. O desperdício de espaço é a desvantagem.Anormalmente pequeno:
Anormalmente grande:
Cordas anormais:
Your ulimit Open Files limit of 1024 is starving MySQL for handles. From OS command prompt, ulimit -n 36000 and press Enter will dynamically make 36000 handles available - on the next stop/start of MySQL.
To make 36000 handles available over OS restart, follow this URL
DO NOT use 500,000 as in their example, use 36000 to enable MySQL to use up to 20000 - your open_files_limit requested.
Rate Per Second = RPS
Suggestions to consider for your AWS Parameters group
Applying these changes will reduce CPU busy. Your version 5.5.62-38.14 is 18 months past End of Life. New versions have better performance and additional Global Variables to improve and better manage performance. View my profile, Network profile for contact info and free downloadable Utility Scripts to assist with performance tuning.
It looks like your slow query is missing gi combination index on end_datetime and status. If you can move the TWO AND's up about 8 rows to make the JOIN selective, it may help.
Experimente Otimizando a tabela de consulta para um melhor desempenho:
DATETIME
, não poderá obter a hora certa duas vezes por ano - durante a mudança para o horário de verão. UsarTIMESTAMP
.SHOW CREATE TABLE
se precisar de mais ajuda com o esquema para que possamos julgar os índices.It looks like there is a huge misestimation. You wrote this query should return about 500K of rows. MySQL Server estimates it will need to check ~40K of rows (and filter them) and chooses inefficient execution plan. Your tables are large and partitioned. As you may know partitioning is not a performance feature and it complicates things. There may be different ways to improve this query performance but I suppose the first step should be aligning it with the partitions (adding corresponding conditions to reduce the number of used partitions).