What does a god app actually cost a large Django project?
A god app is the single Django app (often called core, main, or named after the product) that ends up holding most of the models, views, and business logic. It rarely starts that way. It grows because adding a model to the existing app is always the cheapest next step. The costs show up later, and most of them come from sharing.
One migrations directory, many writers. Every schema change from every team lands in the same migration graph. When two branches each add a migration on top of the same parent, Django detects multiple leaf nodes and refuses to migrate until someone writes a merge migration. With several engineers working in one app, this becomes a routine part of rebasing.
Circular imports. When orders.py needs Customer and customers.py needs Order, the module graph loops. Teams work around it with function-level imports and string model references. Those workarounds hide the cycle instead of removing it.
Slow, leaky tests. If everything imports everything, you can't run the billing tests without loading inventory, notifications, and their fixtures. Test selection by app means little when there is only one app.
Unclear ownership. Nobody can say which team owns a table, so nobody can safely change it.
Teams with several engineers or squads working in one app feel this the most. A solo developer may never notice. Before reaching for a fix, recognize what the problem is: who owns which data, and which code may depend on which. Moving files into new folders without settling those two questions just spreads the god app across more directories.
What is the difference between Django apps and domain packages?
A Django app is a registry concept. It has an entry in INSTALLED_APPS, an AppConfig, and an app label that Django uses as the namespace for its models. That label is persisted in several places: it is the default prefix of each model's table name, it keys rows in the content types table, it appears in permission codenames, and it names the migration graph that owns the app's schema. Creating a new app therefore creates a new ownership boundary for data, and that boundary is costly to move later.
A domain package is ordinary Python, such as orders/billing/ or orders/fulfillment/, inside an existing app. Django does not track it. Models defined in submodules still belong to the parent app as long as they are imported into the app's models module, so they keep the same label, tables and migration history. You get code boundaries without touching data.
| Option | Cost | Risk | What it buys |
|---|---|---|---|
| One app, domain packages | Low: file moves, import updates | Low: no schema or label changes | Clear code ownership, a place to enforce import rules |
| Multiple Django apps | Medium to high: state-only migrations, label handling | Medium: content types, permissions, generic FKs, fixtures | Separate migration histories, independently reusable apps |
| Extracted services | High: network APIs, separate deploys, data copies | High: consistency, latency, operational load | Independent scaling and release cadence |
Start with packages. Split into apps when a domain needs its own migrations or must be installable on its own. Extract a service only when deployment or scaling truly diverges.
How does splitting a god app into domains work?
The split works because Django separates three things that a god app keeps tangled together: where Python code lives, which app a model is registered under, and which database table holds the rows. You can change each one independently, in that order, and stop at whichever stage solves your problem.
-
Code location. Django registers a model with the app registry when the model's module is imported, and it assigns the app label based on the package the model is defined in (unless
Meta.app_labeloverrides it). That means you can splitmodels.pyinto amodels/package inside the same app and nothing about the model's identity changes. This stage is pure Python refactoring. -
Dependency rules. Once code is grouped by domain, you decide which modules other domains may import, typically a
servicesmodule for writes and aselectorsmodule for reads, and you enforce that with a test or a static import checker in CI. Cross-domain foreign keys use string references like"billing.Invoice", which Django resolves lazily after all apps are loaded, so they add no import-time dependency. -
App ownership. When a domain needs its own migration history, you move its models into a new Django app. Each app has its own migration graph, keyed by app label.
SeparateDatabaseAndStatelets a migration change Django's in-memory model state without running SQL, so the new app can claim an existing table (CreateModelin state only, withdb_tablepinned) and the old app can release it (DeleteModelin state only). -
Label-keyed data. Because content types, permissions, generic relations, fixtures and admin URL names are keyed on the app label, the final step is a data migration that renames the existing
ContentTyperows in place so their IDs, and everything pointing at those IDs, stay valid.
At no stage does the physical table move or get copied. The database sees file moves and a handful of UPDATE statements on django_content_type, nothing else.
How do you restructure a monolithic Django app in place first?
The cheapest first move changes no runtime identity at all. Turn models.py into a models/ package, with one module per candidate domain, such as billing.py, catalog.py and fulfillment.py. Then re-export every model from models/__init__.py. Django registers a model when its module is imported, and the __init__.py imports cover that. Because the models still live inside the same app's package, their app label does not change. Their table names, content types and permissions stay the same, and so does the migration history. Running makemigrations should report no changes. Treat that as the check that the refactor was purely structural.
Apply the same pattern to views, services and admin. Admin autodiscovery imports the app's admin module, so an admin/ package works as long as its __init__.py imports the submodules that call register. Existing imports such as from orders.models import Invoice keep working through the re-exports, so callers can migrate gradually.
Because nothing touches the database, each step can be a small, reviewable pull request that merges straight to main. You don't need a long-lived branch or a coordinated deploy.
This step tests your proposed boundaries before you commit to them. Once code is grouped by domain, imports that cross domains show up as concrete lines you can count. If catalog turns out to reach into fulfillment everywhere, your boundary is wrong. Fixing it means moving a few files between modules. Rewriting app labels and migrations is far more expensive, and that cost should only be paid once a boundary has proven stable.
from .billing import Invoice, Payment
from .catalog import Product, PriceList
from .fulfillment import Shipment
__all__ = ["Invoice", "Payment", "Product", "PriceList", "Shipment"]
from django.db import models
class Shipment(models.Model):
# Lazy string reference: no import from catalog.py, so every
# cross-domain dependency stays visible and countable in review.
product = models.ForeignKey("orders.Product", on_delete=models.PROTECT)
shipped_at = models.DateTimeField(null=True, blank=True)
# No Meta.app_label or db_table needed: the module lives under the
# orders package, so the label stays "orders" and the table stays
# "orders_shipment".
from . import billing, catalog, fulfillment # noqa: F401
Splitting a Django app's models and admin into per-domain modules while re-exporting from init.py, so the app label, tables and migrations stay unchanged, with makemigrations --check confirming that no schema changes were introduced.
How do you enforce dependency direction between domain packages?
Boundaries only hold if something enforces them. Give each domain package a small public surface: a services module for writes and a selectors module for reads. Other domains import from those two modules and nothing else. Models, querysets and internal helpers stay private, so the owning team can restructure them without auditing every caller.
For relations that cross domains, use lazy string references such as 'billing.Invoice' in ForeignKey declarations rather than importing the model class. The database still gets a real foreign key, but the Python import graph stays clean and circular imports can't form at module load time.
Signals are the most common way coupling hides. A post_save receiver in notifications that reacts to orders.Order creates a dependency nobody sees at the call site. Replace these with explicit service calls when the caller needs the outcome. When it doesn't, publish a named domain event and have subscribers register their handlers in their own AppConfig.ready(). That way registration is visible in one predictable place per app.
Then make violations fail the build. A simple custom test can walk each package's imports with the ast module and reject anything that reaches past another domain's services or selectors. A static import-contract checker in CI does the same job declaratively.
The costs are real. You add indirection and wrapper functions that sometimes just forward a query. And no import rule stops someone from using apps.get_model() or raw SQL to read another domain's tables directly, so code review still has to catch that.
import ast
from pathlib import Path
DOMAINS = {"orders", "billing", "notifications"}
PUBLIC = {"services", "selectors"} # the only modules other domains may import
ROOT = Path(__file__).resolve().parent.parent # directory containing the domain packages
def violations(path, own_domain):
tree = ast.parse(path.read_text(), filename=str(path))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
targets = [alias.name for alias in node.names]
elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
# "from billing import models" must be checked by the imported name
if "." not in node.module:
targets = [f"{node.module}.{a.name}" for a in node.names]
else:
targets = [node.module]
else:
continue # relative imports stay inside the current package
for target in targets:
parts = target.split(".")
if parts[0] in DOMAINS and parts[0] != own_domain:
if len(parts) < 2 or parts[1] not in PUBLIC:
yield f"{path}:{node.lineno} imports {target}"
def test_domains_import_only_public_interfaces():
errors = []
for domain in sorted(DOMAINS):
for path in (ROOT / domain).rglob("*.py"):
errors.extend(violations(path, domain))
# Fails CI on e.g. `from billing.models import Invoice` inside orders/.
# It cannot see apps.get_model() or raw SQL, so review still matters.
assert not errors, "Cross-domain import violations:\n" + "\n".join(errors)
A plain pytest-style test that parses every module with the ast module and fails the build when one domain imports anything from another domain other than its services or selectors modules.
How does moving a model to a new Django app work without touching data?
The table stays where it is; only Django's idea of who owns it moves. Start by moving the model class into the new app and setting Meta.db_table to the existing table name. Without that, Django derives a new name from the new app label and expects a table that doesn't exist.
Then write two migrations that use migrations.SeparateDatabaseAndState, each with an empty database_operations list:
- New app: a
CreateModelinstate_operationsthat matches the current schema exactly: same fields, same column names, samedb_table. - Old app: a
DeleteModelinstate_operations. It must depend on the new app's migration so the model is never missing from state while other models still reference it.
Every app with a foreign key to the moved model then needs a migration that repoints the field to the new app label. Use AlterField in state only, since the column and constraint are unchanged. Each of these migrations should depend on the new app's CreateModel migration. Explicit dependencies are what make the ordering deterministic. Don't rely on Django inferring them.
The risk is silent drift. If the hand-written CreateModel differs from the real schema in a default, index, or related_name, nothing fails at migrate time. The difference shows up later, when makemigrations emits an unexpected operation in an unrelated change. Run makemigrations --check immediately after the move and expect no changes.
Foreign keys running in both directions between the old and new apps create a dependency cycle. You'll have to split one side into two migrations: create the model first, add the cross-app foreign key afterward.
Finally, billing_invoice living in an app called invoicing is now permanent unless you rename the table, which does touch data.
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
# Explicit ordering: old app's latest migration and FK targets come first
dependencies = [("billing", "0042_previous"), ("customers", "0007_previous")]
operations = [
migrations.SeparateDatabaseAndState(
database_operations=[], # billing_invoice already exists; no SQL
state_operations=[
migrations.CreateModel(
name="Invoice",
# Must mirror the real schema exactly, or drift appears later
fields=[
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("number", models.CharField(max_length=32, unique=True)),
("customer", models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to="customers.customer")),
],
options={"db_table": "billing_invoice"}, # keep legacy name
),
],
),
]
from django.db import migrations
class Migration(migrations.Migration):
# Runs after the new app owns the model, so state never lacks Invoice
dependencies = [("billing", "0042_previous"), ("invoicing", "0001_initial")]
operations = [
migrations.SeparateDatabaseAndState(
database_operations=[], # never drop the table
state_operations=[migrations.DeleteModel(name="Invoice")],
),
]
Paired state-only migrations that move Invoice from billing to invoicing while the billing_invoice table stays untouched.
What breaks when a model's app label changes?
Most of the breakage sits outside the model table. Django keys several framework tables and conventions on the app_label string, so changing a label leaves those rows and references pointing at a label that no longer exists.
The most damaging case involves content types and permissions. After the move, post_migrate sees invoicing.invoice as a new model. It creates a fresh ContentType row and a new set of Permission rows. The old billing rows stay in place. Groups and users are still linked to the old permission IDs, so every has_perm("invoicing.change_invoice") check returns false. Staff lose access without any error being raised. The fix is to rename the existing rows rather than accept new ones. Write a data migration that updates app_label on the original ContentType before post_migrate runs. The row keeps its ID, and every foreign key to that ID stays valid.
| Artifact | Symptom | Fix |
|---|---|---|
ContentType rows |
Duplicate rows. The stale one has a model_class() of None |
Data migration that renames app_label in place. Then run remove_stale_contenttypes to delete leftovers |
Permission / group assignments |
Users silently lose access. has_perm strings in code fail |
Keep the old content type ID through the rename. Update "billing.*" permission strings in code |
| GenericForeignKey rows | Generic relations resolve to None |
Preserve the content type ID, or remap content_type_id |
| Admin URLs and reverse names | 404s on /admin/billing/invoice/. admin:billing_invoice_change raises NoReverseMatch |
Update templates and reverse() calls. Add redirects for bookmarks |
| Fixtures | loaddata rejects "model": "billing.invoice" |
Rewrite the model labels in fixture files |
| Serialized data (natural keys, queued task payloads, caches) | Deserialization fails on the old label | Drain queues and flush caches before deploy. Migrate any stored payloads |
| Raw SQL and reporting | Queries that filter django_content_type.app_label = 'billing' return nothing |
Search BI tools and SQL files for the old label |
from django.db import migrations
OLD_LABEL = "billing"
NEW_LABEL = "invoicing"
MODELS = ["invoice", "invoiceline"] # lowercase model names that moved
def relabel(apps, schema_editor, old, new):
ContentType = apps.get_model("contenttypes", "ContentType")
db = schema_editor.connection.alias
for model in MODELS:
old_qs = ContentType.objects.using(db).filter(app_label=old, model=model)
if not old_qs.exists():
continue # fresh database: nothing to preserve
# If an earlier migrate already let post_migrate create a duplicate row,
# drop it (its Permission rows cascade). They have no group assignments.
ContentType.objects.using(db).filter(app_label=new, model=model).delete()
# Rename in place: the row keeps its ID, so Permission rows,
# group/user assignments and GenericForeignKey content_type_id values stay valid.
old_qs.update(app_label=new)
def forwards(apps, schema_editor):
relabel(apps, schema_editor, OLD_LABEL, NEW_LABEL)
def backwards(apps, schema_editor):
relabel(apps, schema_editor, NEW_LABEL, OLD_LABEL)
class Migration(migrations.Migration):
# Runs during `migrate`, before post_migrate creates new content types.
dependencies = [
("contenttypes", "0002_remove_content_type_name"),
("invoicing", "0001_initial"),
]
operations = [migrations.RunPython(forwards, backwards)]
A reversible data migration that renames existing billing ContentType rows to invoicing in place, keeping their IDs so permissions, group assignments and generic relations remain linked.
What are the alternatives to splitting a god app into domains?
A domain split is not the only response to a god app, and some alternatives are cheaper if your pain is narrow.
Keep one app and manage migration conflicts. If the main complaint is merge migrations, you can keep the structure and handle conflicts as a routine step: makemigrations --merge generates the merge migration, and squashmigrations collapses a long history into fewer files. This treats the symptom, not the cause. Every team still writes into one migration graph, but it costs almost nothing to adopt.
Split by layer instead of by domain. Some codebases break a large app into models/, views/, serializers/ and services/ packages without grouping by business area. This shortens files and makes navigation easier, but it does nothing for ownership or dependency direction: billing and fulfillment code still sit side by side in every layer and can import each other freely.
Domain packages only, never separate apps. Stopping after the in-place restructure and the import rules is a legitimate end state. You get clear code ownership and enforced boundaries with no migration or content type work. The trade-off is that all domains still share one migration history, so migration conflicts and the single-writer problem remain.
Import rules without moving any code. You can add an import-contract check against the existing module layout and forbid new cross-module imports while tolerating existing ones. This stops the coupling from getting worse while you decide whether to restructure.
Extract services. Moving a domain behind a network API gives independent deploys and scaling, but adds distributed consistency, latency, and operational overhead. As the earlier table notes, it is the most expensive option and only pays off when deployment or scaling needs have genuinely diverged.
Start a new app for new work only. New features go into new, well-bounded apps, while the god app is frozen and shrinks opportunistically. This avoids a big migration project but leaves the old app's problems in place, often for years.
How can splitting a god app save engineering time?
The savings come from removing recurring friction, not from a one-time speedup, so they only show up if the team keeps paying the costs described at the top of this article.
Fewer migration conflicts. Once each domain owns its own app, two engineers working in different domains add migrations to different graphs. Django only requires a merge migration when one app has multiple leaf nodes, so cross-domain work no longer collides. Conflicts still happen inside a busy domain, but less often.
Targeted test runs. With separate apps, python manage.py test billing runs only the billing app's tests. Be precise about what this saves: Django still loads every installed app and builds the test database by applying all migrations, so setup time does not shrink. The saving is in the number of tests executed during local development and in CI jobs that are scoped to changed domains.
Faster review and onboarding. A reviewer for a billing change reads code inside billing plus calls into other domains' services and selectors, rather than tracing through a shared module. A new engineer can learn one domain without loading the whole app into their head.
Faster incident triage. When a table, a set of permissions and a migration history belong to one app, it is clear which team to page and where a schema change came from.
Illustrative estimate (not a measured result). Assume a team of 8 engineers sharing one god app. Assume they hit 4 migration conflicts per week, each taking 30 minutes to resolve, rebase and re-run CI: about 2 hours per week. Assume each engineer runs the test suite 5 times per working day, the full suite takes 12 minutes, and the domain subset they usually need takes 4 minutes after setup. That is 8 minutes saved per run, or about 8 × 5 × 8 = 320 minutes, roughly 5 hours per day across the team. Under these assumed inputs, the recurring saving is on the order of 25 hours per week, which you would compare against a one-off restructure that the next section describes as taking weeks. Replace every assumed input with your own team's numbers before using this to justify the work; with a small test suite or rare conflicts, the result can easily be close to zero.
When should you split, when should you avoid it, and how should you roll it out?
When not to split
Skip the restructure if a small team owns the whole codebase, if the domain model is still changing every sprint, or if nobody is actually blocked by merge conflicts, slow test runs, or unclear ownership. Package boundaries drawn around an unstable model end up in the wrong places, and moving them later costs more than never drawing them. The work is real: renaming imports, rewriting migrations, and fixing content types can take weeks. That is only worth it when the time it saves in review, onboarding, and incident triage clearly exceeds it. A modular monolith still has one database and one deploy. It makes later extraction possible, but it does not commit you to microservices.
How to roll it out
Move one bounded domain at a time. Run makemigrations --check in CI so that an unintended schema diff fails the build. Test every state-moving migration against a production-sized copy, because lock duration and row counts only show up at real scale. Ship small deploys that you can reverse. Avoid long-lived refactor branches, since they rot against the main branch faster than you can rebase them.
Target layout
- Project package: settings, root URLconf, ASGI/WSGI entry points, and nothing else.
domains/directory: focused apps such as billing, accounts, and catalog, each owning its models and services.- Thin
shared/package: base classes and truly generic utilities. Review additions to it strictly, or it becomes the next god app.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to large django project structure, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.