SlideShare une entreprise Scribd logo
1  sur  49
Télécharger pour lire hors ligne
Memory Issues
in Rails Applications
I am @simeons
recruit amazing people
solve hard problems
!
ship
!
make users happy
!
repeat
Problems of Success
(good problems)
Too many users 
Too much traffic
Too much data
Memory Issues
in Rails Applications
Common Problem of Success
Display Advertising

Makes the Web Suck
User-focused optimization
Tens of millions of users
1000+% better than average
200+% better than Google
Swoop Fixes That
Mobile	
  SDKs	
  
iOS	
  &	
  Android
Web	
  SDK	
  
RequireJS	
  &	
  jQuery
Components	
  
AngularJS
NLP,	
  etc.	
  
Python
Targe<ng	
  
High-­‐Perf	
  Java
Analy<cs	
  
Ruby	
  2.0
Internal	
  Apps	
  
Ruby	
  2.0	
  /	
  Rails	
  3
Pub	
  Portal	
  
Ruby	
  2.0	
  /	
  Rails	
  3
Ad	
  Portal	
  
Ruby	
  2.0	
  /	
  Rails	
  4
Before
1hr @ 4Gb
Before
1hr @ 4Gb
When problems grow faster
than the rate at which you
can throw HW at them, you
actually have to solve them
Before
1hr @ 4Gb
After
5min @ 230Mb
Resolving Memory Issues
in Rails Applications
Using Streams
CSV
0
125
250
375
500
0 25,000 50,000 75,000 100,000
Rows
Memory
(Mb)
0
125
250
375
500
0 25,000 50,000 75,000 100,000
Rows
Memory
(Mb)
You are here
0
125
250
375
500
0 25,000 50,000 75,000 100,000
Rows
Memory
(Mb)
You are here
This sucks
0
125
250
375
500
0 25,000 50,000 75,000 100,000
Rows
Memory
(Mb)
You are here
This sucks
Start thinking here
Memory Leaks
class AddDomainsStep
def call(hashes)
hashes.map do |hash|
transform_and_return(hash)
end
end
end
1 class AddDomainsStep
2 def initialize
3 @domain_config =
DomainConfig.instance
4 end
5 
6 def call(hashes)
7 hashes.each do |hash|
8 hash['domain'] =
9 @domain_config.
10 domain_for(hash['domain_id'])
11 end
12 end
13 end
1 class DomainConfig
2 include Singleton
3 
4 def initialize
5 @domains = {}
6 end
7 
8 def domain_for(id)
9 @domains[id] ||= Domain.name_for(id) || ''
10 end
11 end
@domains[id] ||= Domain.name_for(id) || ''
Memory Leak
•Memory that will never be released
by the garbage collector.
•Memory usage grows the longer the
process runs.
Avoid Global State
•Global variables
•Class variables
•Singletons
•Per-process instance state
Memory Churn
hashes.map do |hash|
hash['domain'].downcase.strip
end
hashes.each do |hash|
hash['domain'].downcase!
hash['domain'].strip!
end
vs
Memory Churn
•Allocating and deallocating tons of
objects slows down processing
•Mutation limits allocations, but
makes it easier to introduce bugs
1 hashes.each do |hash|
2 hash['domain'].downcase!
3 hash['domain'].strip!
4 end
Spot the Bug!
# In shared state:
@domains[id] ||= Domain.name_for(id) || ''
!
# Much later:
hash['domain'].downcase!
hash['domain'].strip!
Good News!
•Allocating and freeing objects is
fairly fast in Ruby
•Keeping your stack frame light
will limit the effects of memory
churn
Memory Bloat
def to_csv
csv = [CSV.generate_line(headers)]
!
rows.each do |row|
values = headers.map do |header|
row[header] || defaults[header]
end
!
csv << CSV.generate_line(values)
end
!
csv.join('')
end
def to_csv
csv = [CSV.generate_line(headers)]
!
rows.each do |row|
values = headers.map do |header|
row[header] || defaults[header]
end
!
csv << CSV.generate_line(values)
end
!
csv.join('')
end
def to_csv
csv = [CSV.generate_line(headers)]
!
rows.each do |row|
values = headers.map do |header|
row[header] || defaults[header]
end
!
csv << CSV.generate_line(values)
end
!
csv.join('')
end
Memory Bloat
•Memory usage grows with data set
•Loading too much data at once
Laziness
rename_report_fields(
squash(
add_domains(
add_properties(
unwind_variations(
rows
)
)
)
)
)
def duplicate(number, count)
if count > 0
[number] + repeat(number, count - 1)
else
[]
end
end
!
def sum(list)
list.inject(0) do |result, number|
result + number
end
end
sum(repeat(5,10))
# => 50
duplicate :: Int -> Int -> [Int]
duplicate number count
| count <= 0 =
[]
| otherwise =
number:duplicate number (count - 1)
!
sum :: [Int] -> Int
sum [x] = x
sum (x:remaining) = x + sum remaining
> sum $ duplicate 5 10
50
Be Proactive
About Being Lazy
Enumerable
class AddDomainsStep
def initialize(source)
@source = source
end
!
def each
@source.each do |hash|
hash['domain'] =
DomainConfig.
instance.
domain_for(hash['domain_id'])
yield hash
end
end
end
RenameReportFieldsStep.new(
SquashStep.new(
AddDomainsStep.new(
AddPropertiesStep.new(
UnwindVariationsStep.new(
rows
)
)
)
)
)
Buffering

Contenu connexe

Tendances

Xclone presentation final
Xclone presentation finalXclone presentation final
Xclone presentation final
Burning Lin
 
Considerations for building your private cloud folsom update
Considerations for building your private cloud   folsom updateConsiderations for building your private cloud   folsom update
Considerations for building your private cloud folsom update
Ryan Richard
 

Tendances (20)

Solr on Docker - the Good, the Bad and the Ugly
Solr on Docker - the Good, the Bad and the UglySolr on Docker - the Good, the Bad and the Ugly
Solr on Docker - the Good, the Bad and the Ugly
 
Integrating multiple CDN providers at Etsy - Velocity Europe (London) 2013
Integrating multiple CDN providers at Etsy - Velocity Europe (London) 2013Integrating multiple CDN providers at Etsy - Velocity Europe (London) 2013
Integrating multiple CDN providers at Etsy - Velocity Europe (London) 2013
 
(SDD404) Amazon RDS for Microsoft SQL Server Deep Dive | AWS re:Invent 2014
(SDD404) Amazon RDS for Microsoft SQL Server Deep Dive | AWS re:Invent 2014(SDD404) Amazon RDS for Microsoft SQL Server Deep Dive | AWS re:Invent 2014
(SDD404) Amazon RDS for Microsoft SQL Server Deep Dive | AWS re:Invent 2014
 
Resource Scheduling using Apache Mesos in Cloud Native Environments
Resource Scheduling using Apache Mesos in Cloud Native EnvironmentsResource Scheduling using Apache Mesos in Cloud Native Environments
Resource Scheduling using Apache Mesos in Cloud Native Environments
 
Doing QoS Before Ceph Cluster QoS is available - David Byte, Alex Lau
Doing QoS Before Ceph Cluster QoS is available - David Byte, Alex LauDoing QoS Before Ceph Cluster QoS is available - David Byte, Alex Lau
Doing QoS Before Ceph Cluster QoS is available - David Byte, Alex Lau
 
Twitter Fatcache
Twitter FatcacheTwitter Fatcache
Twitter Fatcache
 
Troubleshooting redis
Troubleshooting redisTroubleshooting redis
Troubleshooting redis
 
To Cloud or Not To Cloud?
To Cloud or Not To Cloud?To Cloud or Not To Cloud?
To Cloud or Not To Cloud?
 
Global deduplication for Ceph - Myoungwon Oh
Global deduplication for Ceph - Myoungwon OhGlobal deduplication for Ceph - Myoungwon Oh
Global deduplication for Ceph - Myoungwon Oh
 
OOPs, OOMs, oh my! Containerizing JVM apps
OOPs, OOMs, oh my! Containerizing JVM appsOOPs, OOMs, oh my! Containerizing JVM apps
OOPs, OOMs, oh my! Containerizing JVM apps
 
Redis acl
Redis aclRedis acl
Redis acl
 
RBD: What will the future bring? - Jason Dillaman
RBD: What will the future bring? - Jason DillamanRBD: What will the future bring? - Jason Dillaman
RBD: What will the future bring? - Jason Dillaman
 
Container Orchestration with Amazon ECS
Container Orchestration with Amazon ECSContainer Orchestration with Amazon ECS
Container Orchestration with Amazon ECS
 
Scaling Django for X Factor - DJUGL Oct 2012
Scaling Django for X Factor - DJUGL Oct 2012Scaling Django for X Factor - DJUGL Oct 2012
Scaling Django for X Factor - DJUGL Oct 2012
 
Shillings in Serverless
Shillings in ServerlessShillings in Serverless
Shillings in Serverless
 
HBase Low Latency
HBase Low LatencyHBase Low Latency
HBase Low Latency
 
Automatic Operation Bot for Ceph - You Ji
Automatic Operation Bot for Ceph - You JiAutomatic Operation Bot for Ceph - You Ji
Automatic Operation Bot for Ceph - You Ji
 
Flickr Php
Flickr PhpFlickr Php
Flickr Php
 
Xclone presentation final
Xclone presentation finalXclone presentation final
Xclone presentation final
 
Considerations for building your private cloud folsom update
Considerations for building your private cloud   folsom updateConsiderations for building your private cloud   folsom update
Considerations for building your private cloud folsom update
 

Similaire à Memory Issues in Ruby on Rails Applications

Web20expo Scalable Web Arch
Web20expo Scalable Web ArchWeb20expo Scalable Web Arch
Web20expo Scalable Web Arch
guest18a0f1
 
Intro to big data choco devday - 23-01-2014
Intro to big data   choco devday - 23-01-2014Intro to big data   choco devday - 23-01-2014
Intro to big data choco devday - 23-01-2014
Hassan Islamov
 
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
xlight
 
Scalable Web Architectures: Common Patterns and Approaches - Web 2.0 Expo NYC
Scalable Web Architectures: Common Patterns and Approaches - Web 2.0 Expo NYCScalable Web Architectures: Common Patterns and Approaches - Web 2.0 Expo NYC
Scalable Web Architectures: Common Patterns and Approaches - Web 2.0 Expo NYC
Cal Henderson
 
Web Development using Ruby on Rails
Web Development using Ruby on RailsWeb Development using Ruby on Rails
Web Development using Ruby on Rails
Avi Kedar
 

Similaire à Memory Issues in Ruby on Rails Applications (20)

Web20expo Scalable Web Arch
Web20expo Scalable Web ArchWeb20expo Scalable Web Arch
Web20expo Scalable Web Arch
 
Web20expo Scalable Web Arch
Web20expo Scalable Web ArchWeb20expo Scalable Web Arch
Web20expo Scalable Web Arch
 
Web20expo Scalable Web Arch
Web20expo Scalable Web ArchWeb20expo Scalable Web Arch
Web20expo Scalable Web Arch
 
Cvcc performance tuning
Cvcc performance tuningCvcc performance tuning
Cvcc performance tuning
 
Node.js Performance Case Study
Node.js Performance Case StudyNode.js Performance Case Study
Node.js Performance Case Study
 
Loom promises: be there!
Loom promises: be there!Loom promises: be there!
Loom promises: be there!
 
Intro to big data choco devday - 23-01-2014
Intro to big data   choco devday - 23-01-2014Intro to big data   choco devday - 23-01-2014
Intro to big data choco devday - 23-01-2014
 
Data Science
Data ScienceData Science
Data Science
 
Fixing twitter
Fixing twitterFixing twitter
Fixing twitter
 
Fixing_Twitter
Fixing_TwitterFixing_Twitter
Fixing_Twitter
 
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
 
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
 
Joyent circa 2006 (Scale with Rails)
Joyent circa 2006 (Scale with Rails)Joyent circa 2006 (Scale with Rails)
Joyent circa 2006 (Scale with Rails)
 
Chirp 2010: Scaling Twitter
Chirp 2010: Scaling TwitterChirp 2010: Scaling Twitter
Chirp 2010: Scaling Twitter
 
The Mobile Web - HTML5 on mobile devices
The Mobile Web - HTML5 on mobile devicesThe Mobile Web - HTML5 on mobile devices
The Mobile Web - HTML5 on mobile devices
 
Scalable Web Architectures: Common Patterns and Approaches - Web 2.0 Expo NYC
Scalable Web Architectures: Common Patterns and Approaches - Web 2.0 Expo NYCScalable Web Architectures: Common Patterns and Approaches - Web 2.0 Expo NYC
Scalable Web Architectures: Common Patterns and Approaches - Web 2.0 Expo NYC
 
Web Development using Ruby on Rails
Web Development using Ruby on RailsWeb Development using Ruby on Rails
Web Development using Ruby on Rails
 
IMCSummit 2015 - Day 2 IT Business Track - 4 Myths about In-Memory Databases ...
IMCSummit 2015 - Day 2 IT Business Track - 4 Myths about In-Memory Databases ...IMCSummit 2015 - Day 2 IT Business Track - 4 Myths about In-Memory Databases ...
IMCSummit 2015 - Day 2 IT Business Track - 4 Myths about In-Memory Databases ...
 
Ruby Conf Preso
Ruby Conf PresoRuby Conf Preso
Ruby Conf Preso
 
Scaling a MeteorJS SaaS app on AWS
Scaling a MeteorJS SaaS app on AWSScaling a MeteorJS SaaS app on AWS
Scaling a MeteorJS SaaS app on AWS
 

Plus de Simeon Simeonov

Build a Story Factory for Inbound Marketing in Five Easy Steps
Build a Story Factory for Inbound Marketing in Five Easy StepsBuild a Story Factory for Inbound Marketing in Five Easy Steps
Build a Story Factory for Inbound Marketing in Five Easy Steps
Simeon Simeonov
 
Customer Development: The Second Decade by Bob Dorf
Customer Development: The Second Decade by Bob DorfCustomer Development: The Second Decade by Bob Dorf
Customer Development: The Second Decade by Bob Dorf
Simeon Simeonov
 

Plus de Simeon Simeonov (11)

HyperLogLog Intuition Without Hard Math
HyperLogLog Intuition Without Hard MathHyperLogLog Intuition Without Hard Math
HyperLogLog Intuition Without Hard Math
 
High accuracy ML & AI over sensitive data
High accuracy ML & AI over sensitive dataHigh accuracy ML & AI over sensitive data
High accuracy ML & AI over sensitive data
 
Revolutionazing Search Advertising with ElasticSearch at Swoop
Revolutionazing Search Advertising with ElasticSearch at SwoopRevolutionazing Search Advertising with ElasticSearch at Swoop
Revolutionazing Search Advertising with ElasticSearch at Swoop
 
The Rough Guide to MongoDB
The Rough Guide to MongoDBThe Rough Guide to MongoDB
The Rough Guide to MongoDB
 
Three Tips for Winning Startup Weekend
Three Tips for Winning Startup WeekendThree Tips for Winning Startup Weekend
Three Tips for Winning Startup Weekend
 
Swoop: Solve Hard Problems & Fly Robots
Swoop: Solve Hard Problems & Fly RobotsSwoop: Solve Hard Problems & Fly Robots
Swoop: Solve Hard Problems & Fly Robots
 
Build a Story Factory for Inbound Marketing in Five Easy Steps
Build a Story Factory for Inbound Marketing in Five Easy StepsBuild a Story Factory for Inbound Marketing in Five Easy Steps
Build a Story Factory for Inbound Marketing in Five Easy Steps
 
Strategies for Startup Success by Simeon Simeonov
Strategies for Startup Success by Simeon SimeonovStrategies for Startup Success by Simeon Simeonov
Strategies for Startup Success by Simeon Simeonov
 
Patterns of Successful Angel Investing by Simeon Simeonov
Patterns of Successful Angel Investing by Simeon SimeonovPatterns of Successful Angel Investing by Simeon Simeonov
Patterns of Successful Angel Investing by Simeon Simeonov
 
Customer Development: The Second Decade by Bob Dorf
Customer Development: The Second Decade by Bob DorfCustomer Development: The Second Decade by Bob Dorf
Customer Development: The Second Decade by Bob Dorf
 
Beyond Bootstrapping
Beyond BootstrappingBeyond Bootstrapping
Beyond Bootstrapping
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 

Memory Issues in Ruby on Rails Applications