# Django, SQLite, and Production

Source: https://djangotv.com/videos/djangocon-europe/2024/djangocon-europe-2024-django-sqlite-and-production/
Date: 2024-07-11
Speakers: Anže

## Summary

Anže argues that SQLite can be a sound production database for many Django applications, but whether it is appropriate depends on the workload. It is simple, portable, stable, and fast for read-heavy or modestly sized applications, while concurrent writes, SQLite’s single-writer locking, horizontal scaling, and backups require careful handling. He explains practical techniques including WAL mode, immediate transactions, separate database files, LiteFS, safe backups, and online replication, and highlights Django 5.1 improvements that make SQLite configuration easier.

## Transcript

### [00:09] Introduction and Production Use Cases

[00:09] So hello everyone, my name is Anje and I'm going to talk about Django C and production. And so to start with, at the speaker dinner a few days ago we were talking how awesome it is DjangoCon that talks Sort of feed off of each other. And that's exactly what I did because I watched last year's talk by Tom about using SQLite in production, and I got really excited. Excited about what Tom was telling us and Tom was essentially asking us to try out a new SQLite in production and then

[00:55] let us know how it went. And that's exactly what they did. I created a site project and I put SQLite in production. I've been running this site project for the last year. I read most of the documentation in SQLite to better understand how it works. And I even wrote a few blog posts about SQLite and Django, how they work together, all so that I could hopefully answer this question: whether or not we should actually have SQLite in production. And I'm now here to tell you all that the answer to this question is it depends.

### [01:42] SQLite Fundamentals

[01:42] Unfortunately that's Is a quite a peculiar database. It has its strengths and weaknesses, and as an application developer, you do have to be aware of those at least a little bit to make sure that. That you make a good decision and not create an application that's impossible for you to scale properly. So Tom Stalk did an excellent job explaining how SQLite works. So I won't go too much into the details on what he said. I've essentially put his whole talk in a single slide here.

[02:30] So essentially what SQLite is, it's a single file that acts as your database. So that means that you don't really need a DBA like Karen to manage that. It's on Your file system you can access it without requir without connecting to the database server through a username and password. And that of course makes it super attractive for us developers since I can understand how a file on my file system works so it's a lot easier and lost less daunting for me to work with that. But it's still ACID compliant.

### [03:15] Fedidevs and Read-Only Deployment

[03:15] It's in the public domain, so it can be embedded anywhere where you're running your code. It's heavily tested and really, really stable. It's also available anywhere, you can run it on pretty much any machine. It's primarily been used mostly in embedded devices, but as we'll see it can also work well for use cases where Django comes in so hosting data for your web application. So just quickly the side projects that I was working on is called fedidevs. com and it's essentially an aggregate of different Mastodon

[04:01] accounts so that you can find people to follow that have similar interests as t as you do. So here we see a list of Django developers. So it's And it makes it a little bit easier to find friends in the Fediverse. I also built a little feature so if you want to follow the conversation around conferences, there's An aggregated view that shows all the posts about DjangoCon Europe. So if you want to check that out as well. And Fedidevs essentially started out as a read-only application.

[04:48] I aggregated all the data on my laptop and I then put it into the SQLite file and then what I did was I essentially just copied the SQL Lite file into a Docker image and then just deployed that Docker image. And this is essentially the benefit of the flexibility that SQLite gives you, since it's a normal file, you can really stick it anywhere that you and even into places where you probably shouldn't. So I'm not saying That this is what you should do. I'm just saying that if you want something out quickly to gather some feedback, or if you're more of a

[05:39] data science person and just want to share the results of your work, SQL Does give you the option to share this very easily with others. And it's still quite fast. I'm not sure if you can see the numbers on This graph, but because this is a benchmark, the numbers don't matter anyway. But we'll see how these numbers change through the different benchmarks that I performed for this talk. Here we can see that SQL Light is just slightly faster for read-only operations than Postgres and MySQL. And I believe that is due to the fact that it doesn't have the overhead of

### [06:26] Adding Writes to SQLite

[06:26] connections. It can just access the system, the file system directly. So after I deployed Fedidevs in the container, I sort of entered this honeymoon phase with SQLite, everything was going well. it with just rainbows and butterflies everywhere, things were fast. I was I was super happy. But then as people started to use the site project that I built People also started to ask for new features. And some of these features, of course, required me to support writes as well as just reads.

[07:13] And because the way that I had deployed SQLite. This wasn't just a simple change in the code. I now had to do a few things to make sure that I can actually support rights as well. And most cloud providers they offer you a way to attach a volume, so some permanent storage to your container image. And then you can put the SQLite file there and it's going to stay there between your deployments and that makes and that essentially solves this issue for you.

[07:58] Of course this box Can only be attached to a single instance or a single deployment, which means that some of the fan benefits that I've had before, where I could just ship that container image pretty much in any data center. In the vault now isn't as easily doable. So yeah, I had to remove it from Docker and that sorted out the deployment. Issue, but I immediately figured out that there are other problems when you introduce writes into your application with SQLite. And this fact is that writes are

### [08:44] Write Contention and WAL Mode

[08:44] a block Your database operations. And by default, if you don't adjust any of the settings, writes not only block other writes to the database, they also block your reads, which means that your throughput is essentially going to plummet if you just start writing to the database or while you're reading to it. So in the previous slide we were doing like let's Say 2000 requests per second. When I introduced writes to the mix, this number plummeted to 200, 300 requests per second. And this I mean, this is a 10X decrease in performance and does

[09:30] Doesn't really sound that appealing anymore. Like we're sort of seeing some issues in the relationship with me and SQLite at this point. Fortunately you can at least unblock reads very easily and you've probably seen this configuration option that enables the write ahead logging in SQLite. Now the Only reason that this isn't the default already for SQLite itself is because SQLite like Django always wants to make sure that all the new features and changes are backwards compatible.

[10:15] So they never change the default to this new journal mode that was added years after the initial release. But it is a stable way to resolve this issues, at least for your reads. And as we can see for this new benchmark with right ahead logging enabled, we are back in like around one thousand requests per second, which makes it It's still slower than when we were doing the re only reads, but it is usually fast enough for certain type of s certain type of applications.

### [11:03] Transactions and Database-Locked Errors

[11:03] Now these blocking rights have another issue that you might s encounter when you're working with SQLite and these are database And this sort of confused me quite a bit at first, mostly because so essentially you get this database's locked error if your right operation can't acquire a lock in the specified amount of time, which is essentially your timeout. So if your right operation doesn't isn't able to get the lock in five seconds, which is the default, it's g to raise this databases locked error.

[11:49] But what I've noticed is that I was I kept getting this error on requests that finished in 200 milliseconds Seconds or less. So there was something else going on. And when I was debugging this, I even tried setting the timeout to an insanely high number to see if that's going to resolve the issue, but for some reason it has hadn't and I still kept getting this database is locked errors. And yeah, I keep g I kept getting these emails and at this point in time My relationship with SQLite sort of entered this crisis stage.

[12:35] I was considering maybe migrating the project to Postgres. Maybe just s yeah, just try out my SQL. I don't know, I it felt like there was there were issues with how we were doing things with SQLite. of course complained about this on the internet and as it happens usually when I'm wrong or confused the internet sets me straight and thankfully someone on the internet actually Told me to look at how transactions actually work in SQLite

[13:20] and because that might solve some of the problems that I've been having. So quickly Without going into too much details of ACID isolation levels, I do want to point out that by default SQLite tries to defer the acquisition of the lock as long as possible. This means that this is because as we saw before in the right benchmark, acquiring a lock Is expensive and it slows down your database. So SQLite tries to be helpful

[14:06] and tries to do this as late as possible. So in this example here, we start Started the begin statement. SQLite doesn't essentially do anything at this point. We do our first query because this isn't a write query, SQLite still doesn't acquire a lock at this point. Point. And then finally, when we get to this update statement, this is now where SQLite actually needs a lock. So this is where it is going to try to acquire one for you. And if there There's no other operation going on at the moment, everything's going to be well, the transaction is going to commit, and at that point the lock is going to be released.

[14:58] But if there is another right happening at this very moment where we try to access the lock. SQLite won't be able to of course attain that lock and it won't Even be able to retry and wait until the timeout passes before raising the next option. And the reason for this is that SQLite has the serializable isolation guarantee and if because at this point we would have to wait for another transaction to continua to finish, that other transaction

[15:43] might change data in the off user table that we read at the beginning of the transaction and that could essentially invalidate our assumptions on what we're doing with the update statement and thus causing potential problems for us. So because of this, there's no retrying in this particular case and you're going to get the database's locked error in your application when this happens. The solution for this is the begin immediate clause which basically tells SQLite to acquire the lock at the beginning of the transaction and then

### [16:29] Write-Heavy Workloads

[16:29] The And then you don't have this problem where you've already read the data when somebody before somebody changed it, and that makes this problem go away. But of course this makes your whole application a little bit slower because the locks are a little bit longer and that of course impacts performance as well. So we probably all can now see That bright heavy workloads probably aren't the best fit for SQLite because of these limitations. Like the serializable isolation mode is not ideal for just

[17:15] Django applications where we're usually used to running in read committed mode, but read committed isn't something that SQL that SQLite actually supports. it right with writes it gets even worse because you might assume that writing to one table in your database doesn't impact writing into other tables in the database, but in SQL Like this actually isn't the case. So if you have a big l table that is constantly getting writes, like an events table or something like that, it is going to

[18:00] impact writes to the auth users table or any other table in your system. And in this write-only benchmark we can see that you there is an impact to SQL like performance due to all of this. This benchmark was simply inserting a single row into a single table and even then it was the performance was much slower like half the performance of Postgres and sick and my SQL. Although I do have to point out that in this particular benchmark I was writing about six hundred rows per second, which is still quite

[18:45] quite a lot for most applications. So even though it is slower, measurably slower, it might still be plenty for the use case of your Django application. Now of course, not for every company, not for every size of load, but for a lot of Django projects, this is probably going to be fast enough. And if you need just a little bit more speed, out of your rights, you do have an option to split your database into multiple smaller database files. So like if the events table that I mentioned, an option for you is always to split that into its own database server,

### [19:32] Scaling and Backups

[19:32] database file, and then the rights are going to be unblocked from your other tables. So this is also an option. That you can use. Now, the main question on everybody's mind right now is probably how to go beyond a single server. So a SQLite doesn't have any support. Support for networking or managing connections, which of course makes it a lot simpler to deal with, but when you do have to scale horizontally, things get a little bit more tricky. One solution for this is to use LiteFS,

[20:20] but even then I would say that for right heavy applications it might not be a good fit since All the rights still have to go to a single database server with or your single application server that runs your primary database and you're going to have all the same problems That we had while running in on a single server. And of course, as also Karen mentioned, backups are super important when you're run A database in production, and since SQLite is just a single file on your system, you might be tempted

[21:08] to just copy paste it and make a backup that way. But that is Essentially not safe you have if you have active connections on the database and you might end up with a corrupt backup file. So when doing backups, always make sure to use the dot backup command inside SQLite and that's going to make a full backup for you safely. Full backups can sometimes take a long time, especially if your data database size has grown quite a lot. So there is also an option of online backups and that's a tool that you can use called Lightstream that can essentially

[21:55] stream data coming into your SQLite database to some other server or S3 or anywhere else that is safe. So finally after all of these struggles and learning on how SQLite works, we have finally enter this partnership stage of the relationship where I now think I understand how SQLite thinks, how it works and we're now in this healthy relationship. And my goal was to also make sure make sure to help other people trying to be in a relationship with Sick

### [22:41] Django Improvements for SQLite

[22:41] for Light. So I wrote a few blog posts on all of this and I've also helped make some small contributions to Django itself to make it a little bit easier to deal with. So Coming in Django five point one, there's a new transaction mode option for you to be able to configure immediate transactions to for your whole application and that so that you don't have to deal with databases lock terrors the same way that I do

[23:27] That I did. And if you're not on not able to upgrade to five point one immediately, the other option is to you have to basically subclass the SQLite backend and then overwrite one of the methods there. You we can talk a little bit about this afterwards if you're interested on how to get it to work. And this was actually my first contribution to Django itself. So thank you. So hopefully this is going to be the first of many, so I'm I was really excited to get this change merged into Django itself.

[24:14] The other thing that was added in five point one was the init command that you can use to configure certain properties or settings for SQLite so that you can make it a little bit more performant. So these settings are I basically borrowed them from the Ruby community that is currently going really headfirst into SQLite for pretty much everything. And there's this blog post that I have linked there that goes into a lot of details on how what these settings do and why they might be really appropriate for you for

### [24:59] Future Improvements and Conclusion

[24:59] the Use case of web applications. And this brings us to future improvements. So ideally, I would say that you, as the application developer, shouldn't really have to know the intricate Of using deferred transactions and all these configuration options. So I do believe that Django should help you or at least guide you to get some good defaults out of the box. Now unfortunately changing the defaults is difficult because or we usually don't want to do that because

[25:45] we don't want to break any existing application. But maybe there's other things that we can do. Perhaps the start project template would configure SQLite in a way that's a little bit more appropriate for web application use cases instead of more the embedded world that is the default for SQLite. And I'm planning to start a discussion around this after the five point one release and when we see how that goes. And there's always things that we can do to improve the documentation around all of this, so that's also on my mind. Unfortunately there's

[26:30] a lot more topics about SQLite that I wanted to cover but just didn't have enough time. So to circle back to the beginning of my talk when I said that I was inspired by a talk from Django Con last year. So at least me personally I would love to see more talks about SQLite, about all of these topics that I have listed here. Like did you know that you can even have full text search in SQLite? I think that's mind-blowing. So there's there is definitely a lot more content here. And like the main benefit of using SQLite, like

[27:16] for a lot of use cases, the database is fast enough and reliable enough for us to consider it, and it does simplify the maintenance and the way that we developers interact with the database. So I think it is it has its place in the Django community, even in production environments. So that's it. If you have questions
