Back to the video

Django & Celery: A love story of async proportions with Hugo Bessa

Transcript

By Hugo Bessa. From DjangoCon US 2024. Published December 6, 2024.

Watch the video Markdown version 4,946 words · auto-generated · en

Summary

Django’s request-based processes are costly for long-running work, so Celery can move non-urgent operations into separate worker processes and return a response quickly. Hugo Bessa explains Celery’s broker, workers, and results backend, then shows how background tasks support jobs such as API calls with retries, caching, recurring work, and database processing. He stresses that distributed execution introduces stale data, duplicate runs, difficult error feedback, and conflicting operations, which require passing IDs rather than model objects, making tasks atomic and idempotent, tracking state, and designing user feedback carefully. He recommends exponential retry backoff, exception handling, monitoring, smaller tasks with timeouts, and using tools such as Flower, eager mode, and remote debugging; for complex workflows, he suggests considering Temporal instead of relying on Celery alone.

Transcript

Automatically transcribed, so expect mistakes in names and technical terms. Filler words are removed.

0:00 Introduction to Django and Celery

Carbon Hey folks, I'm really happy to speak at GenCon US 2024. I'm going to talk a little bit about Django and Celery and their amazing love story, right? My name is Hugo I'm a partner at Vinta Software, where I've been working for the past seven years. Some of you folks might have already crossed with Vinta before by using one of our open source packages for Django like Django React boilerplate, Django World Permissions, DRF read and write serializers Django virtual models in the newest one which is really

fresh which is Django AI assistant you should really have a look We are a company that really cares about the open source world and especially the Python community. We contribute in with a lot of open source software and also we are we've been present in most conferences all over the world so that's something we really love and we've been there for a while already so about myself I've been working with Django for the past 10 years in very different kinds of projects, most of them using celery, and that's what we're going to talk about today.

1:47 Django’s Strengths and Performance Limits

So To start this talk, I'd like to talk a little bit about Django. Django is almost 20 years old and its philosophy has made many projects very successful so far. What I really love about Django is it has batteries included there is kind of the right way of doing things like authentication, authorization, interacting with data. security things like that Chengui's school of good opinions on all these topics so and But that basically allows us to work together and make a whole ecosystem in an integrated way, built on top of Django, like

using the same base. And that's because of that we have tons of packages that are really useful. We have events, we have meetups we have and especially There is an active development in the main framework which introduces exciting new features on every new version. But there's a known problem of Django that couldn't still be fixed. And that's like Jingle performance, right? Jingle uses Python, which is not known for being a fast language, like compared to Rust or C or Go. And on top of that, Shango

wasn't built to work with multi-thread. Its asynchronous features are still being developed. actively. They are still being still maturing. The RAM itself can be misleading sometimes with regard to performance. But there are workarounds to make Django a bit faster. In the database side, you can avoid N plus ones, for instance, like being more cautious on the way you write queries You can use caching, you can make smart database indexes, you can use data normalization, you can run operations in the background.

4:06 Request Processing and Background Work

All these techniques could make our application run smoothly and serve a ton of users simultaneously. That has already been done in the past by big companies. But I want to talk a little bit more about the last one running operations in the background. Before that, let's have a look on how Django works in the in the in the in the background right basically django exposes a ws gi interface or web server gateway interface. That's what a server like Unicorn or WISGI uses To run a Django process, right?

They kind of connected that W WSGI file in your Django project. These servers themselves have a request load balancer. Basically, they res this part of the server receives a lot of requests and they map these requests to processes they have right so each Django process has like the whole Django environment loaded there in memory. Each of these processes speaks a request at a time and only gets the next one when the previews has finished being processed, right? So long running requests are kind of expensive, right? Each Django process loads

the whole framework core, right? So it also it's expensive to have too many processes right because all of them have like a cost to be loaded right And requests hold a Django process each while being processed. So there's no way to run multiple requests at the same in the same process, right? There's no multi-thread. In Django processes usually right there might be workarounds but we're focused on the on the main thing today. Why so why running operations in background, right? Requests should be processed quickly so we don't have to roll the process for too long.

We want to be able to process the next request. as quick as possible. Otherwise the queue is going to be too long. And we also want to give feedback to the user as quick as possible as well So we can retain their attention, right? Attention is very valuable in these days. So we don't want like the user to switch tab while they wait. For an operation he started on our app right we want to keep him in our tab and like maintain retain his attention their attention in our in our platform right and salary it's a tool that can help with that right

7:10 Celery Integration with Django

Salary is a an a an asynchronous task queue or job queue which is based on a distributed message passing right so it's what the most important word here is distributed right it separates a syntax execution from your main application. So it doesn't run in the same process that Django runs. It's a completely separate process that just worries about these as asynchronous tasks. It is also very fast And it's very well integrated with many tools, right? Including Django, right? So with Salary you can have access to your models, to your services, your functions, your classes.

and all that jazz, right? And celery loves Django, right? Celery basically has dedicated documentation for integrating with Django. Actually there are ways to configure salary using Django settings with no extra boilerplate. Django is it's allowed to be accessed within tasks, so you have full access to your RM and your managers and your query sets and your services, classes, etc. And there is also an important community around Celery and Django building packages that like enhance these integrations.

that uses Django database for managing some of salary things and things like that so there's a whole ecosystem that helps us integrate them both right And here's how it looks like to integrate Django and Celery. This is like a very basic use case, so I'm just showing you how it can be done, how quick you can integrate them. Basically here I'm writing this process order view. Right, it receives a request, it creates an order object based on the user, and it calculates it kind of call the calculate user score task. So suppose you have like the this

this function called calculate user score that is very slow but it isn't that important that you run it immediately after you create an order it can have some eventual lack of synchrony and so that's the perfect use case for us to move it mute move this task move this function to another process, right? To running background because it's just going to bloat the request, right? So in here We are moving it to a task function that receives the user ID, it picks the user from the database, and it actually calculates the user score. But before all that happened we actually give a response to the user.

So this delay method here it's just going to add the tasks to the queue it's not going to execute it immediately right it's going to be executed in the background so this is kind of a hello world for salary right And what this can give us basically, what async task can be used for. You can delegate long-lasting jobs like the one that you we we've just seen. We can execute remote API calls like APIs can fail, right? So we can use like salary to run to like kind rap kind of wrap these API calls and

10:59 Task Queues, Brokers, and Results

give like have retries running without blocking the request, right? We can also prepare and cache values right to make queries a bit lighter right we could spread book database insertions over time for instance like to not to avoid overloading our database we can execute recurring jobs things like that right there's many use cases for async tasks right and how does it work with salary basically django uses a salary client that gives kind of that that delay function for instance and it basically queues a message to the broker a broker could be

many platforms, right? Many, many kind of Q managers right it could be like reptinq sqs it could be read ready 's itself right So we can use multiple queue manager as a broker but like we choose one and like when whenever we call this client Django is going to send a message to this broker and put it on the queue and celery is going to be watching this queue and It will mark a task as started. It kind of depends on your settings there. It may or may not mark as

started, it may just start it. But and it marks it X succeeded after it finishes processing it. So the second part is like after salary finishes the processing of that message of that task it will also deliver the result of that task to a kind of database. We call it results backend and it's basically storing task results. So you can query these results with other tasks or even with Django. You may want to wait for a task to run to get its result. In the case that we showed may not make a lot of sense, but there are use cases for that.

If we're just sending an email with salary for instance you might not even want to wait for the result so the result backhand will kind of be useless in that situation but there are situations where it can be used Right. So when you configure seller, you actually have to give it a results backend so it can store the results there. It's just a database, a normal database. So but like n it's n it's a good love story, right? Django and celery but it's not always rainbows and butterflies we can say it's a tough love right There are many things that can go wrong. Whenever you're introducing a distributed system into your application, it makes things a lot more complex, right?

Like all connections may fail. There are a bunch of connections now. You have Django to the to the broker, the broker to salary, the salary to the results backend, the results backend to Django. So there are many connections that may fail, right? You also have a lot of concurrency being added there, adding a lot of complexity. So we can have like tests that never finish, outdated data, issues that only happen in production. It's it's kind of Introduces a lot of noise, right? Let's say salary has a strong personality, right? Salary is a distributed system, which means there are many points of failure

14:56 Task Data and Idempotency

Right? And here we are going to focus up on these four problems that I've been through in the past in my ex whole experience with salary, these things always have caught me in the past and I have to handle it correctly. The first one is outdated data, right? Sending complex data as parameters to salary may result in unexpected stuff, right? In this example I'm giving here we are passing the user model to a seller task right and we are basically calculating the score here and saving the user And why this is kind of tricky? Why is it might not work as expected? Because the user model may change

Between the salary task being scheduled and it actually being executed. And as we are passing a model object the mod the model may be outdated. I can even have deleted that user. If the let let's suppose the task queue is sh is full, right? It has a lot of tasks to be executed there the user may have been deleted and whenever you run this the user may not exist anymore Right? So you calculate the score of an exit and an existent user. In this other case here, the right way to do this is basically passing a reference instead, right I'm passing the ID of the user.

I'm getting the user by the ID. If the user doesn't exist, I just don't run the task anymore right but if i can find the user i'll get the up to date object right and i will calculate the user score accordingly So this is the first thing. You have to be very careful to what you pass to the salary tasks as parameters, right? Usually you should rely on references, not on like complex objects, right? Serialization is necessary. If under the hood by default it uses pickle which can actually pass like complex objects through But that's far away from

ideal. You shouldn't rely on like passing complex objects, you should like pass references and remount that these objects on the task itself. Okay The next problem is duplicate runs, right? Depending on your seller setup and task configuration, it may not be guaranteed that your tasks are only run, are only going to run ones, right? Multiple workers may pick the same task at the same time, for instance, right? You have multiple workers looking at the same queue, both of them both can get the same task at the same time. And this could happen depending on your on your configuration a task may be interrupted and requeued for instance

right if you like a worker fails and re the machine restarts, you may have a task that was interrupted and was requeued and will be executed again. So you have to ensure that your tasks are atomic and eidepontent. Right? In this case that I'm showing here, this example, we're storing a reference to the latest order we processed in the user model. Right, you can see in the line 25 whenever we update the user score on the line 24 after it we just store the latest order id and we save the user, right? We save the user. That means

if we call this task again with the same user and no new order we're just going to pick again this last order ID right and we are not we are going to exclude that user with a reference to that order ID. So if they if there is a new Order we are going to recalculate. But if the order is the same as the last one, we are not going to do anything. We are going to just return early, like in line 22 Right, we are not going to be able to pick the user and we are going to return early. So this function it also has this transaction atomic decorator so if something fails here or if this function

19:36 Error Handling and Conflicting Operations

stops in the middle it will just roll back everything right roll everything back and will not l leave any like data updated not completely right so the other problem we can see in salary projects is a little bit more complexity on error feedback right because whenever you pass the bannon on to a salary worker If it fails there, you may not be waiting anymore in Django. So you may not be able to return an error result to your user.

So user may receive a success message from the request but the home operation may still fail, right? So whenever we are developing a flow that like relies on th sync stuff and async stuff We need to take this possibility into consideration and give like a feedback, not like a success feedback immediately to the user, but a feedback saying that this is still being processed and do some sort of polling to check if this was completely successful or not. You may also need to be able to undo operations if partial it has partially happened synchronously and the other part is happening in asynchronous in

in background, you may need to undo this first part that happened synchronously. So it adds a lot of complexity for error feedback and error handling in general you might you need to take that into consideration when developing features that will touch both sync and async at the same time, right? And especially if it involves user feedback. Okay so there's this fourth problem which is conflicting operations. Why right so while a task haven't still run another operation is triggered by the user for instance right this operation conflicts with the one that's still pending

And creates like a an estate that is not it's not predicted right it's not predictable so For instance, let's consider these use cases. User can add nodes to our system, right? User can also delete a node And user can book create copies of a note. So you can choose a note and create a bunch of nodes based on that existing node, right? So let's look at this following flow I have on the right So let's suppose the user starts creating a new node. It creates then triggers the creation of 10 copies of the node This will run in background because

creating 10 copies may be a little bit longer. We don't want the user to be waiting on that. So it happens in the background. This task is kind of queued, it goes through queue and it's it will be executed by a salary worker. Then the user deletes the original note before the task to copy the 10 notes run. Right? The tasks the task runs, but the original note isn't available anymore, so it cannot be copied. Right? You cannot like copy something that don't even exist anymore in the database Right? There are many solutions to this. Like you can implement, for instance, soft delete on the note. So whenever you delete a note, you don't actually delete it from the database, you just mark it as deleted.

But you can still find it on the database and you can st you are still able to create these copies. You can also cancel all painting tasks before deleting so whenever I try to delete something some note a query for painting tasks around that node that uses that will do something to that node and cancel all of them all the painting ones and after that we can like other like other alternative is just locking nodes with painting operations so whenever we want to do something on the on an existing node we before creating the task we are going to mark this node as like

locked And whenever we try to delete the locked note, we'll get an error, for instance, because it's still locked, so you have to wait for it to be unlocked before you can do other operations with it. So this these are alternatives for these conflicting operations. This is just an example. This can be a lot more complex depending on your use case, but like async May create a lot of issues. You cannot hike like have this just do a rollback, a database rollback. You don't have like atomic operations. So There's it's hard to have like atomicity between the sync part and the async part. So basically you have to handle it by storing state

25:03 Celery Reliability Practices

or even canceling painting stuff right Now let's talk a little bit about how to make things a little bit smoother with celery in Django. There are ways to work around some of these issues that we talked about, right? There's some tips that can help, like we're calling couples therapy here. So some tips to help the relationship to flow between Django and Celery. So if you're going to retry tasks for instance, you need to use exponential backups, right? You don't want to like give a fixed number of seconds or milliseconds between the retries Because for instance, if you are making a request to an API, this API

probably won't be back. If it fails, the request fails, it probably won't be back. Within a fixed number of seconds or milliseconds, right? You probably want to wait a bit more between the latest calls Right, so it's important to keep your backups exponential between retries, right? Also, tasks shouldn't raise exceptions the same way like views don't are not allowed to raise exceptions You if you run an exception in a Django view, it will raise a 500 error and the user won't know what happened, right? So The same thing applies to salary. If you raise an exception, it will just fail

in a in a terrible way, right? In an uncontrolled way. So ideally you should handle all exceptions. And if there is nothing to be done in the code for like adjusting the state because of that exception, you can just like send a report through email or through a monitoring tool Something like that, right? So exceptions should not be unhandled in salary tasks the same way they should not be unhandled in Django views, right? Monitoring is also essential, right? Like salary adds a lot of complexity. You need to kind of be able to see this complexity, see how it's going. So

27:22 Monitoring and Debugging Workers

There's celery flour this is a package that can help right it can help you see the current state of your Stellary setup, right? You can see the running tasks, you can see the tasks that have already run. So it can help a little bit for you to understand what's going on. There's also this flag called Always Eager. You can do it by task or you can do it globally for all salary tasks. And this is very useful for development, right? Whenever this flag is active The tasks kind of run synchronously. So whenever you call a task, it will run immediately instead of running in another process, right? It will just run, which makes debugging a lot easier.

Easier right if you don't want if you are actually wanting to use the remote thing having a different process for salary RDB could be your best friend, right? RDB is basically a remote debugger. So whenever you set up a breakpoint it will stop the execution there and it will open a connection so you can have a terminal connected to it with telnet And you can actually send like debug signals. You can check like the variables values. You can like send a next signal or a continuous signal. things like that you can debug the whole thing even with remote

28:53 Long-Running Tasks

Remote workers that are not in the same process as your django application Right? So RDB could be very helpful. It's kind of a built-in thing, so you can import it from salary library, right? It's available within salary you don't have to install anything external so it's it could be like a really good friend for you it could really help The second part of the couples therapy, I would like to mention a good tip for long tasks, right? Long test dumb may not work exactly as expected with salary, right? Because like Imagine that you were the

the manager of this task. Like you cannot know if the task has for instance Frozen, right? It may have frozen, it will not give any result ever. It's just like locked in there. So in that case, you probably want to have a timeout, right? So this is configurable, but you probably don't want tasks to run that long like hours. You don't want that So in that scenario you probably want to split the task into smaller ones to make sure that you have like a sense of progress, right? And you can know the things are running and there that there's no time out like

Killing your task while they are still running, right? Another thing about celery is that monitoring tools, monitoring tools are very limited. I talked before about celery flour Right or flower. I don't know how you pronounce it. I think it's flower salary flower by flow, right? So you may need to implement some monitoring yourself. Like for instance, I had in the past to implement like Q 's heartbeats, right? To know If my queues are well balanced, I have multiple queues for different sorts of tasks, right? And some cues were like being very full and other queues were being very empty. So

If a queue is full, having a heartbeat may be helpful because if you're scheduling a new task, it may take like too long for it to run. So this is something you might have to implement yourself. I had to implement myself in the past, right? But like there are some paid monitoring tools that might also help in there right like things like new relic or a data dog may help a lot in monitoring your salary tasks and having useful logs and understanding the state and all that jazz right Another thing is that salary is an excellent tool for asynchronous tasks and for doing simple jobs, but like for complex workflows

31:56 Complex Workflows and Temporal

It might not very be very reliable, right? It may be it has a lot of open issues and many complaints of lost tasks and unpredictable behaviors, but when you're running very complex stuff. So it may not be the best tool for that. But don't worry, like there the celery and jangles relationship is no monogamous. Like these tools Other tools can live together with salary, right? For instance you could use salary for doing simple stuff Because it has like very little boilerplate, it's very easy to use, it's the learning curve is very little but you could use like temporal IO

temporal IO to run like more complex stuff. It has like a more robust infrastructure. It's kind of done like created to run these complex workflows. And even include like better monitoring tools like built-in that you can rerun tests and do stuff like that. So for very complex stuff, you may want to look into other tools for that, right? But if you're dealing with simple stuff that needs to run async, Celery could be your best friend, right? So other than that, we also have this that checklist site. Vinta has put that that up, but it's an open source project as well.

33:28 Best-Practices Checklist and Conclusion

It has a bunch of dev checklists and there's one specifically about salary like my co-worker Felipe Shimenez has put this up and it has a lot of best practices you should follow when writing s integrating Django salary So basically you should have a look at that. It can be very useful if we're starting a new application or if you're configuring a new integration Right? And that's it folks. Thank you for hearing me. Hope you enjoyed the presentation and I'll probably be on the on the event channel if you want to talk about celery or django or anything related

I'll probably be there if you want to talk just ping me okay this is my email if you want to talk about it as well and that's it. Thank you