Back to the video

Polyglot Persistence with Django: When One Database Isn't Enough with Abigail Afi Gbadago

Transcript

By Speaker 1, Speaker 2, Speaker 3, Speaker 4. From DjangoCon US 2026. Published October 26, 2026.

Watch the video Markdown version 3,335 words · auto-generated · en

Transcript

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

Speaker 1

Hi, everyone. Welcome again. I know this is right after lunch and we're a bit tired, but if your eyes are getting heavy, you could do an icebreaker. And it's definitely not the database talking; it's the lunch. My name is Afi. Most people call me Afi. I'm a senior software engineer and developer advocate at MongoDB for Django. I'm also a Django Not, and I currently serve as Vice President on the Django Software Foundation board. So, what today is about: backstory. I'll talk about how I tried combining SQL and NoSQL. This doesn't mean I have too much time on my hands. It was just an exploration because I've always dealt with the same databases within the same Django

project. We'll also look at why teams reach out for two databases. We'll look at routers briefly, configuration steps, applying the config, migrations, which is very special to Django, why it failed, obviously what I was expecting, and what I learned. And before you try this, things to note: was it even worth it to begin with? So let's get into it. What is referential integrity? Before we start, this is a word that's normally used in databases. It's a rule in DBs that keeps links between databases correct. It makes sure that foreign keys in one table always point to primary keys in another table. So this is to prevent what we call dead links or fake links that create errors often

records. With referential integrity, there's always a unique ID for a role in a parent table. For example, a user ID. You also have a foreign key, which is a field in a child table that will point to a parent ID. The rule is you cannot add a child record if there is no parent ID. So now back to the backstory. In my seven years of building with Django, I've never combined two different types of databases in the same app, as I was saying. So, to satisfy that sort of curiosity, I decided to try it out and do that within a single Django project. So I had different databases where I had an encrypted database and an unencrypted one. And it was due to a project I had to work on at work.

So, due to the fact that I had to use the same database, I decided to explore using SQL and NoSQL databases. Doing that here reminded me that Django has a database setting that isn't limited to a single connection. Because normally, when we do Django projects, we always use single databases, from my experience. So why do teams actually reach out for two databases sometimes in production? It's not because one database is better than the other or something; it's because sometimes your data may need certain things, such as read or write operations, that a single DB engine cannot give at once. There may also be issues like

or needs like security and compliance, for example, the QE project I talked about. And that's why you may need an extra database, like an encrypted database for those specific fields. Also, keep in mind that a relational database enforces a fixed schema and referential integrity, as I was saying. So every record has to fit some sort of similar shape, and every reference has to point to something. Don't forget the offer records. Also, a document store trades that away for flexibility, since you have records that can freely be in different shapes without having a reference to point to. So the real question isn't which database is better; it is, does this need reinforcement or enforcement

or flexibility? So now, a quick show of hands. How many people have already configured more than one database in a Django project? Wow, the hands are really small. I thought a lot of people. Well, I hope if you try out the process, it's great, but we'll look at what I did. So, as I was saying, Django has had this all along. Django has supported multiple database connections since Django 1.2 through the Django database settings and database routers. Django 1.2 added the ability to use more than one database in the project, thereby letting queries be issued at specific databases using the `.using()` method on the QuerySet object.

Now, with the configuration, for those who don't know, it's in three steps. The first one is to add a second connection to your database. So your default database is still going to be there. It's not anything scary. The second part is to write your router, and then the third is to register it in your database routers. That is the actual kick that flips the light switch on. So the first example you see, as I said, is the default database up there, where you could configure your relational or non-relational database. And in the second part, you could have the alternate version. So now we have two databases, one pointing to the default, and then the other one pointing to the document database. The second part is a configuration for MongoDB. For that one, I know most of us are from a relational background. For MongoDB, you need the engine, host, and then the name.

You can store these credentials in your env file and pick it back in over doing stock, since you talked about honeypot and all that. That got me a little bit scared. Now the second part is to define your router. So that's step two. In here, you write your router, which is a Python class that tells Django which models belong to which connection. So there are four methods here that we always add, which are db for read, allow relation, allow migrate, and db for write. The third part is to register it, which I said is the part that turns everything on. Without this line in database routers, Django never calls your router at all. It just silently ignores it.

So this is the stuff that switches it on. One thing I didn't realize, or didn't say in the beginning, was to get the second database installed. I did a pip install Django MongoDB backend. That was for me to have a local instance of MongoDB running in order to use it as a second database. So now the same question from a few slides back comes up. Does this data that I'm working with need to be in lockstep with other forms of data, or does it need to vary, or should it be standalone? In this case, I'm going to use a very simple example with orders or, let's say, products in a catalog, like some sort of e-commerce shop. So orders will need an order and then its

line items updated, and then catalog will be the second, and it will need, like, probably laptop attributes and T-shirt attributes that don't share the same shape. That means it's a bit flexible. So now in the catalog, we have these fields. So we have the class Product: name, SKU, price, and specification. We realized in this modeling for order and order item that the product SKU and name are plain fields here, and we'll see why we did that in a few slides. So this is a simple class where we have order and then the order item. Apologies. I remember from Frank and Calvin's talk they said we shouldn't be using the word clean and simple. So it's a class.

Now, migrations minus the safety net. Migrations will still work here, mostly because the same mental model applies, but there's a road trap. Because if you just run migrate with no flag, it will only touch the default, because that's what it's supposed to do. It does this quietly, and you don't really realize; there's no error, there's no warning, it just skips it. So that's why you see me being explicit by mentioning which exact database I wanted to be applied to that document. The second thing is, if you are adopting data that exists everywhere, there's not much of a shortcut here. Normally, you reach for maybe InspectDB to generate models from an existing database or table

or `migrate --fake-initial` to tell Django that, hey, this already exists; don't recreate it. But that doesn't exist for this backend. So you have to write a model by hand and hope that you match the shape correctly. Then this is the one you actually worry about a bit, because SQL databases catch you when you forget to do a migration. When a column does not exist, you get an error thrown at you. But with some NoSQL databases, it doesn't have that backstop by default. So your code will just quietly work against documents that don't match what your models actually think is there anymore. So now for this demo, I tried different types of relational and non-relational databases.

For this demo, I use SQLite, and the same enforcement applies for other relational databases in a deployment. So if you've built with Django apps before, you see that orders will have a line item that should point to a product as a foreign key. An order item will also point to a product. So we'll see that next. So after running that, where it fails is when we do the migrations. Because makemigrations doesn't touch the database at all. It only writes a description of the changes it has to make to the file. That step succeeds, no errors, because there's nothing to check against. Since relational databases can't add a foreign key to an existing table with a simple ALTER TABLE, in this case Django will try and work around that limitation by rebuilding the entire table behind the scenes, copying the existing data out, dropping the old table, and creating a new one with the other

column and renaming it into place. As part of making sure that the rebuild is actually valid, Django will check the referential integrity of the new table, meaning that it needs to confirm that the table being referenced, which is catalog_products, exists in the same database file. But guess what? It never did. So the router will keep everything belonging to the catalog app entirely out of default. That's the whole point of the router, because that's its job. So catalog_products was never going to be sitting in that database. The check fails, and then you see the error, OperationalError, and then you realize what actually happened. So any relational database enforcing the foreign key constraint needs a reference table to exist in that same database.

So this is the feedback, or this is the error that I got, and what I learned. So here's the actual takeaway. Enforced referential integrity is a same-database feature. I mean, most of us know this, but we haven't tinkered or found out why it's that way. And that's what I was trying to really find out. Orders and products were never a good fit for reference anyway for a different database. Prices would change and products would get discontinued. And then a live reference will let old orders silently show new prices or break entirely. That's why order items store product SKU and product name as a snapshot, if you remember the plain text field, not a pointer to the current state.

So the split didn't enforce a compromise here. It already forced a design that was already accepted. So what actually brought me to this? In the beginning of the backstory, I was telling you about how I was working with the project, and in that project there were two databases, and I was like, why do we even need two databases? But it was because some fields needed to be hidden or encrypted. So with crypto encryption, I tried that out and I realized that, okay, I could use two different databases simultaneously, where I could only hash—is it hash? Probably convert certain text into cipher text with QE. So the setup was a financial service-style risk assessment API. It was DORA-compliant, and it meant that PII

Sensitive data needed to be hidden at rest, in transit, and in use. So this is how I designed the model. I drew an ERD diagram, highlighting what needed to be hidden, what needed to be exposed, and so on. Names, titles, descriptions, anything carrying PII, yes, needed to be hidden; scores, data, and anything that needed to be filtered or not. So this project actually started the whole talk. Encrypted fields produce ciphertext, as I was saying.

And every time the same value gets encrypted, the filter and get_or_create method won't work against them. So that's why I had to choose which fields to encrypt. The other thing is, performance is going to be a real cost, because every encrypted field on every row that you return would have to be decrypted. So if it's a thousand times encrypted, it has to be decrypted a thousand times. So, what do you trade away? With everything, there's always going to be some form of trade-off. For the first part, the select_for_update method, which we normally would reach for to lock a row during a transaction, does not really work here. It silently does nothing, and the row doesn't get locked. So it's the same shape of problem as we saw earlier.

And it doesn't fail, but it also doesn't throw an error, which is sometimes even worse than having an error. Secondly, no Django backend or engine gives you transactions that span across separate or different databases. That coordination is always on you. Now, two or three questions before you add a second database. These are things that you probably need to consider before you add a database, not because it's shiny or it's something that's cool, because that adds a different level of complexity. Does a specific part of your data have an access pattern that your primary or your default database doesn't really serve, or does it serve awkwardly? Do you have compliance or security requirements mapping onto one defined part of data that you need to fix?

Is your team willing to operate, monitor, and back up a second database, which will be an ongoing process, not a one-time thing? Now, to this point, was all of this worth it? Because, I mean, we never ever tried this. We already know referential integrity. We have an idea of what we should do and what we shouldn't do. So why is Afi wasting her time trying to do something that she knows will fail? Yes, the trade-offs are specific and documented. There's always an avenue for exploration and an understanding of why certain things wouldn't work in play. Honestly, polyglot persistence adds complexity when a specific piece of your data, as I was saying, needs something that your primary database cannot fulfill.

Not because a second engine looks interesting. And do you remember the foreign key value that failed before? That's exactly why it failed. And so you need to plan for what needs to stay together before you decide what needs to go apart. That brings me to the end of my talk. This is my experience, and the QR is the QR to the slides. I'm open for questions. Any questions? Okay.

Speaker 2

Okay. So if you had decided to stick with a single database engine instead of doing this multi-database split, what trade-offs would you have chosen to avoid in that case?

Speaker 1

If I had chosen to

Speaker 2

If you had not done the polyglot setup and just done a single database, what kind of trade-offs would you be losing in that? What would have gone wrong?

Speaker 1

Well, in this case, nothing really would have gone wrong, because you have the same database which has the same tables, but you don't need an extra database. So you wouldn't have performance issues or performance costs, or have to do different read and write operations from different databases. Sometimes the reason why people go for a different database, an additional one, is to serve a particular purpose. For example, in the QA example, I needed an encrypted database that was different from the unencrypted one. So where your data or the access patterns are different, that is why you need a second database, or when it serves a different purpose. Because we don't really see it as something that's really done, like having two different databases existing in one project. We normally just have one and

Yeah, have all our tables in it. So I was wondering why we don't have different kinds and why we don't normally see two different databases in a Django project. It was out of curiosity.

Speaker 3

Thank you for your talk. You mentioned a foreign key failure. Did you expect that in the first place or not?

Speaker 1

Well, the people who you do your dry runs with are grilling you on stage. No, I did know it was going to fail. I just didn't understand why it had to fail. I understood referential integrity, I understood that the tables were going to be different, and the shapes of the data were different, but I hadn't seen it in action. In previous experiences where I used to work in different organizations, I've seen the use of two databases within a microservice architecture, but I didn't start it. I've never created it from scratch. This was my first time using two different databases at work, using Queryable Encryption with encrypted databases and unencrypted ones. And I was like, why don't we have different databases in one, like relational and non-relational? And that's how come...

I got to read it. Django docs. I saw the new PR was from, I think, a DjangoCon Europe talk on transactions spanning across databases. And that brought me to this point. So no, I didn't. I knew it was going to fail, but I didn't understand why, and I needed to satisfy that curiosity. So that was it.

Speaker 4

Okay, hello. So my question is, if someone is on the fence and the person is trying to get this done in their projects, what is that one thing that you tell them?

Speaker 1

Hmm, yeah, you have to really figure out if you really need it, because once you bring an extra database, there's going to be an increase in complexity, and that's one of the things, and performance. So you have to sit down and really figure out if the data you are trying to save or work with cannot be handled, or if there's a particular need that's not being handled by the primary database. You must have a very, very good case point to make sure that adding a second database really makes sense and that you have your team on board to handle the increase in complexity. And that's also going to increase costs, so that's money.