title: Stream Version in Event Sourcing
body: <p>In <em>Event Sourcing</em>, you store all individual <em>Domain Events</em> that have happened for one <em>Aggregate</em> instance, known as <em>Event Stream</em>. Along with <em>Event Stream</em> you also store a <em>Stream Version</em>.</p>
  
  <p>Should the <em>version</em> be related with each <em>Domain Event</em>, or it should be related with transactional changes (aka commands)?</p>
  
  <hr>
  
  <p>Example:</p>
  
  <p>Our current state of Event Store is: </p>
  
  <pre><code>aggregate_id | version | event
  -------------|---------|------
  1            | 1       | E1
  1            | 2       | E2
  </code></pre>
  
  <p>A new command is executed in aggregate 1. This command produces two new events E3 and E4.</p>
  
  <p><strong>Approach 1:</strong></p>
  
  <pre><code>aggregate_id | version | event
  -------------|---------|------
  1            | 1       | E1
  1            | 2       | E2
  1            | 3       | E3
  1            | 4       | E4
  </code></pre>
  
  <p>With this approach optimistic concurrency can be done by storage mechanism using unique index but replaying the events until version 3 could leave the aggregate/system in a inconsistent state.</p>
  
  <p><strong>Approach 2:</strong></p>
  
  <pre><code>aggregate_id | version | event
  -------------|---------|-----
  1            | 1       | E1
  1            | 2       | E2
  1            | 3       | E3
  1            | 3       | E4
  </code></pre>
  
  <p>Replaying the events until version 3 leave the aggregate/system in a consistent state.</p>
  
  <p>Thanks!</p>