ExpectedVersion use case?

What is the expected use of optimistic concurrency in writing to the event stream? I may be thinking to trivially, but I’d like to understand what situations would require clients to write their events in a specific sequence. How would race conditions or multiple writing clients cause a problem?



(WithdrawMoney $50000)
(DepositMoney $50000)

order may matter in some cases.

You can only deactivate an inventory item whos name starts with the letter p


InventoryItemCreated name=popeye pants


Server 1 tries to do

ChangeInventoryName name=olive oil spandex shorts

Tries to write

NameChanged name=olive oil spandex shorts

Server 2 tries to do


tries to write


It makes a big difference which happens first here (otherwise a business rule get broken).

For some systems (downstream event processors as an example). You don’t care and just collect the events. If you are processing commands for say a line of business system then you may really want to have concurrency control.



In such a case, would you not have an aggregate of, say, Bank Ledger, which subscribes to that stream.

Command: Withdraw Money $50k would fail, due to an inadequate balance.

Command: Deposit Money $50k would succeed, write to the stream, the aggregate subscription would then update it’s projection.

Command: Withdraw Money $50k would then succeed.

Ordering within a transaction from a single client makes sense, but between threads it would just need a retry?


“Ordering within a transaction from a single client makes sense, but between threads it would just need a retry?”

Depends on the use case. Very often in line of business systems I cannot make my change as a user unless I have seen your change.

Ok. So if server 1 succeeds first, the name is changed. Then server 2 records the de-activation. So we have a deactivated item starting with ‘O’.
If server 2 succeeds first the item is de-activated. Then server 1 records the name change. So we have a deactivated item starting with ‘O’.

So the concurrency protection indicates that you need to re-consume your subscription before performing your operation in order to enforce your business rule.

Which rule succeeds isn’t very deterministic, though. Hmmm. Worth pondering.

It is deterministic. Whichever one happens first eg wins the race to be written first.

Yes. You are correct. I had meant predictable, and was imprecise with my language.

Same as with say SQL. When you have two threads so closely timed at some point you will hit a lock.

And what your code is doing with epected version is “if any change happened before my write gets there, fail”.

That gives you the hook to retry automatically or let the user decide in the ui or whatever the situation dictates. It doesn’t actually matter which event actually got written.