SlideShare a Scribd company logo
1 of 28
Download to read offline
This slide was intentionally left blank
Speed is a feature
A mystical journey through Django performance
optimization techniques, tools and gotchas
Roadmap
How to find performance problems
Sneak peak: Front-end performance
How to fix them in Django
Why?
[Google] found that Half a
second delay caused a 20% drop
in traffic.
[Amazon] found that even very
small delays would result in
substantial and costly drops in
revenue.
Users really respond to speed
2006
There’s nothing like data
Don’t start with the code. Profile and gather real usage data.
There’s nothing like real data
Identify bottlenecks
New Relic
Paid service
Very good
Google Analytics
Free of charge
Less detail
Your logs
No data to third parties
Harder to use
Profiling
Complex setup required
Overhead
New Relic
New Relic
Google Analytics Site Speed
There’s nothing like data
Let’s find the culprit!
django-debug-toolbar
django-debug-toolbar-template-timings
Time all the things!
Typical backend bottlenecks
Database
External Services
CPU Intensive task
Template Rendering
Database
Missing index
select_related()
prefetch_related()
Order
select_related()
>>> for c in Comment.objects.all():
print c.user.name
# select * from comments;
# select * from users where id = 1;
# select * from users where id = 2;
...
>>> comments = Comment.objects.all();
>>> for c in comments.select_related(“user”):
print c.user.name
# select comments.*, users.*
# from comments, users
# where comments.user_id = users.id;
prefech_related()
>>> for u in User.objects.filter(id__lt=10):
print len(u.comments.all())
# select * from users;
# select * from comments where user_id = 1;
...
>>> users = User.objects.filter(id__lt=10)
>>> for u in users.prefetch_related(“comments”):
print len(u.comments.all())
# select * from users where id < 10;
# select * from comments
# where user_id in (1,2,3,4,5,6,7,8,9);
## Joins them in python
Background Jobs
Celery
from celery import task
@task
def send_confirmation_email(user_id):
...
def login(req):
...
send_confirmation_email.delay(req.user.id)
return HttpResponseRedirect(“/home/”)
Caching!
DB
External Services
CPU intensive tasks
Caching!
Per view cache
from django.views.decorators.cache import
cache_page
@cache_page(60 * 15) # seconds
def my_view(request):
...
Caching!
Low level cache API
>>> from django.core.cache import get_cache
>>> cache = get_cache('default')
>>> cache.set('my_key', 'hello, world!', 30)
>>> cache.get('my_key')
>>> from django.core.cache import caches
>>> cache = caches['default']
Caching!
from django.core.cache import get_cache
cache = get_cache('default')
def last_comments(request):
comments_ids = cache.get('last_comments')
if comments_ids:
comments = Comment.objects.filter(id__in=comments_ids)
else:
comments = fetch_last_comments()
comments_ids = [c.id for c in comments]
cache.set('last_comments', comments_ids)
...
Low level cache API
Caching!
Django Cacheback
from cacheback.decorators import cacheback
@cacheback
def fetch_last_comments_ids():
...
def last_comments(request):
comments_ids = fetch_last_comments_ids()
comments = Comment.objects.filter(id__in=comments_ids)
...
Template Compilation
Use
django.template.loaders.cached.Loader
TEMPLATE_LOADERS = (
('django.template.loaders.cached.Loader', (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)),
)
Template Fragment Caching
{% load cache %}
{% cache 500 “last_comments” %}
.. last comments ..
{% endcache %}
{% load cache %}
{% cache 500 “my_recent_comments” user.id %}
.. user’s recent comments ..
{% endcache %}
Don’t forget about the browser
80% or more of the end-user response
time is spent in the front end
Combine
Compress
Cache
Less is more
Load slow things later
Focus on making the
important things faster
Don’t forget about the browser
Google PageSpeed Insights
webpagetest.org
Chrome & Firefox
Assets
Django Compressor
{% compress js %}
<script src="/static/js/one.js"></script>
<script>obj.value = "value";</script>
{% endcompress %}
Django Assets
{% assets "js_all" %}
<script async src="{{ ASSET_URL }}"></script>
{% endassets %}
Q & Maybe A
@polmuz
References
Performance is a feature - http://blog.codinghorror.com/performance-is-a-feature/
Marissa Mayer at Web 2.0 - http://glinden.blogspot.com.ar/2006/11/marissa-mayer-at-web-20.html
Psychology of Web Performance - http://www.websiteoptimization.com/speed/tweak/psychology-web-performance/
New Relic - http://newrelic.com
Google Analytics - http://www.google.com/analytics/
Tracking Application Response Time with Nginx - http://lincolnloop.com/blog/tracking-application-response-time-nginx/
Logging Apache response times - http://www.moeding.net/archives/33-Logging-Apache-response-times.html
Django Debug Toolbar - http://django-debug-toolbar.readthedocs.org/
DDT Template Timings - https://github.com/orf/django-debug-toolbar-template-timings
Django Database Optimizations - https://docs.djangoproject.com/en/1.7/topics/db/optimization/
Two Hard Things - http://martinfowler.com/bliki/TwoHardThings.html
Django Cache Docs - https://docs.djangoproject.com/en/1.7/topics/cache/
Django Cacheback - http://django-cacheback.readthedocs.org/en/latest/index.html
Cached Templates - https://docs.djangoproject.com/en/1.7/ref/templates/api/#django.template.loaders.cached.Loader
Google PageSpeed Insights - https://developers.google.com/speed/pagespeed/insights/
Web Page Test - http://www.webpagetest.org/
Django Compressor - http://django-compressor.readthedocs.org/en/1.3/
Django Assets - http://django-assets.readthedocs.org/en/0.8/

More Related Content

What's hot

Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOdoo
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of DjangoJacob Kaplan-Moss
 
OSCON Google App Engine Codelab - July 2010
OSCON Google App Engine Codelab - July 2010OSCON Google App Engine Codelab - July 2010
OSCON Google App Engine Codelab - July 2010ikailan
 
Workshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastWorkshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastMichelangelo van Dam
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Michelangelo van Dam
 
Take Data Validation Seriously - Paul Milham, WildWorks
Take Data Validation Seriously - Paul Milham, WildWorksTake Data Validation Seriously - Paul Milham, WildWorks
Take Data Validation Seriously - Paul Milham, WildWorksNodejsFoundation
 
A re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbaiA re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbaiPraveen Puglia
 
QA Fest 2017. Яков Крамаренко. Minimum Usable Framework
QA Fest 2017. Яков Крамаренко. Minimum Usable FrameworkQA Fest 2017. Яков Крамаренко. Minimum Usable Framework
QA Fest 2017. Яков Крамаренко. Minimum Usable FrameworkQAFest
 
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...QAFest
 
Incremental Type Safety in React Apollo
Incremental Type Safety in React Apollo Incremental Type Safety in React Apollo
Incremental Type Safety in React Apollo Evans Hauser
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projectsIgnacio Martín
 
Better Testing With PHP Unit
Better Testing With PHP UnitBetter Testing With PHP Unit
Better Testing With PHP Unitsitecrafting
 
Metrics-Driven Engineering at Etsy
Metrics-Driven Engineering at EtsyMetrics-Driven Engineering at Etsy
Metrics-Driven Engineering at EtsyMike Brittain
 
An Introduction to Celery
An Introduction to CeleryAn Introduction to Celery
An Introduction to CeleryIdan Gazit
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDMichele Capra
 

What's hot (19)

Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI Framework
 
Graphql, REST and Apollo
Graphql, REST and ApolloGraphql, REST and Apollo
Graphql, REST and Apollo
 
Magento Indexes
Magento IndexesMagento Indexes
Magento Indexes
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of Django
 
OSCON Google App Engine Codelab - July 2010
OSCON Google App Engine Codelab - July 2010OSCON Google App Engine Codelab - July 2010
OSCON Google App Engine Codelab - July 2010
 
Kyiv.py #17 Flask talk
Kyiv.py #17 Flask talkKyiv.py #17 Flask talk
Kyiv.py #17 Flask talk
 
Django tricks (2)
Django tricks (2)Django tricks (2)
Django tricks (2)
 
Workshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastWorkshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfast
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
Take Data Validation Seriously - Paul Milham, WildWorks
Take Data Validation Seriously - Paul Milham, WildWorksTake Data Validation Seriously - Paul Milham, WildWorks
Take Data Validation Seriously - Paul Milham, WildWorks
 
A re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbaiA re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbai
 
QA Fest 2017. Яков Крамаренко. Minimum Usable Framework
QA Fest 2017. Яков Крамаренко. Minimum Usable FrameworkQA Fest 2017. Яков Крамаренко. Minimum Usable Framework
QA Fest 2017. Яков Крамаренко. Minimum Usable Framework
 
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
 
Incremental Type Safety in React Apollo
Incremental Type Safety in React Apollo Incremental Type Safety in React Apollo
Incremental Type Safety in React Apollo
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projects
 
Better Testing With PHP Unit
Better Testing With PHP UnitBetter Testing With PHP Unit
Better Testing With PHP Unit
 
Metrics-Driven Engineering at Etsy
Metrics-Driven Engineering at EtsyMetrics-Driven Engineering at Etsy
Metrics-Driven Engineering at Etsy
 
An Introduction to Celery
An Introduction to CeleryAn Introduction to Celery
An Introduction to Celery
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
 

Viewers also liked

WordCamp Vancouver 2010 - Search Engine Optimization (SEO) Tips for WordPress
WordCamp Vancouver 2010 - Search Engine Optimization (SEO) Tips for WordPressWordCamp Vancouver 2010 - Search Engine Optimization (SEO) Tips for WordPress
WordCamp Vancouver 2010 - Search Engine Optimization (SEO) Tips for WordPressMcBuzz Communications
 
Ch. 2-optimization-techniques
Ch. 2-optimization-techniquesCh. 2-optimization-techniques
Ch. 2-optimization-techniquesanj134u
 
Optimization techniques
Optimization  techniquesOptimization  techniques
Optimization techniquesbiniyapatel
 
Demand, Supply, and Market Equilibrium
Demand, Supply, and Market EquilibriumDemand, Supply, and Market Equilibrium
Demand, Supply, and Market EquilibriumNoel Buensuceso
 

Viewers also liked (6)

WordCamp Vancouver 2010 - Search Engine Optimization (SEO) Tips for WordPress
WordCamp Vancouver 2010 - Search Engine Optimization (SEO) Tips for WordPressWordCamp Vancouver 2010 - Search Engine Optimization (SEO) Tips for WordPress
WordCamp Vancouver 2010 - Search Engine Optimization (SEO) Tips for WordPress
 
Ch. 2-optimization-techniques
Ch. 2-optimization-techniquesCh. 2-optimization-techniques
Ch. 2-optimization-techniques
 
Optimization techniques
Optimization techniquesOptimization techniques
Optimization techniques
 
Optimization techniques
Optimization techniques Optimization techniques
Optimization techniques
 
Optimization techniques
Optimization  techniquesOptimization  techniques
Optimization techniques
 
Demand, Supply, and Market Equilibrium
Demand, Supply, and Market EquilibriumDemand, Supply, and Market Equilibrium
Demand, Supply, and Market Equilibrium
 

Similar to Speed is a feature - Django Meetup Buenos Aires June 2014

Speed is a Feature - PyConAr 2014
Speed is a Feature - PyConAr 2014Speed is a Feature - PyConAr 2014
Speed is a Feature - PyConAr 2014Martín Blech
 
Inside PyMongo - MongoNYC
Inside PyMongo - MongoNYCInside PyMongo - MongoNYC
Inside PyMongo - MongoNYCMike Dirolf
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Djangofool2nd
 
Django for mobile applications
Django for mobile applicationsDjango for mobile applications
Django for mobile applicationsHassan Abid
 
Mini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesMini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesLeonardo Fernandes
 
Python Development (MongoSF)
Python Development (MongoSF)Python Development (MongoSF)
Python Development (MongoSF)Mike Dirolf
 
國民雲端架構 Django + GAE
國民雲端架構 Django + GAE國民雲端架構 Django + GAE
國民雲端架構 Django + GAEWinston Chen
 
Naive application development
Naive application developmentNaive application development
Naive application developmentShaka Huang
 
Scaling python webapps from 0 to 50 million users - A top-down approach
Scaling python webapps from 0 to 50 million users - A top-down approachScaling python webapps from 0 to 50 million users - A top-down approach
Scaling python webapps from 0 to 50 million users - A top-down approachJinal Jhaveri
 
What the heck went wrong?
What the heck went wrong?What the heck went wrong?
What the heck went wrong?Andy McKay
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3masahiroookubo
 
Using Task Queues and D3.js to build an analytics product on App Engine
Using Task Queues and D3.js to build an analytics product on App EngineUsing Task Queues and D3.js to build an analytics product on App Engine
Using Task Queues and D3.js to build an analytics product on App EngineRiver of Talent
 
Engitec - Minicurso de Django
Engitec - Minicurso de DjangoEngitec - Minicurso de Django
Engitec - Minicurso de DjangoGilson Filho
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и DjangoMoscowDjango
 
Django - Know Your Namespace: Middleware
Django - Know Your Namespace: MiddlewareDjango - Know Your Namespace: Middleware
Django - Know Your Namespace: Middlewarehowiworkdaily
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Jacob Kaplan-Moss
 

Similar to Speed is a feature - Django Meetup Buenos Aires June 2014 (20)

Speed is a Feature - PyConAr 2014
Speed is a Feature - PyConAr 2014Speed is a Feature - PyConAr 2014
Speed is a Feature - PyConAr 2014
 
Inside PyMongo - MongoNYC
Inside PyMongo - MongoNYCInside PyMongo - MongoNYC
Inside PyMongo - MongoNYC
 
Django Show
Django ShowDjango Show
Django Show
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Django
 
Django for mobile applications
Django for mobile applicationsDjango for mobile applications
Django for mobile applications
 
Mini Curso de Django
Mini Curso de DjangoMini Curso de Django
Mini Curso de Django
 
Mini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesMini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico Ces
 
Python Development (MongoSF)
Python Development (MongoSF)Python Development (MongoSF)
Python Development (MongoSF)
 
國民雲端架構 Django + GAE
國民雲端架構 Django + GAE國民雲端架構 Django + GAE
國民雲端架構 Django + GAE
 
Naive application development
Naive application developmentNaive application development
Naive application development
 
Scaling python webapps from 0 to 50 million users - A top-down approach
Scaling python webapps from 0 to 50 million users - A top-down approachScaling python webapps from 0 to 50 million users - A top-down approach
Scaling python webapps from 0 to 50 million users - A top-down approach
 
What the heck went wrong?
What the heck went wrong?What the heck went wrong?
What the heck went wrong?
 
Implementation of GUI Framework part3
Implementation of GUI Framework part3Implementation of GUI Framework part3
Implementation of GUI Framework part3
 
Using Task Queues and D3.js to build an analytics product on App Engine
Using Task Queues and D3.js to build an analytics product on App EngineUsing Task Queues and D3.js to build an analytics product on App Engine
Using Task Queues and D3.js to build an analytics product on App Engine
 
Engitec - Minicurso de Django
Engitec - Minicurso de DjangoEngitec - Minicurso de Django
Engitec - Minicurso de Django
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и Django
 
Django - Know Your Namespace: Middleware
Django - Know Your Namespace: MiddlewareDjango - Know Your Namespace: Middleware
Django - Know Your Namespace: Middleware
 
Gae
GaeGae
Gae
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)
 

Recently uploaded

8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedDelhi Call girls
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 

Recently uploaded (20)

8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 

Speed is a feature - Django Meetup Buenos Aires June 2014

  • 1. This slide was intentionally left blank
  • 2. Speed is a feature A mystical journey through Django performance optimization techniques, tools and gotchas
  • 3. Roadmap How to find performance problems Sneak peak: Front-end performance How to fix them in Django
  • 4. Why? [Google] found that Half a second delay caused a 20% drop in traffic. [Amazon] found that even very small delays would result in substantial and costly drops in revenue. Users really respond to speed 2006
  • 5. There’s nothing like data Don’t start with the code. Profile and gather real usage data.
  • 6. There’s nothing like real data Identify bottlenecks New Relic Paid service Very good Google Analytics Free of charge Less detail Your logs No data to third parties Harder to use Profiling Complex setup required Overhead
  • 10. There’s nothing like data Let’s find the culprit! django-debug-toolbar django-debug-toolbar-template-timings
  • 11. Time all the things!
  • 12. Typical backend bottlenecks Database External Services CPU Intensive task Template Rendering
  • 14. select_related() >>> for c in Comment.objects.all(): print c.user.name # select * from comments; # select * from users where id = 1; # select * from users where id = 2; ... >>> comments = Comment.objects.all(); >>> for c in comments.select_related(“user”): print c.user.name # select comments.*, users.* # from comments, users # where comments.user_id = users.id;
  • 15. prefech_related() >>> for u in User.objects.filter(id__lt=10): print len(u.comments.all()) # select * from users; # select * from comments where user_id = 1; ... >>> users = User.objects.filter(id__lt=10) >>> for u in users.prefetch_related(“comments”): print len(u.comments.all()) # select * from users where id < 10; # select * from comments # where user_id in (1,2,3,4,5,6,7,8,9); ## Joins them in python
  • 16. Background Jobs Celery from celery import task @task def send_confirmation_email(user_id): ... def login(req): ... send_confirmation_email.delay(req.user.id) return HttpResponseRedirect(“/home/”)
  • 18. Caching! Per view cache from django.views.decorators.cache import cache_page @cache_page(60 * 15) # seconds def my_view(request): ...
  • 19. Caching! Low level cache API >>> from django.core.cache import get_cache >>> cache = get_cache('default') >>> cache.set('my_key', 'hello, world!', 30) >>> cache.get('my_key') >>> from django.core.cache import caches >>> cache = caches['default']
  • 20. Caching! from django.core.cache import get_cache cache = get_cache('default') def last_comments(request): comments_ids = cache.get('last_comments') if comments_ids: comments = Comment.objects.filter(id__in=comments_ids) else: comments = fetch_last_comments() comments_ids = [c.id for c in comments] cache.set('last_comments', comments_ids) ... Low level cache API
  • 21. Caching! Django Cacheback from cacheback.decorators import cacheback @cacheback def fetch_last_comments_ids(): ... def last_comments(request): comments_ids = fetch_last_comments_ids() comments = Comment.objects.filter(id__in=comments_ids) ...
  • 22. Template Compilation Use django.template.loaders.cached.Loader TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )), )
  • 23. Template Fragment Caching {% load cache %} {% cache 500 “last_comments” %} .. last comments .. {% endcache %} {% load cache %} {% cache 500 “my_recent_comments” user.id %} .. user’s recent comments .. {% endcache %}
  • 24. Don’t forget about the browser 80% or more of the end-user response time is spent in the front end Combine Compress Cache Less is more Load slow things later Focus on making the important things faster
  • 25. Don’t forget about the browser Google PageSpeed Insights webpagetest.org Chrome & Firefox
  • 26. Assets Django Compressor {% compress js %} <script src="/static/js/one.js"></script> <script>obj.value = "value";</script> {% endcompress %} Django Assets {% assets "js_all" %} <script async src="{{ ASSET_URL }}"></script> {% endassets %}
  • 27. Q & Maybe A @polmuz
  • 28. References Performance is a feature - http://blog.codinghorror.com/performance-is-a-feature/ Marissa Mayer at Web 2.0 - http://glinden.blogspot.com.ar/2006/11/marissa-mayer-at-web-20.html Psychology of Web Performance - http://www.websiteoptimization.com/speed/tweak/psychology-web-performance/ New Relic - http://newrelic.com Google Analytics - http://www.google.com/analytics/ Tracking Application Response Time with Nginx - http://lincolnloop.com/blog/tracking-application-response-time-nginx/ Logging Apache response times - http://www.moeding.net/archives/33-Logging-Apache-response-times.html Django Debug Toolbar - http://django-debug-toolbar.readthedocs.org/ DDT Template Timings - https://github.com/orf/django-debug-toolbar-template-timings Django Database Optimizations - https://docs.djangoproject.com/en/1.7/topics/db/optimization/ Two Hard Things - http://martinfowler.com/bliki/TwoHardThings.html Django Cache Docs - https://docs.djangoproject.com/en/1.7/topics/cache/ Django Cacheback - http://django-cacheback.readthedocs.org/en/latest/index.html Cached Templates - https://docs.djangoproject.com/en/1.7/ref/templates/api/#django.template.loaders.cached.Loader Google PageSpeed Insights - https://developers.google.com/speed/pagespeed/insights/ Web Page Test - http://www.webpagetest.org/ Django Compressor - http://django-compressor.readthedocs.org/en/1.3/ Django Assets - http://django-assets.readthedocs.org/en/0.8/