What is DDD, and how do you actually apply it?
Domain-Driven Design explained by the parts that pay off, then applied to a real estate domain in Django with working code. Plus an honest section on when DDD is the wrong tool.
Most DDD advice I read falls into one of two camps. Camp one: “DDD means domain/, application/, infrastructure/ folders and an interface in front of everything.” Camp two: “DDD is for banks and airlines, not for us.” Both miss the point.
DDD is not a folder layout. It is about two things: getting the language of the business into the code without distortion, and cutting a large system along the right lines. Aggregates, repositories and events are tools that serve those two goals. Use them without the goals and you get ceremony.
This post covers the ideas first, then applies them to a real estate domain in Django, with code. I picked real estate because I have built several things in it: emlakagenti.az, Khalif Estate and Estate Listing Pusher. The code here is written to teach, it is not lifted from those projects.
Where DDD comes from
The name comes from Eric Evans’ book “Domain-Driven Design: Tackling Complexity in the Heart of Software”, published by Addison-Wesley in 2003. People call it the Big Blue Book. Ten years later Vaughn Vernon published “Implementing Domain-Driven Design”, the Big Red Book. In 2015 Evans released the free “DDD Reference”, a short summary of every pattern in the book plus three that came later: Domain Events, Partnership and Big Ball of Mud.
The subtitle is the whole thesis. The hard part of most software is not the framework, it is the business. When is a property “sold” at a real estate agency? When the buyer pays the deposit? When the title deed changes hands? When the money arrives? Write the code without asking the agent and it will run. It will just be wrong.
Strategic DDD: where to cut the system
DDD has two halves. The strategic half deals with the big picture: how to split the system, and which part deserves your best effort. The tactical half deals with how to write the code inside one of those parts. Most people jump straight to tactics. Most of the value is in strategy.
Ubiquitous Language
Evans’ idea: developers and domain experts build one shared, precise vocabulary, and the code uses that vocabulary as is. Martin Fowler puts the reason plainly: software does not cope well with ambiguity. The language also is not fixed. As the team understands the business better, the language and the model change together, and domain experts are supposed to push back on terms that feel wrong.
In practice: if agents in Baku say “beh” for the deposit a buyer pays to hold a property, the code has one name for that concept and uses it everywhere. If agents distinguish between a listing that was “archived” and one that was “sold”, the code has two statuses, not one is_active = False.
A quick test: can someone from the business read your function names and roughly follow what happens? If not, the language has drifted.
Bounded Context
In a large system the same word means different things in different places. Fowler’s example comes from an electricity utility, where “meter” meant three different things to three departments: the link between the grid and a location, the link between the grid and a customer, and the physical device on the wall.
Real estate has the same problem. “Price” in the listings part is what the seller is asking, and it moves. In the deals part it is the price written in the contract, and it does not move after signing. “Client” in the CRM is a person looking for a home. In commission accounting it is the party paying the fee.
Try to cram all of that into one Property model and one Client model and you know the result: sixty fields, half of them null=True, and every new requirement breaks an old one.
A bounded context draws an explicit line around the place where a model applies. Evans says to set those boundaries in terms of team organization, the part of the application that uses the model, and physical things like code bases and database schemas. Inside the line the language is strict. Outside it, a different model is allowed.
A reasonable split for an agency:
| Context | Job | Key words |
|---|---|---|
| Listings | describing the property, asking price, photos, publishing | listing, owner, asking price |
| CRM | people looking for a home, viewings, matching | client request, budget, viewing |
| Deals | deposit, contract, closing, commission | deal, agreed price, commission |
| Portals | pushing listings to outside sites | external ID, portal, publish status |
Context maps
Splitting is half the job. You also need to see how the contexts relate, and that is what a context map is for. The DDD Reference names the usual relationships: Partnership, Shared Kernel, Customer/Supplier, Conformist, Anticorruption Layer, Open-host Service, Published Language and Separate Ways.
The one I reach for most is the Anticorruption Layer. Put a translation layer between your model and an outside system, so that however messy the outside system is, your code keeps speaking its own language.
Estate Listing Pusher posts listings to bina.az, tap.az, yeniemlak.az, vipemlak.az and arenda.az. None of these sites offers a public API for listings: bina.az and tap.az are reached over GraphQL, the others through ordinary HTML forms. Each site lives in its own module, and adding one does not touch the others. That is the anticorruption idea exactly. How tap.az structures a form never leaks into the listing model.
Core Domain
Evans is blunt about this one: not every part of the design will be equally refined, so set priorities. The part that makes the business different from competitors is the core domain, and it gets your strongest work. Login, payment collection and SMS delivery are generic subdomains, and you should cover them with existing solutions where you can.
For a real estate agency the core is usually matching (which client for which property) and pricing. It is not the login page.
Tactical DDD: code inside a context
Entities and value objects
An entity is defined by identity. Its attributes change and it is still the same thing: a listing with a new price is the same listing. Evans warns that mistaken identity leads to corrupted data.
A value object only cares about its value. 150,000 AZN is 150,000 AZN wherever it appears, it has no identity of its own. Value objects are immutable and validate themselves. Replace a loose Decimal plus a separate currency field with a Money value object and a whole class of currency mix-up bugs disappears.
Aggregates and invariants
This is the part people get wrong most often.
An aggregate is a cluster of objects that must stay consistent together. It has one root, and the outside world talks only to the root. Fowler’s summary: any references from outside the aggregate should go only to the root, and transactions should not cross aggregate boundaries.
An invariant is a business rule that must always hold. Vernon defines it as a business rule that must always be consistent. “The price of a sold property does not change.” “Commission is calculated only when the deal closes.”
Vernon’s essay “Effective Aggregate Design” gives four rules, and to me they are the most practical thing in all of DDD:
- Model true invariants in consistency boundaries. You do not draw an aggregate around objects that are related. You draw it around rules that must be true within one transaction.
- Design small aggregates. Vernon cites one project where about 70% of aggregates were just a root entity with a few value-typed properties. Your split will differ, but the direction is clear.
- Reference other aggregates by identity. A deal stores
listing_id, not the listing. - Use eventual consistency outside the boundary. If one command has to change another aggregate, do it through an event, a moment later, not in the same transaction.
When rule four gets hard to call, Vernon passes on a question he got from Evans: whose job is it to make this consistent? If it is the job of the user running the use case, make it transactional. If it is another user’s job, or the system’s, let it be eventually consistent.
Domain events
A domain event records that something happened that domain experts care about: “Deal closed”, “Price reduced”, “Deposit received”. Evans added the pattern after the book, because an entity’s current state does not tell you how it got there.
Events are also the cleanest way to keep contexts apart. The deals context does not reach into the listings context and flip a status. It announces “deal closed”, and listings reacts on its own terms.
Repositories
Evans defines a repository as query access to aggregates expressed in the ubiquitous language. In Django you rarely need a separate Repository class for that. A custom QuerySet already is one. What matters is that its method names come from the business: not filter(budget__gte=...) scattered through views, but ClientRequest.objects.that_fit(...).
Applying it in Django: a real estate example
Here is the awkward part. Django is built on Active Record. Its own design philosophy says models should encapsulate every aspect of an object, following Fowler’s Active Record pattern. So doing DDD in Django does not require throwing the ORM away and writing a “pure” domain layer with mappers. In my experience of Django codebases, that path usually costs more than it returns.
The pragmatic route: Django models act as aggregate roots, business rules live in model methods, and views, serializers and admin actions never assign status fields directly.
Layout
Each bounded context is its own Django app:
estate/
shared/ money.py, errors.py, bus.py
listings/ models.py, handlers.py, apps.py
crm/ models.py
deals/ models.py, events.py, services.py
portals/ base.py, binaaz.py, tapaz.py
The rule: one app never imports another app’s model to change it. Between contexts, only IDs, events and plain data objects travel.
A value object: Money
from dataclasses import dataclass
from decimal import Decimal, ROUND_HALF_UP
@dataclass(frozen=True)
class Money:
amount: Decimal
currency: str = "AZN"
def __post_init__(self):
amount = Decimal(str(self.amount)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
if amount < 0:
raise ValueError("Money cannot be negative")
object.__setattr__(self, "amount", amount)
def percent(self, rate: Decimal) -> "Money":
return Money(self.amount * Decimal(rate) / 100, self.currency)
def __add__(self, other: "Money") -> "Money":
if other.currency != self.currency:
raise ValueError("Currencies differ")
return Money(self.amount + other.amount, self.currency)
class DomainError(Exception):
pass
Listings: rules inside the model
First, what an anemic model is. Fowler called it an anti-pattern back in 2003: objects named after domain nouns, connected by rich relationships, but with almost no behavior, “bags of getters and setters”. All the logic sits in separate services. His point is that this is procedural code wearing an object costume, and you pay the cost of a domain model without getting the benefit.
In Django, anemia looks like listing.status = "sold"; listing.save() repeated in a view, a serializer, an admin action and a Celery task. The rule is spread over four places, and whoever writes the fifth forgets it.
Instead:
from django.db import models
from shared.errors import DomainError
from shared.money import Money
class Listing(models.Model):
class Status(models.TextChoices):
DRAFT = "draft"
ACTIVE = "active"
SOLD = "sold"
owner_id = models.PositiveBigIntegerField(db_index=True)
title = models.CharField(max_length=200)
area_m2 = models.DecimalField(max_digits=8, decimal_places=2)
asking_amount = models.DecimalField(max_digits=12, decimal_places=2)
currency = models.CharField(max_length=3, default="AZN")
status = models.CharField(max_length=10, choices=Status.choices, default=Status.DRAFT)
sold_by_deal_id = models.PositiveBigIntegerField(null=True, blank=True)
@property
def asking_price(self) -> Money:
return Money(self.asking_amount, self.currency)
def publish(self):
if self.status != self.Status.DRAFT:
raise DomainError("Only a draft can be published")
if self.asking_amount <= 0:
raise DomainError("A listing needs a price before it goes live")
self.status = self.Status.ACTIVE
def change_price(self, new_price: Money):
if self.status == self.Status.SOLD:
raise DomainError("The price of a sold property does not change")
if new_price.currency != self.currency:
raise DomainError("Currency changes are a separate decision")
self.asking_amount = new_price.amount
def mark_sold(self, deal_id: int):
if self.status == self.Status.SOLD and self.sold_by_deal_id == deal_id:
return
if self.status == self.Status.SOLD:
raise DomainError("This property was already sold in another deal")
self.status = self.Status.SOLD
self.sold_by_deal_id = deal_id
A few things worth noticing. Method names are the agent’s words: publish, change price, mark sold. Calling mark_sold twice for the same deal quietly does nothing. That is on purpose, because events can be delivered twice and the handler has to survive it. And owner_id is not a ForeignKey, because the owner belongs to another context.
Be honest about the trade-off. Referencing by ID costs you the database foreign key constraint, select_related and cascading deletes. On a small project that price can be too high. I only do it across contexts. Inside one context, a ForeignKey is fine.
CRM: a QuerySet as the repository
from django.db import models
from shared.money import Money
class ClientRequestQuerySet(models.QuerySet):
def open(self):
return self.filter(closed_at__isnull=True)
def that_fit(self, price: Money, area_m2):
return self.open().filter(
budget_amount__gte=price.amount,
currency=price.currency,
min_area_m2__lte=area_m2,
)
class ClientRequest(models.Model):
client_name = models.CharField(max_length=120)
phone = models.CharField(max_length=20)
budget_amount = models.DecimalField(max_digits=12, decimal_places=2)
currency = models.CharField(max_length=3, default="AZN")
min_area_m2 = models.DecimalField(max_digits=8, decimal_places=2, default=0)
closed_at = models.DateTimeField(null=True, blank=True)
objects = ClientRequestQuerySet.as_manager()
that_fit takes a price and an area, not a Listing. The CRM does not know the listings model and does not need to.
Deals: an aggregate that raises an event
from dataclasses import dataclass
@dataclass(frozen=True)
class DealClosed:
deal_id: int
listing_id: int
client_request_id: int
from decimal import Decimal
from django.db import models
from django.utils import timezone
from deals.events import DealClosed
from shared.errors import DomainError
from shared.money import Money
class Deal(models.Model):
class Status(models.TextChoices):
OPEN = "open"
CLOSED = "closed"
CANCELLED = "cancelled"
listing_id = models.PositiveBigIntegerField(db_index=True)
client_request_id = models.PositiveBigIntegerField(db_index=True)
agreed_amount = models.DecimalField(max_digits=12, decimal_places=2)
currency = models.CharField(max_length=3, default="AZN")
commission_rate = models.DecimalField(max_digits=4, decimal_places=2)
commission_amount = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True)
status = models.CharField(max_length=10, choices=Status.choices, default=Status.OPEN)
closed_at = models.DateTimeField(null=True, blank=True)
@classmethod
def start(cls, listing_id: int, client_request_id: int, agreed_price: Money, commission_rate: Decimal):
if commission_rate <= 0:
raise DomainError("Commission rate must be positive")
return cls(
listing_id=listing_id,
client_request_id=client_request_id,
agreed_amount=agreed_price.amount,
currency=agreed_price.currency,
commission_rate=commission_rate,
)
@property
def agreed_price(self) -> Money:
return Money(self.agreed_amount, self.currency)
@property
def pending_events(self) -> list:
if not hasattr(self, "_pending_events"):
self._pending_events = []
return self._pending_events
def close(self):
if self.status != self.Status.OPEN:
raise DomainError("Only an open deal can be closed")
self.status = self.Status.CLOSED
self.closed_at = timezone.now()
self.commission_amount = self.agreed_price.percent(self.commission_rate).amount
self.pending_events.append(
DealClosed(deal_id=self.pk, listing_id=self.listing_id, client_request_id=self.client_request_id)
)
The invariant: commission is calculated only when the deal closes. That is literally how Khalif Estate works, commission is paid only when a deal actually closes. In this code the rule lives in one place, close(), and there is no reason left to compute commission anywhere else.
Notice that close() does not touch the listing. Marking the property sold is not the deal aggregate’s job.
The application layer stays thin
Evans on the application layer: it is kept thin, holds no business rules, and only coordinates tasks and delegates work to domain objects.
from django.db import transaction
from deals.models import Deal
from shared.bus import publish
def close_deal(deal_id: int) -> Deal:
with transaction.atomic():
deal = Deal.objects.select_for_update().get(pk=deal_id)
deal.close()
deal.save()
events = list(deal.pending_events)
transaction.on_commit(lambda: publish(events))
return deal
transaction.on_commit is built into Django: the callback runs only after the transaction commits, and is discarded if it rolls back. So “deal closed” goes out only when the deal is really closed in the database.
The other context reacts
from collections import defaultdict
_handlers = defaultdict(list)
def subscribe(event_type, handler):
_handlers[event_type].append(handler)
def publish(events):
for event in events:
for handler in _handlers[type(event)]:
handler(event)
from django.db import transaction
from deals.events import DealClosed
from listings.models import Listing
from shared.bus import subscribe
def mark_listing_sold(event: DealClosed):
with transaction.atomic():
listing = Listing.objects.select_for_update().get(pk=event.listing_id)
listing.mark_sold(event.deal_id)
listing.save()
def register():
subscribe(DealClosed, mark_listing_sold)
from django.apps import AppConfig
class ListingsConfig(AppConfig):
name = "listings"
def ready(self):
from listings import handlers
handlers.register()
That is Vernon’s fourth rule in practice. The deal closes in its own transaction. The listing becomes sold in a separate one, a moment later. Whose job is it? The agent closing the deal is responsible for the deal. Fixing the listing status is the system’s job.
A caveat I would rather say than hide: this in-process bus is the simple version. If the handler fails after the commit, the listing stays unsold. In production it is safer to write the event into an outbox table in the same transaction and let a separate process deliver it, which Chris Richardson calls the transactional outbox pattern. For a start, on_commit plus a Celery task with retries is a fine middle ground.
Portals: the anticorruption layer
from dataclasses import dataclass
from decimal import Decimal
from typing import Protocol
@dataclass(frozen=True)
class ListingSnapshot:
listing_id: int
title: str
area_m2: Decimal
price_amount: Decimal
currency: str
photos: tuple[str, ...]
class Portal(Protocol):
name: str
def publish(self, listing: ListingSnapshot) -> str: ...
def unpublish(self, external_id: str) -> None: ...
Each portal (binaaz.py, tapaz.py and so on) implements Portal in its own way. One builds a GraphQL request, another fills in an HTML form. The listings context knows none of this. It hands over a ListingSnapshot and gets back an external ID. When a portal changes its form tomorrow, one file changes.
Event Storming: the fastest way to find the language
So where do the contexts, events and aggregates come from? In 2013 Alberto Brandolini introduced Event Storming, which he describes as a workshop format for quickly exploring complex business domains.
The mechanics are simple. A long wall, lots of sticky notes. Orange notes carry domain events in the past tense: “Listing published”, “Viewing booked”, “Deposit received”, “Deal closed”, “Commission paid”. Then a blue note goes in front of each event for the command that caused it. Brandolini suggests 6 to 8 people in the room: people who know which questions to ask and people who know the answers. In other words, the developer and the agent, together.
Brandolini’s claim is that this gets you a model of a business flow in hours rather than weeks. The most useful moment tends to be when two people discover they use the same word for different things. That is where a context boundary runs.
When not to use DDD
Plainly: most websites do not need full DDD.
- Simple CRUD. Microsoft’s .NET microservices guide says the same: for a simple CRUD service, entities that only hold data can be good enough, and the heavier DDD patterns may not be worth it. In their reference application the ordering service uses DDD patterns and the catalog service does not.
- Generic parts. Login, file uploads, notifications. Take something ready-made and save the effort for the core.
- No domain expert. DDD is built on talking to the business. With nobody to build the language with, “DDD” turns into folder names.
- An unknown domain that needs a quick test. The strategic ideas (language, boundaries) still pay off. The heavy tactical structure can wait.
Evans himself describes the “Smart UI” approach, calling it an anti-pattern with tongue in cheek, as a fork in the road that is incompatible with DDD but has real advantages and situations where it works best. DDD is a tool, not a religion.
A short migration path
If you want to bring DDD into an existing Django project, this is the order I would go in:
- Spend an hour with someone from the business. Write down the 20 words they use most, each with a one-sentence meaning.
- Find words with two meanings. Your context boundaries run there.
- Pick the rule that hurts most (say, “a sold listing’s price does not change”) and move it into a model method. Delete the direct
status =assignments from views. - Replace direct cross-context model changes with events.
- Move integrations with outside systems into their own module, an anticorruption layer.
You do not have to rewrite the system in one go. Each step makes the code better on its own.
I wrote about the business side of the same domain in CRM for real estate agencies.
If you are building something with real business rules in it, here is what I do for real estate software, or just get in touch.
Sources
- Eric Evans, Domain-Driven Design: Tackling Complexity in the Heart of Software (Addison-Wesley, 2003)
- Eric Evans, DDD Reference (2015, CC BY 4.0)
- Vaughn Vernon, Implementing Domain-Driven Design (Addison-Wesley, 2013)
- Vaughn Vernon, Effective Aggregate Design, Part I
- Vaughn Vernon, Effective Aggregate Design, Part II
- Martin Fowler, BoundedContext
- Martin Fowler, UbiquitousLanguage
- Martin Fowler, DDD_Aggregate
- Martin Fowler, AnemicDomainModel
- Alberto Brandolini, Introducing Event Storming (2013)
- Microsoft Learn, Designing a microservice domain model
- Django, Design philosophies: Models
- Django, Database transactions: on_commit
- Chris Richardson, Transactional outbox
-
What is TikSocket, and is there anything like it?
2026-11-16 · 9 min
-
How to add Epoint payments to your website
2026-11-12 · 9 min
-
Why is my website slow, and how do I fix it?
2026-11-11 · 8 min