SlideShare a Scribd company logo
1 of 30
Download to read offline
Database Optimization

Scaling
Ruby-on-Rails
By Example
Karsten Meier
meier-online.com
My Technical Background
●

1986: SQL at university

●

1996: QuarkXpress -> HTML Converter

●

1998-2001: WebObjects, MVC, ORM

●

2004: First contact with Ruby (Pleac)

●

Since 2005: Handylearn Projects

●

Since 2009: Use of Rails in projects

2
Use Case: Cycosmos
●

Community

●

Webobjects

●

●

ORM
Enterprise Objects
3 Appserver,
1 DB Server

3
Effects Of Less Database Queries
●

●
●

●

Better response
times
Less database load
300% higher
throughput
Higher stability
Layers Of A Web Application
Fat Objects
imo

id
teu

grt

call_sign

build_year

name
speech_of_sponsor

draft
machine

imo_certificate
company

legal_country
Schadow Objects
ContainerVessel.
select('id, name')
order('name')
●

Read-Only

●

Only given attributes

●

●

Exception
if unknown

ActiveRecord::ReadOnlyRecord

ActiveRecord::MissingAttributeError

ID does not throw
exception
Cherrypicking
●

Only one column

●

Object not needed

●

pluck(column)

●

since Rails 3.2

ContainerVessel.pluck(:name)
['Australia', 'Brisbane', 'Busan',...]
Is vessel ready to cast off?
Outsourcing
●

Weight of all container on the vessel?

●

DB can do the calculation

●

Rails does not see the individual containers
@vessel.containers.inject{...}
@vessel.containers.sum('weight')
Linked Objekts
●

A company with a list of vessels, each with a
flag country
Sequence Diagram
includes()
@container_vessels =
@company.container_vessels.
order(:name).
includes(:legal_country)
SELECT "container_vessels".*
FROM "container_vessels"
WHERE "container_vessels"."company_id" = 2
ORDER BY name
SELECT "countries".*
FROM "countries"
WHERE "countries"."id" IN (8, 7, 4)
includes()
●

Each query returns objects of one type

●

Rails always in control

●

Nesting possible

●

Fine tuning difficult
.includes(:legal_country => :tax_rates)
.select('country.image????')
How does a join works again?
Inner/Left/Outer/Right
Rails joins
@container_vessels =
@company.container_vessels.
order(:name).
joins(:legal_country)
●

●

No vessels without a
flag state
No country data
Filter with joins()
●

Filter with conditions in linked data

●

Only target objects are returned

●

Beware possible duplications!

@companies = Company.order(:name).
joins(:container_vessels).
where(["container_vessels.build_year > ?", 2009])
SELECT "companies".*
FROM "companies"
INNER JOIN "container_vessels"
ON "container_vessels"."company_id" = "companies"."id"
WHERE (container_vessels.build_year > 2009)
ORDER BY name
Automatic Join
in Associations
class Country < ActiveRecord::Base
has_many :registering_companies,
:through => :registered_vessels,
:source => 'company',
:class_name => 'Company',
:uniq => true
...
@companies = @country.registering_companies
SELECT DISTINCT "companies".*
FROM "companies"
INNER JOIN "container_vessels"
ON "companies"."id" = "container_vessels"."company_id"
WHERE "container_vessels"."legal_country_id" = 10
Use Database-Join directly?
Real Database Joins In Rails
connection = Company.connection
columns = "container_vessels.id, container_vessels.name,
container_vessels.imo, container_vessels.teu, 
countries.name as legal_country_name"

sql = 'SELECT ' + columns + ' FROM "container_vessels" 
JOIN "countries" 
ON "countries"."id" = "container_vessels"."legal_country_i
WHERE "container_vessels"."company_id" = ' + @company.id.t
' ORDER BY "container_vessels".name'
@vessel_data = connection.select_all(
sql, 'ContainerVessel Overview Load')
Returned Values
●

select_all: array of hashes

●

select_rows: array of arrays

<% @vessel_data.each do |data| %>
<tr>
<td><%= data['name'] %></td>
<td><%= data['imo'] %></td>
<td><%= data['teu'] %></td>
<td><%= data['legal_country_name'] %></td>
...
<% end %>
Checking Parameters
●
●

●

●

SQL-Injection
Methods difficult to
find
Since Rails 3.2:
ActiveRecord::
Sanitization
For IDs: to_i.to_str

Company.where(
'name like '%?', input)
record.sanitize_sql_array(..)
replace_bind_variables()
quote_bound_value()
connection.quote_string()
Writing
If you have performance problems during
writing, the implications are often bad.
IDs
●

●

ID-delivery can be a
central bottle neck
Sometimes already
existing IDs can be
used
Transactions
●

Ensure consistency (ACID)

●

Less locking, faster writes

●

Use them if you have more than one write
operation in an action
Mass Updates
●

Company is sold

●

All vessels get a new owner

UPDATE container_vessels
SET company_id = 7
WHERE company_id = 5

connection.update_sql(sql, "Updating vessel...")
Linked Updates
●
●

Example usage: denormalisation
Name of country should also be stored in
vessel table

UPDATE container_vessels, country
SET container_vessels.country_name = country.name
WHERE container_vessels.legal_country_id = country.id
Don't be afraid of SQL

"Many people treat the relational database
like a crazy aunt who's shut up in an attic
and whom nobody wants to talk about"
Martin Fowler: OrmHate
... end
Website of Karsten Meier:

meier-online.com
Pictures:
Container ship by jogdragoon, openclipart.org
Hammer5 by Krystof Jetmar, openclipart.org
OOCL Montreal & Cosco Hope photos by Karsten Meier in port of Hamburg 2012

More Related Content

What's hot

What's hot (20)

Mongo DB 102
Mongo DB 102Mongo DB 102
Mongo DB 102
 
Basics of MongoDB
Basics of MongoDB Basics of MongoDB
Basics of MongoDB
 
Web Services with Objective-C
Web Services with Objective-CWeb Services with Objective-C
Web Services with Objective-C
 
Replicating application data into materialized views
Replicating application data into materialized viewsReplicating application data into materialized views
Replicating application data into materialized views
 
FITC presents: Mobile & offline data synchronization in Angular JS
FITC presents: Mobile & offline data synchronization in Angular JSFITC presents: Mobile & offline data synchronization in Angular JS
FITC presents: Mobile & offline data synchronization in Angular JS
 
Mongo db
Mongo dbMongo db
Mongo db
 
Mongo Nosql CRUD Operations
Mongo Nosql CRUD OperationsMongo Nosql CRUD Operations
Mongo Nosql CRUD Operations
 
Lecture 40 1
Lecture 40 1Lecture 40 1
Lecture 40 1
 
Mongo db basics
Mongo db basicsMongo db basics
Mongo db basics
 
Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012
 
Updating materialized views and caches using kafka
Updating materialized views and caches using kafkaUpdating materialized views and caches using kafka
Updating materialized views and caches using kafka
 
Core Data Migrations and A Better Option
Core Data Migrations and A Better OptionCore Data Migrations and A Better Option
Core Data Migrations and A Better Option
 
Electron, databases, and RxDB
Electron, databases, and RxDBElectron, databases, and RxDB
Electron, databases, and RxDB
 
Data Binding in Silverlight
Data Binding in SilverlightData Binding in Silverlight
Data Binding in Silverlight
 
Ajax
AjaxAjax
Ajax
 
Mongo db
Mongo dbMongo db
Mongo db
 
AJAX
AJAXAJAX
AJAX
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
MongoDB - A next-generation database that lets you create applications never ...
MongoDB - A next-generation database that lets you create applications never ...MongoDB - A next-generation database that lets you create applications never ...
MongoDB - A next-generation database that lets you create applications never ...
 
FOXX - a Javascript application framework on top of ArangoDB
FOXX - a Javascript application framework on top of ArangoDBFOXX - a Javascript application framework on top of ArangoDB
FOXX - a Javascript application framework on top of ArangoDB
 

Viewers also liked

Viewers also liked (7)

Datenbankoptimierung für Ruby on Rails
Datenbankoptimierung für Ruby on RailsDatenbankoptimierung für Ruby on Rails
Datenbankoptimierung für Ruby on Rails
 
Risiko, Sicherheit und menschliche Entscheidungsfindungen
Risiko, Sicherheit und menschliche EntscheidungsfindungenRisiko, Sicherheit und menschliche Entscheidungsfindungen
Risiko, Sicherheit und menschliche Entscheidungsfindungen
 
Database Optimization Service
Database Optimization ServiceDatabase Optimization Service
Database Optimization Service
 
Database performance tuning and query optimization
Database performance tuning and query optimizationDatabase performance tuning and query optimization
Database performance tuning and query optimization
 
Sass Code Reviews - How one code review changed my life #SassConf2015
Sass Code Reviews - How one code review changed my life #SassConf2015Sass Code Reviews - How one code review changed my life #SassConf2015
Sass Code Reviews - How one code review changed my life #SassConf2015
 
A Beginners Guide to noSQL
A Beginners Guide to noSQLA Beginners Guide to noSQL
A Beginners Guide to noSQL
 
Montreal Girl Geeks: Building the Modern Web
Montreal Girl Geeks: Building the Modern WebMontreal Girl Geeks: Building the Modern Web
Montreal Girl Geeks: Building the Modern Web
 

Similar to Rails database optimization

Using Amazon Simple Db With Rails
Using Amazon Simple Db With RailsUsing Amazon Simple Db With Rails
Using Amazon Simple Db With Rails
Akhil Bansal
 
IndyCodeCamp SDS May 16th 2009
IndyCodeCamp SDS May 16th 2009IndyCodeCamp SDS May 16th 2009
IndyCodeCamp SDS May 16th 2009
Aaron King
 
CHOReOS Web Services FISL Conference Brazil 2012
CHOReOS Web Services FISL Conference Brazil 2012CHOReOS Web Services FISL Conference Brazil 2012
CHOReOS Web Services FISL Conference Brazil 2012
choreos
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
Aren Zomorodian
 

Similar to Rails database optimization (20)

Using Amazon Simple Db With Rails
Using Amazon Simple Db With RailsUsing Amazon Simple Db With Rails
Using Amazon Simple Db With Rails
 
SQL for Web APIs - Simplifying Data Access for API Consumers
SQL for Web APIs - Simplifying Data Access for API ConsumersSQL for Web APIs - Simplifying Data Access for API Consumers
SQL for Web APIs - Simplifying Data Access for API Consumers
 
IndyCodeCamp SDS May 16th 2009
IndyCodeCamp SDS May 16th 2009IndyCodeCamp SDS May 16th 2009
IndyCodeCamp SDS May 16th 2009
 
State management
State managementState management
State management
 
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael PizzoADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
 
CHOReOS Web Services FISL Conference Brazil 2012
CHOReOS Web Services FISL Conference Brazil 2012CHOReOS Web Services FISL Conference Brazil 2012
CHOReOS Web Services FISL Conference Brazil 2012
 
Agile data presentation 3 - cambridge
Agile data   presentation 3 - cambridgeAgile data   presentation 3 - cambridge
Agile data presentation 3 - cambridge
 
Ch05 state management
Ch05 state managementCh05 state management
Ch05 state management
 
NoSQL meets Microservices - Michael Hackstein
NoSQL meets Microservices -  Michael HacksteinNoSQL meets Microservices -  Michael Hackstein
NoSQL meets Microservices - Michael Hackstein
 
Data models in Angular 1 & 2
Data models in Angular 1 & 2Data models in Angular 1 & 2
Data models in Angular 1 & 2
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
 
Ch 7 data binding
Ch 7 data bindingCh 7 data binding
Ch 7 data binding
 
Perchè potresti aver bisogno di un database NoSQL anche se non sei Google o F...
Perchè potresti aver bisogno di un database NoSQL anche se non sei Google o F...Perchè potresti aver bisogno di un database NoSQL anche se non sei Google o F...
Perchè potresti aver bisogno di un database NoSQL anche se non sei Google o F...
 
Introduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRIntroduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIR
 
Beeline Firebase talk - Firebase event Jun 2017
Beeline Firebase talk - Firebase event Jun 2017Beeline Firebase talk - Firebase event Jun 2017
Beeline Firebase talk - Firebase event Jun 2017
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
Replacing ActiveRecord With DataMapper
Replacing ActiveRecord With DataMapperReplacing ActiveRecord With DataMapper
Replacing ActiveRecord With DataMapper
 
MongoDB: Comparing WiredTiger In-Memory Engine to Redis
MongoDB: Comparing WiredTiger In-Memory Engine to RedisMongoDB: Comparing WiredTiger In-Memory Engine to Redis
MongoDB: Comparing WiredTiger In-Memory Engine to Redis
 
OrientDB the database for the web 1.1
OrientDB the database for the web 1.1OrientDB the database for the web 1.1
OrientDB the database for the web 1.1
 
6 tips for improving ruby performance
6 tips for improving ruby performance6 tips for improving ruby performance
6 tips for improving ruby performance
 

Recently uploaded

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

Rails database optimization