Skip to content

Eventual Consistency with ARs

eswann edited this page Feb 23, 2012 · 3 revisions

Eventual Consistency within ARs

Sometimes it's wanted that there's a consistency boundary around a group of ARs (Aggregate Roots), such as "username unique".

Global Constraint on Username

In the above image we're creating a user 'Greg' which didn't exist at the point in time when the command was sent.

At the same time, another user can be reading from the eventually consistent read model which doesn't have the resulting events from the "concurrent 'UserRegistered "Greg"'" event.

The event handler for the UserRegistered event can have a table with a UNIQUE constraint on the username property - you would have to check for duplicate messages and de-duplicate them, and let the table with its constraint handle the duplicate command outcome (the two events with differently sourced ARs).

In this case it's important to recognize that while the Read Model is eventually consistent, it is not likely to be two users sending a 'RegisterUser "Greg"' within those e.g. 500ms which it takes for the events to propagate.

The above modelling can be done with Poission Distributions and Queues: http://www.mathpages.com/home/kmath026/kmath026.htm

The mean queueing time would be Tserver which is a mean latency time for applying a command and publishing the resulting events.

Workarounds to decrease the probability of a global constraint violation

  1. Let's say you are working on a single server - you could keep the last 30 seconds' worth of created users in memory and not only check the ThinReadLayer but also the memory of the server.
  2. Let the domain side ACIDly insert the username into a table/list of usernames with a UNIQUE constraint - this would create a single point of failure, but is a way of having an absolutely consistent model. You would put the logic for handling the global constraint in this table.