SlideShare a Scribd company logo
100500 способов
кэширования в Oracle
Database или как достичь
максимальной скорости
обработки запросов
минимальной ценой
Токарев Александр
DataArt
Agenda
• Database caches
• Result cache
• Result cache in DBMSs different from Oracle
• Hand-made Oracle result cache implementation
• Embedded Oracle result cache implementation
• Performance tests
• Limitations and caveats
• Cases
• Conclusion
Agenda
• Retailer case
• Finance case
• Limitations and caveats
• Loyalty case
• Conclusion
Database caches
• Buffer cache – cache for data pages/data blocks
• Statement cache – cache of queries plan
• Result cache – rows from queries
• OS cache
Retailer case
DWH report
Oracle 11
20 Tb
300 users
20 min
350 distinct SKU
5000 rows
Select sku_id,
Shop_id,
sku_detail(sku_id),
…..
from dim_sales
where ….
Order by shop_id……..
Create or replace
function
sku_detail(sku_id
number) return
number is
Select 1
If Select 2
Else Select 3
…
…
…
Select 30
End;
400 lines of
SQL+PL/SQL
0.2 second per SKU
5000 * 0.2 = 1000 seconds
Retailer case Hand-made cache
DWH
report
Oracle 11
20 Tb
300 users
4 min
350 distinct SKU
5000 rows
Select sku_id,
Shop_id,
sku_detail(sku_id),
…..
from dim_sales
where ….
Order by shop_id……..
Create or replace function
sku_full(sku_id number)
return number is
Select 1
If Select 2
Else Select 3
…
…
…
Select 30
End;
400 lines of SQL+PL/SQL
0.2 second per SKU
350* 0.2 = 70 seconds
CREATE PACKAGE BODY cache_sku AS
TYPE sku_cache_aat IS TABLE OF number INDEX BY PLS_INTEGER;
cache sku_cache_aat;
end cache_sku;
cache
FUNCTION sku_detail(sku
number) RETURN number IS
BEGIN
IF NOT cache.EXISTS(sku) THEN
cache(sku) := sku_full(sku);
END IF;
RETURN cache(sku);
END sku_detail;
Hand-made cache Memory
12X
Hand-made cache
Pros:
- Very fast
- Easy to implement
- No configuration efforts
- No intra-process sync logic burden
Cons:
- Cache consumes expensive memory from DB
- Memory is allocated per-session basis
- PL/SQL or other DB stored logic is required
- Vendor specific
- No automatic invalidation
Hand-made cache Not Oracle
No cache
Hand-made cache Not Oracle
With propopulated cache
Case 2 Recommendation engine
Oracle
main
Oracle
DG
Application
server
Application
server
Load
balancer
Client
browser
4000
users
10000
requests
per
second
In-
memory
cluster
Case 2 Recommendation engine
Recommendation rules
1. 10 best recommendations by text match
2. Multilanguage capabilities
3. Should be taken from 12 previous recognized documents of the client
4. If there is no documents – from all clients of the same industry
5. If no in same industry – from clients similar by margin and e.t.c
max
100
rows
2-3 columns
max 100 users
Case 2 Recommendation engine
1 week before the Release
1. Recommendations work slow – 5 minutes for 1 document
2. Code freeze
Case 2 Recommendation engine
Solution
1. Use database to cache queries
2. Use Oracle Database Result Cache
Why
1. SQL to get recommendation works 0.5 sec, no options for query
tuning – Oracle full text search engine + it is really heavy SQL
2. Same parameters appear at least 5-10 times – cache will be used
3. Data to get recommendations is refreshed 1 hour basis
4. PL/SQL is prohibited
Oracle Result Cache
Oracle result cache
1. Memory area to share query result sets
2. Read consistent – auto invalidation during DML
3. Automatic dependency tracking
4. Minimal changes in the application
5. There is an option how not to change application
6. Could cache PL/SQL logic as well
Oracle Result Cache Way 1
ID of result
First execution Second execution
Oracle Result Cache Table annotations
No query changes
but RC works
Oracle Result Cache Table annotations
No annotation on JOBS table – no result cache
Oracle Result Cache Table annotations
2 annotations –result cache works
Oracle Result Cache Dependency Tracking
No in dependency list
Oracle Result Cache Dependency Tracking
Oracle Result Cache Inline Views
Oracle Result Cache Inline Views
Oracle Result Cache Simple Views
Oracle Result Cache Invalidation
Oracle Result Cache Invalidation
Cache is ignored for current session
Good for others sessions
Oracle Result Cache Invalidation
Invalidated after commit for others sessions!
Oracle Result Cache Invalidation
Unexpected cache invalidation
1. SELECT FOR UPDATE statement even there were no changes at all
2. an unindexed foreign key + delete/update/insert a record from
parent table
3. Update/delete statements in main table with no records affected +
an update to any table where rows were affected.
P.S. Result Cache doesn’t track partitions even if a result cache query
works with only 1 partition. Table level tracking always.
Case 2 Recommendation engine
Final solution
1. Do not use annotations – not all queries should
be cached
2. Use /*+ result_cache*/ for long-running query
3. Performance is tested. Document recognition –
30 seconds.
Time for production
Case 2 Recommendation engine Early morning
Level 3 support
Production incident
Severity 1
Users can’t provide document recognition. Recognition takes 20 minutes
at least. Sessions hangs.
Regards, L2 support team.
Case 2 Recommendation engine
• Active user count: 400
• Database active session count: 1200 = 400* 3
• Row count: 500
• Columns count: 5-8
X5 more!
Monitoring features
View Name Description
V$RESULT_CACHE_STATISTICS Lists cache settings and memory usage statistics
V$RESULT_CACHE_MEMORY Lists all the memory blocks and corresponding
statistics
V$RESULT_CACHE_OBJECTS Lists all the objects(cached results and
dependencies) along with their attributes
V$RESULT_CACHE_DEPENDENCY Lists the dependency details between the cached
results and dependencies
V$SQLAREA Lists SQL statements issued inside Oracle database
Management features
Procedure Name Description
BYPASS Instruction to ignore result cache: for current
session or for all DB
FLUSH Clean cache
MEMORY_REPORT Memory detail report
STATUS Checks the status
INVALIDATE Invalidates the specified result-set object
Package: DBMS_RESULT_CACHE
V$RESULT_CACHE_MEMORY
V$RESULT_CACHE_OBJECTS
V$RESULT_CACHE_STATISTICS
DBMS_RESULT_CACHE.MEMORY_REPORT
Locks Result cache prior 12.2 – use very careful!!!
Case 2 Recommendation engine Investigations
Strange queries for 40 small tables each minute:
ETL
Case 2 Recommendation engine Investigations
Result cache annotation
Still 20 minutes per document 
Case 2 Recommendation engine
We have received very positive feedback about Oracle Adaptive Statistic feature from customer with respect to adaptive
plans. It has proved to be very able at improving system performance for a huge range of workloads. (c) Oracle
20000 queries
10 minutes per document!!!
Via bug? WTF!!!
Result cache latches
Latches are Oracle-internal low-level locks that protect the memory
structures of the system global area (SGA) against simultaneous
accesses.
Result cache latches
Result cache latches Type 1
When sets
First row of dataset is placed in Result Cache
When release
Last row of dataset is placed in Result Cache
Who waits
Sessions with same SQL which requested the latch
How much
_RESULT_CACHE_TIMEOUT – 10 seconds. Next - result cache bypassed.
Result cache latches Type 2
When sets
First row of dataset is requested from Result Cache
When release
Last row of dataset is read from Result Cache
Who waits
Sessions with same SQL which requested the latch
How much
It depends 
Result cache latches
Latches not only makes SQL to wait but consumes CPU.
There is no options to get rid of result cache latches – slow for
concurrent environment..
Be ready to convince DBA latches wait time saves DB time.
Result cache statistics
NAME VALUE
Block Size (Bytes) 1024
Block Count Maximum 4096
Block Count Current 4096
Result Size Maximum
(Blocks) 204
Create Count Success 500
Create Count Failure 0
Find Count 20000
Invalidation Count 10000
Delete Count Invalid 155
Delete Count Valid 14000
Hash Chain Length 1
Find Copy Count 1770
Latch (Share) 0
They are equal – the cache is full!!!
Proper results are deleted
Memory estimate
Result Cache Size = row width (bytes)* expected row count
NAME VALUE
Block Size (Bytes) 1024
Block Count Maximum 4096
Block Count Current 4096
Memory allocated by blocks!!!
Result Cache Size = block size (if fits in 1024) * expected row count
Administration
23 undocumented parameters
6 documented parameters
Administration
Parameter Purpose
RESULT_CACHE_MAX_SIZE memory allocated to the server result cache in bytes. default – 0 bytes
RESULT_CACHE_MAX_RESULT maximum amount of server result cache memory (in percent) that can be
used for a single result. The default value is 5%.
RESULT_CACHE_MODE Default is MANUAL which means that the cache should be requested
explicitly via the RESULT_CACHE hint
_RESULT_CACHE_TIMEOUT
(undocumented)
Maximum time a session request for a latch. Default 10 sec.
6 minutes per document!!!
Case 2 Recommendation engine
NAME VALUE
Block Size (Bytes) 1024
Block Count Maximum 4096
Block Count Current 4096
Result Size Maximum
(Blocks) 204
Create Count Success 500
Create Count Failure 0
Find Count 20000
Invalidation Count 10000
Delete Count Invalid 155
Delete Count Valid 14000
Hash Chain Length 1
Find Copy Count 1770
Latch (Share) 0
A lot of updates on source tables
Case 2 Recommendation engine
Final statistics for result cache
40 seconds per document!!!
NAME VALUE
Block Size (Bytes) 1024
Block Count Maximum 4096
Block Count Current 4096
Result Size Maximum
(Blocks) 204
Create Count Success 500
Create Count Failure 0
Find Count 20000
Invalidation Count 10000
Delete Count Invalid 155
Delete Count Valid 14000
Hash Chain Length 1
Find Copy Count 1770
Latch (Share) 0
NAME VALUE
Block Size (Bytes) 1024
Block Count Maximum 8192
Block Count Current 6000
Result Size Maximum
(Blocks) 204
Create Count Success 1000
Create Count Failure 0
Find Count 20000
Invalidation Count 30
Delete Count Invalid 155
Delete Count Valid 0
Hash Chain Length 1
Find Copy Count 1770
Latch (Share) 0
Case 2 Recommendation engine Auto-expiring
SHELFLIFE = read-consistent result life time in seconds
SNAPSHOT = NON-read-consistent result life time in seconds
Restrictions
• Dictionary tables/views (sys. schema)
• Temporary and external tables
• Sequences (nextval and curval columns)
• Non-deterministic SQL functions:
current_date, current_time, local_timestamp, sys_guid…
• Non-deterministic PL/SQL function:
dbms_random, hand-written, …
• Pipelined functions (returning rowsets)
• Only IN parameter with simple data types: no CLOB, BLOB, records, objects,
collections, ref cursors
• The same for return result
Result cache inside Oracle
Where in Oracle
Jobs related stuff
SELECT /*+ NO_STATEMENT_QUEUING RESULT_CACHE (SYSOBJ=TRUE) */
OBJ#,SCHEDULE_LMT,PRIO,JOB_WEIGHT FROM "SYS"."SCHEDULER$_PROGRAM" WHERE bla-bla-bla
APEX
SELECT /*+result_cache*/ NAME, VALUE FROM WWV_FLOW_PLATFORM_PREFS
WHERE NAME IN ( 'QOS_MAX_WORKSPACE_REQUESTS', 'QOS_MAX_SESSION_REQUESTS', bla-bla-bla
select *
from v$sqlarea
where upper(sql_fulltext) like
'%RESULT_CACHE%‘
Result cache inside Oracle
Dynamic sampling
SELECT /* OPT_DYN_SAMP */ /*+ ALL_ROWS RESULT_CACHE(SNAPSHOT=3600)
opt_param('parallel_execution_enabled', 'false') NO_PARALLEL(SAMPLESUB)
NO_PARALLEL_INDEX(SAMPLESUB) NO_SQL_TUNE */ NVL(SUM(C1),:"SYS_B_0"),
NVL(SUM(C2),:"SYS_B_1") FROM (bla-bla-bla
Adaptive statistic
SELECT /* DS_SVC */ /*+ dynamic_sampling(0) no_sql_tune no_monitoring
optimizer_features_enable(default) no_parallel RESULT_CACHE(SNAPSHOT=3600) */
NVL(SUM(C1),0) FROM (SELECT /*+ qb_name("innerQuery") NO_INDEX_FFS bla-bla-bla
Oracle internals for result cache
1
2
3
Database result cache pros&cons
Pros:
- Minimal or no intervention at all into application code
- No DB stored logic required
- Read consistency
- Fast in certain scenarios
Cons:
- Cache consumes expensive memory from database
- Should be properly set up
- Sometimes could lead even to performance degradation
- Vendor specific
We are not alone
1. Не расчитан размер кэша Troubleshooting Latch Free (Result Cache: RC Latch) Issues When The Result Cache is Full (Doc ID 2143739.1)
2. Блокировки Patch 14665745: DBMS_RESULT_CACHE.MEMORY_REPORT LOCKS OUT WRITERS TO THE RESULT CACHE
Bug 19846066 : LATCH FREE IN RESULT CACHE WHEN QUERYING V$RESULT_CACHE_OBJECTS
Patch 14665745: DBMS_RESULT_CACHE.MEMORY_REPORT LOCKS OUT WRITERS TO THE RESULT CACHE
We are not alone
Result_cache_max_size /*+ result_cache*/ removed or
dbms_result_cache.add_to_black_list or
/*+ no_result_cache*/
We are not alone: Lessons learned
Best approach to roll out updates:
1. Adjust result cache memory
2. Disable cache before bulk loading
dbms_result_cache.bypass;
data ingestion scripts;
Issue dbms_result_cache.bypass(false);
Client side result cache
DB
Client cache is ON
Client driver
2. Configuration message
Connection thread 1
Connection
thread 2
Result cache
3. SQL
Statistics messages
1. connect
1. connect 3.
Cached
SQL 1
4. Results
4. Results
5. Cached
SQL 1
6. Results
CACHE SIZE
Client side result cache Invalidation Case 1
DB
Client cache is ON
Client driver
Connection thread 1
Result cache
1. non-cached SQL
2. Invalid resultset list
2. Results
t last cached SQL 1 < Invalidation lag
Invalidation rules = Invalidation rules for Server Side Result Cache
Invalidation
Client side result cache Invalidation Case 1
DB
Client cache is ON
Client driver
Result cache
1. Get invalid result set list
2. Invalid result set list
Current time = t Invalidation message + Invalidation lag
Invalidation rules = Invalidation rules for Server Side Result Cache
Invalidation
Client side result cache Configuration
Parameter Purpose
CLIENT_RESULT_CACHE_LAG maximum time in milliseconds that client result cache can lag behind
changes in the database that affect its result sets. Default 3000 milliseconds
CLIENT_RESULT_CACHE_SIZE the maximum size of the client result set cache for each client process.
Default 0 – not active, min - 32KB, max – 2G
Client side result cache
Client side result cache
Client side result cache
NAME VALUE
Block Size (Bytes) 256
Block Count Maximum 256
Block Count Current 3
Create Count Success 1
Create Count Failure 0
Find Count 9
Invalidation Count 0
Delete Count Invalid 0
Delete Count Valid 0
= 10
Client side Result cache pros&cons
Pros:
- Cheap client memory
- JDBC and .NET drivers
- Minimal or no intervention at all into application code
- Significant CPU, I/O, network roundtrip reduction
- No extra caching layer/API is required
- No latches
Cons:
- Eventual read consistency with delay
- Oracle OCI client should be installed
- Vendor specific
- 2 Gb per client limitation
- Not enough information about production
Hand-made cache bad scenario
• Cache invalidation in case of data changes is a must
• Database stored logic isn’t in favor
• There is strong database developers team
• PL/SQL business logic is already in place
• There are limitations which don’t permit others caching techniques
Hand-made cache good scenario
Server side Result cache bad scenario
• SQL populates a large number of distinct result sets
• SQL statement takes more than _RESULT_CACHE_TIMEOUT
• Cached results are requested very often from many sessions
Result cache good scenario
• Queries have a limited number of possible result sets
• Result sets are relatively small (200-300 rows)
• SQL statements are relatively expensive
• Queries run against relatively static tables
• There is a strong DBA
Client side Result cache bad scenario
• Instant cache invalidation in case of data changes is a must
• Thin drivers are required
• There is fine middle-tier developers team
• Middle tier uses a lot of SQL without any caching layer
• There are DB server hardware limitations
Hand-made cache good scenario
Conclusion
1. Estimate memory size properly:
volume (Mb) = (
number of result rows * block size+
avg number of apex usage +
avg number adaptive statistic usage
)/1024
2. Add auto-cleaning capabilities with (snapshot + shelflife) options
3. Bypass the cache during bulk data changes
4. Adjust _result_cache_timeout to expected queries duration
5. Never use FORCE mode for all database
6. Check does FORCE used as expected in table annotations
7. Decide about adaptive statistics: _optimizer_ads_use_result_cache = false
Q&A
Alexander Tokarev
Database expert
DataArt
Alexander.Tokarev@dataart.com
THANK YOU.
WE ARE HIRING!

More Related Content

What's hot

Apache Solr for begginers
Apache Solr for begginersApache Solr for begginers
Apache Solr for begginers
Alexander Tokarev
 
In Memory Database In Action by Tanel Poder and Kerry Osborne
In Memory Database In Action by Tanel Poder and Kerry OsborneIn Memory Database In Action by Tanel Poder and Kerry Osborne
In Memory Database In Action by Tanel Poder and Kerry Osborne
Enkitec
 
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Alex Zaballa
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
Alex Zaballa
 
Tanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools shortTanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools short
Tanel Poder
 
DBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should KnowDBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should Know
Alex Zaballa
 
Oracle Database 12.1.0.2 New Features
Oracle Database 12.1.0.2 New FeaturesOracle Database 12.1.0.2 New Features
Oracle Database 12.1.0.2 New Features
Alex Zaballa
 
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should KnowOTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
Alex Zaballa
 
Flex Cluster e Flex ASM - GUOB Tech Day - OTN TOUR LA Brazil 2014
Flex Cluster e Flex ASM - GUOB Tech Day - OTN TOUR LA Brazil 2014Flex Cluster e Flex ASM - GUOB Tech Day - OTN TOUR LA Brazil 2014
Flex Cluster e Flex ASM - GUOB Tech Day - OTN TOUR LA Brazil 2014
Alex Zaballa
 
Drilling Deep Into Exadata Performance
Drilling Deep Into Exadata PerformanceDrilling Deep Into Exadata Performance
Drilling Deep Into Exadata Performance
Enkitec
 
Oracle 12.2 sharding learning more
Oracle 12.2 sharding learning moreOracle 12.2 sharding learning more
Oracle 12.2 sharding learning more
Leyi (Kamus) Zhang
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
Alex Zaballa
 
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
Dave Stokes
 
Ukoug15 SIMD outside and inside Oracle 12c (12.1.0.2)
Ukoug15 SIMD outside and inside Oracle 12c (12.1.0.2)Ukoug15 SIMD outside and inside Oracle 12c (12.1.0.2)
Ukoug15 SIMD outside and inside Oracle 12c (12.1.0.2)
Laurent Leturgez
 
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and HistogramsDutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
Dave Stokes
 
Top 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tipsTop 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tips
Nirav Shah
 
Introduction to MySQL Query Tuning for Dev[Op]s
Introduction to MySQL Query Tuning for Dev[Op]sIntroduction to MySQL Query Tuning for Dev[Op]s
Introduction to MySQL Query Tuning for Dev[Op]s
Sveta Smirnova
 
Introduction into MySQL Query Tuning
Introduction into MySQL Query TuningIntroduction into MySQL Query Tuning
Introduction into MySQL Query Tuning
Sveta Smirnova
 
Sql killedserver
Sql killedserverSql killedserver
Sql killedserver
ColdFusionConference
 
JPA and Hibernate Performance Tips
JPA and Hibernate Performance TipsJPA and Hibernate Performance Tips
JPA and Hibernate Performance Tips
Vlad Mihalcea
 

What's hot (20)

Apache Solr for begginers
Apache Solr for begginersApache Solr for begginers
Apache Solr for begginers
 
In Memory Database In Action by Tanel Poder and Kerry Osborne
In Memory Database In Action by Tanel Poder and Kerry OsborneIn Memory Database In Action by Tanel Poder and Kerry Osborne
In Memory Database In Action by Tanel Poder and Kerry Osborne
 
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
Oracle Database 12c - The Best Oracle Database 12c Tuning Features for Develo...
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
 
Tanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools shortTanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools short
 
DBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should KnowDBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should Know
 
Oracle Database 12.1.0.2 New Features
Oracle Database 12.1.0.2 New FeaturesOracle Database 12.1.0.2 New Features
Oracle Database 12.1.0.2 New Features
 
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should KnowOTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
 
Flex Cluster e Flex ASM - GUOB Tech Day - OTN TOUR LA Brazil 2014
Flex Cluster e Flex ASM - GUOB Tech Day - OTN TOUR LA Brazil 2014Flex Cluster e Flex ASM - GUOB Tech Day - OTN TOUR LA Brazil 2014
Flex Cluster e Flex ASM - GUOB Tech Day - OTN TOUR LA Brazil 2014
 
Drilling Deep Into Exadata Performance
Drilling Deep Into Exadata PerformanceDrilling Deep Into Exadata Performance
Drilling Deep Into Exadata Performance
 
Oracle 12.2 sharding learning more
Oracle 12.2 sharding learning moreOracle 12.2 sharding learning more
Oracle 12.2 sharding learning more
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
 
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
 
Ukoug15 SIMD outside and inside Oracle 12c (12.1.0.2)
Ukoug15 SIMD outside and inside Oracle 12c (12.1.0.2)Ukoug15 SIMD outside and inside Oracle 12c (12.1.0.2)
Ukoug15 SIMD outside and inside Oracle 12c (12.1.0.2)
 
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and HistogramsDutch PHP Conference 2021 - MySQL Indexes and Histograms
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
 
Top 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tipsTop 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tips
 
Introduction to MySQL Query Tuning for Dev[Op]s
Introduction to MySQL Query Tuning for Dev[Op]sIntroduction to MySQL Query Tuning for Dev[Op]s
Introduction to MySQL Query Tuning for Dev[Op]s
 
Introduction into MySQL Query Tuning
Introduction into MySQL Query TuningIntroduction into MySQL Query Tuning
Introduction into MySQL Query Tuning
 
Sql killedserver
Sql killedserverSql killedserver
Sql killedserver
 
JPA and Hibernate Performance Tips
JPA and Hibernate Performance TipsJPA and Hibernate Performance Tips
JPA and Hibernate Performance Tips
 

Similar to Oracle result cache highload 2017

Analyzing and Interpreting AWR
Analyzing and Interpreting AWRAnalyzing and Interpreting AWR
Analyzing and Interpreting AWR
pasalapudi
 
11g R2
11g R211g R2
11g R2
afa reg
 
Presentation of OrientDB v2.2 - Webinar
Presentation of OrientDB v2.2 - WebinarPresentation of OrientDB v2.2 - Webinar
Presentation of OrientDB v2.2 - Webinar
Orient Technologies
 
Day 7 - Make it Fast
Day 7 - Make it FastDay 7 - Make it Fast
Day 7 - Make it Fast
Barry Jones
 
Windows Azure Acid Test
Windows Azure Acid TestWindows Azure Acid Test
Windows Azure Acid Test
expanz
 
Best Practices for Building Robust Data Platform with Apache Spark and Delta
Best Practices for Building Robust Data Platform with Apache Spark and DeltaBest Practices for Building Robust Data Platform with Apache Spark and Delta
Best Practices for Building Robust Data Platform with Apache Spark and Delta
Databricks
 
Performance Tuning
Performance TuningPerformance Tuning
Performance Tuning
Ligaya Turmelle
 
Dataswft Intel benchmark 2013
Dataswft Intel benchmark 2013Dataswft Intel benchmark 2013
Dataswft Intel benchmark 2013
dhulis
 
Investigate SQL Server Memory Like Sherlock Holmes
Investigate SQL Server Memory Like Sherlock HolmesInvestigate SQL Server Memory Like Sherlock Holmes
Investigate SQL Server Memory Like Sherlock Holmes
Richard Douglas
 
01 oracle architecture
01 oracle architecture01 oracle architecture
01 oracle architecture
Smitha Padmanabhan
 
All (that i know) about exadata external
All (that i know) about exadata externalAll (that i know) about exadata external
All (that i know) about exadata external
Prasad Chitta
 
OracleStore: A Highly Performant RawStore Implementation for Hive Metastore
OracleStore: A Highly Performant RawStore Implementation for Hive MetastoreOracleStore: A Highly Performant RawStore Implementation for Hive Metastore
OracleStore: A Highly Performant RawStore Implementation for Hive Metastore
DataWorks Summit
 
Collaborate 2011-tuning-ebusiness-416502
Collaborate 2011-tuning-ebusiness-416502Collaborate 2011-tuning-ebusiness-416502
Collaborate 2011-tuning-ebusiness-416502
kaziul Islam Bulbul
 
Top 5 things to know about sql azure for developers
Top 5 things to know about sql azure for developersTop 5 things to know about sql azure for developers
Top 5 things to know about sql azure for developers
Ike Ellis
 
Developing on SQL Azure
Developing on SQL AzureDeveloping on SQL Azure
Developing on SQL Azure
Ike Ellis
 
ASH and AWR Performance Data by Kellyn Pot'Vin
ASH and AWR Performance Data by Kellyn Pot'VinASH and AWR Performance Data by Kellyn Pot'Vin
ASH and AWR Performance Data by Kellyn Pot'Vin
Enkitec
 
SQL Server Wait Types Everyone Should Know
SQL Server Wait Types Everyone Should KnowSQL Server Wait Types Everyone Should Know
SQL Server Wait Types Everyone Should Know
Dean Richards
 
Tales from production with postgreSQL at scale
Tales from production with postgreSQL at scaleTales from production with postgreSQL at scale
Tales from production with postgreSQL at scale
Soumya Ranjan Subudhi
 
Ash architecture and advanced usage rmoug2014
Ash architecture and advanced usage rmoug2014Ash architecture and advanced usage rmoug2014
Ash architecture and advanced usage rmoug2014
John Beresniewicz
 
Troubleshooting SQL Server
Troubleshooting SQL ServerTroubleshooting SQL Server
Troubleshooting SQL Server
Stephen Rose
 

Similar to Oracle result cache highload 2017 (20)

Analyzing and Interpreting AWR
Analyzing and Interpreting AWRAnalyzing and Interpreting AWR
Analyzing and Interpreting AWR
 
11g R2
11g R211g R2
11g R2
 
Presentation of OrientDB v2.2 - Webinar
Presentation of OrientDB v2.2 - WebinarPresentation of OrientDB v2.2 - Webinar
Presentation of OrientDB v2.2 - Webinar
 
Day 7 - Make it Fast
Day 7 - Make it FastDay 7 - Make it Fast
Day 7 - Make it Fast
 
Windows Azure Acid Test
Windows Azure Acid TestWindows Azure Acid Test
Windows Azure Acid Test
 
Best Practices for Building Robust Data Platform with Apache Spark and Delta
Best Practices for Building Robust Data Platform with Apache Spark and DeltaBest Practices for Building Robust Data Platform with Apache Spark and Delta
Best Practices for Building Robust Data Platform with Apache Spark and Delta
 
Performance Tuning
Performance TuningPerformance Tuning
Performance Tuning
 
Dataswft Intel benchmark 2013
Dataswft Intel benchmark 2013Dataswft Intel benchmark 2013
Dataswft Intel benchmark 2013
 
Investigate SQL Server Memory Like Sherlock Holmes
Investigate SQL Server Memory Like Sherlock HolmesInvestigate SQL Server Memory Like Sherlock Holmes
Investigate SQL Server Memory Like Sherlock Holmes
 
01 oracle architecture
01 oracle architecture01 oracle architecture
01 oracle architecture
 
All (that i know) about exadata external
All (that i know) about exadata externalAll (that i know) about exadata external
All (that i know) about exadata external
 
OracleStore: A Highly Performant RawStore Implementation for Hive Metastore
OracleStore: A Highly Performant RawStore Implementation for Hive MetastoreOracleStore: A Highly Performant RawStore Implementation for Hive Metastore
OracleStore: A Highly Performant RawStore Implementation for Hive Metastore
 
Collaborate 2011-tuning-ebusiness-416502
Collaborate 2011-tuning-ebusiness-416502Collaborate 2011-tuning-ebusiness-416502
Collaborate 2011-tuning-ebusiness-416502
 
Top 5 things to know about sql azure for developers
Top 5 things to know about sql azure for developersTop 5 things to know about sql azure for developers
Top 5 things to know about sql azure for developers
 
Developing on SQL Azure
Developing on SQL AzureDeveloping on SQL Azure
Developing on SQL Azure
 
ASH and AWR Performance Data by Kellyn Pot'Vin
ASH and AWR Performance Data by Kellyn Pot'VinASH and AWR Performance Data by Kellyn Pot'Vin
ASH and AWR Performance Data by Kellyn Pot'Vin
 
SQL Server Wait Types Everyone Should Know
SQL Server Wait Types Everyone Should KnowSQL Server Wait Types Everyone Should Know
SQL Server Wait Types Everyone Should Know
 
Tales from production with postgreSQL at scale
Tales from production with postgreSQL at scaleTales from production with postgreSQL at scale
Tales from production with postgreSQL at scale
 
Ash architecture and advanced usage rmoug2014
Ash architecture and advanced usage rmoug2014Ash architecture and advanced usage rmoug2014
Ash architecture and advanced usage rmoug2014
 
Troubleshooting SQL Server
Troubleshooting SQL ServerTroubleshooting SQL Server
Troubleshooting SQL Server
 

More from Alexander Tokarev

Rate limits and all about
Rate limits and all aboutRate limits and all about
Rate limits and all about
Alexander Tokarev
 
rnd teams.pptx
rnd teams.pptxrnd teams.pptx
rnd teams.pptx
Alexander Tokarev
 
FinOps for private cloud
FinOps for private cloudFinOps for private cloud
FinOps for private cloud
Alexander Tokarev
 
Graph ql and enterprise
Graph ql and enterpriseGraph ql and enterprise
Graph ql and enterprise
Alexander Tokarev
 
FinOps introduction
FinOps introductionFinOps introduction
FinOps introduction
Alexander Tokarev
 
Open Policy Agent for governance as a code
Open Policy Agent for governance as a code Open Policy Agent for governance as a code
Open Policy Agent for governance as a code
Alexander Tokarev
 
Relational databases for BigData
Relational databases for BigDataRelational databases for BigData
Relational databases for BigData
Alexander Tokarev
 
Cloud DWH deep dive
Cloud DWH deep diveCloud DWH deep dive
Cloud DWH deep dive
Alexander Tokarev
 
Cloud dwh
Cloud dwhCloud dwh
Inmemory BI based on opensource stack
Inmemory BI based on opensource stackInmemory BI based on opensource stack
Inmemory BI based on opensource stack
Alexander Tokarev
 
Oracle InMemory hardcore edition
Oracle InMemory hardcore editionOracle InMemory hardcore edition
Oracle InMemory hardcore edition
Alexander Tokarev
 
Tagging search solution design Advanced edition
Tagging search solution design Advanced editionTagging search solution design Advanced edition
Tagging search solution design Advanced edition
Alexander Tokarev
 
Faceted search with Oracle InMemory option
Faceted search with Oracle InMemory optionFaceted search with Oracle InMemory option
Faceted search with Oracle InMemory option
Alexander Tokarev
 
Tagging search solution design
Tagging search solution designTagging search solution design
Tagging search solution design
Alexander Tokarev
 
Data structures for cloud tag storage
Data structures for cloud tag storageData structures for cloud tag storage
Data structures for cloud tag storage
Alexander Tokarev
 

More from Alexander Tokarev (15)

Rate limits and all about
Rate limits and all aboutRate limits and all about
Rate limits and all about
 
rnd teams.pptx
rnd teams.pptxrnd teams.pptx
rnd teams.pptx
 
FinOps for private cloud
FinOps for private cloudFinOps for private cloud
FinOps for private cloud
 
Graph ql and enterprise
Graph ql and enterpriseGraph ql and enterprise
Graph ql and enterprise
 
FinOps introduction
FinOps introductionFinOps introduction
FinOps introduction
 
Open Policy Agent for governance as a code
Open Policy Agent for governance as a code Open Policy Agent for governance as a code
Open Policy Agent for governance as a code
 
Relational databases for BigData
Relational databases for BigDataRelational databases for BigData
Relational databases for BigData
 
Cloud DWH deep dive
Cloud DWH deep diveCloud DWH deep dive
Cloud DWH deep dive
 
Cloud dwh
Cloud dwhCloud dwh
Cloud dwh
 
Inmemory BI based on opensource stack
Inmemory BI based on opensource stackInmemory BI based on opensource stack
Inmemory BI based on opensource stack
 
Oracle InMemory hardcore edition
Oracle InMemory hardcore editionOracle InMemory hardcore edition
Oracle InMemory hardcore edition
 
Tagging search solution design Advanced edition
Tagging search solution design Advanced editionTagging search solution design Advanced edition
Tagging search solution design Advanced edition
 
Faceted search with Oracle InMemory option
Faceted search with Oracle InMemory optionFaceted search with Oracle InMemory option
Faceted search with Oracle InMemory option
 
Tagging search solution design
Tagging search solution designTagging search solution design
Tagging search solution design
 
Data structures for cloud tag storage
Data structures for cloud tag storageData structures for cloud tag storage
Data structures for cloud tag storage
 

Recently uploaded

E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
Yara Milbes
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
Alina Yurenko
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative AnalysisOdoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Envertis Software Solutions
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
Rakesh Kumar R
 
zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
YousufSait3
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 

Recently uploaded (20)

E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative AnalysisOdoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
Odoo ERP Vs. Traditional ERP Systems – A Comparative Analysis
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
 
zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 

Oracle result cache highload 2017

  • 1. 100500 способов кэширования в Oracle Database или как достичь максимальной скорости обработки запросов минимальной ценой Токарев Александр DataArt
  • 2. Agenda • Database caches • Result cache • Result cache in DBMSs different from Oracle • Hand-made Oracle result cache implementation • Embedded Oracle result cache implementation • Performance tests • Limitations and caveats • Cases • Conclusion
  • 3. Agenda • Retailer case • Finance case • Limitations and caveats • Loyalty case • Conclusion
  • 4. Database caches • Buffer cache – cache for data pages/data blocks • Statement cache – cache of queries plan • Result cache – rows from queries • OS cache
  • 5. Retailer case DWH report Oracle 11 20 Tb 300 users 20 min 350 distinct SKU 5000 rows Select sku_id, Shop_id, sku_detail(sku_id), ….. from dim_sales where …. Order by shop_id…….. Create or replace function sku_detail(sku_id number) return number is Select 1 If Select 2 Else Select 3 … … … Select 30 End; 400 lines of SQL+PL/SQL 0.2 second per SKU 5000 * 0.2 = 1000 seconds
  • 6. Retailer case Hand-made cache DWH report Oracle 11 20 Tb 300 users 4 min 350 distinct SKU 5000 rows Select sku_id, Shop_id, sku_detail(sku_id), ….. from dim_sales where …. Order by shop_id…….. Create or replace function sku_full(sku_id number) return number is Select 1 If Select 2 Else Select 3 … … … Select 30 End; 400 lines of SQL+PL/SQL 0.2 second per SKU 350* 0.2 = 70 seconds CREATE PACKAGE BODY cache_sku AS TYPE sku_cache_aat IS TABLE OF number INDEX BY PLS_INTEGER; cache sku_cache_aat; end cache_sku; cache FUNCTION sku_detail(sku number) RETURN number IS BEGIN IF NOT cache.EXISTS(sku) THEN cache(sku) := sku_full(sku); END IF; RETURN cache(sku); END sku_detail;
  • 8. Hand-made cache Pros: - Very fast - Easy to implement - No configuration efforts - No intra-process sync logic burden Cons: - Cache consumes expensive memory from DB - Memory is allocated per-session basis - PL/SQL or other DB stored logic is required - Vendor specific - No automatic invalidation
  • 9. Hand-made cache Not Oracle No cache
  • 10. Hand-made cache Not Oracle With propopulated cache
  • 11. Case 2 Recommendation engine Oracle main Oracle DG Application server Application server Load balancer Client browser 4000 users 10000 requests per second In- memory cluster
  • 12. Case 2 Recommendation engine Recommendation rules 1. 10 best recommendations by text match 2. Multilanguage capabilities 3. Should be taken from 12 previous recognized documents of the client 4. If there is no documents – from all clients of the same industry 5. If no in same industry – from clients similar by margin and e.t.c max 100 rows 2-3 columns max 100 users
  • 13. Case 2 Recommendation engine 1 week before the Release 1. Recommendations work slow – 5 minutes for 1 document 2. Code freeze
  • 14. Case 2 Recommendation engine Solution 1. Use database to cache queries 2. Use Oracle Database Result Cache Why 1. SQL to get recommendation works 0.5 sec, no options for query tuning – Oracle full text search engine + it is really heavy SQL 2. Same parameters appear at least 5-10 times – cache will be used 3. Data to get recommendations is refreshed 1 hour basis 4. PL/SQL is prohibited
  • 15. Oracle Result Cache Oracle result cache 1. Memory area to share query result sets 2. Read consistent – auto invalidation during DML 3. Automatic dependency tracking 4. Minimal changes in the application 5. There is an option how not to change application 6. Could cache PL/SQL logic as well
  • 16. Oracle Result Cache Way 1 ID of result First execution Second execution
  • 17. Oracle Result Cache Table annotations No query changes but RC works
  • 18. Oracle Result Cache Table annotations No annotation on JOBS table – no result cache
  • 19. Oracle Result Cache Table annotations 2 annotations –result cache works
  • 20. Oracle Result Cache Dependency Tracking No in dependency list
  • 21. Oracle Result Cache Dependency Tracking
  • 22. Oracle Result Cache Inline Views
  • 23. Oracle Result Cache Inline Views
  • 24. Oracle Result Cache Simple Views
  • 25. Oracle Result Cache Invalidation
  • 26. Oracle Result Cache Invalidation Cache is ignored for current session Good for others sessions
  • 27. Oracle Result Cache Invalidation Invalidated after commit for others sessions!
  • 28. Oracle Result Cache Invalidation Unexpected cache invalidation 1. SELECT FOR UPDATE statement even there were no changes at all 2. an unindexed foreign key + delete/update/insert a record from parent table 3. Update/delete statements in main table with no records affected + an update to any table where rows were affected. P.S. Result Cache doesn’t track partitions even if a result cache query works with only 1 partition. Table level tracking always.
  • 29. Case 2 Recommendation engine Final solution 1. Do not use annotations – not all queries should be cached 2. Use /*+ result_cache*/ for long-running query 3. Performance is tested. Document recognition – 30 seconds. Time for production
  • 30. Case 2 Recommendation engine Early morning Level 3 support Production incident Severity 1 Users can’t provide document recognition. Recognition takes 20 minutes at least. Sessions hangs. Regards, L2 support team.
  • 31. Case 2 Recommendation engine • Active user count: 400 • Database active session count: 1200 = 400* 3 • Row count: 500 • Columns count: 5-8 X5 more!
  • 32. Monitoring features View Name Description V$RESULT_CACHE_STATISTICS Lists cache settings and memory usage statistics V$RESULT_CACHE_MEMORY Lists all the memory blocks and corresponding statistics V$RESULT_CACHE_OBJECTS Lists all the objects(cached results and dependencies) along with their attributes V$RESULT_CACHE_DEPENDENCY Lists the dependency details between the cached results and dependencies V$SQLAREA Lists SQL statements issued inside Oracle database
  • 33. Management features Procedure Name Description BYPASS Instruction to ignore result cache: for current session or for all DB FLUSH Clean cache MEMORY_REPORT Memory detail report STATUS Checks the status INVALIDATE Invalidates the specified result-set object Package: DBMS_RESULT_CACHE
  • 35. Case 2 Recommendation engine Investigations Strange queries for 40 small tables each minute: ETL
  • 36. Case 2 Recommendation engine Investigations Result cache annotation Still 20 minutes per document 
  • 37. Case 2 Recommendation engine We have received very positive feedback about Oracle Adaptive Statistic feature from customer with respect to adaptive plans. It has proved to be very able at improving system performance for a huge range of workloads. (c) Oracle 20000 queries 10 minutes per document!!! Via bug? WTF!!!
  • 38. Result cache latches Latches are Oracle-internal low-level locks that protect the memory structures of the system global area (SGA) against simultaneous accesses.
  • 40. Result cache latches Type 1 When sets First row of dataset is placed in Result Cache When release Last row of dataset is placed in Result Cache Who waits Sessions with same SQL which requested the latch How much _RESULT_CACHE_TIMEOUT – 10 seconds. Next - result cache bypassed.
  • 41. Result cache latches Type 2 When sets First row of dataset is requested from Result Cache When release Last row of dataset is read from Result Cache Who waits Sessions with same SQL which requested the latch How much It depends 
  • 42. Result cache latches Latches not only makes SQL to wait but consumes CPU. There is no options to get rid of result cache latches – slow for concurrent environment.. Be ready to convince DBA latches wait time saves DB time.
  • 43. Result cache statistics NAME VALUE Block Size (Bytes) 1024 Block Count Maximum 4096 Block Count Current 4096 Result Size Maximum (Blocks) 204 Create Count Success 500 Create Count Failure 0 Find Count 20000 Invalidation Count 10000 Delete Count Invalid 155 Delete Count Valid 14000 Hash Chain Length 1 Find Copy Count 1770 Latch (Share) 0 They are equal – the cache is full!!! Proper results are deleted
  • 44. Memory estimate Result Cache Size = row width (bytes)* expected row count NAME VALUE Block Size (Bytes) 1024 Block Count Maximum 4096 Block Count Current 4096 Memory allocated by blocks!!! Result Cache Size = block size (if fits in 1024) * expected row count
  • 46. Administration Parameter Purpose RESULT_CACHE_MAX_SIZE memory allocated to the server result cache in bytes. default – 0 bytes RESULT_CACHE_MAX_RESULT maximum amount of server result cache memory (in percent) that can be used for a single result. The default value is 5%. RESULT_CACHE_MODE Default is MANUAL which means that the cache should be requested explicitly via the RESULT_CACHE hint _RESULT_CACHE_TIMEOUT (undocumented) Maximum time a session request for a latch. Default 10 sec. 6 minutes per document!!!
  • 47. Case 2 Recommendation engine NAME VALUE Block Size (Bytes) 1024 Block Count Maximum 4096 Block Count Current 4096 Result Size Maximum (Blocks) 204 Create Count Success 500 Create Count Failure 0 Find Count 20000 Invalidation Count 10000 Delete Count Invalid 155 Delete Count Valid 14000 Hash Chain Length 1 Find Copy Count 1770 Latch (Share) 0 A lot of updates on source tables
  • 49. Final statistics for result cache 40 seconds per document!!! NAME VALUE Block Size (Bytes) 1024 Block Count Maximum 4096 Block Count Current 4096 Result Size Maximum (Blocks) 204 Create Count Success 500 Create Count Failure 0 Find Count 20000 Invalidation Count 10000 Delete Count Invalid 155 Delete Count Valid 14000 Hash Chain Length 1 Find Copy Count 1770 Latch (Share) 0 NAME VALUE Block Size (Bytes) 1024 Block Count Maximum 8192 Block Count Current 6000 Result Size Maximum (Blocks) 204 Create Count Success 1000 Create Count Failure 0 Find Count 20000 Invalidation Count 30 Delete Count Invalid 155 Delete Count Valid 0 Hash Chain Length 1 Find Copy Count 1770 Latch (Share) 0
  • 50. Case 2 Recommendation engine Auto-expiring SHELFLIFE = read-consistent result life time in seconds SNAPSHOT = NON-read-consistent result life time in seconds
  • 51. Restrictions • Dictionary tables/views (sys. schema) • Temporary and external tables • Sequences (nextval and curval columns) • Non-deterministic SQL functions: current_date, current_time, local_timestamp, sys_guid… • Non-deterministic PL/SQL function: dbms_random, hand-written, … • Pipelined functions (returning rowsets) • Only IN parameter with simple data types: no CLOB, BLOB, records, objects, collections, ref cursors • The same for return result
  • 52. Result cache inside Oracle Where in Oracle Jobs related stuff SELECT /*+ NO_STATEMENT_QUEUING RESULT_CACHE (SYSOBJ=TRUE) */ OBJ#,SCHEDULE_LMT,PRIO,JOB_WEIGHT FROM "SYS"."SCHEDULER$_PROGRAM" WHERE bla-bla-bla APEX SELECT /*+result_cache*/ NAME, VALUE FROM WWV_FLOW_PLATFORM_PREFS WHERE NAME IN ( 'QOS_MAX_WORKSPACE_REQUESTS', 'QOS_MAX_SESSION_REQUESTS', bla-bla-bla select * from v$sqlarea where upper(sql_fulltext) like '%RESULT_CACHE%‘
  • 53. Result cache inside Oracle Dynamic sampling SELECT /* OPT_DYN_SAMP */ /*+ ALL_ROWS RESULT_CACHE(SNAPSHOT=3600) opt_param('parallel_execution_enabled', 'false') NO_PARALLEL(SAMPLESUB) NO_PARALLEL_INDEX(SAMPLESUB) NO_SQL_TUNE */ NVL(SUM(C1),:"SYS_B_0"), NVL(SUM(C2),:"SYS_B_1") FROM (bla-bla-bla Adaptive statistic SELECT /* DS_SVC */ /*+ dynamic_sampling(0) no_sql_tune no_monitoring optimizer_features_enable(default) no_parallel RESULT_CACHE(SNAPSHOT=3600) */ NVL(SUM(C1),0) FROM (SELECT /*+ qb_name("innerQuery") NO_INDEX_FFS bla-bla-bla
  • 54. Oracle internals for result cache 1 2 3
  • 55. Database result cache pros&cons Pros: - Minimal or no intervention at all into application code - No DB stored logic required - Read consistency - Fast in certain scenarios Cons: - Cache consumes expensive memory from database - Should be properly set up - Sometimes could lead even to performance degradation - Vendor specific
  • 56. We are not alone
  • 57. 1. Не расчитан размер кэша Troubleshooting Latch Free (Result Cache: RC Latch) Issues When The Result Cache is Full (Doc ID 2143739.1) 2. Блокировки Patch 14665745: DBMS_RESULT_CACHE.MEMORY_REPORT LOCKS OUT WRITERS TO THE RESULT CACHE Bug 19846066 : LATCH FREE IN RESULT CACHE WHEN QUERYING V$RESULT_CACHE_OBJECTS Patch 14665745: DBMS_RESULT_CACHE.MEMORY_REPORT LOCKS OUT WRITERS TO THE RESULT CACHE
  • 58. We are not alone Result_cache_max_size /*+ result_cache*/ removed or dbms_result_cache.add_to_black_list or /*+ no_result_cache*/
  • 59. We are not alone: Lessons learned Best approach to roll out updates: 1. Adjust result cache memory 2. Disable cache before bulk loading dbms_result_cache.bypass; data ingestion scripts; Issue dbms_result_cache.bypass(false);
  • 60. Client side result cache DB Client cache is ON Client driver 2. Configuration message Connection thread 1 Connection thread 2 Result cache 3. SQL Statistics messages 1. connect 1. connect 3. Cached SQL 1 4. Results 4. Results 5. Cached SQL 1 6. Results CACHE SIZE
  • 61. Client side result cache Invalidation Case 1 DB Client cache is ON Client driver Connection thread 1 Result cache 1. non-cached SQL 2. Invalid resultset list 2. Results t last cached SQL 1 < Invalidation lag Invalidation rules = Invalidation rules for Server Side Result Cache Invalidation
  • 62. Client side result cache Invalidation Case 1 DB Client cache is ON Client driver Result cache 1. Get invalid result set list 2. Invalid result set list Current time = t Invalidation message + Invalidation lag Invalidation rules = Invalidation rules for Server Side Result Cache Invalidation
  • 63. Client side result cache Configuration Parameter Purpose CLIENT_RESULT_CACHE_LAG maximum time in milliseconds that client result cache can lag behind changes in the database that affect its result sets. Default 3000 milliseconds CLIENT_RESULT_CACHE_SIZE the maximum size of the client result set cache for each client process. Default 0 – not active, min - 32KB, max – 2G
  • 66. Client side result cache NAME VALUE Block Size (Bytes) 256 Block Count Maximum 256 Block Count Current 3 Create Count Success 1 Create Count Failure 0 Find Count 9 Invalidation Count 0 Delete Count Invalid 0 Delete Count Valid 0 = 10
  • 67. Client side Result cache pros&cons Pros: - Cheap client memory - JDBC and .NET drivers - Minimal or no intervention at all into application code - Significant CPU, I/O, network roundtrip reduction - No extra caching layer/API is required - No latches Cons: - Eventual read consistency with delay - Oracle OCI client should be installed - Vendor specific - 2 Gb per client limitation - Not enough information about production
  • 68. Hand-made cache bad scenario • Cache invalidation in case of data changes is a must • Database stored logic isn’t in favor • There is strong database developers team • PL/SQL business logic is already in place • There are limitations which don’t permit others caching techniques Hand-made cache good scenario
  • 69. Server side Result cache bad scenario • SQL populates a large number of distinct result sets • SQL statement takes more than _RESULT_CACHE_TIMEOUT • Cached results are requested very often from many sessions Result cache good scenario • Queries have a limited number of possible result sets • Result sets are relatively small (200-300 rows) • SQL statements are relatively expensive • Queries run against relatively static tables • There is a strong DBA
  • 70. Client side Result cache bad scenario • Instant cache invalidation in case of data changes is a must • Thin drivers are required • There is fine middle-tier developers team • Middle tier uses a lot of SQL without any caching layer • There are DB server hardware limitations Hand-made cache good scenario
  • 71. Conclusion 1. Estimate memory size properly: volume (Mb) = ( number of result rows * block size+ avg number of apex usage + avg number adaptive statistic usage )/1024 2. Add auto-cleaning capabilities with (snapshot + shelflife) options 3. Bypass the cache during bulk data changes 4. Adjust _result_cache_timeout to expected queries duration 5. Never use FORCE mode for all database 6. Check does FORCE used as expected in table annotations 7. Decide about adaptive statistics: _optimizer_ads_use_result_cache = false
  • 72. Q&A

Editor's Notes

  1. Добрый день. Меня зовут Александр и я занимаюсь в компании DataArt вопросами, связаными с базами данных как в части построения систем «с нуля», так и оптимизации имеющихся.
  2. Итак, у нас сегодня штатная презентация по архитектуре очередного решения от СУБД Oracle для ускорения данных. Сегодня я буду рассказывать многих важных вещах таких как... Хотя не, слишком скучно. Ценность данной конференции в том, что тут рассказывается не о технических деталях, которые можно найти в google, а о практическим примерах их использования и их нюансах
  3. В данном докладе я буду рассказывать как устроена технология server side Result cache и чем она лучше чем самодельное кэширование на plsql на примерах двух проектов Компании DataArt. Далее мы подытожим результаты этих проектов и выработаем некие подходы к правильной работе с данной технологией. Так же очень поверхностно посмотрим, что могут предложить другие СУБД относительно кэширования результатов запросов. Вооруженные набором знаний мы попробуем понять причины сбоя в российской cloud системе расчёта лояльности, который имел недавно место быть по причине того самого result cache. У Оракла есть client side result cache, я поверхностно расскажу об его архитектуре, но без детализации – он сам по-себе тема отдельного доклада.
  4. Есть 3 основных вида кэшей в базах данных: кэш данных, кэш операторов и их планов и кэш результатов строк. Интересно заметить, что последний пункт из известных мне БД остался только в Oracle. В postgress result cache нет. Он присутствует только в стороннем продукте pgpool. Это связано с некими сложностями, которые мы рассмотрим ниже.
  5. Итак. Кейс 1. Хранилище ретейлера. Было хранилище и в нём был отчёт. Получение его занимало около 20 минут и пользователи печалились. В чем была интрига данного отчёта? В нём на 5000 строк данных было 350 уникальных товаров, но для каждой строчки вызывалась функция получения информациии по товару. Функция по коду была довольно сложная, тяжело поддающаяся рефакторингу и многие вещи в ней было просто боязно переписывать. Так как система находилась на поддержке, то использовать что-то новое типа embedded result cache было запрещено, поэтому был использован стандартный подход с hand-made кэшированием.
  6. Итак, мы переименовали долгую функцию, а вместо нее создали пакет и функцию, которая использует ассоциативный массив в данном пакете. Данный массив это фактически on demand cache. Если в нём данных нет, то происходит вызов функции.
  7. Важно понимать, в какой из областей памяти расположены коллекции. Помещаются они в области памяти, которая называется PGA, выделяемой под каждую сессию. Именно это определяет их достоинства и недостатки.
  8. Итак, самодельные кэши. Плюсы очевидны: легко запрограммировать, никакой конфигурации, нет необходимости думать о синхронизации, да они просто быстрые! Минусы тоже понятны: если в проекте запрещена хранимая логика их невозможно использовать, нет механизма автоматической инвалидации и так как память на кэш выделяется в рамках одной сессии БД, а не экземпляра, то её потребление завышено. Более того, в случае с вариантом использования connection pool необходимо не забывать сбрасывать кэши если для каждой сессии кэширование должно быть разное. Существуют ещё другие варианты hand-made кэшей на основе materialized views, temporary tables, но от них идёт бОльшая нагрузка на систему ввода-вывода, поэтому они не рассматриваются в данной презентации. Они более склонны для других баз данных. Варианты с oracle client cache и scalar subquery caching я тоже не рассказываю, так как по ним мало эффектных кейсов, но после доклада готов рассказать.
  9. Рассмотрим как часто решают задау кэширования в MsSQL для получения списка сопутствующих товаров.
  10. Таблицу GetRelatedItems пересчитывают, например, периодическим заданием или перед началом работы с соответствующим куском функционала. Если в ней данных нет, обращаются к сложному view. В целом, подход относительно похож, но работает не в памяти БД как в части получения данных, так и первичного заполнения, засчёт этого может быть медленнее. В общем, самодельные result cache активно используются, но иным подходом к реализации данной задачи является in-database result cache. Его и как не получилось quick win мы рассмотрим далее...
  11. Теперь рассмотрим второй кейс. Это система полуавтоматизированной обработки финансовой документации. Архитектура системы стандартна для Enterprise. Клиент, балансировщик, 2 сервера приложений для расчёта бизнес-логики, база данных Oracle и её резервный экземляр.
  12. Одной из множества задач является задача коррекции документов после их автоматического распознавания. Упрощённо говоря она выглядит так Есть документы, для каждого нераспознанного автоматически системой показателя предлагается набор показателей либо из предыдущих документов клиента, либо из похожей индустрии, либо по похожей доходности, при этом ещё сравнивает с распознанным значением, чтобы не предложить лишнее. Что важно документы многоязычные. Пользователь выбирает нужное значение и повторяет для каждой пустой строчки. Важно отметить, что показатели повторяются как в строках, так и столбцах. В целом задача по
  13. 1 неделя до релиза На обработку документа уходит минимум 5 минут Java код менять нельзя В команду разработки баз данных приходят с просьбой о помощи
  14. Принимаем решение использовать базу данных и Oracle Result cache так как Возможности по оптимизации исчерпаны Параметры активно повторяются Данные рекомендаций редко обновляются, так как используют полнотекстовый индекс
  15. Что такое result cache. Это технология от Oracle по кэшИированию результатов с минимальным влиянием на приложение.
  16. Как же всё это выглядит. По-факту он включается указанием инструкции result_cache. На втором выполнении видно, что никаких операций с базой данных не происходит. Всё получается из кэша. Как мы видим изменения минимальны.
  17. Есть второй способ, а именно аннотации. Они включают result_cache для таблицы если она участвует в запросе.
  18. Если хоть одна из таблиц без аннотации, то result_cache исчезает.
  19. Если все с ним, то весь запрос кэшируется.
  20. Для SQL зависимости определяются через план запроса, что весьма забавно, так как Oracle может преобразовывать запрос выкидывая ненужные таблицы из запроса и их не окажется в списке зависимостей. Например, в запросе на слайде применена трансформация join elimination из-за того, что есть FK и таблицы нет в зависимостях.
  21. Убираем constraint и Oracle пересчитывает дерево зависимостей. Для plsql кода зависимости определяются в run-time. Это позволяет делать даже dependency tracking для динамического sql и сложной условной логики.
  22. Оракл позволяет кэшировать результаты не только всего запроса целиком, но и его части. Это либо inline view как в виде with.
  23. Так и в виде from.
  24. Более того, можно создать кэшированное view. Например, в джоине таблица прочиталась как обычно, а вью было взято из кэша результатов.
  25. Итак, посмотрим когда же Оракл инвалидирует result cache. Видно, что если в рамках своей сессии произошли изменения, то кэш игнорируется именно в этой сессии. Другие сессии продолжают использовать сохранённый результат. Как только происходит операция commit и другие сессии ожидают нового результата.
  26. Итак, посмотрим когда же Оракл инвалидирует result cache. Видно, что если в рамках своей сессии произошли изменения, то кэш игнорируется именно в этой сессии. Другие сессии продолжают использовать сохранённый результат. Как только происходит операция commit и другие сессии ожидают нового результата.
  27. Как только мы подтверждаем наши изменения они становятся неактуальными для других сессий
  28. К сожалению, не все так гладко. Oracle производит инвалидации и в ряде неочевидных случаев. 1. При любом вызове select for update 2. Если в вашей таблице есть неиндексированый внешний ключ и в его родительской таблице произошло изменение данных. Это произойдёт даже если родительская таблица не упомянута в запросе. 3. Неудачный апдейт по основной таблице и удачный по другойstatement Выглядит, что на самом деле обновление учитывает факт наличия блокироки, факт попытки апдейта и количество задействованных строк отличное от нуля, причём всё равно в какой из таблиц.
  29. Итак, мы изучили всё вышеуказанное и решили идти в прод
  30. Придя утром на работе мы обнаружили письмо примерно следующего содержания. Почему зависают сессии? Каким образом 30 секунд превратились в 20 минут? В общем, мы начали разбираться.
  31. Мы увидели 40 пользователей, делающих распознавание и даже упустим тот факт, что их не 10, как мы ожидали. Гораздо более странно, что было видно, что в базе данных количество сессий всегда было ровно в 3 раза больше. Проведя внутреннее расследование мы выяснили, что java разработчики делают распознавание в 3 потока. И это было ещё не на пике. Это была наша первая ошибка. Мы неодоценили нагрузку. Но в целом всё равно такого проседания быть было не должно. Почему резалт кэш не любит частое к нему обращение расскажу позже.
  32. Для поиска проблем в result_cache нам понадобится небольшой набор view и хранимых процедур.
  33. Самая важная для нас процедура – процедура получения информации о памяти
  34. Что важное я хочу отметить, что в документации про данные случаи не указано. Это видно только из support notes. Таким образом, всё нюансы result cache ТОЛЬКО на саппорте.
  35. Мы решили понять, сколько же у нас закэшировано объектов. Для этого мы воспользовались представлением v$result_cache_objects. Записей было явно много больше чем мы ожидали. Также мы решили посмотреть, что же это за объекты. Мы были сильно удивлены, но это были не наши запросы. Причем по характеру видно, что это явно ETL-процесс.
  36. И мы вспомнили, что сами включили для этих таблиц аннотации, так как из них довольно часто приложению требовались данные и там кэширование было уместно. Однако запросы к таблицам с интервалом 1 минуты на поиск изменённых данных наводнили кэш приведя к вымыванию наших запросов. Анотации мы отключать не стали, но отключили принудительно кэширование в etl. Мы почистили объекты, но скоро их количество вернулось к 120000. Мы продолжили изучать, что же ещё кэшируется, так как скорость не менялась.
  37. Мы обнаружили следующие запросы. Это были запросы от Adaptive Statistics, которую Oracle применяет для построения планов. На форуме поддержки мы довольно оперативно нашли баг про этот функционал и result cache. Отключили использование result cache и производительность улучшилась до 10 минут за документ. Что же такое за latch free, которые возникают при result cache?
  38. Итак, что такое latch и к чему они приводят Так как нам неоходимо обеспечить согласованность по чтению, то необходимо использовать блокировки. Result cache это единственное место, где читатели могу заблокировать читателей.
  39. Оракл пытается установить защёлку несколько раз и потом засыпает
  40. Рассказ про latch
  41. Рассказ про latch
  42. Итак, мы получили отчёт об использовании памяти. Подскажите, по каким показателям можно понять, что что-то пошло не так? Таким образом, стало понятно, что памяти не хватает из-за некорректного расчёта её объёма.
  43. Таким образом, стало понятно, что памяти не хватает из-за некорректного расчёта её объёма. Мы использовали следующую формулу: ширина строки результатов * ожидаемое кол-во результатов, но не учли, что выделение памяти происходит блоками размером минимум 1 Кб. Что и привело к известным ошибкам в процессе переполнения кэша. Как же надо рассчитывать память? А считать её надо в блоках.
  44. Итак, неужели нам нужны все эти параметры? Конечно же нет!
  45. Как уже упоминалось досточно четырёх. В кейсе мы обошлись одним – общим размером памяти.
  46. Хотя мы и достигли улучшения с 20 минут до 6 время продолжало быть неприемлемым. Посмотрим, что нам ещё может дать отчёт об использовании кэша. Видите ли вы что в отчёте ещё странного?
  47. Путём неких изысканий мы обнаружили, что отключен джоб обновления рекомендаций, что на самом деле приводило их обновлению данных сразу же . Мы запустили джоб с часовым интервалом как и было задумано, что автоматически отключило функционал постоянного обновления таблицы.
  48. Итак, количество инвалидаций уменьшилось до минимального, удаление корректных записей исчезло, а производительность вернулась в ожидаемые границы даже при пятикратном увеличении нагрузки.
  49. Мы не захотели, чтобы данная ситуация повторилась в дальнейшем и изучая как же Oracle использует result cache в ядре, обнаружили, что для ряда вещей используется недокументированный параметр shelflive по истечению которого результат запроса самоудаляется из кэша. Этот параметр был встроен в новую версию приложения. Важно, что он так же удаляется, если было изменение данных. Если факт изменения не критичен для кэша, можно воспользоваться опцией SNAPSHOT – тогда изменения данных не будут инвалидировать кэш.
  50. Если вы не испугались после наших кейсов result cache то есть ещё ряд неозвученных ограничений, ряд из которых очевиден. Нет возможности кэширования объектов в схеме SYS Нельзя кэшировать временные и внешние таблицы. Важно, что по-факту можно и оракл это явно не ограничивает. Это приводит к тому, что можно увидеть то, что раньше было немыслимо, а именно, содержимое временных таблиц других пользователей. Более того, оракл декларирует, что это исправлено, но в 12.2 до сих данная проблема есть. Нелязя использовать недетерменированные sql и pl/sql функции Конвеерные функции Входные и выходные параметры должны быть простых типов данных. На самом деле есть подходы как обходить ограничения с current_date. Могу показать скрипты после докладка.
  51. Result cache широко используется ядром оракла. Для поиска таких мест можно использовать запрос к шаред пулу. Очень активно кэш используется при работе с джобами, средой разработки приложений APEX. Обратите внимание на недокументированную опцию sysobj – я её нашёл именно тут.
  52. Также через резалт кэш сохраняется информация по адаптивной статистике и dynamic sampling – механизмам корректной генерации статистики и трансформации планов. Что важно данные механизмы используют опцию snapshot, которую я именно тут и обнаружил.
  53. Кратко подитожим работу result cache: Данные при запросе попадают с уровня хранения в буферный кэш Данные из буферного кэша попадают в область памяти result cache Результаты переиспользуются с использование блокировок Исходя из услышанного сведём достоинства и недостатки.
  54. Рассмотрим сначала плюсы. Можно не менять код приложения вообще или свести изменения к минимуму Не требуется использовать внутренние языки программирования Целостность данных при многопользовательском доступе через автоматическую инвалидацию Может быть очень быстрым Минусы мы уже увидели: Кэш должен быть правильно использован. При неправильном сценарии может привести к иллюзии роста скорости, а потом её падению База данных должна быть правильно настроена Решение очень проприетарное (хотя я не верю в миф независимости приложения от базы данных) Хочется отметить, что даже системы, разрабатываемые Oracle наткнулись на проблемы с некорректным использованием result cache.
  55. Например, даже erp система Oracle E-Business suite склонна к падениям по причине некорректного использования result cache. Однако нам интересны не сам факт наличия проблем, а способы их недопущения, так как сейчас мы имеем достаточно информации для их предотвращения. В процессе подготовки презентации было обнаружено письмо службы технической поддержки крупнейшей российской cloud системы рассчёта лояльности. На ней рассчитывают свои параметры известные сети по продаже косметики, торговые марки индустрии красоты, крупные ретейлеры электроники. Итак, переходим к непосредственно письму.
  56. Рассмотрим технические причины, которые вполне очевидно привели к сбою Блокировки из-за неправильного размера кэша при bulk заливке, которая наверняка была в той самой подготовительной работе Возможно это всё же v$result_cache_memory или dbms_result_cache.memory_report, так как по нему баг не закрыт. Однако, тесты багов написаны так хитро, что в них фактически явно говорится, что в v_result_cache_objects есть ошибка.
  57. Итак, после был изменён параметр result_cache_max_size Скорее всего убран /*+ result_cache/ или созданы black_list или добавлен no_result_cache Как мы видим, были предприняты практически идентичные действия как в случае с Recommendation engine. Как же надо было провести безболезненное обновление?
  58. Что бы надо было сделать на самом деле: Оценить на сколько изменится итоговый размер кэша. Формула расчёта будет приведена позднее. Уменьшить влияние заливки набора данных в result cache: разово после загрузки, а не сразу же по каждому оператору Проверить анонсированые Oracle исправления перед накатом изменений
  59. Как мы заметили основаная проблема кэшей на сервере это расход дорогой серверной памяти. Для решения этой проблемы есть решение Client side result cache. Он работает так. Есть база данных и драйвер. При попытке подключения запрашивается конфигурация с БД и поднимается кэш. ........... Остальные потоки сразу же запрашивают общий кэш драйвера тем самым экономя память и ресурсы сервера. Иногда в зависимости от нагрузки драйвер присылает в БД статистику по использования кэша, которую потом можно будет посмотреть.
  60. Правила инвалидации клиентского кэша такие же как и для серверного, но гораздо интереснее посмотреть как это происходит в динамике. Есть 2 случая инвалидации. Первый – когда запросы идут часто и не наступил Invalidation lag. В таком случае поток пойдёт в базу данных, обновит кэши и считает данные из него.
  61. Ежели никаких запрос в период от прихода сообщения до Invalidation lag не было, то сам драйвер через Invalidation lag запросит список инвалидированных резалтсетов. Таким образом кэш обеспечивает самоподдерживаемость.
  62. Итак, посмотрим как надо сконфигурировать БД, чтобы заработал client side result cache. Всё весьма просто. Есть 2 параметра, которые мы уже упомянали. Посмотрим на примеры кода с использованием клиентского кэша.
  63. Вот пример кода на .net. Как мы видим в коде нет ничего такого, что включает клиентский кэш. Однажды активировав его на сервере мы на клиенте указываем уже известный хинт result_cache
  64. java
  65. Собственно после того как выполнено java-приложении можно посмотреть как оно использовало клиентский result cache. Это табличка, при отключении сессии записи удаляются Тут указан запрос для текущей сессии, но в целом надо искать по sid из session_connect_info. Почему Oracle не вынес это прямо в данную таблицу (а это таблица, а не view) я понять не смог. Именно поэтому я считаю, что этот функционал не очень востребован, хотя как мне кажется очень нужен.
  66. Достоинства, как всегда следуют из архитектуры. Дешёвая память Любые драйвера Минимальное изменение кода приложения Сильное уменьшение нагрузки на базу данных Отсутствие необходимости использовать дополнительные программные продукты для кэширования Минусы понятны Согласованность по чтению с задержкой Необходимость толстого клиента, решение от вендора, максимум 2 Гб на клиента и как-то подозрительно мало багов на саппорте (я нашел около пяти), что говорит о малом использовании в production. Или бы иначе никто не стал пользоваться кэширующим сервером Oracle Oracle coherence. Исходя из всех кейсов мы можем окончательно сформулировать плохие и хорошие сценарии для использования всех видов кэшей
  67. Первый случай – если после изменения данных кэш должен мгновенно стать неактуальным. Для самодельных кэшей тяжело создать корректную инвалидацию в случае изменения объектов, на которых они построены. Если использование хранимой в БД логики запрещено политиками разработки
  68. Если кэш будет наполнен множеством разных значений, то они не будут переиспользоваться. Например, кэш созданный по идентификаторам транзакций бесполезен по причине того, что транзакции не так часто ищутся. Все аналогичные запросы подвисают на время данного таймаута ожидая выполнения главного запроса Одновременный многопользовательский доступ провоцирует возникновение блокировок
  69. Первый случай – если после изменения данных кэш должен мгновенно стать неактуальным. Для самодельных кэшей тяжело создать корректную инвалидацию в случае изменения объектов, на которых они построены. Если использование хранимой в БД логики запрещено политиками разработки Есть команда разработки средней квалификации Уже используется много SQL без использования внешнего кэширующего слоя Есть ограничения по ресурсам сервера СУБД
  70. Оцените верно размер памяти с учётом количества запросов, а не количества результатов. Не бойтесь использовать auto-expiring. Он сохранит место удаляя неиспользуемое. Не перегружайте запросами во время загрузки больших объемов данных Прогревайте кэш Убедитесь, что _result_cache_timeout соответствует вашим ожиданиям НИКОГДА не используйте FORCE для БД Проверяйте, адекватно ли используется FORCE для таблиц Проверьте find count и убедитесь надо ли вам использовать result cache для адаптивной статистики
  71. I would like to tell thank you for you time and questions once again. Good luck in your projects.