SlideShare a Scribd company logo
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

PPTX
Mongo DB Presentation
PDF
Introduction to ajax
PPTX
The Basics of MongoDB
PPT
Ajax Presentation
PPT
Mongo db basics
PPTX
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
PDF
mobile in the cloud with diamonds. improved.
PPT
Applied component i unit 2
Mongo DB Presentation
Introduction to ajax
The Basics of MongoDB
Ajax Presentation
Mongo db basics
Mongo DB: Fundamentals & Basics/ An Overview of MongoDB/ Mongo DB tutorials
mobile in the cloud with diamonds. improved.
Applied component i unit 2

What's hot (20)

PPTX
Mongo DB 102
PPTX
Basics of MongoDB
PPT
Web Services with Objective-C
PDF
Replicating application data into materialized views
PDF
FITC presents: Mobile & offline data synchronization in Angular JS
PDF
Mongo db
PPTX
Mongo Nosql CRUD Operations
PPT
Lecture 40 1
PDF
Mongo db basics
PDF
Getting started with MongoDB and Scala - Open Source Bridge 2012
PDF
Updating materialized views and caches using kafka
PPTX
Core Data Migrations and A Better Option
PDF
Electron, databases, and RxDB
PDF
Data Binding in Silverlight
PPTX
PPT
PPT
ADO.NET
PPTX
MongoDB - A next-generation database that lets you create applications never ...
PDF
FOXX - a Javascript application framework on top of ArangoDB
Mongo DB 102
Basics of MongoDB
Web Services with Objective-C
Replicating application data into materialized views
FITC presents: Mobile & offline data synchronization in Angular JS
Mongo db
Mongo Nosql CRUD Operations
Lecture 40 1
Mongo db basics
Getting started with MongoDB and Scala - Open Source Bridge 2012
Updating materialized views and caches using kafka
Core Data Migrations and A Better Option
Electron, databases, and RxDB
Data Binding in Silverlight
ADO.NET
MongoDB - A next-generation database that lets you create applications never ...
FOXX - a Javascript application framework on top of ArangoDB
Ad

Viewers also liked (7)

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

Similar to Rails database optimization (15)

PDF
How to avoid hanging yourself with Rails
PDF
Ruby on Rails PostgreSQL: An Inclusive Guide On Set Up & Usage
PDF
Intro to-rails-webperf
PPTX
Querying with Rails
PDF
High Performance Rails with MySQL
PPTX
Boosting the Performance of your Rails Apps
PDF
6 tips for improving ruby performance
PDF
Scaling Twitter
PDF
Scaling Twitter 12758
PPT
How to scale your web app
PPTX
Optimize the obvious
PPT
How To Scale v2
PDF
Rails Tips and Best Practices
PPTX
Rails best practices
PPT
Ruby On Rails
How to avoid hanging yourself with Rails
Ruby on Rails PostgreSQL: An Inclusive Guide On Set Up & Usage
Intro to-rails-webperf
Querying with Rails
High Performance Rails with MySQL
Boosting the Performance of your Rails Apps
6 tips for improving ruby performance
Scaling Twitter
Scaling Twitter 12758
How to scale your web app
Optimize the obvious
How To Scale v2
Rails Tips and Best Practices
Rails best practices
Ruby On Rails

Recently uploaded (20)

PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Spectroscopy.pptx food analysis technology
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
sap open course for s4hana steps from ECC to s4
Spectroscopy.pptx food analysis technology
The Rise and Fall of 3GPP – Time for a Sabbatical?
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Review of recent advances in non-invasive hemoglobin estimation
MIND Revenue Release Quarter 2 2025 Press Release
Building Integrated photovoltaic BIPV_UPV.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Reach Out and Touch Someone: Haptics and Empathic Computing
Programs and apps: productivity, graphics, security and other tools
NewMind AI Weekly Chronicles - August'25 Week I
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Mobile App Security Testing_ A Comprehensive Guide.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx

Rails database optimization