Slide 1

Slide 1 text

Django the next steps

Slide 2

Slide 2 text

Django is great*!

Slide 3

Slide 3 text

Tips, tricks and tuning -beyond- simple Django projects.

Slide 4

Slide 4 text

premature optimization is the root of all evil

Slide 5

Slide 5 text

yet we should not pass up our opportunities in that critical 3%

Slide 6

Slide 6 text

victor neo Lead Engineer @ Carousell hi there, I am

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

Caching ORM / Database Asynchronous Tasks Logging / Monitoring * *

Slide 9

Slide 9 text

Posts + Comments Count

Slide 10

Slide 10 text

1. GET /index 2. Load posts from DB 3. Render template Homepage of a Blog Takes 200~500ms :(

Slide 11

Slide 11 text

first layer of defence Caching is your

Slide 12

Slide 12 text

1. GET /index 2. Return cached output Speeding it up (completes in < 50ms!)

Slide 13

Slide 13 text

Django’s per view cache @cache_page(60 * 15)! def homepage(request): Caches homepage for ~15 minutes

Slide 14

Slide 14 text

No content

Slide 15

Slide 15 text

CONTROL But I need more !

Slide 16

Slide 16 text

Django’s low level cache posts = Post.objects.….all() cache.set(‘posts’, posts, 60) # some complicated logic here

Slide 17

Slide 17 text

Django Cache Machine Automatic caching and invalidation of Models Provides a Cache Manager

Slide 18

Slide 18 text

Cache Machine # models.py! class Post(models.Model):! objects = CachingManager() Post.objects.….all() Subsequent calls are cached!

Slide 19

Slide 19 text

REDIS Can I use?

Slide 20

Slide 20 text

Redis for Caching Django-Redis: Use redis instead of Memcached Django-cacheops: Similar to Cache Machine, for Redis

Slide 21

Slide 21 text

Memcached Redis Feature-packed Cache Machine Django-Cacheops Custom Roll your own with Django cache API Django-Redis Decisions, decisions

Slide 22

Slide 22 text

Rule of thumb Cache if data freshness is not an issue Critical if computation is expensive

Slide 23

Slide 23 text

Caching ORM / Database Asynchronous Tasks Logging / Monitoring

Slide 24

Slide 24 text

Foreign Keys e = Post.objects.get(id=5)! ! e.blog.name! ! ! # Additional ! ! ! ! ! ! ! ! ! ! ! # DB query! ! ! ! ! ! ! ! ! ! ! # for blog

Slide 25

Slide 25 text

select_related e = Entry.objects.\! select_related(‘blog’).\! get(id=5)! ! e.blog.name! ! ! # No DB query!

Slide 26

Slide 26 text

select vs prefetch related One-to-one / Foreign Key: select_related ! Many-to-many / Many-to-one / Generic relations: prefetch_related

Slide 27

Slide 27 text

Post.objects.filter( is_published=True, is_edited=True, …).all()

Slide 28

Slide 28 text

SELECT … FROM blog_posts WHERE is_published = true AND is_edited = true AND …

Slide 29

Slide 29 text

Database Know thy !

Slide 30

Slide 30 text

PostgreSQL EXPLAIN ANALYZE

Slide 31

Slide 31 text

Non-Active Users User.objects.\! filter(is_active=False).\! .all()

Slide 32

Slide 32 text

Non-Active Users (SQL) SELECT * FROM auth_users! WHERE is_active = false;

Slide 33

Slide 33 text

Analyzing Queries EXPLAIN ANALYZE! SELECT * FROM AUTH_USERS! WHERE is_active = false; Prepend

Slide 34

Slide 34 text

QUERY PLAN! ---------------------------------! Seq Scan on auth_user ! ! (cost=0.00..15761.01 rows=2413 width=140) (actual time=0.161..279.318 rows=2384 loops=1)! Filter: (NOT is_active)! ! Total runtime: 280.890 ms! ! (3 rows)

Slide 35

Slide 35 text

CREATE INDEX CONCURRENTLY! ON auth_user (is_active)! WHERE is_active = false; Create an Index on is_active attribute

Slide 36

Slide 36 text

QUERY PLAN! ------------------------------- Index Scan using auth_user_is_active_idx on auth_user! ! (cost=0.00..59.19 rows=2413 width=140)! (actual time=0.129..8.824 rows=2384 loops=1)! ! Index Cond: (is_active = false)! ! Total runtime: 9.779 ms! ! (3 rows)

Slide 37

Slide 37 text

No content

Slide 38

Slide 38 text

Wait, how do I view the SQL queries?

Slide 39

Slide 39 text

Django debug toolbar

Slide 40

Slide 40 text

Silk

Slide 41

Slide 41 text

Django Query Inspector [SQL] repeated query (6x): SELECT "customer_role"."id", "customer_role"."contact_id", "customer_role"."name" FROM "customer_role" WHERE "customer_role"."contact_id" = ? Suitable for API projects with no web UI

Slide 42

Slide 42 text

Search Engine? PostgreSQL comes with full-text search Heavy search traffic? Consider Elasticsearch, Solr

Slide 43

Slide 43 text

No content

Slide 44

Slide 44 text

Haystack Supports Elasticsearch, Solr and more Easy to get started with manage.py commands Familiar ORM syntax for searching

Slide 45

Slide 45 text

Doing a search SearchQuerySet().models(Post).! filter(content=‘Python’).all()! ! [! ,! ,! …]

Slide 46

Slide 46 text

Happy ORM Use select/prefetch related to reduce queries Understand your DB’s query planner Haystack for search

Slide 47

Slide 47 text

Caching ORM / Database Asynchronous Tasks Logging / Monitoring

Slide 48

Slide 48 text

No content

Slide 49

Slide 49 text

View is slow :( reset_pw_email(user.email)! ! # needs to wait for email to! # be sent before we can send ! # a response! ! return HttpResponse(…)

Slide 50

Slide 50 text

Celery Tasks @task! def reset_pw_email(email):! … Just add @task decorator!

Slide 51

Slide 51 text

Calling Tasks # In your Django view! ! reset_pw_email.delay(user.email) View continues, without waiting for email to be sent

Slide 52

Slide 52 text

HTTP Callback tasks HttpDispatchTask.delay(! url='http://a.com/multiply',! method=‘GET', x=10, y=10) Awesome for microservices

Slide 53

Slide 53 text

Caching ORM / Database Asynchronous Tasks Logging / Monitoring

Slide 54

Slide 54 text

django.db.models.query in get MultipleObjectsReturned: get() returned more than one User -- it returned 2!

Slide 55

Slide 55 text

Errors Happen Let’s deal with them

Slide 56

Slide 56 text

Watch them as they happen

Slide 57

Slide 57 text

Log errors when they happen in production Sentry Open source Django project Awesome web interface

Slide 58

Slide 58 text

No content

Slide 59

Slide 59 text

Monitoring or “is someone using my app”

Slide 60

Slide 60 text

New Relic

Slide 61

Slide 61 text

Instrument Everything

Slide 62

Slide 62 text

No content

Slide 63

Slide 63 text

No content

Slide 64

Slide 64 text

Logging activity c = statsd.Counter('UserSignups') c.increment()

Slide 65

Slide 65 text

What to track? Technical Metrics: Cache misses, images uploaded Business Metrics: Number of signups

Slide 66

Slide 66 text

Web Operations Keeping the Data On Time

Slide 67

Slide 67 text

Caching: Asynchronous Tasks: memcached, redis FK keys, DB queries, Haystack ORM / Database: Celery Logging / Monitoring: Sentry, Graphite

Slide 68

Slide 68 text

Thank You! @victorneo come chat with me anytime