# From Development to Production, Getting Insights to Optimize Django Performance

Source: https://djangotv.com/videos/djangocon-europe/2021/djangocon-2021-from-development-to-production-getting-insights-to-optimize-django-performance/
Date: 2021-07-31
Speakers: Jérôme Vieilledent

## Summary

Jérôme Vieilledent explains how Blackfire profiles and monitors Django applications from development through production. Its Python probe collects function timing, CPU and I/O time, memory use, database queries, and external requests on demand, while an agent aggregates and anonymizes the data; visualizations such as timelines, call graphs, metrics, and memory graphs expose slow templates, excessive queries, bottlenecks, and leaks. In production, monitoring shows real-user response times, errors, traffic, impactful transactions, deployment effects, and spans, while automatic and on-demand profiling plus synthetic YAML-defined scenarios turn those observations into actionable performance checks and recommendations.

## Transcript

### [00:07] Introduction to Blackfire

[00:07] Hi everyone. I hope you're enjoying your last conference day, I mean before the screen days and stuff. So today I want to show you a tool, a specific tool for Python developments that can help you help you out debugging and developing your application from your development environment to staging and production and beyond. So this specific tool, well, is called a profiler specifically, and so I'm going to

[00:54] talk about BlackFire itself which is a profiler and monitoring tool. So first, well, I'm so Jérôme Vieidon and I'm a developer advocate at BlackFire. io. So that will be, I will take on tour. on what you can do with Blackfire and how it can be useful for you. The goal here is to make your development life easier. And so that you can focus on what really matters for you for developing your applications and specifically to junk go So for this, I'm gonna first share my screen, of course.

### [01:42] Blackfire Architecture

[01:42] Here we go. Right. So as I explained just before, Blackfire is first and foremost a profiling tool. Like many others in the Python ecosystem, I know that there are several profilers, open source profilers in the Python world. Here I will try to explain what can differentiate these tools from Blackfire. First, BlackFire is a tracing profile profiler it means that it will take traces from every functions that are executed in your code.

[02:28] how it is how it works, it you have two main components. First Here we can see in the middle the probe. The probe is the components, is a PIP package for your Python application that will gather all the data coming from the Python engine. So we get when we talk about data, it's how long functions took, how long Python I was waiting for external things to happen like file system operations or database queries and stuff like that. So that's what we call input-output how long you had on CPU time, I mean

[03:14] computate real computation, how much memory you took, etc. etc. And this for each and every function from your application. So that's the first component that needs to be installed like any other PIP package. It's written in C, so everything, every binding is in C so that it's the fastest possible. The only things in Python will would be the SDK so that you can interact directly with the probe to enable profiling. Very important thing to know about the probe in is that it is completely production safe.

[04:00] You can and well you should actually install it in production because it's always an on-demand profiler. It means that when unless you don't ask for a profile, it does nothing. It stays completely inert. And when you do ask for a profile, of course there would be an overhead, because you know, measuring things from within from within the Python engine, even if it's very fast, it always comes with a cost. But this cost, this overhead, will won't

[04:45] affect your end users in any way Because it's always on demand. When you ask a profile, the profile will only be for you. And the other users will don't know that there is a provider and that you're providing. So no overhead at all. The second component you can see here is called the agent. The agent is the demon that just sits there and waits for raw data from the probe. To because the probe in order to limit to limit the overhead won't do the aggregation stuff aggregating the data and stuff like that they will it the probe collects raw

[05:31] data and then sends this raw data to the agent which lies into your infrastructure as well. It can be in a dedicated container you then usually Docker container or within your Kubernetes pod or whatever fancy. They only need one agent and the agent We'll take this raw data, aggregates them because we take samples, 10 samples to have proper average. We'll see that in a minute. And then we 'll anonymize sensitive data such as external HTTP requests with tokens and stuff like that and SQL queries so that Yeah, well, things are quite

### [06:18] Profiling a Django Application

[06:18] Straightforward and good to good to exploit for you. And the agent, when it's done, is uploading the aggregated profile to BlackRock servers. So that's the basics, let's say. So here, well, this is the same application. If you already followed the workshop, you would find this quite familiar. This is a very small application written in Django. It's like a blog-like application for so here it's all about hunting the Bigfoot. So instead of articles, we are writing sightings, reporting sightings of the Bigfoot, and members of the club can

[07:04] comment this out, each sighting out. So here we're on the detail page and we're still in production. You can see I'm here locally. I'm running the development web server, the manage. py run server. So pure development environment and well before commenting and the and deploying i want to understand where I could have performance bottom next or well or maybe much simpler understand how my application is behaving exactly because you know When you're running your code, your application is becoming

[07:50] kind of a black box. You cannot really know unless you're profiling, you cannot really know what's happening within. Because when you're writing code, you're writing like the blueprints. But when everything is running through the ser the run server from the Django development server or with gunicorn well then you do not have any insights And this is exactly what a profiler is about. A profiler like Blackberry. It gives you like bionic glasses to know, to see exactly what's going on. So to trigger profile here, I'm I just have to click on this

### [08:36] Timeline and Call-Graph Analysis

[08:36] very big red button to get started from my Firefox extension. It's also available for Chrome. And I just need to be authenticated. So let's click on it. And when I click to trigger a profile, it's taking, like I said, 10 samples. So it can to 0 to 100%. and then averaging things. And now I have the summary of the profile for this page. Well I have like different dimensions there So wall time, which is the overall time execution for this page in your application, which is all split it into two flavors.

[09:21] The first one is the I. O. time. So as mentioned earlier, it's a time spent by Python waiting for other operations from the from the operating system. So it might be file system, it might be network calls, HTTP requests, and well, stuff like that. The second one is the CPU time, so the actual computation time when Python is really doing something. The memory, so very important aspect. Well, external HTTP request, well here we have none, and SQL queries And then we have two kind of visualizations available. So I will first click on the timeline.

[10:08] So the timeline view is a visualization of the profile on a time base. So this is quite unusual to most providers. Most providers are only showing interactions between functions or lines and stuff like that. And we if I with Blackfire, you will be able to have this as well. This is actually the main one. But as a developer, usually you have well this is my case at least i have a representation of the profile of how my application is behaving on over time. I know that well I enter here from my whiskey

[10:55] from my whiskey scripts and then I'm going to my Django view etc and you get this visualization s thanks to the timeline view. If you're already familiar to Flame graphs, this is kind of similar, except that here well it's like a reverse flame graph. I like to call them pit graphs. And well the deeper the pits the more complex your application is basically And each block here represents the function call. So we have all the middlewares from Django here getting to the WISD handler. And here well the our view

[11:41] and well goes going to templates and to sql queries from Django models etc All the blocks are proportional to the time spent. So the longer the block, the longer the function. And with this representation, you can quite easily spot where from within your application you can have performance issues here. So for example, there I can see that these two template blocks are quite take a lot of time, right? It's really long.

[12:26] Here it's citing show. html, which is taking well 564 milliseconds, which is almost all the time for all the requests, because we are here on 600 milliseconds. So there might be something to have a look at. I can click on it and to get the whole call stack and understand from where it's going. Well here it's very straightforward once I can see that it's coming from my settings show Django view All right. So another very interesting part of this view is the blue graph in the background.

[13:12] This blue graph represents the memory consumption growing, right? The peak memory actually, the peak memory, which is the envelope which is growing over time. And this is a very interesting graph because from this blue graph you could easily spot memory leaks. And thus issues, performance issues introduced by too much memory consumption. So It's always good to have an eye on this graph. Also, well, timeline metrics. Metrics are combinations of aggregation of functions that are related to a domain, specific domain.

[13:57] those are actually automatically gathered by black fire itself you don't have to do anything here to make them appear So we can see that well for the query sets we have 70 calls bound to query sets and it's it took well 50 five more than 500 milliseconds so we definitely have an issue with this metric and we can see that Thanks to the color code in pink we had a lot of calls there. So yeah, we definitely have an issue. And sample, well, Django templates and Django views, etc. etc. All right, so that was for

[14:42] For this one. Then well I have these representations of the profiles from the different dimensions. And this is quite important because you can see that if I do not zoom, I can see what is my critical path. This is something very useful to find bottom line. When you find these kind of guys of nodes, well, this is where it's really intense. And well, actually it's been called more than almost 1,000 times. Then our goal is to understand well where it's coming from and get getting up

[15:30] and see where it's coming from my application, what triggers, what is the protofly effects where it came from. So well here clearly this is coming from this from this Django model function coming from specific template tags right you can see here that you have a different representation of the call graph depending on how on which dimension you focus on. And so with only one profile you will be able to see. have different aspects of the behavior of the application.

### [16:15] Production Monitoring

[16:15] Okay. Same here with database queries. Have a list of the different data queries. All right, this you would do quite often during your development cycle, right to understand what's going on, to find memory leaks or performance bottlenecks. But then let's say you're done. It's time for deployments. And you have installed everything in everything needed in production in your production service and well this is what i've done here i've deployed i deployed

[17:01] Sorry, I had issues here. Okay. Thank you, Garrett of Tom. Sorry. So I've deployed on here on PlatformSH, actually. This is on the cloud platform with a container. And this is my final thing. But now, well, I my supposition, my guess is that I fixed everything, right? But I cannot be so sure. And this is where monitoring comes into place because I'd like to know how my application is behaving.

[17:46] I mean with real end user traffic and to understand if I did everything correctly. This is the point of monitoring. You probably know or probably already know different monitoring tools. With different services that's like well like insight data. com and URLic on these kind of tools. Which are very complex tools and very useful. Definitely. Well, if you use them, that's fine as well. But here I wanted to show you how Blackware monitoring can help you. So here, yeah, this is the same application, right? It's it's supposed to be super optimized. Well, now then

[18:32] I want to show you this. So Here I'm on my BlackFire account. And the first thing as I subscribe to my to BlackFire monitoring. I want to know how my application how good is the health of my application. And so this is the first dashboard you're getting, the health report. And the health report will gather or will extract key information. From every request coming through your python application. So here it's pure Django. And

[19:18] Everything is going through the same probe and agent goes to the there's nothing specific to do actually. If you already installed for profiling, you're good to go for monitoring And I can see here that from the last week, well, I have very few traffic, right? I have well in average 96 percentile is well 155 milliseconds and a major response time to 60 milliseconds and i can see the evolution of it the number of requests and also very just interesting the number of errors you might have. Well this one is pretty empty. So I'm going to show you

[20:05] another one which is not in Python. I'm sorry about that. To get more data to show you, but you get the idea. I mean it's exactly the same. But and about monitoring here, you would see the most impactful transaction. And this is key. Because when you have your application live, well, usually you get analytics, and if you have already monitoring all logs. you might know where most of your users are going through. But here with the monitoring and the impactful transactions, you will get very precise information about

[20:51] which transaction and which transaction which is actually an identified request. Which transaction is the most impactful for users? So here we only have two. Well, I don't have many pages here, but we can see that the different the response time distribution. On this on these transactions and where we have http status sorry distribution per status and here for example the five hundredths the number of errors which then i can go to the monitoring itself

[21:37] And going so here I can I get the different graphs of to help me select the timeline itself and to understand what went wrong at some point, maybe. And to be able to filter out here down to the transactions and these transactions then again click here to see the same kind of information dedicated on the transaction themselves and also If we're jumping to some to another one having more information, you can see that we also have spans. The spans, well here we have a lot of spans, especially because we have a lot of

[22:26] well quite so a few middlewares. It's this gives you like it's like a mini timeline. It gives you an overview of what kind of component software components are interacting with each other just like you were seeing with the timeline view but here it we're more on the surface but you can still see overall what's going on Right, so now I'm gonna switch to a more extensive one. So this is basically BlackVerrier. io website, right? So I have a full health reports. Live which with real end user data and stuff.

### [23:12] Health Reports and Impactful Transactions

### [23:13] Synthetic User Monitoring

[23:13] So that's can help me show you well here the number of requests and the things I already showed you. Also the successful builds. which is another feature from Blackfire what is what we call the synthetic user monitoring based on scenarios and quickly show you this before getting back again to the health report you we you can define scenarios in a yaml file that the root of your code base and in order to test on a regular basis here on using periodic builds like each hour

[23:58] validates that my scenarios are ex meeting our my expectations. I won't get into details about it because I don't have time for this. I'm sorry. But you have like different constraints here, like about on the memory itself, on the number of SQL queries. Etc the number of tags there different things that you can define that you can test the and to for to validate your performance profile okay and this is important because this data is actually key for your health report We

[24:43] Because here in this section in build and test, you will you will see which well Blackware will extract which transactions are not tested by this kind of scenarios. And if you have quite high expectation, I mean impactful transactions that are not tested, well, it means that you really should test them by this mean. Because these mon synthetic in these bills they do profiles on each every step. while monitoring it's are not profiling anything unless once a day and i will come to that

[25:29] Right. So here we have quite a few impactful transactions with time distribution. And also the top recommendations. This is something that is part of the profiler. Here it well it's all about PHP, but if I can have a look at this YAML parsing that should be cached in production. Yeah, well at least it depends on how it's it's taken into account by the language, but here. We definitely have issues with that because we have to interpret the YAML file of here about SQL queries or RM entities, more too many RM entities that

[26:14] have been created and i can view it within the last profile that triggered this recommendation and this is what we had here right. We had also this parts in our Python profile. Like here. Oops, I didn't enable the cache template loader because I still have the debug file. So this is actionable, directly actionable. You have this recommendation, you can definitely fix this. Even if it's in production, you can see it right away. Okay. Let's go back in. Okay. Then for the monitoring, as I said. Here you can visualize

### [26:59] Monitoring Trends and Deployment Events

[26:59] The graph, I mean the your application's constants. On the y-axis, you have two y-axis. On the left y-axis, you have time for each request. And so the basic roll time and the memory consumption. You can switch from one another. And on the right y-axis, you have the RPMs, which are the number of requests handled by minute. This or you can switch to the server load, like you know the one reported by top command, for instance, and the bandwidth output. So this can help you do a selection. So I already did a selection. You can also

[27:45] see that these vertical bars, these vertical bars are actually events. That have been triggered. Like to when you deploy something, you want to know if it had an imp a positive or negative impact on the overall monitoring. Not the monitoring on your application so you so that you can have you know cue points yeah okay here i did a deploy did it degrade the performance yes or no And this is specifically what it's all about, all this virtual events. Then you can filter out. My HTTP status, by response time distribution as well. So we can see that we yeah, we have like more than 100

[28:34] More than 1000 requests at our 1. 6 seconds long. So that's that's not good. So I can click to filter this out and then the response time visualization changes automatically To show well here the 96 percentile. It means that here the 96 percentile is 12 seconds. So it means that everything that is below 96% of the all the requests are below 12 seconds. And the major time is five seconds. So that's quite long actually. And then, well, I have the top transactions. So a transaction, as I said, is identified request. We're not talking about request

[29:20] anymore here, and it's sorted by impact. So here 80% in impact for the first one here, which is public keys actions. This is something an operation when you that is triggered when you want to trigger a profile it checks all signatures to keep everything safe and I can see that I also had 44 errors so That's not good. Maybe we should have a look at it. And if I if I click here, I keep all my filters. To understand what's dedicated to this very transaction, right? And I even have SQL think

### [30:06] Automatic Profiling in Production

[30:06] well queries here that are being extracted but this is an upcoming feature that i'm showing and the spans So the spans that's the mean timeline that are extracted from extended traces, that can that's usually one percent of all the traces, to show you how your application is behaving but what is mostly important is here the automatic profile so Here from this part, you will get the possibility to treat your profiles yourself from real NGOs or traffic. So because sometimes you know you don't you cannot really reproduce how things are going

[30:52] And actually, Blackfire Monitoring for just do automatic profiling for you on the every day for the top 10. Top most sorry impactful requests transact most impactful transactions so every day money black air monitoring will trigger profiles And this is what monitoring automatic profiling is about. So you don't have to do anything. And I can then click on it and inspect what was going on to understand, well, yeah, what 's what where can be the problem. And well, you can also see say, well, actually I want to profile the next request coming through this the

[31:38] This transaction Let's click on it. And then the next time a user comes through this transaction a profile will be generated and you will be able still to understand what's how your application was behaving. Let's see if it worked here less than one minute ago. That's me So everything here is tightly coupled so that with a with a logic within the things. Monitoring can lead to providing and profiling can lead then to monitoring from dev to production to give you real actionable impact. And

### [32:24] Closing and Beta Program

[32:24] and one of the best examples is the recommendations I already shown. And You keeping the control on how your application is behaving from development to production to production. That was me speaking very fast because there is always a lot to show. And so well I hope you enjoyed it. And I would be very happy to take any questions either from Slack or At our booth.

[33:09] And oh yeah. About Blackberry monitoring for Python. We're currently in a beta stage and we're currently looking for beta testers. So if you're interested to do the beta test with us. Please come by our booth and let's discuss. We have a form where I cannot share the link here, but I will drop it in the segones in the in Slack. To if you if you're interested so that we can contact them contact you afterwards. Thank you for your attention, ladies and gentlemen.
