tuning database itb

45
IF-ITB/TW/22 Dec'03 IF3211 – Database Tuning Page 1 Database Tuning Tricya Widagdo Departemen Teknik Informatika Institut Teknologi Bandung

Upload: yosep-haryanto

Post on 21-Jul-2016

47 views

Category:

Documents


4 download

DESCRIPTION

Tuning Database

TRANSCRIPT

Page 1: Tuning Database Itb

IF-ITB/TW/22 Dec'03IF3211 – Database Tuning

Page 1

Database Tuning

Tricya WidagdoDepartemen Teknik Informatika

Institut Teknologi Bandung

Page 2: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 2

Performance• The measure of efficiency for an application or

multiple applications running in the same environment

• Is usually measured in:– response time: the time that a single task takes to

completeCan be shortened by:• Reducing contention and wait times, particularly disk I/O wait

times• Using faster components• Reducing the amount of time the resources are needed

– throughput: the volume of work completed in a fixed time period

• is commonly measured in transactions per second (tps), but it can also be measured per minute, per hour, per day, and so on

Page 3: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 3

Database Performance

• Can be thought by using the concepts of supply and demand– Users demand information from the database– The DBMS supplies information to those requesting it– The rate at which the DBMS supplies the demand for

information can be termed “database performance”• Five factors influence database performance:

– Workload– Throughput– Resource– Optimization– Contention

Page 4: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 4

Factors Influencing Database Performance

• Workload that is requested of the DBMS defines the demand– A combination of online transactions, batch jobs, ad

hoc queries, data warehousing analysis, and system commands directed through the system

– Can fluctuate drastically, sometimes can be predicted

• Throughput defines the overall capability of the computer to process data– Composite of I/O speed, CPU speed, parallel

capabilities of the machine, and the efficiency of the operating system and system software

Page 5: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 5

Factors Influencing Database Performance (cont.)

• Resources of the system include database kernel, disk space, memory, cache controllers, and microcode

• Optimization of queries is primarily accomplished internal to the DBMSMany factors that need to be optimized:– SQL formulation– Database parameters

• Contention is the condition in which two or more components of the workload are attempting to use a single resource in a conflicting way– As contention increases, throughput decreases

Page 6: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 6

Database Performance Definition

• Database performance can be defined as the optimization of resource use to increase throughput and minimize contention, enabling the largest possible workload to be processed

• Performance management tasks not covered by the definition should be handled by someone other that the DBA – or at a minimum shared between the DBA and other technicians

Page 7: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 7

Performance Tuning

• Adjusting various parameters and design choices to improve system performance for a specific application.

• Tuning is best done by 1. identifying bottlenecks, and2. eliminating them.

• Can tune a database system at 3 levels:– Hardware -- e.g., add disks to speed up I/O, add memory to

increase buffer hits, move to a faster processor.– Database system parameters -- e.g., set buffer size to avoid

paging of buffer, set checkpointing intervals to limit log size. System may have automatic tuning.

– Higher level database design, such as the schema, indices and transactions (more later)

Page 8: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 8

Bottlenecks

• Performance of most systems (at least before they are tuned) usually limited by performance of one or a few components: these are called bottlenecks– E.g. 80% of the code may take up 20% of time and 20% of code

takes up 80% of time• Worth spending most time on 20% of code that take 80% of time

• Bottlenecks may be in hardware (e.g. disks are very busy, CPU is idle), or in software

• Removing one bottleneck often exposes another• De-bottlenecking consists of repeatedly finding

bottlenecks, and removing them– This is a heuristic

Page 9: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 9

Identifying Bottlenecks• Transactions request a sequence of services

– e.g. CPU, Disk I/O, locks• With concurrent transactions, transactions may have to wait

for a requested service while other transactions are being served

• Can model database as a queueing system with a queue for each service– transactions repeatedly do the following

• request a service, wait in queue for the service, and get serviced

• Bottlenecks in a database system typically show up as very high utilizations (and correspondingly, very long queues) of a particular service– E.g. disk vs CPU utilization– 100% utilization leads to very long waiting time:

• Rule of thumb: design system for about 70% utilization at peak load• utilization over 90% should be avoided

Page 10: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 10

Queues In A Database System

Page 11: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 11

Tunable Parameters

• Tuning of hardware• Tuning of schema• Tuning of indices• Tuning of materialized views• Tuning of transactions

Page 12: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 12

Tuning of Hardware

• Even well-tuned transactions typically require a few I/O operations– Typical disk supports about 100 random I/O operations per

second– Suppose each transaction requires just 2 random I/O operations.

Then to support n transactions per second, we need to stripe data across n/50 disks (ignoring skew)

• Number of I/O operations per transaction can be reduced by keeping more data in memory– If all data is in memory, I/O needed only for writes– Keeping frequently used data in memory reduces disk accesses,

reducing number of disks required, but has a memory cost

Page 13: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 13

Hardware Tuning: Five-Minute Rule

• Question: which data to keep in memory:– If a page is accessed n times per second, keeping it in memory saves

• n * price-per-disk-driveaccesses-per-second-per-disk

– Cost of keeping page in memory • price-per-MB-of-memory

pages-per-MB-of-memory

– Break-even point: value of n for which above costs are equal• Buying memory: If accesses are more then saving is greater than cost

– Solving above equation with current disk and memory prices leads to:5-minute rule: if a page that is randomly accessed is used more frequently than once in 5 minutes it should be kept in memory

• (by buying sufficient memory!)

Page 14: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 14

Hardware Tuning: One-Minute Rule

• For sequentially accessed data, more pages can be read per second. Assuming sequential reads of 1MB of data at a time: 1-minute rule: sequentially accessed data that is accessed once or more in a minute should be kept in memory

• Prices of disk and memory have changed greatly over the years, but the ratios have not changed much– so rules remain as 5 minute and 1 minute rules, not 1

hour or 1 second rules!

Page 15: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 15

Hardware Tuning: Choice of RAID Level• To use RAID 1 or RAID 5?

– Depends on ratio of reads and writes• RAID 5 requires 2 block reads and 2 block writes to write out one data

block

• If an application requires r reads and w writes per second– RAID 1 requires r + 2w I/O operations per second– RAID 5 requires: r + 4w I/O operations per second

• For reasonably large r and w, this requires lots of disks to handle workload– RAID 5 may require more disks than RAID 1 to handle load! – Apparent saving of number of disks by RAID 5 (by using parity, as

opposed to the mirroring done by RAID 1) may be illusory!• Thumb rule: RAID 5 is fine when writes are rare and data

is very large, but RAID 1 is preferable otherwise– If you need more disks to handle I/O load, just mirror them since

disk capacities these days are enormous!

Page 16: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 16

Tuning the Database DesignSchema tuning

• Can be done in several ways:– Splitting tables

• Sometimes splitting normalized tables can improve performance• Can split tables in two ways:

– Horizontally– Vertically

• Adds complexity to the applications– Denormalization:

• Adding redundant columns• Adding derived attributes• Collapsing tables• Duplicating tables

– Cluster together on the same disk page records that would match in a frequently required join,• compute join very efficiently when required.

Page 17: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 17

Tuning the Database DesignSchema tuning (cont.)

Horizontal Splitting• Placing rows in two separate tables, depending on data

values in one or more columns• Use horizontal splitting if:

– A table is large, and reducing its size reduces the number of index pages read in a query

– The table split corresponds to a natural separation of the rows, such as different geographical sites or historical versus current data• might choose horizontal splitting if a table stores huge amounts of

rarely used historical data, and the applications have high performance needs for current data in the same table

– Table splitting distributes data over the physical media

Page 18: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 18

Tuning the Database DesignSchema tuning (cont.)

Horizontal Splitting Example

Page 19: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 19

Tuning the Database DesignSchema tuning (cont.)

Vertical Splitting• Partition relations to isolate the data that is accessed most

often – only fetch needed information• Keeps the relation in normal form• Use vertical splitting if:

– Some columns are accessed more frequently than other columns– The table has wide rows, and splitting the table reduces the number

of pages that need to be read• Makes even more sense when both of the above conditions

are true– When a table contains very long columns that are accessed infrequently,

placing them in a separate table can greatly speed the retrieval of the more frequently used columns

– With shorter rows, more data rows fit on a data page, so for many queries, fewer pages can be accessed

Page 20: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 20

Tuning the Database DesignSchema tuning (cont.)

Vertical Splitting Exampleaccount relation with the following schema:account(account-number, brach-name, balance)

can be split into two relations:account-branch(account-number, branch-name)account-balance(account-number, balance)

These two representations are equivalent and in the maximum normal form (BCNF). But, they could give different performance characteristic, depends on the information that usually retrieved at the same time.E.g. Branch-name need not be fetched unless required

Page 21: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 21

Tuning the Database DesignSchema tuning (cont.)

Denormalization• Can be done with tables or columns• Assumes prior normalization• Requires a thorough knowledge of how the data is

being used • Used if:

– All or nearly all of the most frequent queries require access to the full set of joined data

– A majority of applications perform table scans when joining tables

– Computational complexity of derived columns requires temporary tables or excessively complex queries

Page 22: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 22

Tuning the Database DesignSchema tuning (cont.)

Denormalization (cont.)• Denormalization can improve performance by :

– Minimizing the need for joins– Reducing the number of foreign keys on tables– Reducing the number of indexes, saving storage space, and reducing

data modification time– Precomputing aggregate values– Reducing the number of tables (in some cases)

• Disadvantages:– It usually speeds retrieval but can slow data modification– It is always application-specific and must be reevaluated if the

application changes– It can increase the size of tables– In some instances, it simplifies coding; in others, it makes coding

more complex.

Page 23: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 23

Tuning the Database DesignSchema tuning (cont.)

Denormalization (cont.)• Issues to examine when considering denormalization include:

– What are the critical transactions, and what is the expected response time?

– How often are the transactions executed?– What tables or columns do the critical transactions use? How many

rows do they access each time?– What is the mix of transaction types: select, insert, update, and

delete?– What is the usual sort order?– What are the concurrency expectations?– How big are the most frequently accessed tables?– Do any processes compute summaries?– Where is the data physically located?

Page 24: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 24

Tuning the Database DesignSchema tuning (cont.)

Adding Redundant Columns• To eliminate frequent joins for many queries• For example, if performing frequent joins on the

titleauthor and authors tables to retrieve the author’s last name, you can add the au_lnamecolumn to titleauthor.

• The problems with this solution are that it:– Requires maintenance of new columns

• Have to make changes to two tables, and possibly to many rows inone of the tables.

– Requires more disk space

Page 25: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 25

Tuning the Database DesignSchema tuning (cont.)

Adding Derived Columns• Can eliminate some joins and

reduce the time needed to produce aggregate values

• E.g. The total_sales column in the titles table– eliminating both the join and

the aggregate at runtime– increases storage needs, and

requires maintenance of the derived column whenever changes are made to the titlestable

Page 26: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 26

Tuning the Database DesignSchema tuning (cont.)

Collapsing Tables• If most users need to see the full set of joined data

from two tables, collapsing the two tables into one can improve performance by eliminating the join

• The data from the two tables must be in a one-to-one relationship to collapse tables

• Eliminates the join, but loses the conceptual separation of the data– If some users still need access to just the pairs of data

from the two tables, this access can be restored by using queries that select only the needed columns or by using views

Page 27: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 27

Tuning the Database DesignSchema tuning (cont.)

Duplicating Tables• If a group of users

regularly needs only a subset of data, the critical table subset can be duplicated for that group

• Minimizes contention, but requires managing redundancy

Page 28: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 28

Tuning the Database DesignSchema tuning (cont.)

Managing Denormalized Data• Need to ensure data integrity by using:

– Triggers, which can update derived or duplicated data anytime the base data changes

– Application logic, using transactions in each application that update denormalized data, to ensure that changes are atomic• be very sure that the data integrity requirements are well documented and

well known to all application developers and to those who must maintain applications

– Batch reconciliation, run at appropriate intervals, to bring thedenormalized data back into agreement• If 100 percent consistency is not required at all times

• From an integrity point of view, triggers provide the best solution, although they can be costly in terms of performance

Page 29: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 29

Tuning the Database DesignIndex tuning

• Create appropriate indices to speed up slow queries/updates

• Speed up slow updates by removing excess indices (tradeoff between queries and updates)

• Choose type of index (B-tree/hash) appropriate for most frequent types of queries.

• Choose which index to make clustered• Index tuning wizards look at past history of queries

and updates (the workload) and recommend which indices would be best for the workload

Page 30: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 30

Tuning the Database DesignIndex tuning (cont.)

When should indexes be considered• Unique indexes are implicitly used in conjunction with a

primary key for the primary key to work• Foreign keys are also excellent candidates for an index

because they are often used to join the parent table– Most, if not all, columns used for table joins should be indexed

• Columns that are frequently referenced in the ORDER BY and GROUP BY clauses should be considered for indexes

• Indexes should be created on columns with a high number of unique values, or columns when used as filter conditions in the WHERE clause return a low percentage of rows of data from a table

• The effective use of indexes requires a thorough knowledge of table relationships, query and transaction requirements, and the data itself

Page 31: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 31

Tuning the Database DesignIndex tuning (cont.)

When should indexes be avoided• Indexes should not be used on small tables• Indexes should not be used on columns that return a high

percentage of data rows when used as a filter condition in a query's WHERE clause

• Tables that have frequent, large batch update jobs run can be indexed– However, the batch job's performance is slowed considerably by the

index– Might consider dropping the index before the batch job, and then re-

creating the index after the job has completed • Indexes should not be used on columns that contain a high

number of NULL values• Columns that are frequently manipulated should not be

indexed– Maintenance on the index can become excessive

Page 32: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 32

• Materialized views can help speed up certain queries– Particularly aggregate queries

• Overheads– Space– Time for view maintenance

• Immediate view maintenance: done as part of update– time overhead paid by update transaction

• Deferred view maintenance: done only when required– update transaction is not affected, but system time is spent on view

maintenance» until updated, the view may be out-of-date

• Preferable to denormalized schema since view maintenance is system’s responsibility, not programmers– Avoids inconsistencies caused by errors in update programs

Tuning the Database DesignMaterialized Views

Page 33: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 33

• How to choose set of materialized views– Helping one transaction type by introducing a

materialized view may hurt others– Choice of materialized views depends on costs

• Users often have no idea of actual cost of operations

– Overall, manual selection of materialized views is tedious

• Some database systems provide tools to help DBA choose views to materialize– “Materialized view selection wizards”

Tuning the Database DesignMaterialized Views (cont.)

Page 34: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 34

Tuning of Transactions• Basic approaches to tuning of transactions

– Improve set orientation– Reduce lock contention

• Rewriting of queries to improve performance was important in the past, but smart optimizers have made this less important

• Communication overhead and query handling overheads significant part of cost of each call– Combine multiple embedded SQL/ODBC/JDBC queries into

a single set-oriented query• Set orientation -> fewer calls to database• E.g. tune program that computes total salary for each department using

a separate SQL query by instead using a single query that computes total salaries for all department at once (using group by)

– Use stored procedures: avoids re-parsing and re-optimizationof query

Page 35: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 35

Tuning of Transactions (Cont.)

• Reducing lock contention• Long transactions (typically read-only) that

examine large parts of a relation result in lock contention with update transactions– E.g. large query to compute bank statistics and regular

bank transactions

• To reduce contention– Use multi-version concurrency control

• E.g. Oracle “snapshots” which support multi-version 2PL

– Use degree-two consistency (cursor-stability) for long transactions

• Drawback: result may be approximate

Page 36: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 36

Tuning of Transactions (Cont.)• Long update transactions cause several problems

– Exhaust lock space– Exhaust log space

• and also greatly increase recovery time after a crash, and may even exhaust log space during recovery if recovery algorithm is badly designed!

• Use mini-batch transactions to limit number of updates that a single transaction can carry out. E.g., if a single large transaction updates every record of a very large relation, log may grow too big.* Split large transaction into batch of ``mini-transactions,'' each

performing part of the updates • Hold locks across transactions in a mini-batch to ensure serializability

• If lock table size is a problem can release locks, but at the cost of serializability

* In case of failure during a mini-batch, must complete its remaining portion on recovery, to ensure atomicity.

Page 37: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 37

Tuning of SQL Statements• Proper arrangement of tables in the FROM clause

– List the smaller tables first and the larger tables last• Proper order of join conditions

– The join conditions should be in the first position(s) of the WHERE clause followed by the filter clause(s)

– The effective placement of the most restrictive condition in thequery requires knowledge of how the optimizer operates

• The optimizers, in some cases, seem to read from the bottom of the WHERE clause up. Therefore, you would want to place the most restrictive condition last in the WHERE clause

• Rewriting the SQL statement using the IN predicate instead of the OR operator consistently

• Avoiding the HAVING clause• Avoid large sort operation

Page 38: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 38

Performance Simulation• Performance simulation using queuing model useful to

predict bottlenecks as well as the effects of tuning changes, even without access to real system

• Queuing model as we saw earlier– Models activities that go on in parallel

• Simulation model is quite detailed, but usually omits some low level details– Model service time, but disregard details of service – E.g. approximate disk read time by using an average disk read time

• Experiments can be run on model, and provide an estimate of measures such as average throughput/response time

• Parameters can be tuned in model and then replicated in real system– E.g. number of disks, memory, algorithms, etc

Page 39: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 39

Performance Benchmarks

• Suites of tasks used to quantify the performance of software systems

• Important in comparing database systems, especially as systems become more standards compliant.

• Commonly used performance measures:– Throughput (transactions per second, or tps)– Response time (delay from submission of

transaction to return of result)– Availability or mean time to failure

Page 40: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 40

Performance Benchmarks (Cont.)• Suites of tasks used to characterize performance

– single task not enough for complex systems

• Beware when computing average throughput of different transaction types– E.g., suppose a system runs transaction type A at 99 tps and

transaction type B at 1 tps. – Given an equal mixture of types A and B, throughput is not (99+1)/2

= 50 tps.– Running one transaction of each type takes time 1+.01 seconds, giving

a throughput of 1.98 tps.– To compute average throughput, use harmonic mean:

n

– Interference (e.g. lock contention) makes even this incorrect if different transaction types run concurrently

1/t1 + 1/t2 + … + 1/tn

Page 41: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 41

Database Application Classes

• Online transaction processing (OLTP)– requires high concurrency and clever techniques to speed up

commit processing, to support a high rate of update transactions.

• Decision support applications– including online analytical processing, or OLAP applications– require good query evaluation algorithms and query optimization.

• Architecture of some database systems tuned to one of the two classes– E.g. Teradata is tuned to decision support

• Others try to balance the two requirements– E.g. Oracle, with snapshot support for long read-only transaction

Page 42: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 42

Benchmarks Suites

• The Transaction Processing Council (TPC) benchmark suites are widely used. – TPC-A and TPC-B: simple OLTP application

modeling a bank teller application with and without communication• Not used anymore

– TPC-C: complex OLTP application modeling an inventory system• Current standard for OLTP benchmarking

Page 43: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 43

Benchmarks Suites (Cont.)

• TPC benchmarks (cont.)– TPC-D: complex decision support application

• Superceded by TPC-H and TPC-R

– TPC-H: (H for ad hoc) based on TPC-D with some extra queries • Models ad hoc queries which are not known beforehand

– Total of 22 queries with emphasis on aggregation

• prohibits materialized views• permits indices only on primary and foreign keys

– TPC-R: (R for reporting) same as TPC-H, but without any restrictions on materialized views and indices

– TPC-W: (W for Web) End-to-end Web service benchmark modeling a Web bookstore, with combination of static and dynamically generated pages

Page 44: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 44

TPC Performance Measures

• TPC performance measures– transactions-per-second with specified constraints on response

time – transactions-per-second-per-dollar accounts for cost of

owning system

• TPC benchmark requires database sizes to be scaled up with increasing transactions-per-second– reflects real world applications where more customers means

more database size and more transactions-per-second

• External audit of TPC performance numbers mandatory – TPC performance claims can be trusted

Page 45: Tuning Database Itb

IF-ITB/TW/22 Des'03IF3211 – Database Tuning

Page 45

TPC Performance Measures

• Two types of tests for TPC-H and TPC-R– Power test: runs queries and updates sequentially,

then takes mean to find queries per hour– Throughput test: runs queries and updates

concurrently• multiple streams running in parallel each generates queries,

with one parallel update stream

– Composite query per hour metric: square root of product of power and throughput metrics

– Composite price/performance metric