SlideShare une entreprise Scribd logo
Django
Performance
Recipes
September 2015
Jon Atkinson
Technical Director
FARM Digital
Me
• I am not a very good programmer.
• I’m quite a good problem solver.
• I have made a lot of mistakes.
• I prefer valuable solutions.
My Context
• “Fast-moving agency environment”.
• We often participate in launches; demand is
spiky.
• Complex software.
Shared Context
• Traffic is unpredictable.
• We probably host in the cloud.
• The Django ecosystem.
Performance Matters
Speed is all about perception, but:
0-100ms Instant!
100-300ms Small delay.
300-1000ms Something is happening.
1000ms+ Likely task switch.
10000ms+ Abandoned task.
Rule of thumb
50% of users will abandon a task after
3 seconds.
Environment
A web server, talking to:
A managed python process, talking to:
A cache, and a database.
Request Cycle
Web Server
ORM
Middleware
Views + Templates
Web Server
Tools
!
ORM
• Optimising your database is a separate
presentation entirely.
• There are no ‘slow’ databases any more.
• In a read-heavy environment, caching Querysets
is a huge advantage.
ORM
django-cachalot
Caches your Django ORM queries and
automatically invalidates them.
ORM
$ pip install django-cachalot
INSTALLED_APPS += (‘cachalot’)
settings.CACHALOT_ENABLED = True
ORM
from django.conf import settings
from django.test.utils import override_settings
with override_settings(CACHALOT_ENABLED=False):
# SQL queries are not cached in this block
@override_settings(CACHALOT_CACHE=‘second_cache')
def your_function():
# What’s in this function uses another cache
# Globally disables SQL caching until you set it back to True
settings.CACHALOT_ENABLED = False
ORM
• A few other data access tips:
• Is your database doing DNS lookups?
• Do you have a connection timeout set? The
default is 0, and setup/teardown costs time.
settings.DATABASES[‘…’][‘CONN_MAX_AGE’] = 600
Middleware
Middleware is dumb.
Middleware
Middleware
• Think hard. Milliseconds add up.
• Middleware (and context processors!) often
becomes a dumping ground for common
features.
Middleware
Middleware is helpful.
Middleware
django.middleware.http.ConditionalGetMiddleware
Optimises GET requests from modern browsers
django.middleware.http.GZipMiddleware
Compresses responses. But be aware of BREACH!
Middleware
$ pip install django-cprofile-middleware
“Once you've installed it, log in as a user who has
staff privileges and add ?prof to any URL to see the
profiler's stats.”
eg. http://localhost:8000/foo/?prof.
Middleware
7986 function calls (7850 primitive calls) in 1.725 CPU seconds
Ordered by: internal time, call count
List reduced from 392 to 20 due to restriction <20>
ncalls tottime percall cumtime percall filename:lineno(function)
2 1.570 0.785 1.570 0.785 /…/django/db/backends/__init__.py:36(_commit)
15 0.043 0.003 0.043 0.003 /…/linecache.py:68(updatecache)
1 0.020 0.020 0.027 0.027 /…/django/contrib/auth/models.py:1(<module>)
12 0.014 0.001 0.030 0.002 /…/django/utils/importlib.py:18(import_module)
1013 0.010 0.000 0.010 0.000 /…/posixpath.py:56(join)
Views & Templates
• View performance problems are usually obvious:
• Avoid nested loops (especially when generating
QuerySets!)
• Cache where you can.
• Always return at the earliest possible moment.
Views & Templates
• Templates are more interesting.
• It’s easy to duplicate ORM calls already made in
the view.
• It’s easy to traverse relationships in the template
language.
• Templates are loaded from disk by default.
Views & Templates
class Person(models.Model):
def friends(self):
# Hit the database here for something complex…
return friends
# View:
if person.friends():
# Do something here…
# Template:
{% for friend in person.friends %}
Views & Templates
from django.utils.functional import
cached_property
@cached_property
def friends(self):
# Hit the database here for something complex…
return friends
Views & Templates
• Caching template fragments is very powerful.
• Sometimes you need to do something expensive in a
template, but:
{% load cache %}
{% cache 500 sidebar %}
… do something expensive here …
{% endcache %}
Views & Templates
• Where do your templates actually live?
• Cloud disk performance can be erratic.
Views & Templates
# Default setting.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
Views & Templates
TEMPLATE_LOADERS = (
('django.template.loaders.cached.Loader', (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)),
)
nginx
This is my “one weird tip”…
… with a trade-off.
uwsgi_cache_path /tmp/nginx levels=1:2 keys_zone=my_zone:10m;
server {
listen 80;
server_name example.com;
…
uwsgi_cache_use_stale error timeout invalid_header http_500;
uwsgi_cache_valid 10m;
location / {
include uwsgi_params;
uwsgi_pass unix:///tmp/example.sock;
uwsgi_cache cache;
uwsgi_cache_key $scheme:$host$request_uri:$request_method;
uwsgi_cache_bypass $http_pragma $http_authorization;
uwsgi_no_cache $http_pragma $http_authorization;
}
nginx
Tools
• The tool ecosystem is richer now than ever
before.
$ pip install django-debug-toolbar
$ pip install dogslow
• Measure twice, cut once.
• Remember, Schrödinger’s web app.
Tools
Tools
import newrelic.agent
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# This needs to be called after we bootstrapped the application
# otherwise the settings wouldn't be configured
from django.conf import settings # noqa
if hasattr(settings, 'NEWRELIC_CONFIG'):
newrelic.agent.initialize(settings.NEWRELIC_CONFIG 
getattr(settings, 'NEWRELIC_ENVIRONMENT', None))
application = newrelic.agent.WSGIApplicationWrapper(application)
Meta 1
Performance can be personal.
Meta 2
Meta 2
Meta 3
Performance is of huge value.
10x programmers probably don’t exist.
Keep your eyes up.
Concentrate on where the value lies.
Thank You
Questions?
Resources & Credits: http://blog.wearefarm.com

Contenu connexe

Tendances

Building a Dynamic Website Using Django
Building a Dynamic Website Using DjangoBuilding a Dynamic Website Using Django
Building a Dynamic Website Using Django
Nathan Eror
 
Getting started with Django 1.8
Getting started with Django 1.8Getting started with Django 1.8
Getting started with Django 1.8
rajkumar2011
 
Php go vrooom!
Php go vrooom!Php go vrooom!
Php go vrooom!
Elizabeth Smith
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
Anis Ahmad
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
Aizat Faiz
 
Writing Pluggable Software
Writing Pluggable SoftwareWriting Pluggable Software
Writing Pluggable Software
Tatsuhiko Miyagawa
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life better
ZendCon
 
Django multi-tier
Django multi-tierDjango multi-tier
Django multi-tier
smirolo
 
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
Simon Willison
 
Php on the Web and Desktop
Php on the Web and DesktopPhp on the Web and Desktop
Php on the Web and Desktop
Elizabeth Smith
 
WordPress and Ajax
WordPress and AjaxWordPress and Ajax
WordPress and Ajax
Ronald Huereca
 
Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJRealize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
Leonardo Balter
 
HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?
Remy Sharp
 
Free django
Free djangoFree django
Free django
Eugen Oskin
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
Eric Palakovich Carr
 
Web::Scraper
Web::ScraperWeb::Scraper
Web::Scraper
Tatsuhiko Miyagawa
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
Julien Lecomte
 
Don't RTFM, WTFM - Open Source Documentation - German Perl Workshop 2010
Don't RTFM, WTFM - Open Source Documentation - German Perl Workshop 2010Don't RTFM, WTFM - Open Source Documentation - German Perl Workshop 2010
Don't RTFM, WTFM - Open Source Documentation - German Perl Workshop 2010
singingfish
 
Web application development with Django framework
Web application development with Django frameworkWeb application development with Django framework
Web application development with Django framework
flapiello
 
Learning django step 1
Learning django step 1Learning django step 1
Learning django step 1
永昇 陳
 

Tendances (20)

Building a Dynamic Website Using Django
Building a Dynamic Website Using DjangoBuilding a Dynamic Website Using Django
Building a Dynamic Website Using Django
 
Getting started with Django 1.8
Getting started with Django 1.8Getting started with Django 1.8
Getting started with Django 1.8
 
Php go vrooom!
Php go vrooom!Php go vrooom!
Php go vrooom!
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 
Writing Pluggable Software
Writing Pluggable SoftwareWriting Pluggable Software
Writing Pluggable Software
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life better
 
Django multi-tier
Django multi-tierDjango multi-tier
Django multi-tier
 
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
 
Php on the Web and Desktop
Php on the Web and DesktopPhp on the Web and Desktop
Php on the Web and Desktop
 
WordPress and Ajax
WordPress and AjaxWordPress and Ajax
WordPress and Ajax
 
Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJRealize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
 
HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?
 
Free django
Free djangoFree django
Free django
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
Web::Scraper
Web::ScraperWeb::Scraper
Web::Scraper
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 
Don't RTFM, WTFM - Open Source Documentation - German Perl Workshop 2010
Don't RTFM, WTFM - Open Source Documentation - German Perl Workshop 2010Don't RTFM, WTFM - Open Source Documentation - German Perl Workshop 2010
Don't RTFM, WTFM - Open Source Documentation - German Perl Workshop 2010
 
Web application development with Django framework
Web application development with Django frameworkWeb application development with Django framework
Web application development with Django framework
 
Learning django step 1
Learning django step 1Learning django step 1
Learning django step 1
 

Similaire à Django Performance Recipes

Where Django Caching Bust at the Seams
Where Django Caching Bust at the SeamsWhere Django Caching Bust at the Seams
Where Django Caching Bust at the Seams
Concentric Sky
 
Drupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp NorthDrupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp North
Philip Norton
 
Expecto Performa! The Magic and Reality of Performance Tuning
Expecto Performa! The Magic and Reality of Performance TuningExpecto Performa! The Magic and Reality of Performance Tuning
Expecto Performa! The Magic and Reality of Performance Tuning
Atlassian
 
2019 StartIT - Boosting your performance with Blackfire
2019 StartIT - Boosting your performance with Blackfire2019 StartIT - Boosting your performance with Blackfire
2019 StartIT - Boosting your performance with Blackfire
Marko Mitranić
 
Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop...
Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop...Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop...
Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop...
DataWorks Summit
 
High Performance Django 1
High Performance Django 1High Performance Django 1
High Performance Django 1
DjangoCon2008
 
High Performance Django
High Performance DjangoHigh Performance Django
High Performance Django
DjangoCon2008
 
Performance & Scalability Improvements in Perforce
Performance & Scalability Improvements in PerforcePerformance & Scalability Improvements in Perforce
Performance & Scalability Improvements in Perforce
Perforce
 
Top ten-list
Top ten-listTop ten-list
Top ten-list
Brian DeShong
 
Beat the devil: towards a Drupal performance benchmark
Beat the devil: towards a Drupal performance benchmarkBeat the devil: towards a Drupal performance benchmark
Beat the devil: towards a Drupal performance benchmark
Pedro González Serrano
 
Capacity Management from Flickr
Capacity Management from FlickrCapacity Management from Flickr
Capacity Management from Flickr
xlight
 
Scaling PHP apps
Scaling PHP appsScaling PHP apps
Scaling PHP apps
Matteo Moretti
 
Cloud Best Practices
Cloud Best PracticesCloud Best Practices
Cloud Best Practices
Eric Bottard
 
Cloud Computing with .Net
Cloud Computing with .NetCloud Computing with .Net
Cloud Computing with .Net
Wesley Faler
 
Gearman - Northeast PHP 2012
Gearman - Northeast PHP 2012Gearman - Northeast PHP 2012
Gearman - Northeast PHP 2012
Mike Willbanks
 
Profiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / WebgrindProfiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / Webgrind
Sam Keen
 
Gearman: A Job Server made for Scale
Gearman: A Job Server made for ScaleGearman: A Job Server made for Scale
Gearman: A Job Server made for Scale
Mike Willbanks
 
(BDT402) Performance Profiling in Production: Analyzing Web Requests at Scale...
(BDT402) Performance Profiling in Production: Analyzing Web Requests at Scale...(BDT402) Performance Profiling in Production: Analyzing Web Requests at Scale...
(BDT402) Performance Profiling in Production: Analyzing Web Requests at Scale...
Amazon Web Services
 
Real-Time Query for Data Guard
Real-Time Query for Data Guard Real-Time Query for Data Guard
Real-Time Query for Data Guard
Uwe Hesse
 
PyGrunn 2017 - Django Performance Unchained - slides
PyGrunn 2017 - Django Performance Unchained - slidesPyGrunn 2017 - Django Performance Unchained - slides
PyGrunn 2017 - Django Performance Unchained - slides
Artur Barseghyan
 

Similaire à Django Performance Recipes (20)

Where Django Caching Bust at the Seams
Where Django Caching Bust at the SeamsWhere Django Caching Bust at the Seams
Where Django Caching Bust at the Seams
 
Drupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp NorthDrupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp North
 
Expecto Performa! The Magic and Reality of Performance Tuning
Expecto Performa! The Magic and Reality of Performance TuningExpecto Performa! The Magic and Reality of Performance Tuning
Expecto Performa! The Magic and Reality of Performance Tuning
 
2019 StartIT - Boosting your performance with Blackfire
2019 StartIT - Boosting your performance with Blackfire2019 StartIT - Boosting your performance with Blackfire
2019 StartIT - Boosting your performance with Blackfire
 
Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop...
Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop...Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop...
Dr Elephant: LinkedIn's Self-Service System for Detecting and Treating Hadoop...
 
High Performance Django 1
High Performance Django 1High Performance Django 1
High Performance Django 1
 
High Performance Django
High Performance DjangoHigh Performance Django
High Performance Django
 
Performance & Scalability Improvements in Perforce
Performance & Scalability Improvements in PerforcePerformance & Scalability Improvements in Perforce
Performance & Scalability Improvements in Perforce
 
Top ten-list
Top ten-listTop ten-list
Top ten-list
 
Beat the devil: towards a Drupal performance benchmark
Beat the devil: towards a Drupal performance benchmarkBeat the devil: towards a Drupal performance benchmark
Beat the devil: towards a Drupal performance benchmark
 
Capacity Management from Flickr
Capacity Management from FlickrCapacity Management from Flickr
Capacity Management from Flickr
 
Scaling PHP apps
Scaling PHP appsScaling PHP apps
Scaling PHP apps
 
Cloud Best Practices
Cloud Best PracticesCloud Best Practices
Cloud Best Practices
 
Cloud Computing with .Net
Cloud Computing with .NetCloud Computing with .Net
Cloud Computing with .Net
 
Gearman - Northeast PHP 2012
Gearman - Northeast PHP 2012Gearman - Northeast PHP 2012
Gearman - Northeast PHP 2012
 
Profiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / WebgrindProfiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / Webgrind
 
Gearman: A Job Server made for Scale
Gearman: A Job Server made for ScaleGearman: A Job Server made for Scale
Gearman: A Job Server made for Scale
 
(BDT402) Performance Profiling in Production: Analyzing Web Requests at Scale...
(BDT402) Performance Profiling in Production: Analyzing Web Requests at Scale...(BDT402) Performance Profiling in Production: Analyzing Web Requests at Scale...
(BDT402) Performance Profiling in Production: Analyzing Web Requests at Scale...
 
Real-Time Query for Data Guard
Real-Time Query for Data Guard Real-Time Query for Data Guard
Real-Time Query for Data Guard
 
PyGrunn 2017 - Django Performance Unchained - slides
PyGrunn 2017 - Django Performance Unchained - slidesPyGrunn 2017 - Django Performance Unchained - slides
PyGrunn 2017 - Django Performance Unchained - slides
 

Dernier

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 

Dernier (20)

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 

Django Performance Recipes

  • 2. Me • I am not a very good programmer. • I’m quite a good problem solver. • I have made a lot of mistakes. • I prefer valuable solutions.
  • 3. My Context • “Fast-moving agency environment”. • We often participate in launches; demand is spiky. • Complex software.
  • 4. Shared Context • Traffic is unpredictable. • We probably host in the cloud. • The Django ecosystem.
  • 5. Performance Matters Speed is all about perception, but: 0-100ms Instant! 100-300ms Small delay. 300-1000ms Something is happening. 1000ms+ Likely task switch. 10000ms+ Abandoned task.
  • 6. Rule of thumb 50% of users will abandon a task after 3 seconds.
  • 7. Environment A web server, talking to: A managed python process, talking to: A cache, and a database.
  • 8. Request Cycle Web Server ORM Middleware Views + Templates Web Server Tools
  • 9. !
  • 10. ORM • Optimising your database is a separate presentation entirely. • There are no ‘slow’ databases any more. • In a read-heavy environment, caching Querysets is a huge advantage.
  • 11. ORM django-cachalot Caches your Django ORM queries and automatically invalidates them.
  • 12. ORM $ pip install django-cachalot INSTALLED_APPS += (‘cachalot’) settings.CACHALOT_ENABLED = True
  • 13. ORM from django.conf import settings from django.test.utils import override_settings with override_settings(CACHALOT_ENABLED=False): # SQL queries are not cached in this block @override_settings(CACHALOT_CACHE=‘second_cache') def your_function(): # What’s in this function uses another cache # Globally disables SQL caching until you set it back to True settings.CACHALOT_ENABLED = False
  • 14. ORM • A few other data access tips: • Is your database doing DNS lookups? • Do you have a connection timeout set? The default is 0, and setup/teardown costs time. settings.DATABASES[‘…’][‘CONN_MAX_AGE’] = 600
  • 17. Middleware • Think hard. Milliseconds add up. • Middleware (and context processors!) often becomes a dumping ground for common features.
  • 19. Middleware django.middleware.http.ConditionalGetMiddleware Optimises GET requests from modern browsers django.middleware.http.GZipMiddleware Compresses responses. But be aware of BREACH!
  • 20. Middleware $ pip install django-cprofile-middleware “Once you've installed it, log in as a user who has staff privileges and add ?prof to any URL to see the profiler's stats.” eg. http://localhost:8000/foo/?prof.
  • 21. Middleware 7986 function calls (7850 primitive calls) in 1.725 CPU seconds Ordered by: internal time, call count List reduced from 392 to 20 due to restriction <20> ncalls tottime percall cumtime percall filename:lineno(function) 2 1.570 0.785 1.570 0.785 /…/django/db/backends/__init__.py:36(_commit) 15 0.043 0.003 0.043 0.003 /…/linecache.py:68(updatecache) 1 0.020 0.020 0.027 0.027 /…/django/contrib/auth/models.py:1(<module>) 12 0.014 0.001 0.030 0.002 /…/django/utils/importlib.py:18(import_module) 1013 0.010 0.000 0.010 0.000 /…/posixpath.py:56(join)
  • 22. Views & Templates • View performance problems are usually obvious: • Avoid nested loops (especially when generating QuerySets!) • Cache where you can. • Always return at the earliest possible moment.
  • 23. Views & Templates • Templates are more interesting. • It’s easy to duplicate ORM calls already made in the view. • It’s easy to traverse relationships in the template language. • Templates are loaded from disk by default.
  • 24. Views & Templates class Person(models.Model): def friends(self): # Hit the database here for something complex… return friends # View: if person.friends(): # Do something here… # Template: {% for friend in person.friends %}
  • 25. Views & Templates from django.utils.functional import cached_property @cached_property def friends(self): # Hit the database here for something complex… return friends
  • 26. Views & Templates • Caching template fragments is very powerful. • Sometimes you need to do something expensive in a template, but: {% load cache %} {% cache 500 sidebar %} … do something expensive here … {% endcache %}
  • 27. Views & Templates • Where do your templates actually live? • Cloud disk performance can be erratic.
  • 28. Views & Templates # Default setting. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )
  • 29. Views & Templates TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )), )
  • 30. nginx This is my “one weird tip”… … with a trade-off.
  • 31. uwsgi_cache_path /tmp/nginx levels=1:2 keys_zone=my_zone:10m; server { listen 80; server_name example.com; … uwsgi_cache_use_stale error timeout invalid_header http_500; uwsgi_cache_valid 10m; location / { include uwsgi_params; uwsgi_pass unix:///tmp/example.sock; uwsgi_cache cache; uwsgi_cache_key $scheme:$host$request_uri:$request_method; uwsgi_cache_bypass $http_pragma $http_authorization; uwsgi_no_cache $http_pragma $http_authorization; }
  • 32. nginx
  • 33. Tools • The tool ecosystem is richer now than ever before. $ pip install django-debug-toolbar $ pip install dogslow • Measure twice, cut once. • Remember, Schrödinger’s web app.
  • 34. Tools
  • 35. Tools
  • 36. import newrelic.agent from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # This needs to be called after we bootstrapped the application # otherwise the settings wouldn't be configured from django.conf import settings # noqa if hasattr(settings, 'NEWRELIC_CONFIG'): newrelic.agent.initialize(settings.NEWRELIC_CONFIG getattr(settings, 'NEWRELIC_ENVIRONMENT', None)) application = newrelic.agent.WSGIApplicationWrapper(application)
  • 37. Meta 1 Performance can be personal.
  • 40. Meta 3 Performance is of huge value. 10x programmers probably don’t exist. Keep your eyes up. Concentrate on where the value lies.
  • 41. Thank You Questions? Resources & Credits: http://blog.wearefarm.com