Skip to content

A comprehensive, production-ready prompt for implementing row-level tenant isolation in Django projects.

License

Notifications You must be signed in to change notification settings

KikeVen/row-tenant

Django Multi-Tenant Implementation Plan

tenant guard

License: MIT Django Python PRs Welcome

A comprehensive, production-ready prompt for implementing row-level tenant isolation in Django projects. Think of this as pip install multi-tenant for your architecture - copy the implementation prompt, paste it into your AI assistant, and get guided step-by-step through the entire implementation customized to your project.

πŸš€ Quick Start - Get Implementing in 2 Minutes

This is like pip install but fully configured for architecture patterns - copy and go!

  • Step 1: Copy contents of this repository to your Django project folder
  • Step 2: Open implementation-prompt.md and copy its contents
  • Step 3: Paste into your AI assistant (ChatGPT, Claude, GitHub Copilot Chat, etc.)

The AI will guide you through the complete implementation, step-by-step, customized to your project.

πŸ€” What is Row-Level Tenancy?

Row-level tenancy (also called single-database multi-tenancy) is an architecture pattern where multiple organizations (tenants) share the same database and tables, but each row is tagged with a tenant identifier. This means:

  • One database, many tenants - All organizations share the same PostgreSQL database
  • Data isolation per row - Every record has a tenant_id foreign key that isolates data
  • Automatic filtering - Queries automatically filter by tenant, preventing data leaks
  • Shared infrastructure - More cost-effective than separate databases per tenant

Why Row-Level vs. Other Approaches?

Approach Best For Pros Cons
Row-Level (This Guide) SaaS with 100s-1000s of tenants Cost-effective, easy scaling, shared resources Requires careful query filtering
Schema-per-Tenant 10-50 tenants with compliance needs Strong isolation, easier migrations Complex management, higher costs
Database-per-Tenant <10 large enterprise clients Maximum isolation, custom configurations Expensive, difficult to scale

Row-level tenancy is the industry standard for modern SaaS applications like Slack, GitHub, Shopify, and most B2B platforms.

πŸ’‘ Why Use This Prompt Module?

Traditional implementation takes 2-4 weeks and requires deep Django expertise. This prompt-based approach:

⚑ Speed Benefits

  • 30-120 minutes instead of 2-4 weeks - Pre-planned architecture and battle-tested patterns
  • AI-guided implementation - Get unstuck instantly with context-aware guidance
  • Copy-paste code examples - Working code blocks, not just concepts

πŸ›‘οΈ Safety Benefits

  • Proven patterns - Based on production implementations serving thousands of tenants
  • Built-in testing strategy - Comprehensive test coverage prevents data leaks
  • Migration safety - Step-by-step data migration with rollback procedures

πŸ’° Cost Benefits

  • Free and open-source - No consultant fees ($10k-50k savings)
  • Reduced debugging time - Common pitfalls already documented
  • Reusable across projects - Use this pattern for every Django SaaS you build

🎯 Quality Benefits

  • Production-ready - Includes security, performance, and compliance considerations
  • Role-based access control - Four-tier permission system included
  • Performance optimized - Database indexing strategy included

Bottom line: What normally requires hiring a consultant or spending weeks researching is condensed into a simple prompt you paste into ChatGPT/Claude.

🌟 Features

  • πŸ”’ Complete Data Isolation: Row-level tenant separation with automatic query filtering
  • πŸ‘₯ Role-Based Access Control: Four-tier permission system (Owner/Admin/Member/Viewer)
  • πŸ”„ Backward Compatible: Add to existing projects without breaking functionality
  • πŸ“Š Production Ready: Based on proven patterns with comprehensive testing strategies
  • πŸš€ Easy Integration: Clear phase-by-phase implementation guide
  • πŸ“– Extensive Documentation: 9 detailed guides covering every aspect

Alternative: Use the Quick Reference if you prefer to implement manually with a cheat sheet.

πŸ“š What's Included

This repository contains a complete implementation plan with:

πŸ“‹ Planning Documents

  1. Overview & Architecture - High-level design and scope
  2. Architecture & Design - Detailed system architecture
  3. Requirements - Functional and non-functional requirements

πŸ› οΈ Implementation Phases

  1. Phase 1: Foundation - Core models and managers
  2. Phase 2: Middleware & Access - Middleware and decorators
  3. Phase 3: Management & Utilities - Admin and utilities

πŸ§ͺ Quality Assurance

  1. Testing Strategy - Unit, integration, and performance tests
  2. Risks & Success Criteria - Risk management and metrics

πŸ’» Implementation Details

  1. Code Examples & Configuration - Complete working examples

⏱️ Implementation Timeline

Phase Duration Complexity Dependencies
Phase 1: Foundation 2-3 minutes Medium Database migration planning
Phase 2: Middleware & Access 3-4 minutes High Phase 1 complete
Phase 3: Management & Utilities 2-3 minutes Low Phase 2 complete
Testing & Validation 2-3 minutes Medium All phases complete

πŸ“… Total Estimated Duration: 9-13 days

βœ… Prerequisites

  • βœ”οΈ Django 4.0+ project with custom User model
  • βœ”οΈ PostgreSQL database (required for advanced indexing)
  • βœ”οΈ Existing authentication system (django-allauth recommended)
  • βœ”οΈ Python 3.9+ environment

οΏ½ How to Use This Guide

For AI-Assisted Implementation (Recommended - Fastest)

  1. Copy implementation-prompt.md
  2. Paste into ChatGPT, Claude, or GitHub Copilot Chat
  3. Follow the AI's step-by-step guidance customized to your project

For Manual Implementation

  1. Understand the architecture - Read Overview & Architecture
  2. Plan your approach - Review Requirements and Risks & Success Criteria
  3. Implement phase by phase - Follow phases 1-3 in order
  4. Test thoroughly - Use Testing Strategy
  5. Copy code examples - Reference Code Examples & Configuration

For Quick Reference

Use Quick Reference as a cheat sheet while implementing.

⚠️ Critical Success Factors

  1. πŸ’Ύ Database Backup - Always backup before migration
  2. πŸ§ͺ Staging Testing - Test all migrations on staging first
  3. πŸ“ˆ Gradual Rollout - Use feature flags for controlled deployment
  4. ⚑ Performance Monitoring - Monitor query performance impact
  5. πŸ” Security Validation - Test cross-tenant isolation thoroughly

πŸ—οΈ Architecture Overview

Request β†’ Authentication β†’ TenantMiddleware β†’ View Decorator β†’ Tenant-Scoped Query
                              ↓
                        Set request.tenant
                        Set request.user_role

Key Components:

  • Tenant Model: Organization/company data with settings
  • UserTenantMembership: Many-to-many relationship with roles
  • TenantMiddleware: Automatic tenant context detection
  • Decorators: @require_tenant_access, @require_role
  • Managers: .for_tenant() query filtering

🀝 Contributing

Contributions are welcome! Please read our Contributing Guidelines for details on:

  • Reporting bugs
  • Suggesting enhancements
  • Submitting pull requests
  • Code style guidelines

Please note that this project is released with a Code of Conduct. By participating in this project you agree to abide by its terms.

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ’¬ Support & Questions

  • πŸ“– Documentation: Check the implementation phase documents
  • πŸ› Bug Reports: Open an issue with the bug template
  • πŸ’‘ Feature Requests: Open an issue with the feature request template
  • ❓ Questions: Open an issue with the question label

πŸ™ Acknowledgments

  • Built on proven Django multi-tenancy patterns
  • Inspired by real-world production implementations
  • Community contributions and feedback

⭐ Show Your Support

If you find this project helpful, please consider giving it a star on GitHub!


Made with ❀️ for the Django community

About

A comprehensive, production-ready prompt for implementing row-level tenant isolation in Django projects.

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published