# Scaling Django: Mastering Database Routers with AWS Aurora with Leonardo Batista

Source: https://djangotv.com/videos/djangocon-us/2026/scaling-django-mastering-database-routers-with-aws-aurora-with-leonardo-batista/
Date: 2026-10-26
Speakers: Speaker 1, Speaker 2, Speaker 3
Text: lightly edited for readability (verbatim on the page)

## Transcript

**Speaker 1:** [00:14] Good morning, DjangoCon. Good morning, Chicago. Let's talk about database routers. First, a little bit about me. I'm Leo. I'm from Brazil, and I'm a solutions architect and DevSecOps lead at OneBlinc. I've been working with Django for five years. I'm in love with Django since then. I really like it. It's my third DjangoCon online, and this is my first DjangoCon in person and my first conference as a speaker. So, great expectations. So let's talk about the

[01:01] This issue we had in 2024. I was supposed to submit this talk last year, but I'll talk about it at the end. So let's first talk about the breaking point of this situation. First, some context about the company and the team. OneBlinc is a US-based fintech. Most of the team is Brazilian, but the company is US-based, working with the US market. Our main product is Blink Advance, which is a cash advance app. You can find the app on the Play Store and Google Play. You can search later.

[01:48] But our company is really small. We have around 30 people total, and our tech team is really small. We have around 10 to 12, including some management people. We prefer using managed and automated services, as our structure is really lean. So we usually prefer not using some built-in solutions from scratch to avoid maintenance and some maintenance issues.

[02:33] At our current moment, we are growing really fast. We've already reached our operational break-even, like, three months ago, so we are in a good standpoint in the market. Really, really good. And what are the tools that we mainly use? Our core stack: We use Django running on containers at ECS. Our stack is full AWS. We use Aurora PostgreSQL for the database, and we use Redis for cache on ElastiCache. And what

[03:19] was the problem? Back in 2024, our backend was becoming quite overloaded, mainly on peak hours. At that time, we still had a legacy product, which was payroll loans, and we usually saw some peak traffic mainly on Fridays, which were the paydays. With this overload, our backend got really, really overloaded, and we needed to increase the number of nodes. So when the backend stabilized, we

[04:05] reached another problem, which was the database overload. At the moment, we just stopped the current tasks and started analyzing the possibilities for the database, as we hadn't had any situation like that before. So we evaluated increasing the database size, and we evaluated some indexes for the core tables. We discussed some approaches on data cleanup and data archiving, but it wasn't the

[04:50] right moment for some movements like archiving, for example. So the database is the first bottleneck, because horizontal scaling for the backend is really, really easy today. We can just spawn more nodes, and it works really well. Django manages this traffic in a really good manner. But the database is not the same. It's not so easy to scale your database

[05:36] both horizontally and vertically. So the database is your ceiling for your traffic and your workload. When you start having this type of issue with the database, you see some symptoms. Your app latency increases. The connections to the database start failing. You have more errors on your API requests. In this case, adding more app instances for your backend just makes the problem worse. Along with that, you can also see some symptoms on the database side, in the database metrics.

[06:23] So you don't have much margin on database CPU, so you can't do some maintenance processes like vacuum. You see some deadlock issues, some lock contention. We'll see some reads taking a while to complete because the database is overloaded. For this talk, as the AI topic is quite common, I'll try to bring some tips—not big AI slop, but some AI tips from our experience

[07:08] on how you can use AI in a good way to help you understand, identify, and implement a solution like that. For example, in the symptoms case, you can use AI to correlate the logs and metrics from your backend, your database, and all the usage you have, to identify the critical paths, optimize some queries, identify slow queries, and then identify some indexes you may implement. And why do we use Aurora? First,

[07:53] what's Aurora? Who here has already heard about or worked with Aurora? Good, good. So Aurora is a database management system from AWS. It runs on the RDS platform, and it has two versions: one MySQL-compatible and one PostgreSQL-compatible. For both cases, Django doesn't know the difference. For the application, it's basically the same thing. And the two most important things that

[08:39] at my standpoint, Aurora is really good on RDS: the compute and storage are decoupled, so you don't need to increase your CPU just because you need more disk, and vice versa. And the replica configuration is also really easy and really good to manage. So why did we choose Aurora? We chose Aurora mostly because of the reliability. So

[09:25] when you have many reader replicas, if the writer fails, it automatically promotes one of the read replicas to a new writer. This is really quick, less than one minute. This only cuts the connection and switches the traffic to the new node, so it's really good. We also use this to scale the database or do maintenance windows, because you can just spawn a new node with the new configuration and switch the writer to this new one, then phase out the old replica. Also,

[10:11] Aurora shares the storage across the replicas, so the replication lag is really, really low, usually around 10 to 20 milliseconds. Also, the traffic is load-balanced across the reader instances, and this is an important thing: Aurora distributes connections, not query load. So it's important when building the queries across the database instances. And the core feature that we will use for the solution for this talk

[10:58] is the two stable endpoints. Aurora provides two endpoints, one for the writer, which is the primary node, and one for the reader instances. So you can have a read-only connection separate from the writer node, and it enforces read-only. You don't have to manage this type of operation with roles and database permissions. But there's a trade-off: Aurora is more expensive than a regular PostgreSQL instance on RDS, usually 20 to 30 percent. So, okay, we talked about

[11:44] Aurora, but let's implement the router. First, database routers. Who here has already worked with or at least heard about database routers in Django? Good, good, good. So what does a database router do? A database router is basically a class that picks the connection depending on your own rules. You build the rules; you can have some specific for reads and for writes, and it unlocks the databases property from settings, and you can use many databases for many purposes.

[12:30] Effie said yesterday in her talk about database routers with different flavors of databases, but in this case, we will work with the same database with different connections for a similar but different purpose. Database routers need to be registered to the DATABASE_ROUTERS property. So they are consulted in order, and each operation may return the database alias for reads and writes. The method may not be implemented; it's optional.

[13:16] And also, if the method returns None, it just passes the responsibility to the next router, so you can chain many routers in your application. One important thing: database routers are stateless. They don't manage any transaction or any correlation between the queries and the other write operations. And don't override any .using() syntax for the query sets. Database routers basically have four methods: db_for_write and db_for_read. Quite explicit in the name, and it's really clear.

[14:02] So db_for_read specifies which database alias will be used for reads; db_for_write specifies which database alias will be used for writes. Allow_relation will specify if a relation between two models is allowed. As Effie said yesterday, if you try to implement a foreign key between two models in different databases, this won't work. So in this method, you can specify if the relation is allowed or not.

[14:49] And allow_migrate will specify if the migrate operation, the migration command, is allowed on this specific alias. So we've seen some core definitions about database routers. Let's talk about the idea. We were having some scalability issues, and our database was struggling a lot with the load. But for those who have already worked with Aurora, Aurora has a limitation by design for the business model

[15:36] that the nodes scale exponentially. So we reached a moment when the current node size we had for the writer was too small for our load, but the next size was too big and too expensive for our current needs. So we needed to search for some alternatives. We implemented some indexes, and we did some cleaning, as I mentioned, but they weren't enough. So we got this idea after searching a little about the endpoints that Aurora provides, and we decided to build a database router

[16:22] with multiple database connections to both Aurora endpoints, reader and writer. Basically, what we did: We built a default connection, which was the one already in place that points to the writer, and we created a new one called read-only, of course, pointing to the read-only endpoint. Then we implemented the router. The router is a really simple class. You'll see it in the implementation here. And

[17:08] we implemented the four methods. Here, the two I would call the selectors: db_for_read points to the read-only connection; db_for_write points to the default connection, which is the writer. And then we built the validators, as I call them. Allow_relation is always true because it's the same database; all objects can relate to any other object. And allow_migrate only allows migrations to the writer, because the reader cannot allow any write operations. So this is the really big implementation,

[17:55] really complex, the full database router. To finish, you just need to add the database router you built to the DATABASE_ROUTERS property. And that's it. That's the solution. Not actually. The main point of this presentation is not to give the implementation of the router, but actually the insights from this process. So, some points that might need some attention. First, when do you need to enforce the writer connection?

[18:41] Sometimes, although the replicas exist, you need to enforce the writer for many reasons. In some cases, read-after-write operations. For example, refresh_from_db(), some async tasks triggered right before a write in the database, and these tasks need to read the result from the previous operation; some session operations, some redirects. For example, you have a form that you need to submit. Let's say you need to enroll a customer to your platform manually.

[19:29] You submit the form and redirect right after the form to the user's list, and you need to ensure that the new user is listed in this user list. Sometimes the replication lag is not enough, and this new user may not appear in the list. So you need to ensure that this new user is listed right after the redirect. Some locking operations are also required to happen in the writer. Any transaction and locking operation needs to be pointed to the writer. If you try to do any

[20:16] locking operation on the reader, it will raise an error, and you will not be able to complete the operation. So this is an example of locking a transaction to the writer. In this case, you need to override the target for the operation in each step of the transaction. For example, in this first get here, the select for update, you need to enforce the writer because you need to make sure that the up-to-date data

[21:02] is retrieved from the database in order to do the operation correctly. Some other situations where you need to enforce the writer are some critical decisions that need correctness. So, in the finance area, balance and limit checks need to happen on the writer. Some get-or-create operations that have a constraint, some exact counters, and rate limits that need to be strict—these types of

[21:47] of operations need to go to the writer. And, of course, any structural change needs to go to the writer. That's why the migrations need to go there. So how do you analyze this? It depends on your workload. What tolerates the replication lag is on your side. You need to know what is acceptable and what's not. The real work here is to analyze the trade-offs and understand your needs. This analysis process

[22:33] is the most important part of the whole implementation. For that, you may use AI to understand the needs and optimize some queries for this process. Also use the agents and code reviewer tools to identify these writer-bound operations during the review process and during the implementation process, because we've had some issues in the past implementing some of these writer-bound flows without checking whether they were actually writer-bound

[23:18] and when we sent them to production, they failed. This part is where AI is being really helpful. We've been using this for some months, and Claude AI has already identified some specific paths that needed to be changed before deployment to ensure correctness. For this implementation, there are some cost-optimization tips that I may give you when working with Aurora and this solution

[24:04] that will help you maintain your project. It's not for small projects; it's something bigger, but these tips might be really helpful. First, you need to separate the metrics for the writer and the reader. They have completely different behaviors. They need to be handled completely separately. One of the most important parts after we implemented this solution was auto-scaling. Aurora provides some auto-scaling rules that are not charged for the main maintenance and management; it just charges you for the

[24:50] instance hours and the CloudWatch metrics. So you can specify some rules to trigger a new node depending on your workload, and you can scale predictably for some specific hours and cycles. We usually scale a new reader node on payment dates, as our traffic is bigger than usual. Another tip is to use savings plans or reserved instances for at least the baseline of your workload

[25:38] and leave the on-demand costs only for auto-scaling. And here is a cost comparison for both Aurora models, provisioned and serverless, but I won't deep dive into these numbers. The only rule I can offer is that if your time spent with the database online is less than 40% on average, the serverless option is the most indicated and most recommended.

[26:23] And if your workload is above 60% of the time, you should go to provisioned instances. But you can combine them: you can have a writer using provisioned instances and use serverless for the readers when you have variable traffic. For cost optimization, a good tip is to use AI tools to analyze your metrics, understand your workloads, and then identify some possibilities for better allocation of your resources. So maybe AI tools must suggest

[27:08] a different instance family, a different instance size, some more and smaller instances for your readers than you have. Many options. And some lessons that we've learned during this implementation. First, as you could see, the router implementation is really simple. The main work here is on the consistency of your data and your application execution. Auto-scaling may save your life, but sometimes it might be tricky. So

[27:53] when an auto-scaling instance is scaling in, aka being shut down, the connections pointing to the instance may be closed unexpectedly. For this case, it's recommended to have shorter timeout configurations for your database connections. Another tip I can give for auto-scaling is to use the same instance family and size across all your instances, both writers and readers, because if you mix

[28:39] sizes, the metrics may confuse you when you're making a decision. What is 30% CPU for one instance size is completely different from what is 30% CPU on another instance size. About the lag on Aurora, sometimes it's usually milliseconds, but sometimes this isn't enough for your use case, your application, or your users, and sometimes it may be

[29:26] far more than that. I've seen some cases during maintenance windows and some high-volume hours reaching a few seconds, for example. It depends a lot on your usage. A tip that we learned with this process is that you need to avoid some early optimization. Sometimes you just need to build some indexes. They fix like 90% of your problem. Sometimes you just need one more year or six months in a bigger instance size until you figure out your workload and optimize some stuff.

[30:14] And most importantly, measure and understand your workload. This is really important. So where are we now in our implementation? We have a writer and two fixed readers, with some extra readers being triggered on peak hours on demand. Our current focus is on continuously identifying and optimizing the writer-bound workloads and also reducing the scaling impacts of connections closing.

[31:02] So I presented the solution, but we need to go further. We can have some other possibilities with this implementation. If you don't use AWS, disclaimer: I've not tested this, and I've never heard about any of these solutions; I've just searched about them, so no guarantees. GCP, as my search returns, has AlloyDB, which I've never heard about. But apparently, it's the same idea as Aurora. GCP users may know more about this than me.

[31:47] Azure has a similar solution, but it only offers one reader instance. It doesn't provide any horizontal scaling as Aurora does. And you can build your own solution. Congrats if you do. So, last thing: you can adapt this solution to your needs. If you don't use Aurora or if it's not your use case, you can even use this database routers approach for

[32:32] distinct roles, different connection configurations for different queries, and different workload operations for long-running queries. This is a good approach. We almost used it for a pilot we did, which was multi-tenancy. You can use database routers to route your requests across multiple databases or multiple schemas depending on your tenant. So you can even do sharding by tenant using database routers. You can have a context var

[33:17] that stores the current customer and routes the request to the respective database or schema. And one last AI tip: this is a crazy one. Feel free to try it. For replication lag specifically, you can even connect a small LLM model to analyze your metrics and your replication metrics, and dynamically shift the traffic between the writer and the readers to reduce the replication lag. Completely crazy, this idea.

[34:04] Feel free to use it. But that's it, guys. Thank you so much. This QR code points to my website. My contacts are there. Please follow me on LinkedIn and connect with me. I'm really happy to talk with any of you. So, yeah, and a quick notice on the Andral project, which makes these amazing illustrations possible. Congrats to them, too. Thank you.

**Speaker 2:** [34:45] Now we have time for questions. Anyone else?

**Speaker 3:** [34:55] So I understand the constraints that you have on needing some of the reads to stay on your write replica. In your application, do you have a feel for what percentage of your traffic you're able to switch to the readers?

**Speaker 1:** [35:14] Not a specific percentage, but for now, we have two reader instances, and they are most of the time at 60 or 70% usage. We trigger some other replicas; they are the same size as the writer. The writer's baseline is 15% CPU, so the amount of read operations we have is really much bigger than the write operations. And one important thing that I haven't mentioned

[36:00] in the talk: one of the main gains we got with this is for the data team, because they need to ingest our production database into their lakehouse solution. With this auto-scaling, they can pull our database as much as they can because the auto-scaling handles the traffic according to their demands without degrading the backend usage. Most of these reader demands are from the data team, not actually the application, but also the application.

**Speaker 2:** [36:45] Well, no more questions. This is a gift from the organization.

**Speaker 1:** [36:49] Thank you.

**Speaker 2:** [36:50] Please...
