Skip to content

Having Trouble with DRF in multi-threaded production enviornment. #218

@kardeepak77

Description

@kardeepak77

Stack: Django, DRF, Gunicorn, PostgreSql ( All latest as of Aapril, 2024)

I have implemented multi-tenancy changes as suggested on -

from django_multitenant.fields import *
from django_multitenant.models import *
class Store(TenantModel):
tenant_id = 'id'
name = models.CharField(max_length=50)
address = models.CharField(max_length=255)
email = models.CharField(max_length=50)

class Product(TenantModel):
store = models.ForeignKey(Store)
tenant_id='store_id'
name = models.CharField(max_length=255)
description = models.TextField()
class Meta(object):
unique_together = ["id", "store"]
class Purchase(TenantModel):
store = models.ForeignKey(Store)
tenant_id='store_id'
product_purchased = TenantForeignKey(Product)

'default': {
'ENGINE': 'django_multitenant.backends.postgresql',
......
}

2)For DRF made changes - as per - https://django-multitenant.readthedocs.io/en/latest/django_rest_integration.html

All works fine in development where I am using Django wsgi without Gunicorn.

However, In production I am using Gunicorn with 3 working threads for Django wsgi.
I observed following behavior -

  1. I can successfully login with user [email protected] by calling auth/user/create endpoint which returns JWT token.
  2. Logging in with another user e.g. [email protected] by calling auth/user/create endpoint results in error.

I observed that select query generated against postgresql for 1) has SQL WHERE clause just for the user name.
However, select query generated for 2) has SQL WHERE clause that is filtering by 2 filters -
i) tenant_id of user [email protected]
2) user name [email protected]

Not sure why tenant_id filter is inserted for login call.

Current observation is -
django_multitenant.middlewares.MultitenantMiddleware
isn't calling unset_current_tenant()
Should it call though to avoid above issue?

The unsetting of the tenant is essential because of how webservers work
Since the tenant is set as a thread local, the thread is not killed after the request is processed
So after processing of the request, we need to ensure that the tenant is unset
Especially required if you have public users accessing the site

 This is also essential if you have admin users not related to a tenant.

Any guidance?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions