SlideShare a Scribd company logo
1 of 71
MySQL / MariaDB
성능 최적화
네오클로바 (db@neoclova.co.kr)
▶ 2022. 01
2
목차
구분 내용
DBA
- Hardware
- Operating System
- Modeling
- Objects & Server Variables
- Replication
- Online DDL
- Connection Control
DEV
- SQL 작성
- Explain
- SQL튜닝 사례
- 성능개선 사례
- Troubleshooting
Next Opensource Cloud Value
고정관념
4
고정관념
• MySQL/MariaDB Server는 공짜다?
• 타 DBMS에 비해 성능이 떨어진다?
• Oracle에서는 잘 돌아가는데, MySQL에서는 왜 안돼요?
• MySQL도 SQL실행계획을 재사용 한다?
• MySQL의 SQL튜닝은 DBA가 해야 할 일이다?
5
DBA
구분 내용
DBA
- Hardware
- Operating System
- Modeling
- Objects & Server Variables
- Replication
- Online DDL
- Connection Control
DEV
- SQL 작성
- Explain
- SQL튜닝 사례
- 성능개선 사례
- Troubleshooting
Next Opensource Cloud Value
Hardware
7
Hardware
• Hardware
– CPU
✔ Single processing
✔ More Speed Processor (Fast Clock Speed)
✔ bus speed, cache size
✔ More Cores
– Memory
✔ 슬롯당 최대 RAM Size 우선선택
– Disk
✔ 빠른 Disk speed
✔ redo / undo / binary log 전용 디스크
https://mariadb.com/kb/en/hardware-optimization/
Next Opensource Cloud Value
Operating System
9
Operating System
• OS
– Windows Server
■ NTFS
– Linux
■ Open Files
■ Swappiness
https://mariadb.com/kb/en/operating-system-optimizations/
10
Operating System
• Linux
– IO scheduler
– Open files / core file size
– Swappiness
# cat /sys/block/sda/queue/scheduler
noop [deadline] cfq
# cat /etc/security/limits.conf
mysql soft nofile 65535
mysql hard nofile 65536
mysql soft core unlimited
mysql hard core unlimited
# cat /etc/sysctl.conf
vm.dirty_background_bytes=104857600
vm.swappiness=1
# cat /etc/systemd/system/mysqld.service
…
LimitNOFILE = infinity
LimitMEMLOCK=infinity
TasksMax = infinity
Next Opensource Cloud Value
Modeling
12
Modeling
• Charset
- EUCKR
- UTF8
- UTF8MB4 for emoji
- 다른 Charset간의 Join 주의
• Collation
- Sensitive vs In-Sensitive
- *_bin
- *_general_ci/cs
- *_unicode_ci/cs
- 다른 Collation 컬럼간의 Join에 주의
• MySQL 8 :utf8mb4_0900_ai_ci(한글문제) …utf8mb4_unicode_520_ci
- pad space 주의( 이기종 DB에서 Data Migration 시)
• MariaDB : utf8mb4_unicode_ci
13
Modeling
• Data Type Length 오해
- length()
- char_length()
create table table1 (
id int,
nm1 varchar(10),
primary key(id)
) engine=innodb character set utf8;
-- nm1은 10음절(length) 일까요? 10 bytes 일까요?
14
Modeling
• AUTO_INCREMENT
- Only one per table
- Unique or Primary Key에 유용
- Innodb_autoinc_lock_mode
0 : table lock
1 : Consecutive Lock Mode (default)
2 : lightweight mutex lock(권고)
https://mariadb.com/kb/en/optimization-and-indexes/
https://mariadb.com/kb/en/optimizing-data-structure/
• SEQUENCE
- MariaDB 10.3 부터 지원
- InnoDB engine으로 내부구현
- MySQL은 지원 안함
15
Modeling
• Primary Key 설정
- 선택이 아닌 필수!!!!
- Replication Lag
- 없는것보다 있는것이 좋음
- auto_increment 활용
- 큰Size의 컬럼은 PK로 피하라
- MariaDB 10.1 : innodb_force_primary_key
- MySQL 8.0 : sql_require_primary_key
https://mariadb.com/kb/en/optimizing-tables/
https://mariadb.com/kb/en/system-variables/
16
Modeling
• 적절한 데이터 타입 사용
- 가능하다면 정수형으로 저장하라
- 날짜 데이터를 VARCHAR(14)에 %Y%M%d%H%i%S 저장?
- VARCHAR(4000) ?
- Bit 타입의 활용
- Timestamp 타입의 특수성
- NOT NULL
- 가능하면 작은 Size
17
Modeling
• 테이블 파티셔닝 남용 주의
- 파티셔닝의 목적
- 파티셔닝 제약조건
- 파티션 프루닝
- Primary Key가 변경되었다는 것을 잊지 말자 (App에서 SQL을 변경)
- 파티셔닝 키 함수의 확인
파티션에 사용할 수는 있으나, 파티션 프루닝을 지원하지 않는 함수 검토
- MySQL : explain ~
- MariaDB : explain partitions ~
18
Modeling
❖ Sharding
➢ Spider Storage Engine
➢ Vitess
❖ Distributed SQL
Next Opensource Cloud Value
Objects &
Variables
20
Objects & Variables
• Configuration (my.cnf)
innodb_buffer_pool_size = # Max 80% of physical memory
innodb_buffer_pool_instances = # buffer_pool 크기에 따라 1G이상 고려
innodb_buffer_pool_chunk_size = # buffer_pool 크기가 128GB 이상일때 크기 증
가
innodb_log_file_size = 1G # redo log file size
innodb_flush_method = O_DIRECT # data & log flush
innodb_thread_sleep_delay = 0 # 절전 off
innodb_adaptive_max_sleep_delay = 0 # innodb_thread_sleep_delay 자동조정
innodb_max_dirty_pages_pct_lwm = 0.001 # 최소 더티 페이지 비율
innodb_read_ahead_threshold = 64 # read ahead 페이지수
innodb_thread_concurrency = 0 # 최대 동시 수행 thread수.auto
innodb_purge_thread = 4
innodb_read_io_thread = 4
innodb_write_io_thread = 4
innodb_io_capacity = 20000
thread_handling = pool_of_threads
21
Objects & Variables
• InnoDB 제약 조건
– InnoDB tables can have a maximum of 1,017 columns
– The maximum size for BLOB and TEXT columns is 4GB. This also applies to LONGBLOB and LONGTEXT
– MariaDB imposes a row-size limit of 65,535 bytes for the combined sizes of all columns
– The innodb_large_prefix system variable enables large prefix sizes
That is, when enabled InnoDB uses 3072B index key prefixes for DYNAMIC and COMPRESSED row formats
When disabled, it uses 787B key prefixes for tables of any row format
22
Objects & Variables
• InnoDB Variables
– Innodb thread concurrency
■ default가 0으로 자동 최적값 찾아가는 상태인데, 권고사항은 core * 2로 설정
■ 권고값 이상 늘리면 context switching 가능성이 있음
– Innodb purge thread
■ 데이터가 단일 테이블에 집중되어 있다면 MySQL에서는 최대한 낮게 유지하라고 권고
■ multi table이라면 현재 설정값 감안하여 늘려주고 모니터링
– Innodb buffer pool chunk size
■ 10.5 deprecated : buffer pool instances
■ Buffer pool size 크기가 128GB 보다 크면 chunk size 늘려주라고 권고
– Innodb read io thread, Innodb write io thread
■ 10.5 버전부터는 위 파라미터 2개가 비동기 I/O 쓰레드를 의미하는 것으로 변경
■ 각 세팅값에 256을 곱한 값이 백그라운드 쓰레드 풀에서 동시에 완료할 수 있는 최대 요청 수
■ show innodb status에서 pending read request를 참조
■ 만약 DB I/O에 대한 전반적인 성능 튜닝이 목적이라면, Innodb_io_capacity 튜닝이 더 효율적
Next Opensource Cloud Value
Replication
24
Replication
▪ slave_parallel_threads
▪ slave_parallel_max_queued
▪ group commit
▪ binlog_row_image = minimal (LOB)
https://mariadb.com/kb/en/parallel-replication/
Next Opensource Cloud Value
Online DDL
26
Online DDL
▪ Online DDL
– COPY
– INPLACE
– NOCOPY
– INSTANT
https://dev.mysql.com/doc/refman/8.0/en/innodb-online-ddl.html
https://mariadb.com/kb/en/innodb-online-ddl-overview/
27
Online DDL
Operation Instant In Place Rebuilds Table
Permits
Concurrent DML
Only Modifies
Metadata
Adding a column Yes Yes No Yes No
Dropping a column No Yes Yes Yes No
Renaming a column No Yes No Yes Yes
Reordering columns No Yes Yes Yes No
Setting a column default value Yes Yes No Yes Yes
Changing the column data type No No Yes No No
Extending VARCHAR column size No Yes No Yes Yes
Dropping the column default value Yes Yes No Yes Yes
Changing the auto-increment value No Yes No Yes No
Making a column NULL No Yes Yes Yes No
Making a column NOT NULL No Yes Yes Yes No
Modifying the definition of an ENUM or SET column Yes Yes No Yes Yes
▪ Online DDL Support for Column Operations
Next Opensource Cloud Value
Connection Control
29
Connection Control
▪ WAS Connection Pool 수
○ thread running 수 (동시 쿼리 수행수)
▪ JDBC connection
○ usePipelineAuth=false
○ socketTimeout=180
○ health check timeout
○ connectTimeout
▪ MariaDB
○ wait_timeout
○ interactive_timeout
▪ Linux
○ tcp_keepalive
○ tcp_fin_timeout
30
DEV
구분 내용
DBA
- Hardware
- Operating System
- Modeling
- Objects & Server Variables
- Replication
- Online DDL
- Connection Control
DEV
- SQL 작성
- Explain
- SQL튜닝 사례
- 성능개선 사례
- Troubleshooting
Next Opensource Cloud Value
SQL 작성
32
SQL 작성
• SQL 작성 가이드
– ANSI SQL
– ERD 이해
– PRIMARY KEY & SECONDARY KEY
– JOIN 방식/순서
– 부분범위 처리
– 데이터 타입 우선순위
– Charset / Collation 우선순위
– EXPLAIN
33
SQL 작성
• ANSI SQL
– SQL-89 : 교차 조인 또는 쉼표로 구분된 테이블 목록을 사용하고 조인을 WHERE절에 배치
– SQL-92 ~ : INNER JOIN, LEFT JOIN등의 키워드를 사용하고 하위 절(ON, USING)에 조건 배치
select a.uid, b.pid
from person a
left outer join part b on b.uid = a.uid
where a.age<50;
select a.uid, b.pid
from person a, part b
where a.uid = b.uid(+)
and a.age<50;
34
SQL 작성
• ERD 이해
– 테이블간 관계
– 재귀구조
– 의사소통
– 데이터 표준
– 1:1 , 1: N
35
SQL 작성
• Primary Key
– PK 없으면 6bytes 더미 PK 컬럼 생성
– secondary key lookup
– sql_require_primary_key 설정
http://philipzhong.blogspot.com/2011/06/how-to-improve-mysql-select-count.html
36
SQL 작성
• Secondary Key
– leaf node에 PK 포함
– key lookup 통해서 PK 데이터를 검색
– Covered Index
https://www.slideshare.net/mysqlops/innodb-internal-9032556
37
SQL 작성
• JOIN
– 모든 SQL Single processing
– 오직 Nested Loop Join
– 조인 컬럼을 가지고
Driving Table에서
Driven Table 접근
output
cf) innodb_adaptive_hash_join
https://mariadb.com/kb/en/duplicateweedout-strategy/
38
SQL 작성
• 부분범위 처리
– 실제 필요한 데이터량만 조회처리
– 적절한 Index 생성
alter table person add key person_n_1 (age, rdate);
– Data Sorting이 성능을 좌우한다
select * from person
where age=25
order by rdate asc
limit 0,10;
39
SQL 작성
• 데이터 타입 우선순위
– 명시적 형변환, 묵시적 형변환
– 우선순위
JSON> 날짜형 > 숫자형 > 문자형 > 바이너리형
json > datetime > date > decimal > double > float > bigint > int > … > varchar > …> binary
– 반드시 컬럼타입에 맞게 SQL작성
https://dev.mysql.com/doc/refman/8.0/en/type-conversion.html
https://mariadb.com/kb/en/type-conversion/
create table t_member (id int, jumin1 varchar(6), jumin2 varchar(7), primary key(id));
select * from t_member where jumin1=891212 ;
40
SQL 작성
• CHARSET / COLLATION 우선순위
– database > table > column 문자집합
– 문자열의 대소비교에 적용
– 테이블간 조인에서 조인컬럼 문자집합의 collation이 다를 경우에 한쪽 collation을 다른 한쪽으로 변환 후에 비교
변환에 실패 시 오류발생하기도 함
ERROR 1267 (HY000): Illegal mix of collations (latin1_general_ci,IMPLICIT) and (latin1_Swedish_ci,IMPLICIT) for operation '='
변환에 성공하더라도 charset 우선순위에 따라 column data collation conversioin 발생
mysql> explain select t1.* from t1 inner join t2 on t2.nm=t1.nm;
+----+-------------+-------+------------+-------+---------------+------+---------+------+---------+----------+--------------------------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+-------+---------------+------+---------+------+---------+----------+--------------------------------------------+
| 1 | SIMPLE | t2 | NULL | index | nm | nm | 43 | NULL | 1 | 100.00 | Using index |
| 1 | SIMPLE | t1 | NULL | ALL | nm | NULL | NULL | NULL | 4988104 | 10.00 | Using where; Using join buffer (hash join) |
+----+-------------+-------+------------+-------+---------------+------+---------+------+---------+----------+--------------------------------------------+
mysql> explain select t1.* from t1 inner join t2 on convert(t2.nm using latin1)=t1.nm;
+----+-------------+-------+------------+-------+---------------+------+---------+------+------+----------+-----------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+-------+---------------+------+---------+------+------+----------+-----------------------+
| 1 | SIMPLE | t2 | NULL | index | NULL | nm | 43 | NULL | 1 | 100.00 | Using index |
| 1 | SIMPLE | t1 | NULL | ref | nm | nm | 13 | func | 1 | 100.00 | Using index condition |
+----+-------------+-------+------------+-------+---------------+------+---------+------+------+----------+-----------------------+
Next Opensource Cloud Value
EXPLAIN
42
EXPLAIN
• EXPLAIN / DESC / DESCRIBE
– slow query 확인
– 옵티마이저의 변환
– 적절한 조인 순서
– 인덱스 확인
– SQL 수정 판단
컬럼 설명
id 한 테이블의 SELECT 번호, 쿼리내의 SELECT의 구분번호
select_type
SELECT의 타입(SIMPLE, PRIMARY, UNION, SUBQUERY,
DRIVED, …)
table 해당 table명
type 조인의 타입(system, const, eq_ref, ref, ref_or_null, …)
possible_keys 테이블의 사용 가능한 인덱스 명
key Possible_keys 값들 중에서 실제 사용한 인덱스(key)
Key_len Where절에 사용한 인덱스의 길이(byte)
ref 행을 추출하는데 key와 함께 사용한 컬럼 이나 상수
rows 쿼리수행을 위해 검사대상 예상행수
filtered 조건절에 의해 필터링 되는 행의 비율
extra 쿼리를 해석한 추가적인 정보
43
EXPLAIN
• Query Analysis
– Use EXPLAIN to see how MariaDB Executes a Troublesome Query and if Indexes are Used
– Use EXPLAIN EXTENDED and SHOW WARNINGS to see how MariaDB Rearranges a Query before Execution
MariaDB> EXPLAIN SELECT * FROM employees WHERE MONTH(birth_date) = 10 G
MariaDB> EXPLAIN EXTENDED SELECT ...;
MariaDB> SHOW WARNINGS;
44
EXPLAIN
• select_type
– SIMPLE : UNION 이나 SUBQUERY를 사용하지 않는 단순 SELECT
– PRIMARY : 쿼리 제일 바깥쪽에 있는 SELECT
– DERIVED : SELECT절로 추출된 테이블로 FROM절 내부의 SUBQUERY의미
– UNION : UNION절에서 두번째 이후 SELECT, 첫번째는 DERIVED
– DEPENDENT UNION : 내부 쿼리가 외부 값을 참조하는 UNION절 테이블
– UNION RESULT : UNION 결과 값에 대한 임시 테이블
– SUBQUERY : FROM절 이외의 서브 쿼리 의미
– DEPENDENT SUBQUERY : 서브쿼리가 바깥쪽 SELECT절의 컬럼 값을 참조
– UNCACHEABLE SUBQUERY : 서브쿼리 결과가 외부 쿼리의 변하는 값에 따라 매번 새로 생성
– UNCACHEABLE UNION : 캐싱이 불가능한 요소를 포함한 UNION
45
EXPLAIN
• Scan or Index Method types
– const : A constant value can be read once and cached
– eq_ref : One index access per outer query row
– ref : Multiple index accesses per outer query row
– index_merge : Multiple indexes used, merging into a single result set
– range : Multiple index accesses to return all rows within a range
– index : Full index scan (every index entry is read sequentially)
– all : Full table scan (every record is read sequentially)
46
EXPLAIN
• Analyze Columns
– Analyze Columns with PROCEDURE ANALYSE()
– Use PROCEDURE ANALYSE() for Data Type Recommendations
MariaDB> SELECT gender, hire_date FROM employees PROCEDURE ANALYSE() G
MariaDB> SELECT salary FROM salaries PROCEDURE ANALYSE()G
47
EXPLAIN
• Indexes for Performance Optimization
– MariaDB can Resolve Queries Faster with Indexes
Faster Retrieval of Matching Rows, Faster Sorting of Result Sets
Without Indexes, MariaDB does Full Table Scan
– Indexes can be for a Column or Multiple Columns (i.e.,Composites)
– Index for Speed, but Avoid Indexing Excessively or Arbitrarily
– Remove Unused or Redundant Indexes
48
EXPLAIN
• Create Table Indexes
– Use ALTER TABLE or CREATE INDEX to add an Index
– Keep Indexes as Small as Practical
– For Indexing Strings, Use Prefix
MariaDB> ALTER TABLE employees ADD INDEX emp_names (name_last, name_first);
MariaDB> SHOW CREATE TABLE employees G
MariaDB> CREATE INDEX client_names ON clients (name_last(10), name_first(5));
49
EXPLAIN
• Better JOIN Construction
– Foreign Keys used with Joins should be Indexed
– Index Columns in ON and USING Clauses
– Keep GROUP BY and ORDER BY columns in one Table for better Indexing
SELECT last_name, city, country_name
FROM clients
JOIN country_names USING(country_id)
WHERE clients.country_id IN('de','fr','it','uk')
ORDER BY country_name, city, last_name;
50
EXPLAIN
• SHOW PROFILES
– 세션에서 실행한 SQL에 대하여 서버의 리소스 사용량을 확인 가능
– session variable (profiling) 을 이용
SET SESSION PROFILING=1;
SELECT * FROM 테이블~; #사용자 수행쿼리.
…
# 현재 세션에서 수행한 SQL들에 대한 프로파일링 요약.
SHOW PROFILES;
# 마지막 수행된 SQL을 프로파일링.
SHOW PROFILE;
#현재 세션에서 수행한 QUERY_ID에 대한 프로파일링.
SHOW PROFILE FOR QUERY #N;
#현재 세션에서 수행한 QUERY_ID에 대한 CPU정보 포함 프로파일링
SHOW PROFILE CPU FOR QUERY #N;
Next Opensource Cloud Value
SQL튜닝사례
52
SQL 튜닝사례
• Not Found Index : Create Index
• Wrong Data Type : Correct Data Binding
• Subquery, Subquery, … : Join Conversion
• Change of column! : Change Scalar Values.
• Covering Index : Composite Index
• COUNT ~ left join ~ : Don't use the framework as an excuse.
• ORDER BY ~ LIMIT 1; : 부분집합처리
• Index Columns Order : 선택도가 좋은 컬럼부터 ~
• FULLTEXT/NGRAM : 전문검색엔진이 없다면~
• LEFT JOIN ~ ON ~ WHERE ~ : ON절과 WHERE절 조건처리의 명확한 이해
• Paging SQL , row_number() : 아직은 ROW_NUMBER() OVER()가 비효율적이네요
• Generated Column : function based index …
• Invisible Column : create table tx(id int, ivnm varchar(10) invisible);
• Function Based Index : create table ty (id int not null, nm varchar(3) not null, key ((substring(nm,2,2))) );
• Update join : in 제거
• Charset/collation conversion : table / index full scan
• Stored Procedure : batch.
Next Opensource Cloud Value
성능개선사례
54
성능개선사례
• DB/Infra Architecture 개선
⮚ Oracle -> MariaDB (E**)
⮚ MaxScale + read replica (E**)
⮚ Replication (인*)
⮚ Table Partitioning (LG*** **)
⮚ Stored Procedure (S**)
⮚ Galera -> Replication (후*)
⮚ Percona -> MySQL (ka*******)
⮚ MySQL -> MariaDB (하***)
⮚ Aurora -> Xpand (수**)
⮚ DR Configuration(신***)
⮚ MariaDB upgrade : 10.0 -> 10.3(L***)
55
성능개선사례
• DB Variables 튜닝
⮚ CPU : innodb_thread_concurrency (투*****)
⮚ table_open_cache, innodb_change_buffering, innodb_fast_shutdown : (후*)
⮚ open_files_limit, tmp_table_size: (L****)
⮚ innodb_buffer_pool_size : (대***)
⮚ stored_program_cache : (T**)
⮚ vm.swappiness, innodb_flush_method, innodb_log_group_home_dir : (하***)
⮚ query_cache : (인*)
⮚ MyISAM : FTS(Full Text Search), character set (euc-kr), Primary Key (비***)
⮚ max_connections, max_allowed_packet : (U***)
⮚ rpl_semi_sync~ : (사*****)
56
성능개선사례
▪ SAMSUNG CLOUD OPERATION TEAM AUTHENTICATES 10 BILLION+ REQUESTS DAILY WITH MARIADB XPAND; CUTS COSTS BY 50%
https://mariadb.com/wp-content/uploads/2021/11/samsung-cloud-authenticates-10-billion-requests-daily-with-mariadb-xpand_customer-story_1127.pdf
▪ Southeast Asia's Largest Bank Migrates to Open Source Database MariaDB
https://mariadb.com/resources/customer-stories/dbs/
▪ Why Uber Engineering Switched from Postgres to MySQL
https://eng.uber.com/postgres-to-mysql-migration/
▪ 카카오, 연내 오라클 DB 전면 걷어낸다
https://www.etnews.com/20200130000324
▪ Netflix Billing Migration to AWS
https://netflixtechblog.com/netflix-billing-migration-to-aws-451fba085a4
▪ MySQL Customers
https://www.mysql.com/customers/
Next Opensource Cloud Value
MySQL
Troubleshooting
58
MySQL Troubleshooting
▪ 장애 대응 사례
장애 사례 원인 파악 문제 해결
DB session 증가로 인한 query
지연 이슈
connection이 늘어남에 따른 query 실행 지연 현상 발생 - WAS에서 DB 서비스에 connection 을 끊어 주지 않아서 발생된 이슈로 확인
File system data size 증가에 따른 disk full로 DB 서비스 중지 발생
- data size가 큰 table을 partitioning 처리하여 backup후 truncate 하는 구조로 로
직 변경
Memory 부족 memory 부족으로 인한 DB 서비스 중지 발생
- my.cnf 설정의 memory 옵션 조정으로 서버 사양에 맞게 조정하여 DB 서비스
복구
Schema 관리 user 실수로 table schema 문제 발생
- 개발자가 기존 table schema를 재 생성 하면서 컬럼 누락으로 이슈 발생, 확인
후 table 재 생성
DB 서비스중지 DB 서버 재부팅으로 인한 서비스 중단 발생 - VM의 OS 오류로 인한 서버 재 부팅 발생으로 VM 이슈 확인
CPU 사용률 증가 OS CPU 사용률 증가로 인한 DB query 지연 발생
- 개발 서비스 SQL문제로 인하여 개발 소스 수정 후 조치 완료
- 실행계획 확인 후 인덱스 추가조치 완료
59
MySQL Troubleshooting
▪ MySQL Error
– Error Messages 확인
– Error log 확인
– MySQL
https://dev.mysql.com/doc/mysql-errors/8.0/en/error-reference-introduction.html
- MariaDB
https://mariadb.com/kb/en/mariadb-error-codes/
https://mariadb.com/kb/en/operating-system-error-codes/
60
MySQL Troubleshooting
▪ InnoDB Recovery
– Crash된 응급상황에서는 innodb_force_recovery 서버변수 설정
0 : 기본값, 정상상황
1 : 누락된 데이터, 손상된 페이지 감지 무시
2 : Undo 로그 삭제 무시
3 : roll-forward 수행 오류 무시
4 : Insert Buffer 손상 무시
5 : Undo 로그 무시하고 강제 COMMIT
6 : roll-forward 무시, Redo 손상에 대한 강제복구
– 0 ~ 6의 순서로 데이터베이스기동 (실패하면 다음 값으로 데이터베이스 시작)
– 데이터베이스 시작이 성공 하면 mysqldump로 백업 / 복원
61
MySQL Troubleshooting
▪ mysql_upgrade
# mysql_upgrade –uroot –p
Phase 1/7: Checking and upgrading mysql database
Processing databases
mysql
mysql.column_stats OK
mysql.columns_priv OK
mysql.db OK
mysql.event OK
...
Phase 2/7: Installing used storage engines... Skipped
Phase 3/7: Fixing views
Phase 4/7: Running 'mysql_fix_privilege_tables'
Phase 5/7: Fixing table and database names
Phase 6/7: Checking and upgrading tables
Phase 7/7: Running 'FLUSH PRIVILEGES'
62
MySQL Troubleshooting
▪ Performance Schema
-- 수행횟수가 가장 많은 상위SQL 10개
MySQL> select digest_text, count_star,(avg_timer_wait/1000000000000) exec_t_s, sum_cpu_time/count_star,
sum_rows_sent/count_star, sum_rows_examined/count_star
from performance_schema.events_statements_summary_by_digest
order by count_star desc
limit 10;
-- 수행횟수가 가장 많고 2초 이상 소요된 상위SQL 10개.
MySQL> select digest_text, count_star, (avg_timer_wait/1000000000000) exec_t_s, sum_cpu_time/count_star,
sum_rows_sent/count_star, sum_rows_examined/count_star
from performance_schema.events_statements_summary_by_digest
where (avg_timer_wait/1000000000000) >= 2
order by count_star desc
limit 10;
63
MySQL Troubleshooting
▪ Performance Schema
-- 평균수행시간이 가장 긴 상위SQL 10개
MySQL> select digest_text, count_star, (avg_timer_wait/1000000000000) exec_t_s, sum_cpu_time/count_star,
sum_rows_sent/count_star, sum_rows_examined/count_star
from performance_schema.events_statements_summary_by_digest
order by avg_timer_wait desc
limit 10;
-- 평균잠금시간이 가장 긴 상위SQL 10개
MySQL> select digest_text, count_star, (avg_timer_wait/1000000000000) exec_t_s, sum_cpu_time/count_star,
sum_rows_sent/count_star, sum_rows_examined/count_star, (SUM_LOCK_TIME/count_star)/1000000000000 as avg_lock_time
from performance_schema.events_statements_summary_by_digest
order by (SUM_LOCK_TIME/count_star) desc
limit 10;
64
MySQL Troubleshooting
▪ Performance Schema
-- 평균반환행수가 가장 많은 상위SQL 10개
MySQL> select digest_text, count_star, (avg_timer_wait/1000000000000) exec_t_s, sum_cpu_time/count_star as avg_cpu_time,
sum_rows_sent/count_star as avg_sent_rows, sum_rows_examined/count_star as avg_examined_rows,
(SUM_LOCK_TIME/count_star)/1000000000000 as avg_lock_time
from performance_schema.events_statements_summary_by_digest
order by (SUM_ROWS_SENT/count_star) desc
limit 10;
-- 비효율 SQL 쿼리확인
MySQL> select schema_name, left(digest_text, 40) qry, count_star, sum_cpu_time,
sum_created_tmp_disk_tables sctdt, sum_select_full_join ssfj, sum_select_range_check ssrc, sum_sort_merge_passes ssmp
from performance_schema.events_statements_summary_by_digest
where sum_created_tmp_disk_tables > 0
OR sum_select_full_join > 0
OR sum_select_range_check > 0
OR sum_sort_merge_passes > 0
ORDER BY sum_sort_merge_passes DESC
LIMIT 10;
65
MySQL Troubleshooting
▪ Performance Schema
-- 특정 SQL의 프로파일링
MySQL> SELECT s.event_id AS Query_ID, TRUNCATE(s.timer_wait/1000000000000, 6) as Duration,LEFT(s.sql_text, 120) AS Query
FROM performance_schema.events_statements_history_long s
INNER JOIN performance_schema.threads t on t.thread_id=s.thread_id
where 1=1
-- and t.processlist_id = CONNECTION_ID() -- 현재 My session
order by Duration desc
limit 10;
MySQL> select event_name, truncate(timer_wait/1000000000000,6) as duration
from performance_schema.events_stages_history_long
where nesting_event_id=874 -- query id
order by timer_start asc;
감사합니다
67
Next Opensource Cloud Value
NeoClova
69
NeoClova
회사명
임직원
대표이사
설립년도
주소
대표전화
홈페이지
주식회사 네오클로바
19명
이 재 중
2011년 11월
서울시 강서구 양천로 583, 우림블루나인 B동 12층
02-539-4880
www.neoclova.co.kr
기업 개요 주요 파트너쉽
주요사업분야
IT 통합유지보수
Red Hat Enterprise Linux, JBoss, Apache / Tomcat,
MySQL / MariaDB / Percona Technical Support
Red Hat Ready Partner
T2 Partner
Registered Partner
Registered Partner
Registered Partner
70
NeoClova reference
주요 고객사
구축 부분
오픈소스
구축
업무분석
운영지원
컨설팅
- 운영시스템 전반 유지보수
- 장애 및 성능 분석 지원
- U.Key 3.0 U2L PI
- Unix Oracle RAC to Linux구축
- Jboss EWS/EAP 전환 및 성능 측정
- MySQL/MariaDB 컨설팅 서비스
- 통합시스템 내 리눅스 부분
유지보수 및 분석 지원
- 정보시스템 클라우드 전환 컨설팅 (ISP)
- 전체운영시스템 클라우드 전환 ISP
- G-Box플랫폼 구축 관련 오픈소스 지원
- ITO 오픈소스 컴플라이언스 검증
- New Kt.com 구축 관련 오픈소스 지원
- 오픈소스 SW 전사기술지원
- 가족관계 등록정보시스템 구축 사업내 오픈소스 구축
- 온라인 출생신고시스템 전산장비 도입 사업내 오픈소스
구축
- 스마트 산업입지 플랫폼 시범사업 전산장비 구축내 오픈소스 부분
- 빅데이터 기반의 차세대 공장설립온라인지원시스템 구축내 오픈소스 부분
- 차세대 운영정보시스템 구축내 오픈소스 부분
- 운영시스템 오픈소스(Linux부분) 운영지원
- 운영시스템 통합유지보수 지원
71
NeoClova
지원제품 List
1.3 Amazon Web Services
2.1 Red Hat OpenStack
Platform
3.1
MySQL
4.1 Red Hat JBoss
EAP
2.4 Red Hat Gluster Storage
5.1 Red Hat Enterprise Linux
1.1 Google Cloud Platform
2.2 Red Hat OpenShift Container Platform
2.3 Red Hat Ceph
Storage
2.6 Azure Stack
2.5 Red Hat Virtualization
3.2 MariaDB
4.2 Red Hat JBoss Web
Server
1.2 Microsoft Azure
4.3 Red Hat OpenShift
4.4
ACCORDION
4.5 Apache / Tomcat / NginX
5.2
CentOS
5.3
Ubuntu
5.4 Oracle Linux
3.4 DBMON-Star(DB 모니터링 자체솔루션)
3.5 DB CHECKER(DataBase 검증 및 자체튜닝 솔루션)
3.3 Percona Server for MySQL

More Related Content

What's hot

MariaDB 마이그레이션 - 네오클로바
MariaDB 마이그레이션 - 네오클로바MariaDB 마이그레이션 - 네오클로바
MariaDB 마이그레이션 - 네오클로바NeoClova
 
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법Ji-Woong Choi
 
Maxscale 소개 1.1.1
Maxscale 소개 1.1.1Maxscale 소개 1.1.1
Maxscale 소개 1.1.1NeoClova
 
MariaDB MaxScale monitor 매뉴얼
MariaDB MaxScale monitor 매뉴얼MariaDB MaxScale monitor 매뉴얼
MariaDB MaxScale monitor 매뉴얼NeoClova
 
[오픈소스컨설팅]Day #2 MySQL Tuning, Replication, Cluster
[오픈소스컨설팅]Day #2 MySQL Tuning, Replication, Cluster[오픈소스컨설팅]Day #2 MySQL Tuning, Replication, Cluster
[오픈소스컨설팅]Day #2 MySQL Tuning, Replication, ClusterJi-Woong Choi
 
MySQL_MariaDB로의_전환_기술요소-202212.pptx
MySQL_MariaDB로의_전환_기술요소-202212.pptxMySQL_MariaDB로의_전환_기술요소-202212.pptx
MySQL_MariaDB로의_전환_기술요소-202212.pptxNeoClova
 
Maxscale_메뉴얼
Maxscale_메뉴얼Maxscale_메뉴얼
Maxscale_메뉴얼NeoClova
 
ProxySQL High Availability (Clustering)
ProxySQL High Availability (Clustering)ProxySQL High Availability (Clustering)
ProxySQL High Availability (Clustering)Mydbops
 
MariaDB Administrator 교육
MariaDB Administrator 교육 MariaDB Administrator 교육
MariaDB Administrator 교육 Sangmo Kim
 
[2019] 200만 동접 게임을 위한 MySQL 샤딩
[2019] 200만 동접 게임을 위한 MySQL 샤딩[2019] 200만 동접 게임을 위한 MySQL 샤딩
[2019] 200만 동접 게임을 위한 MySQL 샤딩NHN FORWARD
 
MySQL GTID 시작하기
MySQL GTID 시작하기MySQL GTID 시작하기
MySQL GTID 시작하기I Goo Lee
 
오픈소스컨설팅 클러스터제안 V1.0
오픈소스컨설팅 클러스터제안 V1.0오픈소스컨설팅 클러스터제안 V1.0
오픈소스컨설팅 클러스터제안 V1.0sprdd
 
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docx
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docxKeepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docx
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docxNeoClova
 
MySQL Advanced Administrator 2021 - 네오클로바
MySQL Advanced Administrator 2021 - 네오클로바MySQL Advanced Administrator 2021 - 네오클로바
MySQL Advanced Administrator 2021 - 네오클로바NeoClova
 
How to build massive service for advance
How to build massive service for advanceHow to build massive service for advance
How to build massive service for advanceDaeMyung Kang
 
mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교Woo Yeong Choi
 
Intro ProxySQL
Intro ProxySQLIntro ProxySQL
Intro ProxySQLI Goo Lee
 
Redo log improvements MYSQL 8.0
Redo log improvements MYSQL 8.0Redo log improvements MYSQL 8.0
Redo log improvements MYSQL 8.0Mydbops
 
MariaDB 10.5 binary install (바이너리 설치)
MariaDB 10.5 binary install (바이너리 설치)MariaDB 10.5 binary install (바이너리 설치)
MariaDB 10.5 binary install (바이너리 설치)NeoClova
 
대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐
대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐
대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐Terry Cho
 

What's hot (20)

MariaDB 마이그레이션 - 네오클로바
MariaDB 마이그레이션 - 네오클로바MariaDB 마이그레이션 - 네오클로바
MariaDB 마이그레이션 - 네오클로바
 
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법
 
Maxscale 소개 1.1.1
Maxscale 소개 1.1.1Maxscale 소개 1.1.1
Maxscale 소개 1.1.1
 
MariaDB MaxScale monitor 매뉴얼
MariaDB MaxScale monitor 매뉴얼MariaDB MaxScale monitor 매뉴얼
MariaDB MaxScale monitor 매뉴얼
 
[오픈소스컨설팅]Day #2 MySQL Tuning, Replication, Cluster
[오픈소스컨설팅]Day #2 MySQL Tuning, Replication, Cluster[오픈소스컨설팅]Day #2 MySQL Tuning, Replication, Cluster
[오픈소스컨설팅]Day #2 MySQL Tuning, Replication, Cluster
 
MySQL_MariaDB로의_전환_기술요소-202212.pptx
MySQL_MariaDB로의_전환_기술요소-202212.pptxMySQL_MariaDB로의_전환_기술요소-202212.pptx
MySQL_MariaDB로의_전환_기술요소-202212.pptx
 
Maxscale_메뉴얼
Maxscale_메뉴얼Maxscale_메뉴얼
Maxscale_메뉴얼
 
ProxySQL High Availability (Clustering)
ProxySQL High Availability (Clustering)ProxySQL High Availability (Clustering)
ProxySQL High Availability (Clustering)
 
MariaDB Administrator 교육
MariaDB Administrator 교육 MariaDB Administrator 교육
MariaDB Administrator 교육
 
[2019] 200만 동접 게임을 위한 MySQL 샤딩
[2019] 200만 동접 게임을 위한 MySQL 샤딩[2019] 200만 동접 게임을 위한 MySQL 샤딩
[2019] 200만 동접 게임을 위한 MySQL 샤딩
 
MySQL GTID 시작하기
MySQL GTID 시작하기MySQL GTID 시작하기
MySQL GTID 시작하기
 
오픈소스컨설팅 클러스터제안 V1.0
오픈소스컨설팅 클러스터제안 V1.0오픈소스컨설팅 클러스터제안 V1.0
오픈소스컨설팅 클러스터제안 V1.0
 
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docx
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docxKeepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docx
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docx
 
MySQL Advanced Administrator 2021 - 네오클로바
MySQL Advanced Administrator 2021 - 네오클로바MySQL Advanced Administrator 2021 - 네오클로바
MySQL Advanced Administrator 2021 - 네오클로바
 
How to build massive service for advance
How to build massive service for advanceHow to build massive service for advance
How to build massive service for advance
 
mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교
 
Intro ProxySQL
Intro ProxySQLIntro ProxySQL
Intro ProxySQL
 
Redo log improvements MYSQL 8.0
Redo log improvements MYSQL 8.0Redo log improvements MYSQL 8.0
Redo log improvements MYSQL 8.0
 
MariaDB 10.5 binary install (바이너리 설치)
MariaDB 10.5 binary install (바이너리 설치)MariaDB 10.5 binary install (바이너리 설치)
MariaDB 10.5 binary install (바이너리 설치)
 
대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐
대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐
대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐
 

Similar to MySQL_MariaDB-성능개선-202201.pptx

개발자도 알아야 하는 DBMS튜닝
개발자도 알아야 하는 DBMS튜닝개발자도 알아야 하는 DBMS튜닝
개발자도 알아야 하는 DBMS튜닝정해 이
 
Vectorized processing in_a_nutshell_DeView2014
Vectorized processing in_a_nutshell_DeView2014Vectorized processing in_a_nutshell_DeView2014
Vectorized processing in_a_nutshell_DeView2014Gruter
 
MariaDB Other Features
MariaDB Other FeaturesMariaDB Other Features
MariaDB Other FeaturesJongJin Lee
 
MySQL InnoDB Cluster 소개
MySQL InnoDB Cluster 소개MySQL InnoDB Cluster 소개
MySQL InnoDB Cluster 소개rockplace
 
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4Seok-joon Yun
 
Intro KaKao ADT (Almighty Data Transmitter)
Intro KaKao ADT (Almighty Data Transmitter)Intro KaKao ADT (Almighty Data Transmitter)
Intro KaKao ADT (Almighty Data Transmitter)I Goo Lee
 
The nosql echossytem
The nosql echossytemThe nosql echossytem
The nosql echossytem종석 박
 
Fundamentals of Oracle SQL
Fundamentals of Oracle SQLFundamentals of Oracle SQL
Fundamentals of Oracle SQLJAEGEUN YU
 
[스마트스터디]MongoDB 의 역습
[스마트스터디]MongoDB 의 역습[스마트스터디]MongoDB 의 역습
[스마트스터디]MongoDB 의 역습smartstudy_official
 
Mongodb 특징 분석
Mongodb 특징 분석Mongodb 특징 분석
Mongodb 특징 분석Daeyong Shin
 
Ndc2011 성능 향상을_위한_데이터베이스_아키텍쳐_구축_및_개발_가이드
Ndc2011 성능 향상을_위한_데이터베이스_아키텍쳐_구축_및_개발_가이드Ndc2011 성능 향상을_위한_데이터베이스_아키텍쳐_구축_및_개발_가이드
Ndc2011 성능 향상을_위한_데이터베이스_아키텍쳐_구축_및_개발_가이드cranbe95
 
From MSSQL to MariaDB
From MSSQL to MariaDBFrom MSSQL to MariaDB
From MSSQL to MariaDBI Goo Lee
 
[스마트스터디]모바일 애플리케이션 서비스에서의 로그 수집과 분석
[스마트스터디]모바일 애플리케이션 서비스에서의 로그 수집과 분석[스마트스터디]모바일 애플리케이션 서비스에서의 로그 수집과 분석
[스마트스터디]모바일 애플리케이션 서비스에서의 로그 수집과 분석smartstudy_official
 
Azure Databases for PostgreSQL MYSQL and MariaDB
Azure Databases for PostgreSQL MYSQL and MariaDBAzure Databases for PostgreSQL MYSQL and MariaDB
Azure Databases for PostgreSQL MYSQL and MariaDBrockplace
 
AWS CLOUD 2018- Amazon Aurora  신규 서비스 알아보기 (최유정 솔루션즈 아키텍트)
AWS CLOUD 2018- Amazon Aurora  신규 서비스 알아보기 (최유정 솔루션즈 아키텍트)AWS CLOUD 2018- Amazon Aurora  신규 서비스 알아보기 (최유정 솔루션즈 아키텍트)
AWS CLOUD 2018- Amazon Aurora  신규 서비스 알아보기 (최유정 솔루션즈 아키텍트)Amazon Web Services Korea
 
MariaDB 제품 소개
MariaDB 제품 소개MariaDB 제품 소개
MariaDB 제품 소개NeoClova
 
MySQL Performance Tuning (In Korean)
MySQL Performance Tuning (In Korean)MySQL Performance Tuning (In Korean)
MySQL Performance Tuning (In Korean)OracleMySQL
 
SQL Azure 실무 도입하기
SQL Azure 실무 도입하기SQL Azure 실무 도입하기
SQL Azure 실무 도입하기정현 남
 
Migration to Azure Database for MySQL
Migration to Azure Database for MySQLMigration to Azure Database for MySQL
Migration to Azure Database for MySQLrockplace
 

Similar to MySQL_MariaDB-성능개선-202201.pptx (20)

개발자도 알아야 하는 DBMS튜닝
개발자도 알아야 하는 DBMS튜닝개발자도 알아야 하는 DBMS튜닝
개발자도 알아야 하는 DBMS튜닝
 
Vectorized processing in_a_nutshell_DeView2014
Vectorized processing in_a_nutshell_DeView2014Vectorized processing in_a_nutshell_DeView2014
Vectorized processing in_a_nutshell_DeView2014
 
MariaDB Other Features
MariaDB Other FeaturesMariaDB Other Features
MariaDB Other Features
 
MySQL InnoDB Cluster 소개
MySQL InnoDB Cluster 소개MySQL InnoDB Cluster 소개
MySQL InnoDB Cluster 소개
 
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
[2015 07-06-윤석준] Oracle 성능 최적화 및 품질 고도화 4
 
Intro KaKao ADT (Almighty Data Transmitter)
Intro KaKao ADT (Almighty Data Transmitter)Intro KaKao ADT (Almighty Data Transmitter)
Intro KaKao ADT (Almighty Data Transmitter)
 
The nosql echossytem
The nosql echossytemThe nosql echossytem
The nosql echossytem
 
Fundamentals of Oracle SQL
Fundamentals of Oracle SQLFundamentals of Oracle SQL
Fundamentals of Oracle SQL
 
[스마트스터디]MongoDB 의 역습
[스마트스터디]MongoDB 의 역습[스마트스터디]MongoDB 의 역습
[스마트스터디]MongoDB 의 역습
 
Mongodb 특징 분석
Mongodb 특징 분석Mongodb 특징 분석
Mongodb 특징 분석
 
Ndc2011 성능 향상을_위한_데이터베이스_아키텍쳐_구축_및_개발_가이드
Ndc2011 성능 향상을_위한_데이터베이스_아키텍쳐_구축_및_개발_가이드Ndc2011 성능 향상을_위한_데이터베이스_아키텍쳐_구축_및_개발_가이드
Ndc2011 성능 향상을_위한_데이터베이스_아키텍쳐_구축_및_개발_가이드
 
From MSSQL to MariaDB
From MSSQL to MariaDBFrom MSSQL to MariaDB
From MSSQL to MariaDB
 
[스마트스터디]모바일 애플리케이션 서비스에서의 로그 수집과 분석
[스마트스터디]모바일 애플리케이션 서비스에서의 로그 수집과 분석[스마트스터디]모바일 애플리케이션 서비스에서의 로그 수집과 분석
[스마트스터디]모바일 애플리케이션 서비스에서의 로그 수집과 분석
 
Azure Databases for PostgreSQL MYSQL and MariaDB
Azure Databases for PostgreSQL MYSQL and MariaDBAzure Databases for PostgreSQL MYSQL and MariaDB
Azure Databases for PostgreSQL MYSQL and MariaDB
 
AWS CLOUD 2018- Amazon Aurora  신규 서비스 알아보기 (최유정 솔루션즈 아키텍트)
AWS CLOUD 2018- Amazon Aurora  신규 서비스 알아보기 (최유정 솔루션즈 아키텍트)AWS CLOUD 2018- Amazon Aurora  신규 서비스 알아보기 (최유정 솔루션즈 아키텍트)
AWS CLOUD 2018- Amazon Aurora  신규 서비스 알아보기 (최유정 솔루션즈 아키텍트)
 
Spark sql
Spark sqlSpark sql
Spark sql
 
MariaDB 제품 소개
MariaDB 제품 소개MariaDB 제품 소개
MariaDB 제품 소개
 
MySQL Performance Tuning (In Korean)
MySQL Performance Tuning (In Korean)MySQL Performance Tuning (In Korean)
MySQL Performance Tuning (In Korean)
 
SQL Azure 실무 도입하기
SQL Azure 실무 도입하기SQL Azure 실무 도입하기
SQL Azure 실무 도입하기
 
Migration to Azure Database for MySQL
Migration to Azure Database for MySQLMigration to Azure Database for MySQL
Migration to Azure Database for MySQL
 

MySQL_MariaDB-성능개선-202201.pptx

  • 1. MySQL / MariaDB 성능 최적화 네오클로바 (db@neoclova.co.kr) ▶ 2022. 01
  • 2. 2 목차 구분 내용 DBA - Hardware - Operating System - Modeling - Objects & Server Variables - Replication - Online DDL - Connection Control DEV - SQL 작성 - Explain - SQL튜닝 사례 - 성능개선 사례 - Troubleshooting
  • 3. Next Opensource Cloud Value 고정관념
  • 4. 4 고정관념 • MySQL/MariaDB Server는 공짜다? • 타 DBMS에 비해 성능이 떨어진다? • Oracle에서는 잘 돌아가는데, MySQL에서는 왜 안돼요? • MySQL도 SQL실행계획을 재사용 한다? • MySQL의 SQL튜닝은 DBA가 해야 할 일이다?
  • 5. 5 DBA 구분 내용 DBA - Hardware - Operating System - Modeling - Objects & Server Variables - Replication - Online DDL - Connection Control DEV - SQL 작성 - Explain - SQL튜닝 사례 - 성능개선 사례 - Troubleshooting
  • 6. Next Opensource Cloud Value Hardware
  • 7. 7 Hardware • Hardware – CPU ✔ Single processing ✔ More Speed Processor (Fast Clock Speed) ✔ bus speed, cache size ✔ More Cores – Memory ✔ 슬롯당 최대 RAM Size 우선선택 – Disk ✔ 빠른 Disk speed ✔ redo / undo / binary log 전용 디스크 https://mariadb.com/kb/en/hardware-optimization/
  • 8. Next Opensource Cloud Value Operating System
  • 9. 9 Operating System • OS – Windows Server ■ NTFS – Linux ■ Open Files ■ Swappiness https://mariadb.com/kb/en/operating-system-optimizations/
  • 10. 10 Operating System • Linux – IO scheduler – Open files / core file size – Swappiness # cat /sys/block/sda/queue/scheduler noop [deadline] cfq # cat /etc/security/limits.conf mysql soft nofile 65535 mysql hard nofile 65536 mysql soft core unlimited mysql hard core unlimited # cat /etc/sysctl.conf vm.dirty_background_bytes=104857600 vm.swappiness=1 # cat /etc/systemd/system/mysqld.service … LimitNOFILE = infinity LimitMEMLOCK=infinity TasksMax = infinity
  • 11. Next Opensource Cloud Value Modeling
  • 12. 12 Modeling • Charset - EUCKR - UTF8 - UTF8MB4 for emoji - 다른 Charset간의 Join 주의 • Collation - Sensitive vs In-Sensitive - *_bin - *_general_ci/cs - *_unicode_ci/cs - 다른 Collation 컬럼간의 Join에 주의 • MySQL 8 :utf8mb4_0900_ai_ci(한글문제) …utf8mb4_unicode_520_ci - pad space 주의( 이기종 DB에서 Data Migration 시) • MariaDB : utf8mb4_unicode_ci
  • 13. 13 Modeling • Data Type Length 오해 - length() - char_length() create table table1 ( id int, nm1 varchar(10), primary key(id) ) engine=innodb character set utf8; -- nm1은 10음절(length) 일까요? 10 bytes 일까요?
  • 14. 14 Modeling • AUTO_INCREMENT - Only one per table - Unique or Primary Key에 유용 - Innodb_autoinc_lock_mode 0 : table lock 1 : Consecutive Lock Mode (default) 2 : lightweight mutex lock(권고) https://mariadb.com/kb/en/optimization-and-indexes/ https://mariadb.com/kb/en/optimizing-data-structure/ • SEQUENCE - MariaDB 10.3 부터 지원 - InnoDB engine으로 내부구현 - MySQL은 지원 안함
  • 15. 15 Modeling • Primary Key 설정 - 선택이 아닌 필수!!!! - Replication Lag - 없는것보다 있는것이 좋음 - auto_increment 활용 - 큰Size의 컬럼은 PK로 피하라 - MariaDB 10.1 : innodb_force_primary_key - MySQL 8.0 : sql_require_primary_key https://mariadb.com/kb/en/optimizing-tables/ https://mariadb.com/kb/en/system-variables/
  • 16. 16 Modeling • 적절한 데이터 타입 사용 - 가능하다면 정수형으로 저장하라 - 날짜 데이터를 VARCHAR(14)에 %Y%M%d%H%i%S 저장? - VARCHAR(4000) ? - Bit 타입의 활용 - Timestamp 타입의 특수성 - NOT NULL - 가능하면 작은 Size
  • 17. 17 Modeling • 테이블 파티셔닝 남용 주의 - 파티셔닝의 목적 - 파티셔닝 제약조건 - 파티션 프루닝 - Primary Key가 변경되었다는 것을 잊지 말자 (App에서 SQL을 변경) - 파티셔닝 키 함수의 확인 파티션에 사용할 수는 있으나, 파티션 프루닝을 지원하지 않는 함수 검토 - MySQL : explain ~ - MariaDB : explain partitions ~
  • 18. 18 Modeling ❖ Sharding ➢ Spider Storage Engine ➢ Vitess ❖ Distributed SQL
  • 19. Next Opensource Cloud Value Objects & Variables
  • 20. 20 Objects & Variables • Configuration (my.cnf) innodb_buffer_pool_size = # Max 80% of physical memory innodb_buffer_pool_instances = # buffer_pool 크기에 따라 1G이상 고려 innodb_buffer_pool_chunk_size = # buffer_pool 크기가 128GB 이상일때 크기 증 가 innodb_log_file_size = 1G # redo log file size innodb_flush_method = O_DIRECT # data & log flush innodb_thread_sleep_delay = 0 # 절전 off innodb_adaptive_max_sleep_delay = 0 # innodb_thread_sleep_delay 자동조정 innodb_max_dirty_pages_pct_lwm = 0.001 # 최소 더티 페이지 비율 innodb_read_ahead_threshold = 64 # read ahead 페이지수 innodb_thread_concurrency = 0 # 최대 동시 수행 thread수.auto innodb_purge_thread = 4 innodb_read_io_thread = 4 innodb_write_io_thread = 4 innodb_io_capacity = 20000 thread_handling = pool_of_threads
  • 21. 21 Objects & Variables • InnoDB 제약 조건 – InnoDB tables can have a maximum of 1,017 columns – The maximum size for BLOB and TEXT columns is 4GB. This also applies to LONGBLOB and LONGTEXT – MariaDB imposes a row-size limit of 65,535 bytes for the combined sizes of all columns – The innodb_large_prefix system variable enables large prefix sizes That is, when enabled InnoDB uses 3072B index key prefixes for DYNAMIC and COMPRESSED row formats When disabled, it uses 787B key prefixes for tables of any row format
  • 22. 22 Objects & Variables • InnoDB Variables – Innodb thread concurrency ■ default가 0으로 자동 최적값 찾아가는 상태인데, 권고사항은 core * 2로 설정 ■ 권고값 이상 늘리면 context switching 가능성이 있음 – Innodb purge thread ■ 데이터가 단일 테이블에 집중되어 있다면 MySQL에서는 최대한 낮게 유지하라고 권고 ■ multi table이라면 현재 설정값 감안하여 늘려주고 모니터링 – Innodb buffer pool chunk size ■ 10.5 deprecated : buffer pool instances ■ Buffer pool size 크기가 128GB 보다 크면 chunk size 늘려주라고 권고 – Innodb read io thread, Innodb write io thread ■ 10.5 버전부터는 위 파라미터 2개가 비동기 I/O 쓰레드를 의미하는 것으로 변경 ■ 각 세팅값에 256을 곱한 값이 백그라운드 쓰레드 풀에서 동시에 완료할 수 있는 최대 요청 수 ■ show innodb status에서 pending read request를 참조 ■ 만약 DB I/O에 대한 전반적인 성능 튜닝이 목적이라면, Innodb_io_capacity 튜닝이 더 효율적
  • 23. Next Opensource Cloud Value Replication
  • 24. 24 Replication ▪ slave_parallel_threads ▪ slave_parallel_max_queued ▪ group commit ▪ binlog_row_image = minimal (LOB) https://mariadb.com/kb/en/parallel-replication/
  • 25. Next Opensource Cloud Value Online DDL
  • 26. 26 Online DDL ▪ Online DDL – COPY – INPLACE – NOCOPY – INSTANT https://dev.mysql.com/doc/refman/8.0/en/innodb-online-ddl.html https://mariadb.com/kb/en/innodb-online-ddl-overview/
  • 27. 27 Online DDL Operation Instant In Place Rebuilds Table Permits Concurrent DML Only Modifies Metadata Adding a column Yes Yes No Yes No Dropping a column No Yes Yes Yes No Renaming a column No Yes No Yes Yes Reordering columns No Yes Yes Yes No Setting a column default value Yes Yes No Yes Yes Changing the column data type No No Yes No No Extending VARCHAR column size No Yes No Yes Yes Dropping the column default value Yes Yes No Yes Yes Changing the auto-increment value No Yes No Yes No Making a column NULL No Yes Yes Yes No Making a column NOT NULL No Yes Yes Yes No Modifying the definition of an ENUM or SET column Yes Yes No Yes Yes ▪ Online DDL Support for Column Operations
  • 28. Next Opensource Cloud Value Connection Control
  • 29. 29 Connection Control ▪ WAS Connection Pool 수 ○ thread running 수 (동시 쿼리 수행수) ▪ JDBC connection ○ usePipelineAuth=false ○ socketTimeout=180 ○ health check timeout ○ connectTimeout ▪ MariaDB ○ wait_timeout ○ interactive_timeout ▪ Linux ○ tcp_keepalive ○ tcp_fin_timeout
  • 30. 30 DEV 구분 내용 DBA - Hardware - Operating System - Modeling - Objects & Server Variables - Replication - Online DDL - Connection Control DEV - SQL 작성 - Explain - SQL튜닝 사례 - 성능개선 사례 - Troubleshooting
  • 31. Next Opensource Cloud Value SQL 작성
  • 32. 32 SQL 작성 • SQL 작성 가이드 – ANSI SQL – ERD 이해 – PRIMARY KEY & SECONDARY KEY – JOIN 방식/순서 – 부분범위 처리 – 데이터 타입 우선순위 – Charset / Collation 우선순위 – EXPLAIN
  • 33. 33 SQL 작성 • ANSI SQL – SQL-89 : 교차 조인 또는 쉼표로 구분된 테이블 목록을 사용하고 조인을 WHERE절에 배치 – SQL-92 ~ : INNER JOIN, LEFT JOIN등의 키워드를 사용하고 하위 절(ON, USING)에 조건 배치 select a.uid, b.pid from person a left outer join part b on b.uid = a.uid where a.age<50; select a.uid, b.pid from person a, part b where a.uid = b.uid(+) and a.age<50;
  • 34. 34 SQL 작성 • ERD 이해 – 테이블간 관계 – 재귀구조 – 의사소통 – 데이터 표준 – 1:1 , 1: N
  • 35. 35 SQL 작성 • Primary Key – PK 없으면 6bytes 더미 PK 컬럼 생성 – secondary key lookup – sql_require_primary_key 설정 http://philipzhong.blogspot.com/2011/06/how-to-improve-mysql-select-count.html
  • 36. 36 SQL 작성 • Secondary Key – leaf node에 PK 포함 – key lookup 통해서 PK 데이터를 검색 – Covered Index https://www.slideshare.net/mysqlops/innodb-internal-9032556
  • 37. 37 SQL 작성 • JOIN – 모든 SQL Single processing – 오직 Nested Loop Join – 조인 컬럼을 가지고 Driving Table에서 Driven Table 접근 output cf) innodb_adaptive_hash_join https://mariadb.com/kb/en/duplicateweedout-strategy/
  • 38. 38 SQL 작성 • 부분범위 처리 – 실제 필요한 데이터량만 조회처리 – 적절한 Index 생성 alter table person add key person_n_1 (age, rdate); – Data Sorting이 성능을 좌우한다 select * from person where age=25 order by rdate asc limit 0,10;
  • 39. 39 SQL 작성 • 데이터 타입 우선순위 – 명시적 형변환, 묵시적 형변환 – 우선순위 JSON> 날짜형 > 숫자형 > 문자형 > 바이너리형 json > datetime > date > decimal > double > float > bigint > int > … > varchar > …> binary – 반드시 컬럼타입에 맞게 SQL작성 https://dev.mysql.com/doc/refman/8.0/en/type-conversion.html https://mariadb.com/kb/en/type-conversion/ create table t_member (id int, jumin1 varchar(6), jumin2 varchar(7), primary key(id)); select * from t_member where jumin1=891212 ;
  • 40. 40 SQL 작성 • CHARSET / COLLATION 우선순위 – database > table > column 문자집합 – 문자열의 대소비교에 적용 – 테이블간 조인에서 조인컬럼 문자집합의 collation이 다를 경우에 한쪽 collation을 다른 한쪽으로 변환 후에 비교 변환에 실패 시 오류발생하기도 함 ERROR 1267 (HY000): Illegal mix of collations (latin1_general_ci,IMPLICIT) and (latin1_Swedish_ci,IMPLICIT) for operation '=' 변환에 성공하더라도 charset 우선순위에 따라 column data collation conversioin 발생 mysql> explain select t1.* from t1 inner join t2 on t2.nm=t1.nm; +----+-------------+-------+------------+-------+---------------+------+---------+------+---------+----------+--------------------------------------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+-------+------------+-------+---------------+------+---------+------+---------+----------+--------------------------------------------+ | 1 | SIMPLE | t2 | NULL | index | nm | nm | 43 | NULL | 1 | 100.00 | Using index | | 1 | SIMPLE | t1 | NULL | ALL | nm | NULL | NULL | NULL | 4988104 | 10.00 | Using where; Using join buffer (hash join) | +----+-------------+-------+------------+-------+---------------+------+---------+------+---------+----------+--------------------------------------------+ mysql> explain select t1.* from t1 inner join t2 on convert(t2.nm using latin1)=t1.nm; +----+-------------+-------+------------+-------+---------------+------+---------+------+------+----------+-----------------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+-------+------------+-------+---------------+------+---------+------+------+----------+-----------------------+ | 1 | SIMPLE | t2 | NULL | index | NULL | nm | 43 | NULL | 1 | 100.00 | Using index | | 1 | SIMPLE | t1 | NULL | ref | nm | nm | 13 | func | 1 | 100.00 | Using index condition | +----+-------------+-------+------------+-------+---------------+------+---------+------+------+----------+-----------------------+
  • 41. Next Opensource Cloud Value EXPLAIN
  • 42. 42 EXPLAIN • EXPLAIN / DESC / DESCRIBE – slow query 확인 – 옵티마이저의 변환 – 적절한 조인 순서 – 인덱스 확인 – SQL 수정 판단 컬럼 설명 id 한 테이블의 SELECT 번호, 쿼리내의 SELECT의 구분번호 select_type SELECT의 타입(SIMPLE, PRIMARY, UNION, SUBQUERY, DRIVED, …) table 해당 table명 type 조인의 타입(system, const, eq_ref, ref, ref_or_null, …) possible_keys 테이블의 사용 가능한 인덱스 명 key Possible_keys 값들 중에서 실제 사용한 인덱스(key) Key_len Where절에 사용한 인덱스의 길이(byte) ref 행을 추출하는데 key와 함께 사용한 컬럼 이나 상수 rows 쿼리수행을 위해 검사대상 예상행수 filtered 조건절에 의해 필터링 되는 행의 비율 extra 쿼리를 해석한 추가적인 정보
  • 43. 43 EXPLAIN • Query Analysis – Use EXPLAIN to see how MariaDB Executes a Troublesome Query and if Indexes are Used – Use EXPLAIN EXTENDED and SHOW WARNINGS to see how MariaDB Rearranges a Query before Execution MariaDB> EXPLAIN SELECT * FROM employees WHERE MONTH(birth_date) = 10 G MariaDB> EXPLAIN EXTENDED SELECT ...; MariaDB> SHOW WARNINGS;
  • 44. 44 EXPLAIN • select_type – SIMPLE : UNION 이나 SUBQUERY를 사용하지 않는 단순 SELECT – PRIMARY : 쿼리 제일 바깥쪽에 있는 SELECT – DERIVED : SELECT절로 추출된 테이블로 FROM절 내부의 SUBQUERY의미 – UNION : UNION절에서 두번째 이후 SELECT, 첫번째는 DERIVED – DEPENDENT UNION : 내부 쿼리가 외부 값을 참조하는 UNION절 테이블 – UNION RESULT : UNION 결과 값에 대한 임시 테이블 – SUBQUERY : FROM절 이외의 서브 쿼리 의미 – DEPENDENT SUBQUERY : 서브쿼리가 바깥쪽 SELECT절의 컬럼 값을 참조 – UNCACHEABLE SUBQUERY : 서브쿼리 결과가 외부 쿼리의 변하는 값에 따라 매번 새로 생성 – UNCACHEABLE UNION : 캐싱이 불가능한 요소를 포함한 UNION
  • 45. 45 EXPLAIN • Scan or Index Method types – const : A constant value can be read once and cached – eq_ref : One index access per outer query row – ref : Multiple index accesses per outer query row – index_merge : Multiple indexes used, merging into a single result set – range : Multiple index accesses to return all rows within a range – index : Full index scan (every index entry is read sequentially) – all : Full table scan (every record is read sequentially)
  • 46. 46 EXPLAIN • Analyze Columns – Analyze Columns with PROCEDURE ANALYSE() – Use PROCEDURE ANALYSE() for Data Type Recommendations MariaDB> SELECT gender, hire_date FROM employees PROCEDURE ANALYSE() G MariaDB> SELECT salary FROM salaries PROCEDURE ANALYSE()G
  • 47. 47 EXPLAIN • Indexes for Performance Optimization – MariaDB can Resolve Queries Faster with Indexes Faster Retrieval of Matching Rows, Faster Sorting of Result Sets Without Indexes, MariaDB does Full Table Scan – Indexes can be for a Column or Multiple Columns (i.e.,Composites) – Index for Speed, but Avoid Indexing Excessively or Arbitrarily – Remove Unused or Redundant Indexes
  • 48. 48 EXPLAIN • Create Table Indexes – Use ALTER TABLE or CREATE INDEX to add an Index – Keep Indexes as Small as Practical – For Indexing Strings, Use Prefix MariaDB> ALTER TABLE employees ADD INDEX emp_names (name_last, name_first); MariaDB> SHOW CREATE TABLE employees G MariaDB> CREATE INDEX client_names ON clients (name_last(10), name_first(5));
  • 49. 49 EXPLAIN • Better JOIN Construction – Foreign Keys used with Joins should be Indexed – Index Columns in ON and USING Clauses – Keep GROUP BY and ORDER BY columns in one Table for better Indexing SELECT last_name, city, country_name FROM clients JOIN country_names USING(country_id) WHERE clients.country_id IN('de','fr','it','uk') ORDER BY country_name, city, last_name;
  • 50. 50 EXPLAIN • SHOW PROFILES – 세션에서 실행한 SQL에 대하여 서버의 리소스 사용량을 확인 가능 – session variable (profiling) 을 이용 SET SESSION PROFILING=1; SELECT * FROM 테이블~; #사용자 수행쿼리. … # 현재 세션에서 수행한 SQL들에 대한 프로파일링 요약. SHOW PROFILES; # 마지막 수행된 SQL을 프로파일링. SHOW PROFILE; #현재 세션에서 수행한 QUERY_ID에 대한 프로파일링. SHOW PROFILE FOR QUERY #N; #현재 세션에서 수행한 QUERY_ID에 대한 CPU정보 포함 프로파일링 SHOW PROFILE CPU FOR QUERY #N;
  • 51. Next Opensource Cloud Value SQL튜닝사례
  • 52. 52 SQL 튜닝사례 • Not Found Index : Create Index • Wrong Data Type : Correct Data Binding • Subquery, Subquery, … : Join Conversion • Change of column! : Change Scalar Values. • Covering Index : Composite Index • COUNT ~ left join ~ : Don't use the framework as an excuse. • ORDER BY ~ LIMIT 1; : 부분집합처리 • Index Columns Order : 선택도가 좋은 컬럼부터 ~ • FULLTEXT/NGRAM : 전문검색엔진이 없다면~ • LEFT JOIN ~ ON ~ WHERE ~ : ON절과 WHERE절 조건처리의 명확한 이해 • Paging SQL , row_number() : 아직은 ROW_NUMBER() OVER()가 비효율적이네요 • Generated Column : function based index … • Invisible Column : create table tx(id int, ivnm varchar(10) invisible); • Function Based Index : create table ty (id int not null, nm varchar(3) not null, key ((substring(nm,2,2))) ); • Update join : in 제거 • Charset/collation conversion : table / index full scan • Stored Procedure : batch.
  • 53. Next Opensource Cloud Value 성능개선사례
  • 54. 54 성능개선사례 • DB/Infra Architecture 개선 ⮚ Oracle -> MariaDB (E**) ⮚ MaxScale + read replica (E**) ⮚ Replication (인*) ⮚ Table Partitioning (LG*** **) ⮚ Stored Procedure (S**) ⮚ Galera -> Replication (후*) ⮚ Percona -> MySQL (ka*******) ⮚ MySQL -> MariaDB (하***) ⮚ Aurora -> Xpand (수**) ⮚ DR Configuration(신***) ⮚ MariaDB upgrade : 10.0 -> 10.3(L***)
  • 55. 55 성능개선사례 • DB Variables 튜닝 ⮚ CPU : innodb_thread_concurrency (투*****) ⮚ table_open_cache, innodb_change_buffering, innodb_fast_shutdown : (후*) ⮚ open_files_limit, tmp_table_size: (L****) ⮚ innodb_buffer_pool_size : (대***) ⮚ stored_program_cache : (T**) ⮚ vm.swappiness, innodb_flush_method, innodb_log_group_home_dir : (하***) ⮚ query_cache : (인*) ⮚ MyISAM : FTS(Full Text Search), character set (euc-kr), Primary Key (비***) ⮚ max_connections, max_allowed_packet : (U***) ⮚ rpl_semi_sync~ : (사*****)
  • 56. 56 성능개선사례 ▪ SAMSUNG CLOUD OPERATION TEAM AUTHENTICATES 10 BILLION+ REQUESTS DAILY WITH MARIADB XPAND; CUTS COSTS BY 50% https://mariadb.com/wp-content/uploads/2021/11/samsung-cloud-authenticates-10-billion-requests-daily-with-mariadb-xpand_customer-story_1127.pdf ▪ Southeast Asia's Largest Bank Migrates to Open Source Database MariaDB https://mariadb.com/resources/customer-stories/dbs/ ▪ Why Uber Engineering Switched from Postgres to MySQL https://eng.uber.com/postgres-to-mysql-migration/ ▪ 카카오, 연내 오라클 DB 전면 걷어낸다 https://www.etnews.com/20200130000324 ▪ Netflix Billing Migration to AWS https://netflixtechblog.com/netflix-billing-migration-to-aws-451fba085a4 ▪ MySQL Customers https://www.mysql.com/customers/
  • 57. Next Opensource Cloud Value MySQL Troubleshooting
  • 58. 58 MySQL Troubleshooting ▪ 장애 대응 사례 장애 사례 원인 파악 문제 해결 DB session 증가로 인한 query 지연 이슈 connection이 늘어남에 따른 query 실행 지연 현상 발생 - WAS에서 DB 서비스에 connection 을 끊어 주지 않아서 발생된 이슈로 확인 File system data size 증가에 따른 disk full로 DB 서비스 중지 발생 - data size가 큰 table을 partitioning 처리하여 backup후 truncate 하는 구조로 로 직 변경 Memory 부족 memory 부족으로 인한 DB 서비스 중지 발생 - my.cnf 설정의 memory 옵션 조정으로 서버 사양에 맞게 조정하여 DB 서비스 복구 Schema 관리 user 실수로 table schema 문제 발생 - 개발자가 기존 table schema를 재 생성 하면서 컬럼 누락으로 이슈 발생, 확인 후 table 재 생성 DB 서비스중지 DB 서버 재부팅으로 인한 서비스 중단 발생 - VM의 OS 오류로 인한 서버 재 부팅 발생으로 VM 이슈 확인 CPU 사용률 증가 OS CPU 사용률 증가로 인한 DB query 지연 발생 - 개발 서비스 SQL문제로 인하여 개발 소스 수정 후 조치 완료 - 실행계획 확인 후 인덱스 추가조치 완료
  • 59. 59 MySQL Troubleshooting ▪ MySQL Error – Error Messages 확인 – Error log 확인 – MySQL https://dev.mysql.com/doc/mysql-errors/8.0/en/error-reference-introduction.html - MariaDB https://mariadb.com/kb/en/mariadb-error-codes/ https://mariadb.com/kb/en/operating-system-error-codes/
  • 60. 60 MySQL Troubleshooting ▪ InnoDB Recovery – Crash된 응급상황에서는 innodb_force_recovery 서버변수 설정 0 : 기본값, 정상상황 1 : 누락된 데이터, 손상된 페이지 감지 무시 2 : Undo 로그 삭제 무시 3 : roll-forward 수행 오류 무시 4 : Insert Buffer 손상 무시 5 : Undo 로그 무시하고 강제 COMMIT 6 : roll-forward 무시, Redo 손상에 대한 강제복구 – 0 ~ 6의 순서로 데이터베이스기동 (실패하면 다음 값으로 데이터베이스 시작) – 데이터베이스 시작이 성공 하면 mysqldump로 백업 / 복원
  • 61. 61 MySQL Troubleshooting ▪ mysql_upgrade # mysql_upgrade –uroot –p Phase 1/7: Checking and upgrading mysql database Processing databases mysql mysql.column_stats OK mysql.columns_priv OK mysql.db OK mysql.event OK ... Phase 2/7: Installing used storage engines... Skipped Phase 3/7: Fixing views Phase 4/7: Running 'mysql_fix_privilege_tables' Phase 5/7: Fixing table and database names Phase 6/7: Checking and upgrading tables Phase 7/7: Running 'FLUSH PRIVILEGES'
  • 62. 62 MySQL Troubleshooting ▪ Performance Schema -- 수행횟수가 가장 많은 상위SQL 10개 MySQL> select digest_text, count_star,(avg_timer_wait/1000000000000) exec_t_s, sum_cpu_time/count_star, sum_rows_sent/count_star, sum_rows_examined/count_star from performance_schema.events_statements_summary_by_digest order by count_star desc limit 10; -- 수행횟수가 가장 많고 2초 이상 소요된 상위SQL 10개. MySQL> select digest_text, count_star, (avg_timer_wait/1000000000000) exec_t_s, sum_cpu_time/count_star, sum_rows_sent/count_star, sum_rows_examined/count_star from performance_schema.events_statements_summary_by_digest where (avg_timer_wait/1000000000000) >= 2 order by count_star desc limit 10;
  • 63. 63 MySQL Troubleshooting ▪ Performance Schema -- 평균수행시간이 가장 긴 상위SQL 10개 MySQL> select digest_text, count_star, (avg_timer_wait/1000000000000) exec_t_s, sum_cpu_time/count_star, sum_rows_sent/count_star, sum_rows_examined/count_star from performance_schema.events_statements_summary_by_digest order by avg_timer_wait desc limit 10; -- 평균잠금시간이 가장 긴 상위SQL 10개 MySQL> select digest_text, count_star, (avg_timer_wait/1000000000000) exec_t_s, sum_cpu_time/count_star, sum_rows_sent/count_star, sum_rows_examined/count_star, (SUM_LOCK_TIME/count_star)/1000000000000 as avg_lock_time from performance_schema.events_statements_summary_by_digest order by (SUM_LOCK_TIME/count_star) desc limit 10;
  • 64. 64 MySQL Troubleshooting ▪ Performance Schema -- 평균반환행수가 가장 많은 상위SQL 10개 MySQL> select digest_text, count_star, (avg_timer_wait/1000000000000) exec_t_s, sum_cpu_time/count_star as avg_cpu_time, sum_rows_sent/count_star as avg_sent_rows, sum_rows_examined/count_star as avg_examined_rows, (SUM_LOCK_TIME/count_star)/1000000000000 as avg_lock_time from performance_schema.events_statements_summary_by_digest order by (SUM_ROWS_SENT/count_star) desc limit 10; -- 비효율 SQL 쿼리확인 MySQL> select schema_name, left(digest_text, 40) qry, count_star, sum_cpu_time, sum_created_tmp_disk_tables sctdt, sum_select_full_join ssfj, sum_select_range_check ssrc, sum_sort_merge_passes ssmp from performance_schema.events_statements_summary_by_digest where sum_created_tmp_disk_tables > 0 OR sum_select_full_join > 0 OR sum_select_range_check > 0 OR sum_sort_merge_passes > 0 ORDER BY sum_sort_merge_passes DESC LIMIT 10;
  • 65. 65 MySQL Troubleshooting ▪ Performance Schema -- 특정 SQL의 프로파일링 MySQL> SELECT s.event_id AS Query_ID, TRUNCATE(s.timer_wait/1000000000000, 6) as Duration,LEFT(s.sql_text, 120) AS Query FROM performance_schema.events_statements_history_long s INNER JOIN performance_schema.threads t on t.thread_id=s.thread_id where 1=1 -- and t.processlist_id = CONNECTION_ID() -- 현재 My session order by Duration desc limit 10; MySQL> select event_name, truncate(timer_wait/1000000000000,6) as duration from performance_schema.events_stages_history_long where nesting_event_id=874 -- query id order by timer_start asc;
  • 67. 67
  • 68. Next Opensource Cloud Value NeoClova
  • 69. 69 NeoClova 회사명 임직원 대표이사 설립년도 주소 대표전화 홈페이지 주식회사 네오클로바 19명 이 재 중 2011년 11월 서울시 강서구 양천로 583, 우림블루나인 B동 12층 02-539-4880 www.neoclova.co.kr 기업 개요 주요 파트너쉽 주요사업분야 IT 통합유지보수 Red Hat Enterprise Linux, JBoss, Apache / Tomcat, MySQL / MariaDB / Percona Technical Support Red Hat Ready Partner T2 Partner Registered Partner Registered Partner Registered Partner
  • 70. 70 NeoClova reference 주요 고객사 구축 부분 오픈소스 구축 업무분석 운영지원 컨설팅 - 운영시스템 전반 유지보수 - 장애 및 성능 분석 지원 - U.Key 3.0 U2L PI - Unix Oracle RAC to Linux구축 - Jboss EWS/EAP 전환 및 성능 측정 - MySQL/MariaDB 컨설팅 서비스 - 통합시스템 내 리눅스 부분 유지보수 및 분석 지원 - 정보시스템 클라우드 전환 컨설팅 (ISP) - 전체운영시스템 클라우드 전환 ISP - G-Box플랫폼 구축 관련 오픈소스 지원 - ITO 오픈소스 컴플라이언스 검증 - New Kt.com 구축 관련 오픈소스 지원 - 오픈소스 SW 전사기술지원 - 가족관계 등록정보시스템 구축 사업내 오픈소스 구축 - 온라인 출생신고시스템 전산장비 도입 사업내 오픈소스 구축 - 스마트 산업입지 플랫폼 시범사업 전산장비 구축내 오픈소스 부분 - 빅데이터 기반의 차세대 공장설립온라인지원시스템 구축내 오픈소스 부분 - 차세대 운영정보시스템 구축내 오픈소스 부분 - 운영시스템 오픈소스(Linux부분) 운영지원 - 운영시스템 통합유지보수 지원
  • 71. 71 NeoClova 지원제품 List 1.3 Amazon Web Services 2.1 Red Hat OpenStack Platform 3.1 MySQL 4.1 Red Hat JBoss EAP 2.4 Red Hat Gluster Storage 5.1 Red Hat Enterprise Linux 1.1 Google Cloud Platform 2.2 Red Hat OpenShift Container Platform 2.3 Red Hat Ceph Storage 2.6 Azure Stack 2.5 Red Hat Virtualization 3.2 MariaDB 4.2 Red Hat JBoss Web Server 1.2 Microsoft Azure 4.3 Red Hat OpenShift 4.4 ACCORDION 4.5 Apache / Tomcat / NginX 5.2 CentOS 5.3 Ubuntu 5.4 Oracle Linux 3.4 DBMON-Star(DB 모니터링 자체솔루션) 3.5 DB CHECKER(DataBase 검증 및 자체튜닝 솔루션) 3.3 Percona Server for MySQL

Editor's Notes

  1. https://www.slideshare.net/mysqlops/innodb-internal-9032556
  2. https://www.slideshare.net/mysqlops/innodb-internal-9032556
  3. http://philipzhong.blogspot.com/2011/06/how-to-improve-mysql-select-count.html
  4. https://www.slideshare.net/mysqlops/innodb-internal-9032556
  5. https://www.slideshare.net/mysqlops/innodb-internal-9032556
  6. https://www.slideshare.net/mysqlops/innodb-internal-9032556
  7. https://www.slideshare.net/mysqlops/innodb-internal-9032556
  8. https://www.slideshare.net/mysqlops/innodb-internal-9032556
  9. https://www.slideshare.net/mysqlops/innodb-internal-9032556
  10. https://www.slideshare.net/mysqlops/innodb-internal-9032556
  11. https://www.slideshare.net/mysqlops/innodb-internal-9032556
  12. https://www.slideshare.net/mysqlops/innodb-internal-9032556
  13. https://www.slideshare.net/mysqlops/innodb-internal-9032556
  14. https://www.slideshare.net/mysqlops/innodb-internal-9032556
  15. https://www.slideshare.net/mysqlops/innodb-internal-9032556
  16. https://www.slideshare.net/mysqlops/innodb-internal-9032556
  17. https://www.slideshare.net/mysqlops/innodb-internal-9032556