Search code examples
atomicconsistencynosql

Atomic consistency


My lecturer in the database course I'm taking said an advantage of NoSQL databases is that they "support atomic consistency of a single aggregate". I have no idea what this means, can someone please explain it to me?


Solution

  • It means that by using aggregates you are able to avoid that your database save inconsistence data by an error of transaction.

    In Domain Driven Design, an aggregate is a collection of related objects that are treated as an unit.

    For example, lets say you have a restaurant and you want to save the orders of each customer.

    You could save your data with two aggregates like below:

     var customerIdGenerated = newGuid();
     var customer = { id: customerIdGenerated , name: 'Mateus Forgiarini'};
    
     var orders = {
         id: 1,
         customerId: customerIdGenerated ,
         orderedFoods: [{
            name: 'Sushi',
            price: 50
         },
         {
            name: 'Tacos',
            price: 12
       }]
       };
    

    Or you could threat orders and customers as a single aggregate:

    var customerIdGenerated = newGuid();
    var customerAndOrders = { 
         customerId: customerIdGenerated ,
         name: 'Mateus Forgiarini',
         orderId: 1,
         orderedFoods: [{
            name: 'Sushi',
            price: 50
         },
         {
            name: 'Tacos',
            price: 12
       }]
       };
    

    By setting your orders and customer as a single aggregate you avoid an error of transaction. In the NoSQL world an error of transaction can occur when you have to write a related data in many nodes (a node is where you store your data, NoSQL databases that run on clusters can have many nodes).
    So if you are treating orders and customers as two aggregates, an error can occur while you are saving the customer but your orders can still be saved, so you would have an inconsistency data because you would have orders with no customer.

    However by making use of a single aggregate, you can avoid that, because if an error occur, you won't have an inconsistency data, since you are saving your related data together.