The document discusses Oracle Database result caching. It provides an overview of database caches including the result cache. It then describes a hand-made result cache implementation for a retailer case study and how it improved performance from 20 minutes to 4 minutes for a report. It also discusses using the Oracle Database result cache explicitly with hints and annotations, how to monitor and manage it using views and packages, limitations, and best practices.
a striped down Version of a presentation about oracle architecture. Goal was a basic understanding and foundation about some components of Oracle, so subsequent discussions should be easier
It is no secret that for high-performance ETL processes, not only queries but also write operations should be parallelized.
But when you make use of it, is it simply "switch on and forget"? What do you have to consider? Can it also have negative effects?
After a short reminder on how it works (including space management methods), some patterns are presented that have been noticed in several ETL review and tuning projects and help to find the answers to the following questions:
What is the interaction between PDML and partitioning of the target table? Can PDML lead to increased fragmentation of the tablespace? Can you control it? How does the Hint PQ_DISTRIBUTE help? Do indexes on the target table have any influence?
Apache Spark is one of the most popular big data projects, offering greatly improved performance over traditional MapReduce models. Much of Apache Spark’s power comes from lazy evaluation along with intelligent pipelining, which can make debugging more challenging. Holden Karau and Joey Echeverria explore how to debug Apache Spark applications, the different options for logging in Spark’s variety of supported languages, and some common errors and how to detect them.
Spark’s own internal logging can often be quite verbose. Holden and Joey demonstrate how to effectively search logs from Apache Spark to spot common problems and discuss options for logging from within your program itself. Spark’s accumulators have gotten a bad rap because of how they interact in the event of cache misses or partial recomputes, but Holden and Joey look at how to effectively use Spark’s current accumulators for debugging before gazing into the future to see the data property type accumulators that may be coming to Spark in future versions. And in addition to reading logs and instrumenting your program with accumulators, Spark’s UI can be of great help for quickly detecting certain types of problems. Holden and Joey cover how to quickly use the UI to figure out if certain types of issues are occurring in your job.
The talk will wrap up with Holden trying to get everyone to buy several copies of her new book, High Performance Spark.
Trace File Analyzer - Usage and Features Sandesh Rao
TFA or Trace File Analyzer is an Oracle tool to collect , analyze and perform machine learning on Oracle log and other data sources. This presentation covers all the options which are available with the tool and is updated to the 18.3.0 version. This is a comprehensive deck for someone who also wants to acquaint themselves with TFA
Troubleshooting tips and tricks for Oracle Database Oct 2020Sandesh Rao
This talk presents 15 different tips and tricks using tools to better troubleshoot and debug problems with Database , Oracle RAC and Oracle Clusterware , ASM and how to get the right pieces of data with the least of commands which today most people do manually. This session will cover tools from the Oracle Autonomous Health Framework (AHF) like Trace file Analyzer (TFA) to collect , organize and analyze log data , Exachk and orachk to perform mass best practices analysis and automation , Cluster Health Advisor to debug node evictions and calibrate the framework , OSWatcher and its analysis engine , oratop for pinpointing performance issues and many others to make one feel like a rockstar DBA.
a striped down Version of a presentation about oracle architecture. Goal was a basic understanding and foundation about some components of Oracle, so subsequent discussions should be easier
It is no secret that for high-performance ETL processes, not only queries but also write operations should be parallelized.
But when you make use of it, is it simply "switch on and forget"? What do you have to consider? Can it also have negative effects?
After a short reminder on how it works (including space management methods), some patterns are presented that have been noticed in several ETL review and tuning projects and help to find the answers to the following questions:
What is the interaction between PDML and partitioning of the target table? Can PDML lead to increased fragmentation of the tablespace? Can you control it? How does the Hint PQ_DISTRIBUTE help? Do indexes on the target table have any influence?
Apache Spark is one of the most popular big data projects, offering greatly improved performance over traditional MapReduce models. Much of Apache Spark’s power comes from lazy evaluation along with intelligent pipelining, which can make debugging more challenging. Holden Karau and Joey Echeverria explore how to debug Apache Spark applications, the different options for logging in Spark’s variety of supported languages, and some common errors and how to detect them.
Spark’s own internal logging can often be quite verbose. Holden and Joey demonstrate how to effectively search logs from Apache Spark to spot common problems and discuss options for logging from within your program itself. Spark’s accumulators have gotten a bad rap because of how they interact in the event of cache misses or partial recomputes, but Holden and Joey look at how to effectively use Spark’s current accumulators for debugging before gazing into the future to see the data property type accumulators that may be coming to Spark in future versions. And in addition to reading logs and instrumenting your program with accumulators, Spark’s UI can be of great help for quickly detecting certain types of problems. Holden and Joey cover how to quickly use the UI to figure out if certain types of issues are occurring in your job.
The talk will wrap up with Holden trying to get everyone to buy several copies of her new book, High Performance Spark.
Trace File Analyzer - Usage and Features Sandesh Rao
TFA or Trace File Analyzer is an Oracle tool to collect , analyze and perform machine learning on Oracle log and other data sources. This presentation covers all the options which are available with the tool and is updated to the 18.3.0 version. This is a comprehensive deck for someone who also wants to acquaint themselves with TFA
Troubleshooting tips and tricks for Oracle Database Oct 2020Sandesh Rao
This talk presents 15 different tips and tricks using tools to better troubleshoot and debug problems with Database , Oracle RAC and Oracle Clusterware , ASM and how to get the right pieces of data with the least of commands which today most people do manually. This session will cover tools from the Oracle Autonomous Health Framework (AHF) like Trace file Analyzer (TFA) to collect , organize and analyze log data , Exachk and orachk to perform mass best practices analysis and automation , Cluster Health Advisor to debug node evictions and calibrate the framework , OSWatcher and its analysis engine , oratop for pinpointing performance issues and many others to make one feel like a rockstar DBA.
Any DBA from beginner to advanced level, who wants to fill in some gaps in his/her knowledge about Performance Tuning on an Oracle Database, will benefit from this workshop.
This presentation provides a clear overview of how Oracle Database In-Memory optimizes both analytics and mixed workloads, delivering outstanding performance while supporting real-time analytics, business intelligence, and reporting. It provides details on what you can expect from Database In-Memory in both Oracle Database 12.1.0.2 and 12.2.
The Deadlock Problem
System Model
Deadlock Characterization
Methods for Handling Deadlocks
Deadlock Prevention
Deadlock Avoidance
Deadlock Detection
Recovery from Deadlock
Deep Dive with Spark Streaming - Tathagata Das - Spark Meetup 2013-06-17spark-project
Slides from Tathagata Das's talk at the Spark Meetup entitled "Deep Dive with Spark Streaming" on June 17, 2013 in Sunnyvale California at Plug and Play. Tathagata Das is the lead developer on Spark Streaming and a PhD student in computer science in the UC Berkeley AMPLab.
Oracle Real Application Clusters (RAC) Roadmap for New Features describes and discusses best practices for new features introduced with Oracle RAC 12c as well as Oracle RAC 18c and provides a short outlook of the road ahead.
Building a fully managed stream processing platform on Flink at scale for Lin...Flink Forward
Apache Flink is a distributed stream processing framework that allows users to process and analyze data in real-time. At LinkedIn, we developed a fully managed stream processing platform on Flink running on K8s to power hundreds of stream processing pipelines in production. This platform is the backbone for other infra systems like Search, Espresso (internal document store) and feature management etc. We provide a rich authoring and testing environment which allows users to create, test, and deploy their streaming jobs in a self-serve fashion within minutes. Users can focus on their business logic, leaving the Flink platform to take care of management aspects such as split deployment, resource provisioning, auto-scaling, job monitoring, alerting, failure recovery and much more. In this talk, we will introduce the overall platform architecture, highlight the unique value propositions that it brings to stream processing at LinkedIn and share the experiences and lessons we have learned.
Session aims at introducing less familiar audience to the Oracle database statistics concept, why statistics are necessary and how the Oracle Cost-Based Optimizer uses them
Dr. Elephant for Monitoring and Tuning Apache Spark Jobs on Hadoop with Carl ...Databricks
Dr. Elephant helps improve Spark and Hadoop developer productivity and increase cluster efficiency by making clear recommendations on how to tune workloads and configurations. Originally developed by LinkedIn, Dr. Elephant is now in use at multiple sites.
This session will explore how Dr. Elephant works, the data it collects from Spark environments and the customizable heuristics that generate tuning recommendations. Learn how Dr. Elephant can be used to improve production cluster operations, help developers avoid common issues, and green light applications for use on production clusters.
The Top 5 Reasons to Deploy Your Applications on Oracle RACMarkus Michalewicz
A presentation for developers, DBAs, and managers. This presentation was first presented in course of the AIOUG Maximum Availability Architecture (MAA)-focus month August 2021. The first reason might surprise you!
100500 способов кэширования в Oracle Database или как достичь максимальной ск...Ontico
HighLoad++ 2017
Зал «Рио-де-Жанейро», 8 ноября, 14:00
Тезисы:
http://www.highload.ru/2017/abstracts/2913.html
Изначально будут раскрыты базовые причины, которые заставили появиться такой части механизма СУБД, как кэш результатов, и почему в ряде СУБД он есть или отсутствует.
Будут рассмотрены различные варианты кэширования результатов как sql-запросов, так и результатов хранимой в БД бизнес-логики. Произведено сравнение способов кэширования (программируемые вручную кэши, стандартный функционал) и даны рекомендации, когда и в каких случаях данные способы оптимальны, а порой опасны.
...
Изначально будут раскрыты базовые причины, которые заставили появиться такой части механизма СУБД, как кэш результатов, и почему в ряде СУБД он есть или отсутствует.
Будут рассмотрены различные варианты кэширования результатов как sql-запросов, так и результатов хранимой в БД бизнес-логики. Произведено сравнение способов кэширования (программируемые вручную кэши, стандартный функционал) и даны рекомендации, когда и в каких случаях данные способы оптимальны, а порой опасны.
Для каждой из рекомендаций будут продемонстрированы как положительные так и отрицательные кейсы из опыта production-эксплуатации реальных систем, где используются разные варианты кэшей
Any DBA from beginner to advanced level, who wants to fill in some gaps in his/her knowledge about Performance Tuning on an Oracle Database, will benefit from this workshop.
This presentation provides a clear overview of how Oracle Database In-Memory optimizes both analytics and mixed workloads, delivering outstanding performance while supporting real-time analytics, business intelligence, and reporting. It provides details on what you can expect from Database In-Memory in both Oracle Database 12.1.0.2 and 12.2.
The Deadlock Problem
System Model
Deadlock Characterization
Methods for Handling Deadlocks
Deadlock Prevention
Deadlock Avoidance
Deadlock Detection
Recovery from Deadlock
Deep Dive with Spark Streaming - Tathagata Das - Spark Meetup 2013-06-17spark-project
Slides from Tathagata Das's talk at the Spark Meetup entitled "Deep Dive with Spark Streaming" on June 17, 2013 in Sunnyvale California at Plug and Play. Tathagata Das is the lead developer on Spark Streaming and a PhD student in computer science in the UC Berkeley AMPLab.
Oracle Real Application Clusters (RAC) Roadmap for New Features describes and discusses best practices for new features introduced with Oracle RAC 12c as well as Oracle RAC 18c and provides a short outlook of the road ahead.
Building a fully managed stream processing platform on Flink at scale for Lin...Flink Forward
Apache Flink is a distributed stream processing framework that allows users to process and analyze data in real-time. At LinkedIn, we developed a fully managed stream processing platform on Flink running on K8s to power hundreds of stream processing pipelines in production. This platform is the backbone for other infra systems like Search, Espresso (internal document store) and feature management etc. We provide a rich authoring and testing environment which allows users to create, test, and deploy their streaming jobs in a self-serve fashion within minutes. Users can focus on their business logic, leaving the Flink platform to take care of management aspects such as split deployment, resource provisioning, auto-scaling, job monitoring, alerting, failure recovery and much more. In this talk, we will introduce the overall platform architecture, highlight the unique value propositions that it brings to stream processing at LinkedIn and share the experiences and lessons we have learned.
Session aims at introducing less familiar audience to the Oracle database statistics concept, why statistics are necessary and how the Oracle Cost-Based Optimizer uses them
Dr. Elephant for Monitoring and Tuning Apache Spark Jobs on Hadoop with Carl ...Databricks
Dr. Elephant helps improve Spark and Hadoop developer productivity and increase cluster efficiency by making clear recommendations on how to tune workloads and configurations. Originally developed by LinkedIn, Dr. Elephant is now in use at multiple sites.
This session will explore how Dr. Elephant works, the data it collects from Spark environments and the customizable heuristics that generate tuning recommendations. Learn how Dr. Elephant can be used to improve production cluster operations, help developers avoid common issues, and green light applications for use on production clusters.
The Top 5 Reasons to Deploy Your Applications on Oracle RACMarkus Michalewicz
A presentation for developers, DBAs, and managers. This presentation was first presented in course of the AIOUG Maximum Availability Architecture (MAA)-focus month August 2021. The first reason might surprise you!
100500 способов кэширования в Oracle Database или как достичь максимальной ск...Ontico
HighLoad++ 2017
Зал «Рио-де-Жанейро», 8 ноября, 14:00
Тезисы:
http://www.highload.ru/2017/abstracts/2913.html
Изначально будут раскрыты базовые причины, которые заставили появиться такой части механизма СУБД, как кэш результатов, и почему в ряде СУБД он есть или отсутствует.
Будут рассмотрены различные варианты кэширования результатов как sql-запросов, так и результатов хранимой в БД бизнес-логики. Произведено сравнение способов кэширования (программируемые вручную кэши, стандартный функционал) и даны рекомендации, когда и в каких случаях данные способы оптимальны, а порой опасны.
...
Изначально будут раскрыты базовые причины, которые заставили появиться такой части механизма СУБД, как кэш результатов, и почему в ряде СУБД он есть или отсутствует.
Будут рассмотрены различные варианты кэширования результатов как sql-запросов, так и результатов хранимой в БД бизнес-логики. Произведено сравнение способов кэширования (программируемые вручную кэши, стандартный функционал) и даны рекомендации, когда и в каких случаях данные способы оптимальны, а порой опасны.
Для каждой из рекомендаций будут продемонстрированы как положительные так и отрицательные кейсы из опыта production-эксплуатации реальных систем, где используются разные варианты кэшей
SQL Server Wait Types Everyone Should KnowDean Richards
Many people use wait types for performance tuning, but do not know what some of the most common ones indicate. This presentation will go into details about the top 8 wait types I see at the customers I work with. It will provide wait descriptions as well as solutions.
Investigate SQL Server Memory Like Sherlock HolmesRichard Douglas
Memory is one part of the holy trinity of resources consumed by SQL Server, the others being CPU and disk. Most people know how to look at disk latency and throughput and then take remedial measures to fix those issues. But what about memory issues?
In this session, you will learn how SQL Server uses memory and various caches, how to gauge memory pressure, and how to address the significant problems it can cause.
You will leave with a much clearer understanding of how to monitor and manage memory consumption within SQL Server using native Dynamic Management Objects.
Top 5 things to know about sql azure for developersIke Ellis
Databases in the cloud are a brave new world. This presentation will show up the issues with migrating your application to SQL Azure and how to address them.
Datadog: a Real-Time Metrics Database for One Quadrillion Points/DayC4Media
Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/2mAKgJi.
Ian Nowland and Joel Barciauskas talk about the challenges Datadog faces as the company has grown its real-time metrics systems that collect, process, and visualize data to the point they now handle trillions of points per day. They also talk about how the architecture has evolved, and what they are looking to in the future as they architect for a quadrillion points per day. Filmed at qconnewyork.com.
Ian Nowland is the VP Engineering Metrics and Alerting at Datadog. Joel Barciauskas currently leads Datadog's distribution metrics team, providing accurate, low latency percentile measures for customers across their infrastructure.
Geek Sync I Need for Speed: In-Memory Databases in Oracle and SQL ServerIDERA Software
You can watch the replay for this Geek Sync webcast in the IDERA Resource Center: http://ow.ly/S6MG50A5ok5
Microsoft introduced IN-MEMORY OLTP, widely referred to as “Hekaton” in SQL Server 2014. Hekaton allows for the creation of fully transactionally consistent memory-resident tables designed for high concurrency and no blocking. With SQL 2016, many of the original restrictions and limitations of this feature have been reduced. IDERA’s Vicky Harp will give an overview of this feature, including how to compile T-SQL code into machine code for an even greater performance boost.
There’s also been a lot of buzz about Oracle 12c’s new IN-MEMORY COLUMN STORE. Oracle ACE Bert Scalzo will cover this new feature, how it works, it’s benefits, scripts to measure/monitor it and more. He will also touch on performance observations from benchmarking this new feature against more traditional SGA memory allocations plus Oracle 11g R2’s Database Smart Flash Cache. All findings, scripts and conclusions from this exercise will be shared. In addition, two very popular database benchmarking tools will be highlighted.
This is the presentation on ASH that I did with Graham Wood at RMOUG 2014 and that represents the final best effort to capture essential and advanced ASH content as started in a presentation Uri Shaft and I gave at a small conference in Denmark sometime in 2012 perhaps. The presentation is also available publicly through the RMOUG website, so I felt at liberty to post it myself here. If it disappears it would likely be because I have been asked to remove it by Oracle.
OracleStore: A Highly Performant RawStore Implementation for Hive MetastoreDataWorks Summit
Today, Yahoo! uses Hive in many different spaces, from ETL pipelines to adhoc user queries. Increasingly, we are investigating the practicality of applying Hive to real-time queries, such as those generated by interactive BI reporting systems. In order for Hive to succeed in this space, it must be performant in all aspects of query execution, from query compilation to job execution. One such component is the interaction with the underlying database at the core of the Metastore.
As an alternative to ObjectStore, we created OracleStore as a proof-of-concept. Freed of the restrictions imposed by DataNucleus, we were able to design a more performant database schema that better met our needs. Then, we implemented OracleStore with specific goals built-in from the start, such as ensuring the deduplication of data.
In this talk we will discuss the details behind OracleStore and the gains that were realized with this alternative implementation. These include a reduction of 97%+ in the storage footprint of multiple tables, as well as query performance that is 13x faster than ObjectStore with DirectSQL and 46x faster than ObjectStore without DirectSQL.
Sql server performance tuning and optimizationManish Rawat
Sql server performance tuning and optimization
SQL Server Concepts/Structure
Performance Measuring & Troubleshooting Tools
Locking
Performance Problem : CPU
Performance Problem : Memory
Performance Problem : I/O
Performance Problem : Blocking
Query Tuning
Indexing
The presentation explains how to setup rate limits, how to work with 429 code, how rate limits are implemented in kubernetes, cni, loadbalancer and so on
the presentation is about federated GraphQL in huge enterprises. I explain why and what for big enterprises need distributed GraphQL and classic one does not work.
The majority of cloud-based DWH provides a wide range of migration tools from in-house DWH. However, I believe that cloud migration success is based not only on reducing infrastructure maintenance costs, but also on additional performance profit inherited from tailored data model.
I am going to prove that copying star or snowflake schemas as is will not lead to maximum performance boost in such DWH as Amazon Redshift and Google BigQuery. Moreover, this approach may cause additional cloud expenses.
We will discuss why data models should be different for each particular database, and how to get maximum performance from database peculiarities.
Most of performance tuning techniques for cloud-based DWH are about adding extra nodes to cluster, but it may lead to performance degradation in some cases, as well as extra costs burden. Sometimes, this approach allows to get maximum speed from current hardware configuration, may be even less expensive servers.
I will show some examples from production projects with extra performance using lower hardware, and edge cases like huge wide fact table with fully denormalized dimensions instead of classical star schema.
the presentation describes a lot of very technical details about row level security, possibble security breaches in relational databases like Oracle and Postgres. A lot of examples how to protect data is shown.
The presentation describes various options for implementing row-level security in enterprise applications: database side, application server side, mixed approaches. we consider oracle virtual private database, different encription options and possible security breaches and their mitigation path.
Oracle JSON treatment evolution - from 12.1 to 18 AOUG-2018Alexander Tokarev
The presentation was prepared for Austria Oracle User group 30 years. It tells us a lot of challenges which Oracle developers face with implementing high-load json processing pipelines.
The presentation describes how to design robust solution for tagging search, how to use tagging for faceted search. Various architecture and data patterns are considered. We discuss relational databases like Oracle, full text search servers like Apache Solr. We will see how Oracle 18c features permit to use embedded faceted search.
The presentation is a deep analysis of Oracle JSON treatment feauture. It is considered to real-life experience and workarounds to defeat known json errors.
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Mind IT Systems
Healthcare providers often struggle with the complexities of chronic conditions and remote patient monitoring, as each patient requires personalized care and ongoing monitoring. Off-the-shelf solutions may not meet these diverse needs, leading to inefficiencies and gaps in care. It’s here, custom healthcare software offers a tailored solution, ensuring improved care and effectiveness.
Atelier - Innover avec l’IA Générative et les graphes de connaissancesNeo4j
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Allez au-delà du battage médiatique autour de l’IA et découvrez des techniques pratiques pour utiliser l’IA de manière responsable à travers les données de votre organisation. Explorez comment utiliser les graphes de connaissances pour augmenter la précision, la transparence et la capacité d’explication dans les systèmes d’IA générative. Vous partirez avec une expérience pratique combinant les relations entre les données et les LLM pour apporter du contexte spécifique à votre domaine et améliorer votre raisonnement.
Amenez votre ordinateur portable et nous vous guiderons sur la mise en place de votre propre pile d’IA générative, en vous fournissant des exemples pratiques et codés pour démarrer en quelques minutes.
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Łukasz Chruściel
No one wants their application to drag like a car stuck in the slow lane! Yet it’s all too common to encounter bumpy, pothole-filled solutions that slow the speed of any application. Symfony apps are not an exception.
In this talk, I will take you for a spin around the performance racetrack. We’ll explore common pitfalls - those hidden potholes on your application that can cause unexpected slowdowns. Learn how to spot these performance bumps early, and more importantly, how to navigate around them to keep your application running at top speed.
We will focus in particular on tuning your engine at the application level, making the right adjustments to ensure that your system responds like a well-oiled, high-performance race car.
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteGoogle
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-pilot-review/
AI Pilot Review: Key Features
✅Deploy AI expert bots in Any Niche With Just A Click
✅With one keyword, generate complete funnels, websites, landing pages, and more.
✅More than 85 AI features are included in the AI pilot.
✅No setup or configuration; use your voice (like Siri) to do whatever you want.
✅You Can Use AI Pilot To Create your version of AI Pilot And Charge People For It…
✅ZERO Manual Work With AI Pilot. Never write, Design, Or Code Again.
✅ZERO Limits On Features Or Usages
✅Use Our AI-powered Traffic To Get Hundreds Of Customers
✅No Complicated Setup: Get Up And Running In 2 Minutes
✅99.99% Up-Time Guaranteed
✅30 Days Money-Back Guarantee
✅ZERO Upfront Cost
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
Utilocate offers a comprehensive solution for locate ticket management by automating and streamlining the entire process. By integrating with Geospatial Information Systems (GIS), it provides accurate mapping and visualization of utility locations, enhancing decision-making and reducing the risk of errors. The system's advanced data analytics tools help identify trends, predict potential issues, and optimize resource allocation, making the locate ticket management process smarter and more efficient. Additionally, automated ticket management ensures consistency and reduces human error, while real-time notifications keep all relevant personnel informed and ready to respond promptly.
The system's ability to streamline workflows and automate ticket routing significantly reduces the time taken to process each ticket, making the process faster and more efficient. Mobile access allows field technicians to update ticket information on the go, ensuring that the latest information is always available and accelerating the locate process. Overall, Utilocate not only enhances the efficiency and accuracy of locate ticket management but also improves safety by minimizing the risk of utility damage through precise and timely locates.
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeAftab Hussain
Understanding variable roles in code has been found to be helpful by students
in learning programming -- could variable roles help deep neural models in
performing coding tasks? We do an exploratory study.
- These are slides of the talk given at InteNSE'23: The 1st International Workshop on Interpretability and Robustness in Neural Software Engineering, co-located with the 45th International Conference on Software Engineering, ICSE 2023, Melbourne Australia
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
Launch Your Streaming Platforms in MinutesRoshan Dwivedi
The claim of launching a streaming platform in minutes might be a bit of an exaggeration, but there are services that can significantly streamline the process. Here's a breakdown:
Pros of Speedy Streaming Platform Launch Services:
No coding required: These services often use drag-and-drop interfaces or pre-built templates, eliminating the need for programming knowledge.
Faster setup: Compared to building from scratch, these platforms can get you up and running much quicker.
All-in-one solutions: Many services offer features like content management systems (CMS), video players, and monetization tools, reducing the need for multiple integrations.
Things to Consider:
Limited customization: These platforms may offer less flexibility in design and functionality compared to custom-built solutions.
Scalability: As your audience grows, you might need to upgrade to a more robust platform or encounter limitations with the "quick launch" option.
Features: Carefully evaluate which features are included and if they meet your specific needs (e.g., live streaming, subscription options).
Examples of Services for Launching Streaming Platforms:
Muvi [muvi com]
Uscreen [usencreen tv]
Alternatives to Consider:
Existing Streaming platforms: Platforms like YouTube or Twitch might be suitable for basic streaming needs, though monetization options might be limited.
Custom Development: While more time-consuming, custom development offers the most control and flexibility for your platform.
Overall, launching a streaming platform in minutes might not be entirely realistic, but these services can significantly speed up the process compared to building from scratch. Carefully consider your needs and budget when choosing the best option for you.
Mobile App Development Company In Noida | Drona InfotechDrona Infotech
Looking for a reliable mobile app development company in Noida? Look no further than Drona Infotech. We specialize in creating customized apps for your business needs.
Visit Us For : https://www.dronainfotech.com/mobile-application-development/
Software Engineering, Software Consulting, Tech Lead, Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Transaction, Spring MVC, OpenShift Cloud Platform, Kafka, REST, SOAP, LLD & HLD.
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
Artificia Intellicence and XPath Extension FunctionsOctavian Nadolu
The purpose of this presentation is to provide an overview of how you can use AI from XSLT, XQuery, Schematron, or XML Refactoring operations, the potential benefits of using AI, and some of the challenges we face.
Graspan: A Big Data System for Big Code AnalysisAftab Hussain
We built a disk-based parallel graph system, Graspan, that uses a novel edge-pair centric computation model to compute dynamic transitive closures on very large program graphs.
We implement context-sensitive pointer/alias and dataflow analyses on Graspan. An evaluation of these analyses on large codebases such as Linux shows that their Graspan implementations scale to millions of lines of code and are much simpler than their original implementations.
These analyses were used to augment the existing checkers; these augmented checkers found 132 new NULL pointer bugs and 1308 unnecessary NULL tests in Linux 4.4.0-rc5, PostgreSQL 8.3.9, and Apache httpd 2.2.18.
- Accepted in ASPLOS ‘17, Xi’an, China.
- Featured in the tutorial, Systemized Program Analyses: A Big Data Perspective on Static Analysis Scalability, ASPLOS ‘17.
- Invited for presentation at SoCal PLS ‘16.
- Invited for poster presentation at PLDI SRC ‘16.
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppGoogle
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-fusion-buddy-review
AI Fusion Buddy Review: Key Features
✅Create Stunning AI App Suite Fully Powered By Google's Latest AI technology, Gemini
✅Use Gemini to Build high-converting Converting Sales Video Scripts, ad copies, Trending Articles, blogs, etc.100% unique!
✅Create Ultra-HD graphics with a single keyword or phrase that commands 10x eyeballs!
✅Fully automated AI articles bulk generation!
✅Auto-post or schedule stunning AI content across all your accounts at once—WordPress, Facebook, LinkedIn, Blogger, and more.
✅With one keyword or URL, generate complete websites, landing pages, and more…
✅Automatically create & sell AI content, graphics, websites, landing pages, & all that gets you paid non-stop 24*7.
✅Pre-built High-Converting 100+ website Templates and 2000+ graphic templates logos, banners, and thumbnail images in Trending Niches.
✅Say goodbye to wasting time logging into multiple Chat GPT & AI Apps once & for all!
✅Save over $5000 per year and kick out dependency on third parties completely!
✅Brand New App: Not available anywhere else!
✅ Beginner-friendly!
✅ZERO upfront cost or any extra expenses
✅Risk-Free: 30-Day Money-Back Guarantee!
✅Commercial License included!
See My Other Reviews Article:
(1) AI Genie Review: https://sumonreview.com/ai-genie-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
#AIFusionBuddyReview,
#AIFusionBuddyFeatures,
#AIFusionBuddyPricing,
#AIFusionBuddyProsandCons,
#AIFusionBuddyTutorial,
#AIFusionBuddyUserExperience
#AIFusionBuddyforBeginners,
#AIFusionBuddyBenefits,
#AIFusionBuddyComparison,
#AIFusionBuddyInstallation,
#AIFusionBuddyRefundPolicy,
#AIFusionBuddyDemo,
#AIFusionBuddyMaintenanceFees,
#AIFusionBuddyNewbieFriendly,
#WhatIsAIFusionBuddy?,
#HowDoesAIFusionBuddyWorks
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
1. 100500 способов
кэширования в Oracle
Database или как достичь
максимальной скорости
обработки запросов
минимальной ценой
DataArt experience
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
5. Database caches
• Buffer cache – cache for data pages/data blocks
• Statement cache – cache of queries plan
• Result cache – rows from queries
• OS cache
6. 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
7. 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;
9. 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
12. Case 2 Recommendation engine
Oracle
main
Oracle
DG
Application
server
Application
server
Load
balancer
Client
browser
400 users
1000
requests
per
second
Hazelcast
13. 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. Parameter length – 100 letter.
max 10 users
14. Case 2 Recommendation engine
1. Recommendations work slow – 5 minutes for 1 document
2. To risky to change JAVA
15. 1. Do not use any cache to not care about expiration
2. Use purchased Oracle options of customer
3. Use “in-Memory for beggars” - KEEP pool for full text search
16. 1. Table with recommendations was too big
2. New DR$ tables in case of frequent index setting changes
3. KEEP pool warming is complicated (iot, lob, small table threshold, etc.)
4. DBA was reluctant to extra pool management, warming stored
procedure, additional permissions
5. Performance gain was not enough – 90 seconds per document
17. 1. Table with recommendations was too big
2. New DR$ tables in case of frequent index setting changes
3. KEEP pool warming is complicated (iot, lob, small table threshold, etc.)
4. DBA was reluctant to extra pool management, warming stored
procedure, additional permissions
5. Performance gain was not enough – 90 seconds per document
18. 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
19. 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
20. Result Cache Way 1
ID of result
First execution Second execution
32. 1. SELECT FOR UPDATE + COMMIT statements even there were no
changes at all:
- no DML statement were issued
- DML updated 0 rows
2. Update/delete statements in a table under result cache with no
records affected + an update to any table where rows were affected +
COMMIT.
SQL Result Cache Unexpected Invalidation
WTF!!!
33. SQL Result Cache Unexpected Invalidation
3. An unindexed foreign key + delete/update/insert a record from
parent table
4. Changes in an arbitrary partition even if a RC query deals with a
different single partition data. Table level tracking only.
40. 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
Performance is tested. Document recognition – 30 seconds.
Time for production
41. 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.
42. Case 2 Recommendation engine
• Active user count: 40
• Row count: 300
• Columns count: 5-8
• Parameter length: 300
• Database active session count: 120 = 40 * 3
X5 more!
43. 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
44. 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
46. Case 2 Recommendation engine Investigations
Strange queries for 40 small tables each minute:
ETL
47. Case 2 Recommendation engine Investigations
Result cache annotation
Still 20 minutes per document
48. 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!!!
49. Result cache latches
Latches are Oracle-internal low-level locks that protect the memory
structures of the system global area (SGA) against simultaneous
accesses.
51. 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. Result cache bypassed after timeout.
52. 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
53. 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.
54. 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
55. 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
59. 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!!!
60. 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
61. Case 2 Recommendation engine
1. Materialize recommendations
2. Refresh on hourly basis
62. 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
63. Case 2 Recommendation engine Auto-expiring
SHELFLIFE = read-consistent result life time in seconds
SNAPSHOT = NON-read-consistent result life time in seconds
68. 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
69. 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%‘
72. 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
74. 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
3. Не проверено исчезновение ошибки после накатов патчей
75. We are not alone
Result_cache_max_size /*+ result_cache*/ removed or
dbms_result_cache.add_to_black_list or
/*+ no_result_cache*/
81. 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);
82. 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
83. 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
84. 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
85. 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
88. 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
89. 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
- Overrides server result cache
90. 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
91. 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
92. 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
93. Conclusion
1. Estimate memory size properly:
volume (Mb) = (
number of result rows * block size+
avg number of apex/scheduler usage +
avg number adaptive statistic usage
)
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
Добрый день. Меня зовут Александр и я занимаюсь в компании DataArt вопросами, связаными с базами данных как в части построения систем «с нуля», так и оптимизации имеющихся.
Сегодня я представлю вам переработанную версию моего доклада с Higload-2017, посвященную различным кэшам в оракле. В ней будет ещё более технического трэша и боли.
Итак, полетели!
Итак, у нас сегодня штатная презентация по архитектуре очередного решения от СУБД Oracle для ускорения данных.
Сегодня я буду рассказывать многих важных вещах таких как...
Хотя не, слишком скучно.
Ценность данной конференции в том, что тут рассказывается не о технических деталях, которые можно найти в google, а о практическим примерах их использования и их нюансах
В данном докладе я буду рассказывать как устроена технология server side Result cache и чем она лучше чем самодельное кэширование на plsql на примерах двух проектов Компании DataArt. Далее мы подытожим результаты этих проектов и выработаем некие подходы к правильной работе с данной технологией. Так же очень поверхностно посмотрим, что могут предложить другие СУБД относительно кэширования результатов запросов.
Вооруженные набором знаний мы попробуем понять причины сбоя в российской cloud системе расчёта лояльности, который имел недавно место быть по причине того самого result cache.
У Оракла есть client side result cache, я поверхностно расскажу об его архитектуре, но без детализации – он сам по-себе тема отдельного доклада.
Есть 3 основных вида кэшей в базах данных: кэш данных, кэш операторов и их планов и кэш результатов строк. Интересно заметить, что последний пункт из известных мне БД остался только в Oracle. В postgress result cache нет. Он присутствует только в стороннем продукте pgpool. Это связано с некими сложностями, которые мы рассмотрим ниже.
Итак. Кейс 1. Хранилище ретейлера.
Было хранилище и в нём был отчёт. Получение его занимало около 20 минут и пользователи печалились. В чем была интрига данного отчёта? В нём на 5000 строк данных было 350 уникальных товаров, но для каждой строчки вызывалась функция получения информациии по товару. Функция по коду была довольно сложная, тяжело поддающаяся рефакторингу и многие вещи в ней было просто боязно переписывать. Так как система находилась на поддержке, то использовать что-то новое типа embedded result cache было запрещено, поэтому был использован стандартный подход с hand-made кэшированием.
Итак, мы переименовали долгую функцию, а вместо нее создали пакет и функцию, которая использует ассоциативный массив в данном пакете. Данный массив это фактически on demand cache. Если в нём данных нет, то происходит вызов функции.
Важно понимать, в какой из областей памяти расположены коллекции. Помещаются они в области памяти, которая называется PGA, выделяемой под каждую сессию. Именно это определяет их достоинства и недостатки.
Итак, самодельные кэши.
Плюсы очевидны: легко запрограммировать, никакой конфигурации, нет необходимости думать о синхронизации, да они просто быстрые!
Минусы тоже понятны: если в проекте запрещена хранимая логика их невозможно использовать, нет механизма автоматической инвалидации и так как память на кэш выделяется в рамках одной сессии БД, а не экземпляра, то её потребление завышено. Более того, в случае с вариантом использования connection pool необходимо не забывать сбрасывать кэши если для каждой сессии кэширование должно быть разное.
Существуют ещё другие варианты hand-made кэшей на основе materialized views, temporary tables, но от них идёт бОльшая нагрузка на систему ввода-вывода, поэтому они не рассматриваются в данной презентации. Они более склонны для других баз данных. Варианты с oracle client cache и scalar subquery caching я тоже не рассказываю, так как по ним мало эффектных кейсов, но после доклада готов рассказать.
Рассмотрим как часто решают задау кэширования в MsSQL для получения списка сопутствующих товаров.
Таблицу GetRelatedItems пересчитывают, например, периодическим заданием или перед началом работы с соответствующим куском функционала. Если в ней данных нет, обращаются к сложному view.
В целом, подход относительно похож, но работает не в памяти БД как в части получения данных, так и первичного заполнения, засчёт этого может быть медленнее.
В общем, самодельные result cache активно используются, но иным подходом к реализации данной задачи является in-database result cache. Его и как не получилось quick win мы рассмотрим далее...
Теперь рассмотрим второй кейс. Это система полуавтоматизированной обработки финансовой документации. Архитектура системы стандартна для Enterprise. Клиент, балансировщик, 2 сервера приложений для расчёта бизнес-логики, база данных Oracle и её резервный экземляр.
Одной из множества задач является задача коррекции документов после их автоматического распознавания.
Упрощённо говоря она выглядит так
Есть документы, для каждого нераспознанного автоматически системой показателя предлагается набор показателей либо из предыдущих документов клиента, либо из похожей индустрии, либо по похожей доходности, при этом ещё сравнивает с распознанным значением, чтобы не предложить лишнее. Что важно документы многоязычные.
Пользователь выбирает нужное значение и повторяет для каждой пустой строчки.
Важно отметить, что показатели повторяются как в строках, так и столбцах.
В целом задача по
1 неделя до релиза
На обработку документа уходит минимум 5 минут
Java код менять нельзя
В команду разработки баз данных приходят с просьбой о помощи
1 неделя до релиза
На обработку документа уходит минимум 5 минут
Java код менять нельзя
В команду разработки баз данных приходят с просьбой о помощи
Таблица с рекомендациями слишком большая
Мы ещё не чётко понимали как устроены индексы и появлялись новые DR$ таблицы
Процедура первичного прогрева оказалась непростой, так как требовалось учитывать кучу нюансов
Активное сопротивление со стороны DBA заказчика по причине появления новой процедуры, которую надо было запускать после деплоя или рестарта инстанса, дополнительных грантов и так далее
Но самое главное – разница в скорости всего в 2 раза
На самом деле сейчас мы уже научились всё это готовить и в других задачах используем этот подход
Но так как это не кэш то я детально останавливаться не буду. Возможно, я успею рассказать про это, когда буду рассказывать про json.
Таблица с рекомендациями слишком большая
Мы ещё не чётко понимали как устроены индексы и появлялись новые DR$ таблицы
Процедура первичного прогрева оказалась непростой, так как требовалось учитывать кучу нюансов
Активное сопротивление со стороны DBA заказчика по причине появления новой процедуры, которую надо было запускать после деплоя или рестарта инстанса, дополнительных грантов и так далее
Но самое главное – разница в скорости всего в 2 раза
На самом деле сейчас мы уже научились всё это готовить и в других задачах используем этот подход
Но так как это не кэш то я детально останавливаться не буду. Возможно, я успею рассказать про это, когда буду рассказывать про json.
Принимаем решение использовать базу данных и Oracle Result cache так как
Возможности по оптимизации исчерпаны
Параметры активно повторяются
Данные рекомендаций редко обновляются, так как используют полнотекстовый индекс
Что такое result cache. Это технология от Oracle по кэшИированию результатов с минимальным влиянием на приложение.
Как же всё это выглядит. По-факту он включается указанием инструкции result_cache. На втором выполнении видно, что никаких операций с базой данных не происходит. Всё получается из кэша. Как мы видим изменения минимальны.
Есть второй способ, а именно аннотации. Они включают result_cache для таблицы если она участвует в запросе.
Как вы думаете, что будет, если в запросе 2 таблицы и только на одной из них аннотация?
Если хоть одна из таблиц без аннотации, то result_cache исчезает.
Если все с ним, то весь запрос кэшируется.
Для SQL зависимости определяются через план запроса, что весьма забавно, так как Oracle может преобразовывать запрос выкидывая ненужные таблицы из запроса и их не окажется в списке зависимостей. Например, в запросе на слайде применена трансформация join elimination из-за того, что есть FK и таблицы нет в зависимостях.
Убираем constraint и Oracle пересчитывает дерево зависимостей. Для plsql кода зависимости определяются в run-time. Это позволяет делать даже dependency tracking для динамического sql и сложной условной логики.
Оракл позволяет кэшировать результаты не только всего запроса целиком, но и его части. Это либо inline view как в виде with.
Так и в виде from.
Более того, можно создать кэшированное view. Например, в джоине таблица прочиталась как обычно, а вью было взято из кэша результатов. Как только появляется result_cache view становится non-mergable и оптимизатор не делает соответствующих трансформаций.
Итак, посмотрим когда же Оракл инвалидирует result cache.
Видно, что если в рамках своей сессии произошли изменения, то кэш игнорируется именно в этой сессии. Другие сессии продолжают использовать сохранённый результат. Как только происходит операция commit и другие сессии ожидают нового результата.
Итак, посмотрим когда же Оракл инвалидирует result cache.
Видно, что если в рамках своей сессии произошли изменения, то кэш игнорируется именно в этой сессии. Другие сессии продолжают использовать сохранённый результат. Как только происходит операция commit и другие сессии ожидают нового результата.
Как только мы подтверждаем наши изменения они становятся неактуальными для других сессий
К сожалению, не все так гладко. Oracle производит инвалидации и в ряде неочевидных случаев.
1. При любом вызове select for update
2. Неудачный апдейт по основной таблице и удачный по другойs tatement (Bug 26964029 : RESULT CACHE INVALIDATED EVEN THOUGH UPDATE ZERO ROWS)
2. Если в вашей таблице есть неиндексированый внешний ключ и в его родительской таблице произошло изменение данных. Это произойдёт даже если родительская таблица не упомянута в запросе.
Выглядит, что на самом деле обновление учитывает факт наличия блокироки, факт попытки апдейта и количество задействованных строк отличное от нуля, причём всё равно в какой из таблиц.
Итак, Вы наверное соскучались. Небольшая загадка. Почему для одинаковых параметров в PL/SQL могут происходить инвалидации?
Когда exception вырывается наружу, будь то
отсутствие блока обработки исключения
Явный эксепшн
Функция, в случае exception, не возвращающая результаты
Т.е. В данном случае я вызывал одну и ту же функцию с одинаковым набором параметров несколько раз
Есть только один способ побороть лишние объекты в Oracle 12.1 и 12.2 – возвращать значения.
Официальный фикс запланирован в 18с в котором будут так называемые Bypass object для таких ситуаций.
Имеющиеся патчи были печальны, но наконец то появилось что-то адекватное.
Ну что, не устали? Готовы вернуться к тому, что начали? Не забыли ещё наше распознавание документов?
Самое сложное найти нужный патч, так как на самом деле обещают фикс в 18-й версии.
Имеющиеся патчи были печальны, но наконец то появилось что-то адекватное.
Ну что, не устали? Готовы вернуться к тому, что начали? Не забыли ещё наше распознавание документов?
Итак, мы изучили всё вышеуказанное и решили идти в прод
Придя утром на работе мы обнаружили письмо примерно следующего содержания. Почему зависают сессии? Каким образом 30 секунд превратились в 20 минут?
В общем, мы начали разбираться.
Мы увидели 40 пользователей, делающих распознавание и даже упустим тот факт, что их не 10, как мы ожидали.
Это была наша первая ошибка. Мы неодоценили нагрузку. Но в целом всё равно такого проседания быть было не должно.
Гораздо более странно, что было видно, что в базе данных количество сессий всегда было ровно в 3 раза больше.
Проведя внутреннее расследование мы выяснили, что java разработчики делают распознавание в 3 потока.
Почему резалт кэш не любит одновременное к нему обращение расскажу позже.
Для поиска проблем в result_cache нам понадобится небольшой набор view и хранимых процедур.
Самая важная для нас процедура – процедура получения информации о памяти
Что важное я хочу отметить, что в документации про данные случаи не указано. Это видно только из support notes.
Важно - все нюансы result cache ТОЛЬКО на саппорте.
Мы решили понять, сколько же у нас закэшировано объектов. Для этого мы воспользовались представлением v$result_cache_objects. Записей было явно много больше чем мы ожидали.
Также мы решили посмотреть, что же это за объекты.
Мы были сильно удивлены, но это были не наши запросы. Причем по характеру видно, что это явно ETL-процесс. Причём запросы запускались весьма часто.
И мы вспомнили, что сами включили для этих таблиц аннотации, так как из них довольно часто приложению требовались данные и там кэширование было уместно.
Однако запросы к таблицам с интервалом 1 минуты на поиск изменённых данных наводнили кэш приведя к вымыванию наших запросов. Анотации мы отключать не стали, но отключили принудительно кэширование в etl.
Мы почистили объекты, но скоро их количество вернулось к 120000. Мы продолжили изучать, что же ещё кэшируется, так как скорость не менялась.
Мы обнаружили следующие запросы. Это были запросы от Adaptive Statistics, которую Oracle применяет для построения планов.
На форуме поддержки мы довольно оперативно нашли баг про этот функционал и result cache. Отключили использование result cache и производительность улучшилась до 10 минут за документ.
Что же такое за latch free, которые возникают при result cache?
Итак, что такое latch и к чему они приводят
Так как нам неоходимо обеспечить согласованность по чтению, то необходимо использовать блокировки. Result cache это единственное место, где читатели могу заблокировать читателей.
Оракл пытается установить защёлку несколько раз и потом засыпает
Рассказ про latch
Рассказ про latch
Важно понимать, что на result cache всегда есть защёлки, поэтому придётся убеждать DBA.
Итак, наш следующий шаг был получить отчётность по аггрегированому состоянию кэша.
Итак, мы получили отчёт об использовании памяти.
Подскажите, по каким показателям можно понять, что что-то пошло не так?
Это также видно по показателю Delete count valid
Таким образом, стало понятно, что памяти не хватает из-за некорректного расчёта её объёма.
Таким образом, стало понятно, что памяти не хватает из-за некорректного расчёта её объёма.
Мы использовали следующую формулу: ширина строки результатов * ожидаемое кол-во результатов, но не учли, что выделение памяти происходит блоками размером минимум 1 Кб.
Что и привело к известным ошибкам в процессе переполнения кэша.
Как же надо рассчитывать память? А считать её надо в блоках.
ksl_get_shared_latch
Адекватно эту ошибку устранили совсем недавно. Выше указан патч для 11 оракла.
Для 12-го я бы выбрал второй патч в зависимости от того, какой сейчас оракл ибо в нём устраняется ещё и ошибка по bypass-объектам для plsql про которую я говорил ранее
Времени на патчинг у нас не было. Надо было что-то подкрутить в базе данных.
Итак, неужели нам нужны все эти параметры? Конечно же нет!
Как уже упоминалось досточно четырёх. В кейсе мы обошлись одним – общим размером памяти.
Хотя мы и достигли улучшения с 20 минут до 6 время продолжало быть неприемлемым. Посмотрим, что нам ещё может дать отчёт об использовании кэша.
Видите ли вы что в отчёте ещё странного?
Путём неких изысканий мы обнаружили, что отключен джоб обновления рекомендаций, что на самом деле приводило их обновлению данных сразу же .
Мы запустили джоб с часовым интервалом как и было задумано, что автоматически отключило функционал постоянного обновления таблицы.
Итак, количество инвалидаций уменьшилось до минимального, удаление корректных записей исчезло, а производительность вернулась в ожидаемые границы даже при пятикратном увеличении нагрузки.
Мы не захотели, чтобы данная ситуация повторилась в дальнейшем и изучая как же Oracle использует result cache в ядре, обнаружили, что для ряда вещей используется недокументированный параметр shelflive по истечению которого результат запроса самоудаляется из кэша. Этот параметр был встроен в новую версию приложения. Важно, что он так же удаляется, если было изменение данных.
Если факт изменения не критичен для кэша, можно воспользоваться опцией SNAPSHOT – тогда изменения данных не будут инвалидировать кэш.
Для начала создадим таблицу
На период RESULT_CACHE_TIMEOUT записи имеют статус New
Давайте понаблюдаем за эволюцией статусов
Статус поменялся, а LRU нет
Поменялся и статус поменялся и LRU
Подождём 5 минут
Количество в кэше увеличивается, т.к. есть ещё память, но invalid объекты уходят. Наш объект, как и ожидалось, ушёл, а так бы висел вечно.
Собственно shelflife устроен так же, только появляются блоки с dependency
Если вы не испугались после наших кейсов result cache то есть ещё ряд неозвученных ограничений, ряд из которых очевиден.
Нет возможности кэширования объектов в схеме SYS
Нельзя кэшировать временные и внешние таблицы. Важно, что по-факту можно и оракл это явно не ограничивает. Это приводит к тому, что можно увидеть то, что раньше было немыслимо, а именно, содержимое временных таблиц других пользователей. Более того, оракл декларирует, что это исправлено, но в 12.2 до сих данная проблема есть.
Нелязя использовать недетерменированные sql и pl/sql функции
Конвеерные функции
Входные и выходные параметры должны быть простых типов данных.
На самом деле есть подходы как обходить ограничения с current_date/sysdate, но для этого нужна pl/sql функция с параметром по-умолчанию. Собственно у Игоря есть даже пример на его сайте.
Result cache широко используется ядром оракла. Для поиска таких мест можно использовать запрос к шаред пулу.
Очень активно кэш используется при работе с джобами, средой разработки приложений APEX. Обратите внимание на недокументированную опцию sysobj – я её нашёл именно тут.
Также через резалт кэш сохраняется информация по адаптивной статистике и dynamic sampling – механизмам корректной генерации статистики и трансформации планов. Что важно данные механизмы используют опцию snapshot, которую я именно тут и обнаружил.
Кратко подитожим работу result cache:
Данные при запросе попадают с уровня хранения в буферный кэш
Данные из буферного кэша попадают в область памяти result cache
Результаты переиспользуются с использование блокировок
Исходя из услышанного сведём достоинства и недостатки.
Рассмотрим сначала плюсы.
Можно не менять код приложения вообще или свести изменения к минимуму
Не требуется использовать внутренние языки программирования
Целостность данных при многопользовательском доступе через автоматическую инвалидацию
Может быть очень быстрым
Минусы мы уже увидели:
Кэш должен быть правильно использован. При неправильном сценарии может привести к иллюзии роста скорости, а потом её падению
База данных должна быть правильно настроена
Решение очень проприетарное (хотя я не верю в миф независимости приложения от базы данных)
Хочется отметить, что даже системы, разрабатываемые Oracle наткнулись на проблемы с некорректным использованием result cache.
Например, даже erp система Oracle E-Business suite склонна к падениям по причине некорректного использования result cache.
Однако нам интересны не сам факт наличия проблем, а способы их недопущения, так как сейчас мы имеем достаточно информации для их предотвращения. В процессе подготовки презентации было обнаружено письмо службы технической поддержки крупнейшей российской cloud системы рассчёта лояльности. На ней рассчитывают свои параметры известные сети по продаже косметики, торговые марки индустрии красоты, крупные ретейлеры электроники.
Итак, переходим к непосредственно письму.
Рассмотрим технические причины, которые вполне очевидно привели к сбою
Блокировки из-за неправильного размера кэша при bulk заливке, которая наверняка была в той самой подготовительной работе
Возможно это всё же v$result_cache_memory или dbms_result_cache.memory_report, так как по нему баг не закрыт. Однако, тесты багов написаны так хитро, что в них фактически явно говорится, что в v_result_cache_objects есть ошибка.
Сами виноваты
Итак, после был
изменён параметр result_cache_max_size
Скорее всего убран /*+ result_cache/ или созданы black_list или добавлен no_result_cache
Как мы видим, были предприняты практически идентичные действия как в случае с Recommendation engine.
Как же надо было провести безболезненное обновление?
Как я уже говорил после выполнения появляются dependency и result, для которых свои блоки
Итак, очищаем кэш, запускаем запрос и смотрим содержимое.
Записи то есть. Но всё же результата, который в теории должен занимать место нет, но зависимости сохраняются, так что всё равно место потребляется.
Поэтому если к вам приходят и говорят, что result cache не работает посмотрите вначале на блэк-листы
Как всегда с Oracle как никогда верно «Но есть нюанс»
Один из них только на саппорте. В документации само собой умалчивается. Так что надо либо воспользоваться параметром, которого конечно же может не хватить, либо делать отдельную процедуру и не забывать её запускать
А как вы думаете, какой второй нюанс? Он виден из этой картинки. Это Oracle 12.2
Что бы надо было сделать на самом деле:
Оценить на сколько изменится итоговый размер кэша. Формула расчёта будет приведена позднее.
Уменьшить влияние заливки набора данных в result cache: разово после загрузки, а не сразу же по каждому оператору
Проверить анонсированые Oracle исправления перед накатом изменений руками, а не верить тому, что пишет документация
Итак, мы близимся к завершению. Остался последний вид кэша.
Как мы заметили основаная проблема кэшей на сервере это расход дорогой серверной памяти. Для решения этой проблемы есть решение Client side result cache.
Он работает так. Есть база данных и драйвер. При попытке подключения запрашивается конфигурация с БД и поднимается кэш.
...........
Остальные потоки сразу же запрашивают общий кэш драйвера тем самым экономя память и ресурсы сервера.
Иногда в зависимости от нагрузки драйвер присылает в БД статистику по использования кэша, которую потом можно будет посмотреть.
Правила инвалидации клиентского кэша такие же как и для серверного, но гораздо интереснее посмотреть как это происходит в динамике.
Есть 2 случая инвалидации. Первый – когда запросы идут часто и не наступил Invalidation lag.
В таком случае поток пойдёт в базу данных, обновит кэши и считает данные из него.
Ежели никаких запрос в период от прихода сообщения до Invalidation lag не было, то сам драйвер через Invalidation lag запросит список инвалидированных резалтсетов.
Таким образом кэш обеспечивает самоподдерживаемость.
Итак, посмотрим как надо сконфигурировать БД, чтобы заработал client side result cache.
Всё весьма просто.
Есть 2 параметра, которые мы уже упомянали.
Посмотрим на примеры кода с использованием клиентского кэша.
Вот пример кода на .net.
Как мы видим в коде нет ничего такого, что включает клиентский кэш. Однажды активировав его на сервере мы на клиенте указываем уже известный хинт result_cache
java
Собственно после того как выполнено java-приложении можно посмотреть как оно использовало клиентский result cache.
Это табличка, при отключении сессии записи удаляются
Тут указан запрос для текущей сессии, но в целом надо искать по sid из session_connect_info. Почему Oracle не вынес это прямо в данную таблицу (а это таблица, а не view) я понять не смог.
Именно поэтому я считаю, что этот функционал не очень востребован, хотя как мне кажется очень нужен.
Достоинства, как всегда следуют из архитектуры.
Дешёвая память Любые драйвера Минимальное изменение кода приложения Сильное уменьшение нагрузки на базу данных
Отсутствие необходимости использовать дополнительные программные продукты для кэширования
Минусы понятны
Согласованность по чтению с задержкой
Необходимость толстого клиента, решение от вендора, максимум 2 Гб на клиента и как-то подозрительно мало багов на саппорте (я нашел около пяти), что говорит о малом использовании в production. Или бы иначе никто не стал пользоваться кэширующим сервером Oracle Oracle coherence.
Исходя из всех кейсов мы можем окончательно сформулировать плохие и хорошие сценарии для использования всех видов кэшей
Первый случай – если после изменения данных кэш должен мгновенно стать неактуальным. Для самодельных кэшей тяжело создать корректную инвалидацию в случае изменения объектов, на которых они построены.
Если использование хранимой в БД логики запрещено политиками разработки
Если кэш будет наполнен множеством разных значений, то они не будут переиспользоваться. Например, кэш созданный по идентификаторам транзакций бесполезен по причине того, что транзакции не так часто ищутся.
Все аналогичные запросы подвисают на время данного таймаута ожидая выполнения главного запроса
Одновременный многопользовательский доступ провоцирует возникновение блокировок
Первый случай – если после изменения данных кэш должен мгновенно стать неактуальным. Для самодельных кэшей тяжело создать корректную инвалидацию в случае изменения объектов, на которых они построены.
Если использование хранимой в БД логики запрещено политиками разработки
Есть команда разработки средней квалификации
Уже используется много SQL без использования внешнего кэширующего слоя
Есть ограничения по ресурсам сервера СУБД
Теперь подве
Так как я считаю, что в основном доклад про result cache выводы я буду делать по нему
Оцените верно размер памяти с учётом количества запросов, а не количества результатов.
Не бойтесь использовать auto-expiring. Он сохранит место удаляя неиспользуемое.
Не перегружайте запросами во время загрузки больших объемов данных
Прогревайте кэш
Убедитесь, что _result_cache_timeout соответствует вашим ожиданиям
НИКОГДА не используйте FORCE для БД
Проверяйте, адекватно ли используется FORCE для таблиц
Проверьте find count и убедитесь надо ли вам использовать result cache для адаптивной статистики