A practical design for tenant context, query boundaries, authorization and tests that prevent cross-tenant data leaks in Python services.
Make tenant context explicit, enforce it at durable boundaries and test negative access cases as seriously as successful reads.
Define the isolation invariant
Start with a precise statement: a request, task or operator may read or mutate only records belonging to an authorised tenant context. Name the exceptions, such as a tightly audited support role, rather than letting them emerge from a broad database session.
Carry tenant context in an explicit request or job object. Avoid hidden globals and optional filters that a developer can forget while adding a repository method.
Enforce at more than one layer
Application filters provide useful errors and make intent visible, but they are not sufficient when a query path is missed. PostgreSQL row-level security, scoped repositories or database views can provide a second boundary where the risk justifies the complexity.
Caches, search indexes, exports and background jobs need the same tenant key. A correctly filtered API can still leak data through a shared cache key or an unscoped asynchronous task.
Prove the negative cases
Tests should create two tenants and attempt every important operation across the boundary: list, lookup by identifier, update, export, retry and administrative action. A 404 and a 403 may carry different information risks; choose deliberately.
Include review evidence for migrations and backfills. A script that runs outside the web request path must still receive and enforce tenant scope.
Evidence to take into review
- Tenant context is explicit across requests and jobs.
- Every data access path enforces tenant scope.
- Caches, exports and indexes include tenant identity.
- Cross-tenant negative tests cover read and write paths.
- Exceptional support access is audited and narrowly defined.
Explore all engineering notes.
Use PRODUCTION-7 to connect this concern with the other dimensions of a trustworthy backend.
View all articles Get the checklist