Level Up Your Django Performance with Mohammad Ahtasham ul Hassan and Shafqat Farhan Ahmed
Transcript
By Mohammad Ahtasham ul Hassan, Speaker 2. From DjangoCon US 2024. Published December 6, 2024.
Watch the video Markdown version 2,127 words · auto-generated · en
Summary
Django’s ORM abstracts database queries and evaluates them lazily, but that convenience can produce the N+1 query problem: one query loads a set of objects, followed by one additional query for each related object. The speakers show how six talks can trigger seven queries when each talk accesses its conference, and explain how Django Debug Toolbar, code reviews, and query-count assertions can reveal the issue. They recommend `select_related()` for foreign-key relationships and `prefetch_related()` for many-to-many, reverse, and one-to-many relationships, while warning that eager loading can increase memory use and should be applied only when needed, including in Django REST Framework serializers.
Transcript
Automatically transcribed, so expect mistakes in names and technical terms. Filler words are removed.
0:00 Introduction
Carbon
Mohammad Ahtasham ul Hassan
Good morning and good afternoon, everyone. Wherever you are and in whichever time zone you are in. My name is Mohammed Shamul Hassan and today along with my co-presenter Shafkat Farhan Ahmed we'll be presenting to you the topic identifying and theming n plus one queries. Before diving into the topic a brief introduction about us that we both work as software engineers at Arbisoft which is a service software services company in Pakistan In this talk, we will explore how performance can be impacted by N plus one QE problem and
more importantly how we can tackle it and resolve it effectively. Over to the agenda. First, we'll start with the overview of ORMs and how they interact with relational databases. Then we will discuss how performance is important for us in software applications. We'll also dive into what is the N plus one problem actually and how it impacts performance of our applications. We'll show you an example to help identify the N plus one problem as well as we will look into the strategies
1:51 Django ORM Fundamentals
Mohammad Ahtasham ul Hassan
to explore to resolve and to you know fix these problems the problem of the n plus one curies and finally we will wrap up with some key considerations and takeaways before opening the floor for all of you for any questions that you might have. So Let's move forward to the overviews of ORM, which stands for the Object Relational Mappers or Mapping that provide us a layer of abstraction and simplify our database interactions by automatically generating queries for us. So they provide us an abstraction on the top of the database and help us execute the queries
More easily and without actually writing the queries by ourselves. And on the top of that Django ORM which we will be which we'll be using like many others it operates on the lazy curing principle which means that when we write any operations that deal with the database they are not actually evaluated at that time but they are actually evaluated when we actually access the database. While this can be efficient, it also introduces the N plus one query problem, particularly when we are dealing with large datasets where it can be actually problematic. And this problem
3:29 Why Performance Matters
Mohammad Ahtasham ul Hassan
can significantly impact the performance of our software applications So next we'll look into why the performance is actually beneficial and important for us before diving into what is N plus one problem and how it affects us So why performance matters for us? First and foremost, it impacts our user experience because slow applications tend to frustrate the user and in result it results in poor user retention for our applications And performance issues can also lead us to timeouts on our applications and even random crashes
due to the memory overloads. And one important aspect is the search engine optimization where search engine rankings will be affected if our application is slow and leading to low user turnouts and reduced visibility for us. Ultimately, what all these things contribute to is the low user turnout for our application And this is the downside of low performance applications for us. So while using ORMs, we have to consider all these impacts of performance. While the abstraction that the
5:00 The N+1 Query Problem
Mohammad Ahtasham ul Hassan
ORM provides to us is beneficial for us in many cases, it can also cause headaches for us in many cases. other cases as well. So we have to be mindful of its impact on our applications, particularly when dealing with applications that deal with a large volume of data set. So let's move forward to the actual problem that we'll be dealing with. That is the n plus one problem. So the N plus one pro problem in itself is where we have single Curie for our actual database model and in turn
it also makes n queries where n stands for the number of records which are related to our actual call. So this scenario can occur in cases where we have foreign key mappings, foreign key relationships actually, where we have many-to-many relationships we where we are doing some reverse foreign key lookups and it can also occur for us where we are using templates that execute or queries or we have DRF APIs Django Rest framework serializer APIs where the serializers rely on ORM queries that in turn execute n plus one queries
6:31 ORM Flexibility and Trade-offs
Mohammad Ahtasham ul Hassan
so if this issue is so widespread and so common, why doesn't the Django ORM itself handle this? It trickles down to two main factors which are performance and flexibility. As we mentioned, that ORMs use lazy loading to minimize the initial query size which is also beneficial for us with large data sets when we are not going to you know utilize or we when we are not going to need all of the related dataset But this flexibility comes at the cost of performance in certain scenarios with large data sets and where we have complex relationships. So as an example,
7:17 Conference and Talk Example
Mohammad Ahtasham ul Hassan
we have taken two models here the conference model Which is a simple model having two fields and the top model which contains a foreign key relationship to the conference table And next up, we have a use case where we'll try to fetch conference names from their respective talks. So first we fetch all the talks and then we try to fetch all their talks conferences so from the outset if you look at this code this just looks like a simple code which gets the job done for us But actually deep inside that lies our N plus one problem and
for actually Explaining that to you and identifying that problem. I'll hand it over to Shafkat who will help you identify the problem as well as rectify and resolve the issue. So over to Shafkat
8:20 Performance Impact
Speaker 2
Thank you, Adam. Before I jump into identifying the problem I want to highlight the importance and the impact, performance impact of the N plus one problem in a software application. First and foremost, it leads to increased database round trips for each query. For example, every time we evaluate the data, a new database query is executed to fetch that data. Eventually Increases the number of round trips made to the database. This, as Atisham has already explained, will result in a D
in a degraded user experience. and end users may face low page load times or unresponsive pages. Another performance hit could be that our servers are working harder than necessary because leading to leading to the suboptimal resource consumptions because of the inefficient QD execution. And lastly with respect to Django Rest framework API's timeout might occur more frequently due to obviously as I explained earlier the suboptimal or the inefficient QD execution
9:53 Identifying N+1 Queries
Speaker 2
Okay, now let's dive into identifying the problem. I'll use the same example that the Sham showed earlier. With you Django models. Yeah. Thank you, Ethisham. So this is the previous slide that Athic Sam explained. In this there are two models conference and talk which have a foreign key relation Relationship between them. Now let's assume we have six rackets in the talk database table. I use the Django debug toolbar to evaluate the SQL queries, executed during the evaluation of the of the query set. As we can see
there are total seven queries executed One for retrieving the talks and six more, one for each talk to fetch the associated data, which is the conference models fields. So this in particular is an n plus one problem because total seven queries are executed and ideally we should only need one. Other ways of identifying this problem early in the stages is conducting detailed or thorough code reviews and writing unit tests. Unit tests are helpful because we can
we have an ability in Django to excuse me to write the unit test to check the number of queries or the to assert the query count so we can tackle this issue in the early stages or before even deploying the changes to the production servers. And there are few other options we can use third party packages that that detect this problem and plus one problem The one that I in that I've used is the most commonly used one which is the Dango Debug Toolbars SQL window Okay, so now we'll explore the options that Django provides, Django Goarm provides
12:10 select_related and prefetch_related
Speaker 2
to fix this problem. There are two methods that Django ORM provides to eagerly load the data where required. First one is select related. This is effective in models with the foreign key relation. It allows us to load the relational related data in a single query, reducing the number of database round trip just to one. for many to many or reverse lookups or for one-to-many relations Django ORM provides us with prefetch related method. This method performs at least two queries if we have just one prefetch related method added to the ORM query.
So there will be at least two queries and then the data is loaded into the memory and the joins occur in the Python code. Okay, so I've explained both of the methods that Django ORM provides now let's take a look Sorry, at our example problem and let's apply the fix. So for the certificate related as we've seen in the previous slides like the talk table The talk model was fetching all of its data and the related data was being evaluated and additional queries were being executed. So if you can see the first example under the select related section, we have added select related method to the QD.
What it will do is So this method will eventually fetch the associated data in a single query. Next slide please. So here as you can see once we have applied the fix, the Django debugs toolbar SQL window shows that only one query was executed. And this query is now a bit more complex because it involves inner joint operation. But we have achieved our performance We have improved our performance by just curing the database or reducing the database round trips just one. For large datasets, this will bring a significant boost in the performance, especially when we are dealing with enormous
14:37 Performance Considerations
Speaker 2
datasets. Okay, so as we wrap up, here are some considerations and key takeaways. First, the performance impact Of n plus one QRs will be minimal or small dataset, which is obvious asham has explained earlier. However, the as the data grows, so does the impact And solving the n plus one problem in large and complex datasets can sometimes cause ripple effects. Yes, they do. For example Pre-fetching large datasets
can lead to increased memory usage. So it's important to be mindful of this trade-off. Because as we have explained earlier, if we have increased memory then we might or users may face server crashes or server performance might get a hit So third takeaway is that avoid we should avoid pre-fetching related data if there is no specific use case Mindful data fetching is crucial here to maintain the performance. This is why most ORMs work on a lazy loading principle. So it has its own benefits. And finally, we do have to be mindful here, like when working with Django Rest framework, serializers, mostly the model serializers
also. use or work with Django ORM so fetching relational data can also lead to N plus one problems there as well Here are a few resources that are from the Django's official documentation, which you guys can take a look. Yeah, that's all for the presentation. If you have any questions, please let us know. Thank you