Topic 36 / 40
Tenant Middleware: Domain Routing & Thread-Local Storage Isolation
1. Deep Architecture
Django handles requests concurrently across threads. To keep tenant data isolated, we resolve the tenant from the request domain and store the active tenant ID in thread-local storage, keeping the context isolated to that request’s thread lifecycle.
2. The Feynman Gatekeeper
[KNOWLEDGE CHECK] Why is storing tenant state in global variables unsafe in concurrent environments, and how does thread-local storage resolve this?
3. The Code
import threading
class TenantStorage:
_storage = threading.local()
@classmethod
def set_tenant_id(cls, tenant_id):
cls._storage.tenant_id = tenant_id
@classmethod
def get_tenant_id(cls):
return getattr(cls._storage, 'tenant_id', None)
4. The Funnel
Stat Level-Up: Isolation Master (Lvl 1).
Sanjaya Integration: Prevent data leaks across workspaces by enforcing tenant isolation boundaries.