DDD and business rules that need ACID

Viewed 450

The way I understand it : you load all the datas from the database into your entities where your business logics are. It's like having a copy of the database in memory for the current use case.

But I fail to see how to enforce logic that needs the ACID of the database. For example, if we use the example of a bank app.

How do you make sure that you don't withdraw more than the account balance ? If the client logs into the website on two different computer then withdraw a valid amount of money on both session.

There's a little chance that he can withdraw twice the money.

How that kind of business should be handled ?

1 Answers

If eventual consistency (i.e. the data will be consistent again at some point - eventually) is not an option and you really need consistency at all time for specific business entities then you need to make sure to initiate some transaction before you apply the business logic on your domain model.

That means reading the current state of the bank account balance would also happen during a transaction disallowing any updates of the bank account balance in the meantime.

These kinds of transactions could be technically applied within one service, for instance, via database transactions. But such business transactions should only involve one aggregate object at a time.

To get back to your question:

How do you make sure that you don't withdraw more than the account balance?

Taking the bank account as an example one could assume (depending on the business invariants of the bank) that an account balance must never go below zero or at least not below the aggreed overdraw limit. So reserving the amount to be withdrawn must happen within a transaction.

But transferring the reserved amount to another account only needs to be consistent eventually and can happen later within another transaction (which is then performed on the other aggregate account object) to make sure this also only happens once.

Note: Transactions can also be applied across several Microservices by applying patterns such as the Saga Pattern.

Related