Back to the video

The hack behind the curtain!

Transcript

By Emilio Carrión. From DjangoCon Europe 2022. Published October 14, 2022.

Watch the video Markdown version 2,041 words · auto-generated · en

Summary

Mercadona Tech moved its Django-based grocery logistics systems from three isolated, on-premise warehouses to a centralized, multi-tenant service serving many stores. Rather than adding tenant filters throughout roughly 40 applications and rewriting their tests, Emilio Carrión’s team built a Django layer that applies tenant-aware filtering through custom managers and querysets. The solution discovers tenant relationships between models at startup, supports indirect relationships and common query operations, and obtains the current store from request headers or domains; after a year in production, the approach has been packaged for reuse and is intended for open source release.

Transcript

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

0:00 Introduction and Company Context

Okay, Hariri One first of all this is a template okay I'm no an artist so okay. So yeah, we are going to talk about how we migrated a single tenant application to a multi tenant environment in our company and the things we had to do and the bumps in the road. through the approaches. So first of all, a little bit of myself. I'm Emilo Carrion, I'm a staff engineer at Mercadona Tech. We Mercadona we are a grocery store chain in Spain We have more than sixteen hundred stores through Spain and we are currently expanding through to through Portugal. If you are local maybe you know you recognize the name.

Yeah and besides the physical stroke who okay physical Physic okay. And besides the physical store business, we also have an online service, basically an e-commerce where you can buy groceries online and we deliver them to your home. Why I'm talk telling you this? Because for this part of the business, like ninety-nine ninety-five percent of the software and tools we use in the logistics. Scenario are made in-house and like 90% of the backend development we do it's in Django so we have a lot of experience of deploying Django applications and escalating them

1:32 From Warehouses to Stores

up And yeah, this is some examples of tools we have deployed in developed in Django. We have from supplyment to preparation orders. pick picking products and everything about last mile like routing and delivery services it all is in-house custom made And just a little bit of history. We started this project like five, six, seven six years ago. And we started with a business model in which we build like big warehouses where we prepare like from two thousand Who thousand I'm going to use this. From two thousand two thousand

three thousand daily orders. And yeah, they are great, they work pretty well. This one? Okay. So yeah, big warehouses. They prepare a lot of orders daily, pretty performant. We develop a lot of tools for it. But they have a problem that is they only work in high populated areas like big cities, like in this case Valencia, Madrid and Barcelona. And what happens with the what happens with more rural areas where the demand is lower

so this warehouse doesn't make sense. So a year ago we started to change the paradigm and instead of like having three big warehouses we plan it to use our network of our network of stores that we have sixteen hundred of them through the country in order to prepare orders from there. So we moved from a big warehouse with a lot of tools and with a lot of people working to smaller stores with like two to four people preparing orders and instead of three thousand only fifty. And that was a problem because as we had Only three warehouses from the start we followed

3:49 The Multi-Tenancy Challenge

an architecture where each warehouse was isolated from each other. So we deployed all of the systems and Young applications on premise inside the warehouse. One of the reasons is that in case of a connection error, connectivity error, if the warehouse go offline, the young applications continue working, so the people working there is not stopped by it. And we have also a problem because we were moving from three big environments to sixteen hundred smaller ones. That means a lot of With single deployments, that means a lot of redundant CPU, memory, resources, having to maintain 1600 databases

because until then it was one database per environment And yeah we didn't want to do that. So in order to tackle that that problem we decided to go multi-tenant instead of having all deployed Physically in each store we have only cloud-based centralized system with only one database and then all the stores use that service in order to prepare orders. And that reduced complexity. The problem. Until then we were following an

5:20 The Query Filtering Problem

Django architectural development decision that is that As the data is isolated, for fetching data you did not filter for per preparation center. You if you wanted to get all the orders you just did a dot all and that's it. So in order to migrate that to a multi-tenancy service, it's it's simple. You only have to do a filter and just take the orders for that center. The problem with that is that we have lots of projects. We have like forty Django applications in our company and several of them are deployed in its warehouse. So making that migration in application code was going to cost a lot.

6:07 The Django Multi-Tenancy Hack

Not only modifying business logic but also writing the test that sorry checked that business logic change was korrekt. So we decided to not go this way. And we created what we call the hack inside the company. It started as a little file in one of the smaller projects. It was messing around the Django LRM internally to do some magic behind the curtains. and isolate that data filtering from the business logic to the Django managers and not having to do that manually So

6:52 Evaluating Existing Approaches

We took a lot of inspiration in the Django ecosystem because yeah there is a there is lots of implementations already for Django for multitenancy. We are not the first ones to get there But lots of the existing solutions focus on different approaches to multitenancy. For multitency you can have like one at one deployment pointing to different databases and on runtime you select the database you want to use. You can have one application and one database and different schemas. So in runtime you select the schema you want to use and then you have one you can have one application, one database and one big table with all the data and a column that

Tells you from which center is that data. That was the one we wanted to go and there is no much solution we follow found some articles like this from Bidget and some libraries like this called Django Scopes. This is a great library by the way It serves as a line of defense in case you want to do that modification and application code. You can read the article from the creator, that is very interesting. but neither of them fitted our business needs so we decided to spike a little and create a little experiment to see if we could solve the problem ourselves And yeah, and before starting, some caveats

8:25 Relationship Discovery and Query Design

about the solution of the solution and the problem. We knew that we had models like order directly related to a to a set to a tenant that is center Then we knew we had some models that are not related to the center but related to a model that is related to a center. Deep relationship. And then we knew that we had some complex queries. That doesn't is not a complex query, but it's more like filters and excludes. Okay, we wanted to do aggregates, annotates, and more Operations over the database and we wanted all of that handling to be done in the managers instead of in the business logic. So the office station

was this, it's awful, it's just a base query set with a base manager that was applied to all models If you see we are accessing a private variable query and adding a query if you see if you saw the toll from bus, so this is not recommended, of course. But the thing is it worked. Some of the operations were isolated from each other, but things like the payment that is deep relationship was not and some th some things like aggregates did not work too. So with that in mind we do

9:56 Automatic Tenant-Aware Querysets

did a second iteration that was implementing Deathfield's algorithm search Where we navigate through all the registered models in Django looking for the relationship between any model to the ten and one. So in this case, for example payment, it discovered that it has a for in key two order. Then order it sees that has a foreign key to center and then in center it's a tenant model so it finished. In this case, the algorithm registers that payment to tenancy the relationship is order center ID. So with that information calculated on Django startup setup we modify your current or custom query set, but I only want you to focus on what

we do there that instead of using the default all opera we just ala filter afterwards en caso de filter we just a filter afterwards so en este case in this iteration We did not like went low level into modifying Django RRM, but we built a thin layer on top of it that was applied to every model in the in the application. That made that those are two examples, but the custom query is much longer. So that worker and this allowed us to isolate all that operation related to center from the from the business logic.

11:29 Tenant Context Middleware

And then yeah, so these examples worked well. The payment now it was equal to the to all the payments but filtered by the relationship that it was discovered from the next the previous step. And then we build some utils around it like middlewares. This is a center middleware that takes a center ID from the request, sets it to a global variable. And then is used in the in the custom managers in order to isolate that data. It's just get from a header in case the front end

12:14 Deployment Results and Open Source Plans

injects it through Nginx that we have deployed or taking it from the domain because all of the our domains go con with the tenant ID built in so we have we could we can extract the information from there. And this is the curtain of the name of the talk. This has been deployed in our systems for near a year right now. It has worked great. We discovered some bugs, we fixed them, and we have packaged all of these iterations and knowledge in a single package because we wanted to use it in several applications

and that's how we won down constraints. This is a private library for now. We intend to make it open source in the next weeks, months, I don't know, when we have time. But I w we want to share it with the community. And If you see it, the API is pretty similar to Django Scopes. Both libraries are similar in its use, but differ in how they are used. So we will try to explain in the REDMI what differences are there are between Django constraints and Django scopes so you can decide if you want to use it which use And that's a little bit of the things we saw and how many vibrated we are now like fully multi-tenant

in our stores, currently expanding through all of them. and that's it. Yeah just little las reminder we have tomorrow and workshop TD applied to Django API development. So if you wanna come you are invited. So that's all for me. If you have any questions, does you can ask right now or just contact me or the team. Thank you very much