What would be the best approach to make sure the CreateCar command fails if the car already exists? Naturally I could first check the repository, but this won't prevent race conditions...
There is no magic.
If you are going to avoid racy writes, then you need either to acquire a lock on the data store, or you need a data store with compare and swap semantics.
With a lock, you have a guarantee that no conflicting updates will occur between your read of the data in the store and your subsequent write.
lock = lock_for_id id
lock.acquire
Try:
Option[Car] root = repository.load id
switch root {
case None:
Car car = createCar ...
repository.store car
case Some(car):
// deal with the fact that the car has already been created
}
Finally:
lock.release
You'd like to have a lock for each aggregate, but creating locks has the same racy conditions that creating aggregates does. So you will likely end up with something like a coarse grained lock to restrict access to the operation.
With compare-and-swap, you push the contention management toward the data store. Instead of sending the store a PUT, you are sending a conditional PUT.
Option[Car] root = repository.load id
switch root {
case None:
Car car = createCar ...
repository.replace car None
case Some(car):
// deal with the fact that the car has already been created
}
We don't need the locks any more, because we are describing precisely for the store the precondition (eg If-None-Match: *) that needs to be satisfied.
The compare and swap semantic is commonly supported by event stores; "appending" new events onto a stream is done by crafting a query that identifies the expected position of the tail pointer, with specially encoded values to identify cases where the stream is expected to be created (for example, Event Store support an ExpectedVersion.NoStream semantic).