2. Performance tuning http:// www.ggola.com
Tuning Overview
7
Tuning의 종류
Tuning Order : 기대효과 순으로
1. Design(if it's not too late)
2. Application
3. Memory
4. I/O
5. Contention
Oracle Diagnostic Tools
v$views - based on x$ tables (instance information을 가지는
memory structure) v$view는 sys user 소유의 v_$ view의 synonym
으로서 v$fixed_table 에 list되어 있다. x$ table에 기반하는 v$ view
는 instance startup시 populate되고 shutdown시 clear out된다.
x$ tables에 transaction 시간정보를 check할 것인가 즉, timing
information을 저장할 것인가는 initial parameter timed_statistics =
true 냐 false냐에 따라 달라진다. 물론 dynamic하게 alter system명
령을 통해 변화를 줄 수도 있다.
alter system set timed_statistics = true ;
alter system set timed_statistics = false ;
analyze table table_name compute statistics ;
pupulate column : dba_tables, dba_tab_columns, dba_indexes
analyze index index_name validate structure ;
pupulate column : index_stats, index_histograms
use these data dictionary
data distribution within Oracle block,
column values range and distribution,
index values range and distribution
jkspark@hanafos.com -2- 장 경상
3. Performance tuning http:// www.ggola.com
Server Manager Monitor based on v$view
MTS상의 CIRCUITS, DISPATCHERS, SHARED SERVER
공통의 FILE I/O, LATCH, LIBRARY CACHE, LOCK, PROCESS,
ROLLBACK, SESSION, SQL AREA, SYSTEM I/O, SYSTEM
STATISTICS, TABLE ACCESS, TABLESPACE
jkspark@hanafos.com -3- 장 경상
4. Performance tuning http:// www.ggola.com
Diagnosing Problems
Find out the problems
system statistics : v$sysstat로 instance start후의 총 누적 통계를 볼
수있다.
utlbstat.sql과 utlestat.sql script를 이용 report.txt를 분석하기.
troubleshooting the database : dynamic performance views를 활용
하기.
v$views & script
v$views
instance/database
v$backup, v$database, v$instance, v$option, v$parameter,
v$pq_sysstat, v$process, v$sesstat, v$waitstat
memory v$db_object_cache, v$librarycache, v$sysstat, v$sgastat
disk v$backup, v$datafile, v$filestat, v$log, v$log_history
user/session
v$lock, v$open_cursor, v$process, v$session, v$sesstat,
v$transaction
contention v$lock, v$rollname, v$rollstat, v$waitstat
script
running the script : <$ORACLE_HOME/rdbms/admin/...sql>
1. server manager
2. set timed_statistics = true
3. run utlbstat.sql
4. run utlestat.sql
5. confirm report.txt
utlbstat.sql
- sys schema tables and views creation
- object names contain the word 'begin', for example,
STATS$BEGIN_FILE
jkspark@hanafos.com -4- 장 경상
5. Performance tuning http:// www.ggola.com
- populate these objects with beginning database performance
statistics
utlestat.sql
- sys schema tables and views creation
- object names contain the word 'end', for example,
STATS$END_STATS
- populate these objects with ending database performance
statistics
- creates a set of tables that contains the difference between the
beginning statistics and the ending statistics, for example,
STATS$FILE
- create report.txt file (in your current directory)
report.txt
library cache statistics,
system statistics, shown per transaction and per logon
wait events
dbwr statistics
i/o statistics, per file and per tablespace
latch statistics
initialization parameters
dictionary cache statistics
the times that the beginning and ending scripts were run
latch contention
latches protect access to internal structures.
process needing access must get latch first.
next process must wait for first one to release latch. this is latch
contention.
report.txt - need ratio of at least 0.98 , or query v$latch
spin_counter parameter (alter all latches behavior)
a process waiting for a latch can sleep or spin or can keep
trying to get the latch.
the overhead of spinning is equal to the overhead of putting
the process to sleep 일때의 값이 spin_counter의 optimal value
이다.
system events (report.txt에서 보여주는 event information)
v$system_event : instance시작 후 particular event의 총 waits
v$session_event : 위 내용을 session 기준에서 check
v$session_wait : SID, SEQ#, EVENT, WAIT_TIME, P1TEXT,
P1, P1RAW, SECONDS_IN_WAIT, STATE
jkspark@hanafos.com -5- 장 경상
6. Performance tuning http:// www.ggola.com
Database Configuration
Architecture Review
Oracle7 Database의 기본 tablespace :
SYSTEM, TEMP, RBS, USERS, xxx_DATA, xxx_INDEX
Rollback Segment : store before image of changed data used for
rollback, recovery, read-consistency
configuring for safety :
두개이상의 control file 보존
online redo log의 mirroring
주기적인 backup
redo log files의 archive
control file backup
configuring for backups :
backup단위로 tablespace를 사용하기
필요하면 static data의 read-only tablespace 사용
keep volatile data in separate tablespaces
필요하면 divide data for partial backups
I/O Monitoring
To monitor which files are subject to most I/O in an existing
database :
1. v$filestat
2. file i/o monitor in Server Manager
3. file statistics in report.txt
system tablespace 의 heavy i/o :
1. shared pool 이 too small한 경우
2. data segment가 system tablespace에 write되는 경우
3. sort segment가 system tablespace를 사용하는 경우
striping tablespace for I/O improvement
(this is hardware dependent for example 'RAID')
query for redo log files information : v$log, v$logfiles
What is LGWR doing ?
1. 적어도 매 3초안에 변경된 사항을 writes to the redo log files
2. 모든 commit을 disk에 기록
3. log buffer의 1/3이상 차면 flush
jkspark@hanafos.com -6- 장 경상
7. Performance tuning http:// www.ggola.com
Tuning Application
Tune Anything
SQL Trace and TKPROF의 주대상 :
1. most resource를 사용하는 것
2. row당 most resource를 사용하는 것
3. 매우 빈번하게 실행되는것
tune the design :
program에 변경 없이 indexes추가나 access path의 변경을 통
한 향상, parallel query option등의 사용으로 tuning
tune the process : SQL 문장의 수정이나 Application Code의 변경
을 통한 tuning
Optimizer Mode : RULE, COST, CHOOSE
instance level에서 optimizer_mode = CHOOSE (default
value) .... FIRST_ROWS, ALL_ROWS
session level 에서
- alter sessioin set optimize_goal = 'value' (the same as for
optimize_mode)
statement level 에서 hints 사용하기
- select /*+ first_rows */ from dual ;
Trace Tool
Trace Tool step :
1. initialization parameter
max_dump_file_size = n (default 500)
user_dump_dest = directory
timed_statistics = true
2. switch on sql trace
parameter : sql_trace = true
session command : alter session set sql_trace = true ;
package : exec dbms_system.set_sql_trace(true) ; current
session
exec dbms_system.set_sql_trace_in_session ( session_id, serial_id,
true) ; another user's session available
3. run the application
application 실행
4. switch off sql trace
parameter : sql_trace = false
jkspark@hanafos.com -7- 장 경상
8. Performance tuning http:// www.ggola.com
session command : alter session set sql_trace = false ;
package : exec dbms_system.set_sql_trace(false) ; current
session
exec dbms_system.set_sql_trace_in_session ( session_id,
serial_id, false) ; another user's session available
5. format the trace file
tkprof tracefile(the name of the trace output file) outputfile
[sort=option] [print = n] [explain = username/password] [insert =
filename] [sys = NO] [record = filename] [table =
schema.tablename(default plan_table)]
ex) tkprof tracefile outputfile SYS=NO EXPLAIN = usr/pwd
- output file : the name of the formatted file
- sort= : the order in which to sort the statements
- print=n : print the first n statements
- explain=usr/pwd : run explain plan in the specified
username
- insert=filename : generate insert statements
- sys=no : ignore recursive sql stements run as user sys
- record=filename : record statements found in the trace file
- table=schema.tablename : put execution plan into specified
table (rather than the default PLAN_TABLE)
6. interpret the output
output file 해독하기 : Trace statistics 을 잘 이해해야 한다.
- count : parsed, executed 문장수 and fetch call 수
- cpu : processing time for each phase (초단위), statement가
shared pool에 있었던 경우는 0
- elapsed : 경과시간 (초단위) 이지만 다른 process와의 연관때
문에 매우 유용하지는 않다.
- disk : physical data block read
- query : logical buffers retrieved for consistent read (일반적인
select 문)
- current : logical buffers retrieved in current mode (일반적인
DML)
- rows : rows processed by the outer statement.(select는 fetch
phase, DML은 execute phase)
- query + current = total number of logical buffers accessed
Other output from TKPROF
- recursive SQL : Server측면의 statistics로 그다지 유용하지
않음 (sys=no option으로 제거가능)
- library cache misses : memory 에서 cache 되면 이 값은 리스
트되지 않는다.
- user : the ID of the last user to parse the statement
- execution plan : explain parameter사용시 보여주는
execution plan
- optimizer hint : 문장실행 중 사용된 optimizer hint
jkspark@hanafos.com -8- 장 경상
9. Performance tuning http:// www.ggola.com
Other tuning interests
SQL*Plus 상에서 explain plan
SQL> explain plan for select.... (문장)
PLAN_TABLE을 query함으로써 execution plan을 볼 수있다.
Module performance check :
DBMS_APPLICATION_INFO package setting 확인
(dbmsutil.sql로 생성됨. DB 생성시 catproc.sql에서 call됨)
실행 Procedure :
- set_module(module, action) : module start시 call
(48 char까지 v$sqlarea 저장)
- set_action(action) : transaction 시작 전, 후 call
(32 char까지 v$sqlarea 저장)
- set_client_info(client) : session에 대한 client information
(64 char까지 v$session 저장)
- read_module(module, action) : read last module
(위에서 정의한 module중)
- read_client_info(action) : read the last client information
Symptoms of inefficient sql statement
1. index를 사용하지 않는것
2. tree walk (CONNECT BY and START WITH clause)
and group function (include 'having')
3. distinct keyword
4. complex view
jkspark@hanafos.com -9- 장 경상
10. Performance tuning http:// www.ggola.com
Shared Pool
Basic Shared Pool
Shared Pool Factors
shard pool contents :
library cache (store shared sql and pl/sql)
dictionary cache (dictionary objects information)
(MTS 사용시 some user information 포함)
size : shard_pool_size = ??? (default 3,500,000 or under 3.5MB)
library cache : cache managing을 위해 LRU algorithm 사용
statement의 cache여부 판단 :
1.the statement를 ASCII text의 numeric value로 전환
2. 위 전환된 숫자에 hash function 사용
tuning goals
1. 가능한 parsing time 최소화
2. large object라도 pool내에서 가능한 한덩어리의 충분한 공간확
보
parsing time줄이기 :
가능한 많은 문장의 sharing
cache에서 aged out되는 문장들을 가능한 금지시키기
statement sharing 증가시키기 :
가능한 많은 generic code사용
constant보다는 bind variable 사용
bind variable에 동일한 이름 사용
Dynamic Views of The Library Cache
- V$SQLAREA : all shared cursor
- V$SQL
- V$SQLTEXT
- V$DB_OBJECT_CACHE : objects cached, including packages
- V$LIBRARYCACHE : statistics on library cache
- V$SGASTAT : Sizes of all SGA structure
Server Manger상에서 v$sqlarea, v$sqltext를 사용하여 현재 user가
실행중인 sql 문장을 찾을 수 있다.
jkspark@hanafos.com - 10 - 장 경상
11. Performance tuning http:// www.ggola.com
Cursor Shared : select gethitratio from v$librarycache where
namespace = 'SQL AREA' ; 의 결과값이 90% 이상이어야 한다.
Library Cache Reloads
문장 parsing시 이미 aged out된 문장인가를 판단하기 위해
v$librarycache의 reloads column 사용, 이 수치는 특히 pins의 수
치와 관련이 있다.
1. PINS : represent executions of an item in the library cache
2. RELOADS :
- Mean an object definition loaded for this cursor has been aged
out for lack of space
- Should ideally be 0
- never be more than 1% of the number in the PINS column
(이 수치가 1%보다 크다면 shared_pool_size를 늘려주어야 한
다)
3. Use UTLBSTAT/UTLESTAT output (report.txt)
Sizing the Library Cache
1. begin by very large SHARED_POOL_SIZE value
2. For stored object such as packages and views
SQL> SELECT SUM(sharable_mem) FROM v$db_objcet_cache;
3. For SQL statement
SQL> SELECT SUM(sharable_mem) FROM v$sqlarea
WHERE executions > 5;
4. allow about 250 bytes in the shared pool per user per open
cursor
SQL> SELECT SUM(250 * users_opening) FROM v$sqlarea;
5. Parameter Affecting the Library Cache
- SHARED_POOL_SIZE = ???
(the size of the shared pool, in bytes)
- CURSOR_SPACE_FOR_TIME = default FALSE
(TRUE면 shared SQL area are not aged out until cursor
referencing them is closed)
- SHARED_POOL_RESERVED_SIZE = ???
(reserved list for large objects. default 0)
- SHARED_POOL_RESERVED_MIN_ALLOC = ???
(default 5000. SHARED_POOL_RESERVED_SIZE 보다 작아
야 하고 bytes로 표현되는 reserved list를 사용하는 objects의 최
소 크기)
6. 관련 Package 사용법 :
SQL> exec dbms_shraed_pool.keep('package name') ;
jkspark@hanafos.com - 11 - 장 경상
12. Performance tuning http:// www.ggola.com
SQL> exec dbms_shraed_pool.unkeep('package name') ;
(Object kept여부판단은 v$db_object_cache의 'KEPT' 컬럼을
확인한다.
Dictionary Cache
hold definitions of dictionary objects in memory
Monitoring Dictionary Cache :
v$rowcache에서 parameters, gets, getmisses 확인
If the report.txt output indicates a high GET_MISS/GET_REQ
ratio for a number of items, this indicates the
SHARED_POOL_SIZE should be increased.
The ratio of all GETMISSES to all GETS should be less than 15%,
during normal running. if higher, consider increasing
SHARED_POOL_SIZE.
MTS면 : user session information is stored in the shared pool
instead of user memory.
User Global Area(UGA) increase SHARED_POOL_SIZE
User 관련메모리 parameter :
SESSION_CACHED_CURSORS = integer
CLOSE_CACHED_OPEN_CURSORS = Boolean (default
FALSE)
jkspark@hanafos.com - 12 - 장 경상
13. Performance tuning http:// www.ggola.com
Tuning the buffer cache
Buffer Cache
SGA의 일부분, 모든 User의 공유 메모리이고 data block이 copy된
다. Size는 db_block_buffers 와 db_block_size로 결정된다.
Cache내 개개의 버퍼는 a single database block과 대응한다.
Buffer Cache Tuning 목표(OLTP system) :
대부분의 users들은 원하는 데이타를 memory에서 얻는다.
Server Processes가 disk에서 data를 가져오는 일은 가급적 없
도록 한다.
Latch and Cache
LRU Latch Contention :
여러 cpu를 가진 smp장비에서 performance 방해
buffer cache에서 buffer 교환 control
Oracle은 자동으로 CPU system의 반으로 LRU latches 수를 set
단일 cpu system에서는 하나의 LRU latch로 충분하다.
Cache hit ratio : users가 cache에서 data를 요구할 때 성공율로
일반적인 시스템에선 적어도 80% 이상이어야 한다.
Unix 시스템에서 raw device 사용시에는 적어도 90% 이상 되어야
한다.
Cache Hit Ratio 80%이상으로 :
1. V$SYSSTAT의 name = db block gets, consistent gets, physical
reads
- db block gets : access to current copies of blocks
- consistent gets : access to read-consistent block copies
- physical reads : number of blocks read from disk
Server Manager, V$SYSSTAT, report.txt
2. Hit ratio가 80%가 안된다면 buffer추가의 효과를 테스트 하기
위해 늘리고자 하는 buffer수를
DB_BOLCK_LRU_EXTENDED_STATISTICS = 200 지정하여
DB Restart (정보확인 : X$KCBRBH)
3. Hit ratio가 높아서 cache size를 줄이고 싶다면
DB_BLOCK_LRU_STATISTICS = TRUE 를 지정하여 DB
Restart (정보확인 : X$KCBCBH)
4. V$LATCH, V$SYSSTAT > 1% 즉, LRU latch contention 발생시
DB_BLOCK_LRU_LATCHES = value를 조절할 수 있다.
jkspark@hanafos.com - 13 - 장 경상
14. Performance tuning http:// www.ggola.com
(default는 CPU 개수 / 2 이고 최대 CPU갯수 * 2 까지 가능하
다) 이 값은 CPU개수, buffer cache size, current 작업량에 따른
다.
5. V$CACHE : 어떤 block이 현재 cache 상태인가를 확인할 필요
가 있다면 script catparr.sql to generate the V$CACHE view.
(in OPS 환경)
full table scan시 default로 data가 cache되지 않는 것을 방지 하려
면:
- cache hint를 주거나 cache
- hint를 사용하여 table을 생성해야 한다.
관련 parameter : cache_size_threshold 를 정하면 각 table에 cache
되는 blocks limit을 정할수 있다.
(예를 들어 cache_size_threshold = 5 로 지정하면 10 block필요시 처
음 5block만 cache 된다)
SGA가 너무 크다면 O/S는 paging 과 swapping이 늘어나므로
performance가 많이 떨어질 것이고 너무 작다면 일반적인 error는
발생확률이 현저히 떨어지겠지만 application이 많이 늘어질 것이
다.
jkspark@hanafos.com - 14 - 장 경상
15. Performance tuning http:// www.ggola.com
Using Oracle Blocks Efficiently
Block ?
Tuning Goals and Block
tuning 목적중 하나는 data block accesses를 최소화하는데 있다.
- 적절한 block size 결정
- block space사용을 최적화 하기위한 PCTFREE, PCTUSED설정
- row migration 감지 및 해결
- freelists contention 감지 및 해결
Oracle Space
- blocks, extents, segments, files, tablespace, database
- blocks parameter : pctfree, pctused, initrans, maxtrans
(structure : |header| pctfree d | a t | a pctused | )
- stograge parameter : initial, next, maxextents, minextents,
pctincrease, freelists, freelists group
To minimize the number of block visit
- Tuning SQL statement
- Using a larger block size
- Packing rows as closely as possible into blocks
- Preventing row migration
DB Block Size
Block Size Concept :
- database creation시 결정해야 하며
- 일반적으로 default는 2K 내지 4K로 정해진다.
- 따라서 DB block size는 변경이 불가하고
- 변경을 하려면 export후 database recreation and import 해야한
다.
- size 결정은 O/S에 따라 32K까지 확장이 가능하며
- 가능한 O/S수준에서 maximum으로 정함으로써 Parallel Query
Option이나 index read performance를 향상시키는데 도움을 주
도록 한다.
Monitoring Blocks
Monitoring blocks using 'ANALYLAZE' command
- num_rows : table내 row수
- blocks : HWM 이하의 block 수
- empty_blocks : HWM 위의 block 수
- avg_space : bytes로 계산된 average space blocks
- chain_cnt : table내 chained or migrated rows수
jkspark@hanafos.com - 15 - 장 경상
16. Performance tuning http:// www.ggola.com
HWM represents the limit of the blocks which have been used
within a segment
- header block에 기록된다
- table or cluster 생성시 set to the beginning of the segment
- row insert되면서 한번에 5block씩 증가한다
- truncate command로 HWM reset
- table level에서 : alter table <table name> deallocate unused
Using the high water mark
- in a full table scan, oracle 7 reads in blocks below the high
water mark
- empty blocks above high-water mark may waste space
- under-used blocks below the high-water mark degrade
performance
To find the number of blocks containing rows
SQL> SELECT count(distinct substr(rowid,15,4) ||
substr(rowid,1,8)) FROM owner_name.table_name;
HWM 이하의 빈 block을 구하기 위해
"1 - (hwm 이하 block수 / row가 포함하는 block 수)"
cf) dbms_space package (unused_space, free_blocks)
chained rows : 단일 block에 저장할 수 없는 대용량의 rows
row chaining은 불가할 수 있으나 migration은 pctfree값의 넉넉
한 setting으로 막을 수 있다.
PCTFREE = 100 * (평균 Update량 / (평균 Update량 + 평균 row
길이))
Analyze command로 migration감지 :
analyze table table_name list chained rows into table_name
(utlchain.sql - creation chained_rows table)
Monitoring and Rebuild Index :
- Analyze index index_name validate structure ;
index_stats view
select (del_lf_rows_len / lf_rows_len) * 100
from index_stats ;
(you may decide to rebuild if deleted entries represent 20% or
more of current entries)
- Alter index index_name rebuild ;
cf) full table scan의 performance는 depend on :
db_file_multiblock_read_count parameter 와 extent size
Managing Freelists : New blocks go to the head of the freelist when
server processes
- Delete rows so that space used falls below PCTUSED
- When the high water mark has changed
jkspark@hanafos.com - 16 - 장 경상
17. Performance tuning http:// www.ggola.com
Although V$WAITSTAT tells you if there have been waits for
freelists, it does not tell you which table these relate to. (same
table에 대해 insert, delete가 매우 많이 발생한다면 table을 다시
만들어 freelists를 늘려줄 필요가 있다. 왜냐하면 alter command
로는 freelists를 늘릴수 없기 때문이다.)
SQL> SELECT CLASS, COUNT, TIME FROM v$waitstat
WHERE CLASS='FREE LIST' ;
jkspark@hanafos.com - 17 - 장 경상
18. Performance tuning http:// www.ggola.com
Tuning Rollback Segment
Rollback Segment
rollback segment :
used to keep undo information for transaction
used for rollback, recovery, read-consistency
rollback segment tuning
Tuning Goals
- Transactions should never wait for access to rollback segments.
(This depends on having enough rollback segments.(개수))
- Rollback segments should not extend during normal running.
(This depends on the number of extents per segment. (size 조정 :
optimal))
- No transaction, however large or exceptional, should ever run
out of rollback space.
(This means that rollback segments should be sized correctly.)
- Readers can always see the read-consistent images they need.
(This depends on both number and size of rollback segments.)
You need enough rollback segments to prevent transactions
contending for the transaction table.
(Query do not need transaction table access)
Diagnosing Waits
- Any non-zero value in the undo header rows of V$WAITSTAT
indicates contention for rollback segment header blocks.
( SQL> select count, time from v$waitstat where class='undo
header'; )
CLASS COUNT TIME
------------------ ---------- ----------
undo header 44110 4558368
- You can see this also in the WAITS column of V$ROLLSTAT, or
in the HEADER WAITS column of the Server Manager Rollback
Monitor screen.
- report.txt, produced by utlbstat/utlestat, also has a section on
undo statistics.
- Look also in V$SYSTEM_EVENT for the 'undo segment tx slot'
event, which shows waits for transaction slots.
Rollback Segments 수 와 configuration recommendations
- OLTP : 대략 10 users당 1개의 rollback segment
- BATCH : 개개의 concurrent job 당 1개의 rollback segment
Sizing Rollback Segments :
- Set INITIAL value 를 2의 배수로 (2, 4, 8, … 256, 512…등 )
- Set NEXT to the same value as INITIAL
jkspark@hanafos.com - 18 - 장 경상
19. Performance tuning http:// www.ggola.com
- Make all rollback segments the same size
- Set MINEXTENTS to 2
- Set OPTIMAL to make sure that rollback segments do not
shrink below 20 extents. :
( Manual : alter rollback segment rbs_name shrink ; )
V$SYSTEM_EVENT shows waits for 'undo segments extension'.
this includes waits for shrinks.
How Much Rollback?
- Deletes are expensive. TRUNCATE
- Inserts use minimal rollback space; only the ROWID is kept.
- Updates : depends on the number of columns
- updates on indexed columns : old data value, old index value,
new index value
- You can use the V$TRANSACTION view to find out how much
redo is generated by a transaction and whose transaction it is ;
Allocating Rollback Segments
- SET TRANSACTION USE ROLLBACK SEGMENT rbs이름;
문제해결
- Transactions fails for lack of rollback space. bigger rollback
segments
- Snapshot too old error may occur because the rollback image
has been overwritten.
특별한 경우 no other transaction active상태에서 이런 error가
나오는 경우는
. Recursive SQL has overwritten the data
. Lock information has been overwritten
일 때가 있다.
jkspark@hanafos.com - 19 - 장 경상
20. Performance tuning http:// www.ggola.com
Tuning Redo Mechanisms
Redo Mechanisms
redo log : files, groups, members
LGWR는 거의 연속적으로 write작업을 하기 때문에 동일 그룹에
속하는 redo log files은 물리적으로 분리된 disk에 나누도록 한다.
즉, 동일 group내 member들은 서로 다른 disk에 위치시킨다.
Avoiding checkpoint waits
- use large redo log files, to cut down the number of checkpoints
- use more redo log groups, to increase the time before LGWR
needs to overwrite
관련 parameter :
parameter setting
- checkpoint_process : CKPT Process를 사용할 것인가 결정
(TRUE / FALSE)
- log_checkpoint_interval : checkpoint를 발생시키기 위한 O/S
blocks 설정
- log_checkpoint_timeout : checkpoint를 발생시키기 위한 시간
term setting (default 0 : no impact)
- log_checkpoints_to_alert : TRUE 설정시 checkpoint의 시작과 끝
을 alert.log에 기록
v$system_event 'log file space/switch' event확인 : log file I/O
contention을 보여준다. (waits가 있다면 buffer가 작다는 것을 말하
는 것이다)
reducing redo ( back up the tablespace after the below command
has completed)
- SQL*Loader사용시 direct path loading without archiving or in
unrecoverable mode (redo가 generation되지 않는다)
- Parallel query option 사용시 unrecoverable mode로 object를
creation하라.
Redo log buffer latches : single-CPU machine은 one latch, multi
CPU machine은 multiple latches
Redo Latch contention : v$latch 확인, svrmgrl monitor screen,
utlbstat/utlestat 확인
latch request type
- willing to wait : the process waits for the latch (redo allocation
latch)
jkspark@hanafos.com - 20 - 장 경상
21. Performance tuning http:// www.ggola.com
- immediate : the process continues its work without waiting
(redo copy latch)
Columns in the V$LATCH view
- If the ratio of MISSES to GETS is more than 1% for the redo
allocation latch, you should try to reduce contention for it.
(select addr, (misses/gets) * 100 from v$latch where gets <> 0 ; )
LOG_SMALL_ENTRY_MAX_SIZE 줄임.
- If the ratio of IMMEDIAE_MISSES to the sum of
IMMEDIATE_GETS and IMMEDIATE_MISSES is more than 1%
for redo copy latches, you may need more.
(select addr, (immediate_misses/(immediate_gets +
immediate_misses)) * 100 from v$latch where immediate_gets <>
0 ;)
LOG_SIMULTANEOUS_COPIES 값을 증가시킴 (default CPU
수, 최대 CPU수의 두배까지)
jkspark@hanafos.com - 21 - 장 경상
22. Performance tuning http:// www.ggola.com
Monitoring and Detecting lock contention
High Level Data Concurrency
Oracle은 많은 사용자들이 동시에 동일한 data를 안전하게 access할
수 있도록 설계되어 있다. 즉, high level의 data concurrency를 위해
만들어진 Product 이다.
Data Consistency
DML은 row level lock이고 select는 특별히 lock을 지정하지 않는
한 lock이 잡히지 않는다.
Oracle은 다양한 level의 data consistency를 제공한다. 즉, 사용자가
data에 access할 때 다른 사용자가 그것을 변경시킨다 하더라도 일
관되게 access해야 한다
Transaction은 commit 이나 rollback을 만날 때 까지 lock을 잡는다.
Row lock은 table lock으로 확대되지 않는다. 대개의 경우 Oracle
lock은 효과적으로 잘 운용되는데 다음과 같은 경우에 종종 문제가
발생한다.
- 개발자들이 불필요한 high locking level을 code하거나 불필요한
long transaction code한 경우
- 사용자들이 제때에 commit을 하지않은 경우
- Oracle제품이 아닌 다른 product 가 higher locking level을 발생
시키는 경우
DML Locks
- transaction은 table에 shared lock을 얻는다.
- transaction은 변경작업을 할 때 해당 row에 exclusive lock을 얻
는다.
Mechanism
Oracle lock enqueue mechanism
- users who are waiting
- the lock mode they want
- the order in which users requested the lock
DML lock은 row exclusive lock, RX
Table lock 은 TM, row lock TX, in the Mode columns both shows as
SX
Busy system에서 lock 수를 늘리기 위해
- DML_LOCKS 또는 ENQUEUE_RESOURCE parameter를 높인
다.
jkspark@hanafos.com - 22 - 장 경상
23. Performance tuning http:// www.ggola.com
DDL Locks
- exclusive DDL locks : create, alter, drop등 해당 object에
exclusive lock을 잡는다. 단, 해당 table에 대해 어떤 level의 lock
이라도 존재하면 이 lock을 얻을 수 없다.
- shared DDL locks : grant, create package
- breakable parse locks : statement or PL/SQL object. (It will
never cause waits or contention.)
Other Locks
- row share : RS select …. for update ;
- share : S prevent any DML on table
if there is no index on the foreign key column in the child table
any delete on the parent table holds a share lock on the child any
update on referenced columns in the parent holds a share lock on
the child (FK index가 없으면 parent delete 나 update시 child에
lock을 얻는다)
- share row exclusive : SRX delete시 a foreign key constraint
includes on delete cascade (child table의 foreign key column에
index를 만들어서 해결한다)
Explicit Locks UL
- Lock table table_name in mode_name MODE ;
(mode : ROW SHARE, ROW EXCLUSIVE, SHARE, SHARE
ROW EXCLUSIVE), EXCLUSIVE)
cf) dbms_lock package
Monitoring
Lock Monitor
- Server Manager Monitor
- run catblock.sql by user sys and utllockt.sql script
- v$lock (관련 views : dba_locks, dba_ddl_locks, dba_dml_locks,
dba_blockers, dba_waiters)
Dealing with contention
- 어떤 사용자가 lock을 풀지않고 있다면 해당 user를 찾아
commit 또는 rollback을 요구하거나 마지막 방법으로 oracle
session을 끊는다.
- session의 lock contention 정보 : row_wait_block#,
row_wait_row#, row_wait_file#, row_wait_obj#
A deadlock can arise when two or more users wait for data locked
by each other.
- If a deadlock arises, a trace file is dumped in
USER_DUMP_DEST.
- Oracle7 resolves deadlocks at statement level (transaction level
에서는 resolve할 수 없다.)
Data consistency
- statement level read consistency
jkspark@hanafos.com - 23 - 장 경상
24. Performance tuning http:// www.ggola.com
Oracle은 스스로 문장 수준에서의 read consistency를 해결한다.
query의 SCN이 마지막 변경된 SCN보다 오래된 것이면 rollback
segment를 활용하여 read consistency를 해결하고 만일 rollback
segment에 data가 없으면 'snapshot too old' error를 발생시킨다.
- transaction level read consistency : read-only transaction을 사
용하는 경우 SQL> Set transaction read only ;
- serialIzable transactions : can contain DML
SQL> SET TRANSACTION isolation_level = SERIALIZABLE ;
SQL> ALTER SESSION SET isolation_level = SERIALIZABLE ;
jkspark@hanafos.com - 24 - 장 경상
25. Performance tuning http:// www.ggola.com
Tuning for Differing Application Requirements
OLTP and others
OLTP
은행이나 항공사 예약시스템 같은 OLTP 즉, high-throughput의
insert/update 집약 시스템은 대개 대량의 data를 처리하고 지속적
으로 늘어나며 수백이상의 동시사용자의 접급이 필요하므로 그
tuning의 목적은 :
availability, speed, concurrency, recoverability 가 중시된다.
OLTP 와 SPACE 관리
- dynamic space allocation 피하기
OLTP에서 dynamic space allocation은 performance load가 있
다. 즉, allocate space explicitly
table 증가량을 check 확인하여 규칙적인 일정 pattern에 따른
extents creation plan을 설정, 시행
- indexing : OLTP 에서 data retrieval에 가장 중요하며 주기적으로
rebuild를 해줄 필요가 있다.
- hash clusters : equal query를 speed up할 수는 있으나 많은
insert작업이나 large column을 사용하는 update작업에는 피해야
한다.
- rollback segments : OLTP에서 rollback segments의 minextents
추천은 적어도 20이다.
OLTP application issue
- constraints are always most efficient.
- code shared
- 가능한 bind variable 사용
DSS (decision support system)
- full table scan을 많다. 따라서 speed와 availability가 tuning의 주
요목표다.
- 특히 parallel query option이 주요하다.
- large rollback segment 와 low pctfree가 이상적인 system
uniformly distributed data에 대한 optimizer의 선택은 통계치를 적
절히 활용함으로써 해결될 수 있으나 not uniformly distributed
data에 대해선 query의 선택성을 적절하게 산출할 수가 없다.
이때 사용되는 것이 histogram 이다. analyze command를 사용해
where절에 자주사용되는 columns이나 highly-skewd data
distribution 인 columns histogram을 만들 수 있다.
jkspark@hanafos.com - 25 - 장 경상
26. Performance tuning http:// www.ggola.com
Analyze table table_name compute statistics for columns
column_name size 10 ;
확인 : user_histograms, all_histograms, dba_histograms
Bitmap Indexes : 7.3.3 이상에서 사용. ( create bitmap index
index_name on table ( column ) ; )
- low cardinality columns
- Use minimal storage space
- Good for multiple predicates (where절 조건이 복잡)
- Best for read-only systems
- very large tables
DSS : full scan이 많다.
- Data tightly packed into large blocks
- Careful tuning of queries SQL 문 자체 튜닝
- Less concern about parse time
- Well configured parallel query support (table striping 되면 좋다)
- histogram을 사용한다면 bind variable의 사용은 오히려
histogram사용의 이점을 잃는다.
Client-Server load check : using view V$SYSSTAT
- to client (via SQL*Net)
- from client (via SQL*Net)
- round trips from client (via SQL*Net)
- ex) SQL> select name, value from v$sysstat where statistic#
between 133 and 135 ;
NAME VALUE
---------------------------------------------------------------------
bytes sent via SQL*Net to client 1.0049E+12
bytes received via SQL*Net from client 1.4172E+10
SQL*Net roundtrips to/from client 186860209
reconfiguring for varying needs
- OLTP는 보다 많은 indexes를 요구한다.
- DSS는 read-consistency를 위해 보다 큰 rollback segment를 요구
한다.
- OPTP는 parallel query를 사용하지 않지만 DSS는 요구한다.
- OLTP에서 빈번한 update requirement는 DSS의 최적화 상태보
다 더 낮은 PCTFREE를 의미한다.
jkspark@hanafos.com - 26 - 장 경상
27. Performance tuning http:// www.ggola.com
Tuning Sorts
Sort
When, Where, Do and Avoiding
sort tuning의 목표 : 가능한 memory sort, 가급적 disk temporary
segment사용을 피하고 사용시 가능한 빠르게 한다.
언제 sort가 일어나는가 :
- create index
- order by 나 group by 사용시
- distinct keyword 사용시
- union, intersect, minus operaton 사용시 (duplicates 제거를 위해)
Avoiding Sorts
- Use the NOSORT argument when creating indexes for pre sorted
data.(REBUILD option) 이 경우 index를 생성하고자 하는 data
가 미리 sort되어 있어야 한다.
- Use index access for table joins.
- Use UNION ALL instead of UNION
Sorting in memory : parameter SORT_AREA_SIZE보다 더 작은 영
역에서 memory sort 진행
- data is split into separate sort runs.
- server process writes to temporary segments on disk
- segments hold data while the server works on another sort run.
- The Sort space is part of the user's memory area (PGA에 잡힘.
SGA아님)
Has no impact on the SGA except with MTS.
with MTS, becomes part of the UGA in the shared pool
When the sort has finished work but its memory area still contains
sorted rows, this area can shrink to the size specified by the
SORT_AREA_RETAINED_SIZE parameter.
- SORT_AREA_SIZE 와 SORT_AREA_RETAINED_SIZE는 동일한
크기로 하는 것이 좋다. 만일, MTS를 사용하거나 memory가 매우
부족한 경우가 아니라면 말이다.
Tablespace
Temporary tablespace
- create tablespace tablespace_name temporary ; 로 생성한다.
- permanent objects를 가질수 없다.
- tablespace에 permanent objects가 없다면 alter tablespace
..name.. temporary ;로 바꿀 수 있다.
- permanent objects를 가질수 없다.
jkspark@hanafos.com - 27 - 장 경상
28. Performance tuning http:// www.ggola.com
- contains a single sort segment used by the entire instance
- The sort segment는 최초 이 tablespace를 사용하는 첫번째 sort
작업에 의해 생성된다.
sort 를 원하는 demand에 따라 커진다.
역시 extent로 구성되며 각각의 extents는 서로 다른 sort
operation에 사용될 수 있다.
SGA내에 SEP(sort extent pool)로 불린다.
CREATE USER or ALTER USER 명령어로 user에게 temporary
tablespace를 지정해준다.
- sort segments have unlimited extents
- monitor sort segments : V$SORT_SEGMENT
- Recommended configuration (default storage parameter apply
to sort segments)
Choose INITIAL and NEXT value as multiples of
SORT_AREA_SIZE.
Set PCTINCREASE to 0
Bypassing the Buffer Cache :
- Write sort runs directly to disk : SORT_DIRECT_WRITES
=TRUE (default AUTO, 금지는 FALSE) 일반적인 DSS에서는 TRUE
나 AUTO를 사용한다.
- large sort에 유리하고 parallel query speed를 높여준다.
- temporary tablespace를 stripe 하는 것이 특히 중요하다.
- Each sort uses its own memory buffers.(not use the buffer cache)
- Sort writes an entire buffer for each I/O operation.
SORT_WRITE_BUFFERS = between 2 and 8
SORT_WRITE_BUFFER_SIZE = ranges of 32kb and 64kb
- The amount you give to direct write buffers should be less than
one-tenth of SORT_AREA_SIZE.
그 밖에 : sort_read_fac, sort_spacemap_size
- sort_read_fac : (average seek time + average latency + block
transfer time) / block transfer time
- sort_spacemap_size : ( total sort bytes / sort_area_size ) + 64
Monitoring
Monitoring Sorts : V$SYSSTAT, Server Manager, report.txt
- sort (disk) : number of sorts writing to temporary tablespace
- sort (memory) : number of sorts done in memory
- sort (rows) : total rows sorted in the period being monitored.
Unless you are managing a DSS, you should aim to have 95% of
sorts in memory. 즉, OLTP 시스템에선 95% 이상의 memory sort
를 이루도록 해야한다. (disk sort/memory sort < 5%)
jkspark@hanafos.com - 28 - 장 경상
29. Performance tuning http:// www.ggola.com
Optimizing for load
MTS and Networking
MTS
It does not speed up performance, but allows a much greater
number of concurrent users to connect to the database.
- MTS 는 CPU overhead를 감수해야 하므로 운영시스템의 CPU
resource에 문제가 있다면 사용금지
- database-intensive work에 MTS 이점이 없다.
- heavy or batch users should have dedicated servers.
- cnfiguring the Multi-Thread Server
listener.ora : the listener address and the instances it can
connect to
tnsnames.ora : aliases for each instance, specifying usable
connections
- dedicated server가 갖는 overhead를 줄이고, 동시 접속 사용자를
늘릴수 있으며 process slots이나 semaphores같은 resource를 공유
할 수 있다.
Monitoring Dispatcher : a single dispatcher에 최대 접속 가능 users
숫자는 v$mts view의 maximum_connections를 본다.
You identify connection for dispatchers by checking
- Busy rates for existing dispatchers (v$dispatcher)
- Dispatcher waiting time (v$queue)
- users wait for dispatchers
SQL> select decode(sum(total), 0, 'no response',
sum(wait)/sum(totalq) "average wait time"
from v$queue q, v$dispatcher d
where q.type = 'DISPATCHER' and q.paddr = d.paddr ;
- add or remove dispatchers, user the command
SQL> alter system set mts_dispatchers = 'protocol, number' ;
Monitoring Shared servers
- Oracle start up shared server dynamically. MTS_SERVERS
parameter setting하면 shared server가 idle 하더라도 oracle은 이
수만큼의 server는 kill하지 않는다.
- you can remove shared servers by using the following command
SQL> alter system set mts_servers = number ; (대략 100명당
1개의 shared server를 추산한다.)
problem 감지시 process를 확인할 필요가 있다.
- You can query current dispatcher and server use with the
V$CIRCUIT view or server manager monitor.
- check columns : server name, dispatcher name, user session id,
user serial number
jkspark@hanafos.com - 29 - 장 경상
30. Performance tuning http:// www.ggola.com
MTS를 사용하면 shared pool에 some user information이 저장되고
UGA 영역을 shared server가 sort작업에 사용하므로 shared pool의
memory가 더 필요하겠지만, user process의 memory 요구량은 줄
어들게 된다. 또한 UGA를 sort에 사용하는 만큼 parameter
SORT_AREA_RETAINED_SIZE의 크기는 SORT_AREA_SIZE보다
작게 함으로써 가능한 빨리 다른 사용자들을 위해 memory를
release시킬 수 있도록 한다.
SQL*NET
SQL*NET Issues
- IPC Protocol을 사용하라.
If all Oracle7 work is on the same machine you should normally
choose IPC as the protocol for MTS work.)
- Checking the Shared Connection
If the SID in the CONNECT_DATA clause and MTS_SERVICE is
the actual SID for the instance then if the Oracle7 Server cannot
give you a shared server connection, it gives you a dedicated one
instead. (MTS connection실패시 또는 강제로 특정 client에서
tnsnames.ora에 정의된 dedicated server로 연결가능)
- listener.ora file의 TRACE_LEVEL_LISTENER parameter를 이용
하여 tracing할 수 있다. valid values는 "OFF, USER, ADMIN" 이다.
MTS parameter 예 :
- mts_service=HANFIS1
- mts_dispatchers="tcp,25"
- mts_max_dispatchers=200
- mts_servers=50
- mts_max_servers=200
- mts_listener_address= "(ADDRESS=(PROTOCOL=tcp)
(HOST=selsp2g)(PORT=1521))"
jkspark@hanafos.com - 30 - 장 경상
31. Performance tuning http:// www.ggola.com
Sample Testing
Performance and Tuning Test
1. tuning 의 기대효과가 가장높은 것은 ? design
2. normal 상태에서 cache hit ratio 는 ? 80%이상
(raw device 이면 90%이상)
3. users, throughput, tablespace, i/o 등에 대한 성능 통계치를 보여주는 tool 은 ?
oracle performance manager
4. resource wait 상태를 확인하는 view 는 ? v$system_event, v$session_wait, v$session_event
5. latch hit ratio 를 구하기 위한 value 는 ? gets and misses
6. latch contention 발생 가능성을 추측하기 위한 값은? hit ratio > 0.98
7. database 에서 많은 file i/o 감시기 위한 view 는 ? v$filestat
8. system tablespace datafile 의 많은 i/o 의 원인은 ?
shard pool too small, sort segment 나 data segment 가 system tablespace 에 생성되고 있다.
9. LGWR 발생시점은 ? commit occurs, redo log buffer 의 1/3 이상 찾을 때, time-out 발생시,
DBWR 의 checkpoint 발생으로 db buffer cache 를 clean 한 경우
10. TKPROF 에서 recursive sql 을 ignore 하기 위한 option 은 ? sys=no
11. trace tool step ? :
set initialization parameter switch on sql trace run the application
switch off sql trace format the trace file interpret the output
12. set module(module, action) module and action 은 어디에 저장되나 ? v$sqlarea 에 저장
( set_client_info(client)에서 client 는 v$session 에 저장된다)
13. 현재 실행중인 user 의 sql statement 를 보기위한 view 는 ? v$sqlarea, v$sqltext
14. gethitratio query statement 와 정상수치는 ?
select gethitratio from v$librarycache where namespace='SQL AREA' ;
(정상수치는 90%이상이다)
15. report.txt 의 reloads 가 얼마 이상일 때 shared_pool_size 를 늘려야 하나 ? 1%
16. package, view 등을 query 하기 위한 view ? v$db_object_cache
17. package 같은 large object 를 저장하기 위한 예약공간 지정 parameter 는 ?
shared_pool_reserved_size
18. buffer size 를 늘리기 위한 방법은 ?
x$kcbrbh 를 query 하고 db_block_lru_extended_statistics=200 setting 후 서버 restart
19. block visit 최소화 전략은 ?
using a larger block size, packing rows as closely as possible into blocks,
preventing rows migration, tuning sql statement
20. 다음 문장의 의미는 ?
select count(distinct substr(rowed, 15, 4) || substr(rowed, 1, 8)) from schema.table ;
to find the number of blocks containing rows
21. pctfree 산출 공식은 ? 100 * (평균 update 량 / (평균 update 량 + 평균 row length))
22. rollback segment 생성시 initial value 설정 rule 은 ? 2 의 배수로 설정한다.
23. rollback segment 생성시 next value 설정은 ? initial value 와 똑같이 설정한다.
24. checkpoint waiting 을 피하기 위한 방법은 ?
use large redo log files, user more redo log groups
25. LGWR 은 group 이 다차면 checkpoint 를 수행한다. 이것이 의미하는 바는 ?
LGWR flushes the log buffer to disk
jkspark@hanafos.com - 31 - 장 경상
32. Performance tuning http:// www.ggola.com
DBWR write all dirty blocks to the data files.
either LGWR or CKPT update the data file header (SCN 정리)
26. DDL lock 의 종류는 ? exclusive ddl locks, shared ddl locks, breakable parse locks
27. lock contention 을 조사하기 위해 v$session 에 볼 수 있는 column 은 ?
row_wait_block#, row_wait_row#, row_wait_file#, row_wait_obj#
28. dead lock 이 발생되면 ? oracle 은 user_dump_dest 에 trace file 을 남긴다.
29. OLTP tuning 의 목적은 ? availability, speed, concurrency, recoverability
30. disk sorts / memory sorts 가 정상적이라 판단할 수 있는 값은 ? < 5%
31. MTS parameter 중 'protocol, number of dispatcher'를 갖는 parameter 는 ?
MTS_DISPATCHER
32. report.txt 에서 undo statistics section 의 trans_tbl_waits 의 의미는 ?
implies you should add rollback segment.
33. what view to find total rows sorted ? v$sysstat
34. what view to find current dispatcher & shared server usage ? v$circuit
35. 어느 cache 가 사용중인가를 확인하기위해 v$cache 를 사용할 수 있는곳은 ? OPS 환경
36. FILE I/O tuning 을 위해 사용하는 것들은 ? v$filestat, report.txt, performance manager
37. 인접 free space 를 coalescing 해주는 오라클 툴은 ? oracle tablespace manager
38. striping by hand 사용 효과는 ? parallel query option and full table scan
39. immediate miss / immediate gets 의 값이 1%보다 클 때 조치방법은 ?
log_simultaneous_copies 값 증가(default CPU 수 최대 CPU * 2)
40. full table scan 의 performance 는 ?
depend on : db_file_multiblock_read_count parameter 와 extent size
41. reloads (v$librarycache) ?
mean that an object definition loaded for this cursor has been aged out for lack of space.
42. (large pl/sql object 를 위해 사용되는)shared_pool_reserved_size 의 최대값은 ?
half of shared_pool_size
43. select sum(250*user_opening) from v$sqlarea ?
shared pool size 계산시 shared pool per user per open cursor
44. reloads/pins=115 가 의미하는 바는 ?
pins 에 따른 reloads 가 1%를 넘으면 shared_pool_size 를 늘려준다.
45. what is latch contention ? next process must wait for first one to release latch.
46. client/server system 에서 주요 tuning point ?
minimize messages between data and application
47. static data, just read data 에 대한 pctfree value ? 0
48. redo log space 조회하는 view ? v$sysstat
49. MTS monitoring 시 유용한 event ?
busy rates for existing dispatchers(v$dispatcher), dispatcher wait times(v$queue)
50. what is determining the amount of rollback used for updates ? number of columns affected
51. row chaining 을 피할 수 없다면 migration 은 어떻게 막을 수 있는가?
pctfree 를 높게 함으로써 상당 부분의 migration 을 예방할 수 있다.
52. immediate_gets and immediate_misses 정보는 ? v$latch 에서
53. busy system 에서 lock 성능향상 위한 parameter ? dml_locks, enqueue_resources
54. buffer cache hit ratio 를 계산하는데 필요한 factor 들은 ?
db block gets, consistent-gets, physical reads
55. log file 의 I/O contention 을 확인하기 위해선 ?
view v$system_event 의 'log file space/switch' event 확인
56. CURSOR_SPACE_FOR_TIME = TRUE 로 setting 하면 ?
shared SQL area are not aged out until cursor referencing them is closed.
57. full table scan 의 performance 높이기 위해 ?
jkspark@hanafos.com - 32 - 장 경상
33. Performance tuning http:// www.ggola.com
db_file_multiblock_read_count parameter and extent size
58. buffer cache contention 확인 ? v$system_event 에서 buffer_busy_waits 확인
59. sql*net message 를 보는 view 는 ? v$sysstat
60. sort segment 의 최대 max extents 는 ? unlimited
jkspark@hanafos.com - 33 - 장 경상