Video in progress
When an invariant depends on outside data (for example, "an email must be unique in the system"), how do you enforce it in the domain model?
A single object can't check a rule like this on its own: it doesn't know about other objects. I give the check to a domain service or a factory, but the final guarantee is a unique constraint in the database, because two parallel requests can both pass both checks.
📖 Answer
A common but incomplete solution:
if (users.existsByEmail(email)) throw new EmailTakenException(email);
users.save(new User(email));
If two requests arrive within the same millisecond, both see existsByEmail = false and two users get created. That's a check-then-act race.
This is how I separate the layers:
- The object's own invariants go in the constructor: the email format, not being empty. That's the job of
Userand theEmailvalue object. - Collection invariants (uniqueness, "one active subscription") are expressed by a domain service or a factory, which gives the user a clear error:
public User register(Email email) {
if (users.existsByEmail(email)) throw new EmailTakenException(email); // fast, friendly error
try {
return users.saveAndFlush(new User(email));
} catch (DataIntegrityViolationException e) { // the real guarantee
throw new EmailTakenException(email);
}
}
- The real guarantee is
CREATE UNIQUE INDEX ux_user_email ON users (lower(email)). Nothing other than the database can reliably order parallel requests.
For more complex rules ("a user can't have more than one active subscription"), use a partial unique index (WHERE status = 'ACTIVE'), or bring the rule inside one aggregate (Customer manages its own subscriptions and is protected by an optimistic lock).
If the rule spans services (data in another service), there is no strict guarantee: you use eventual consistency and compensation, or move the ownership of the rule into one service.
To avoid breaking the DDD rule "a domain object doesn't call a repository", I put the check in the service, not inside the entity.
Sign up to mark studied questions and save your progress.