Coupling
Consistency
Cohesion
but we have to be mindful of coupling
Requests through a system should see a coherent state
All requests see all updates in the same order
States converge to a single view over time
function addItemToCart(cartId, sku, qty) {
// fetch the whole cart
const cart = Carts.get(cartId)
// make a change
cart.addItem(sku, qty)
// persist the whole object
Carts.put(cart)
}
class Book {
checkOut (userId) {
this.checkOutBy = userId;
this.version ++;
}
updateTitle (newTitle) {
this.title = newTitle;
this.version ++;
}
}
function checkOutBook (bookId, userId) {
const book = BookRepository.get(bookId);
book.checkOut(userId);
// this throws a ConcurrencyError
BookRepository.save(book);
}
Dynamo DB has in-built support for optimistic concurrency control
{
Item: {
pk: cart-123,
sk: __cart,
version: 0,
},
ConditionExpression: "attribute_not_exists(pk)",
}
Update: {
Key: {
pk: cart-123,
sk: __cart,
},
UpdateExpression: "ADD version :inc",
ConditionExpression: "version = :prev",
ExpressionAttributeValues: {
":inc": 1,
":prev": 0,
},
}