Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Committing multiple aggregates in a transaction #64

Merged
merged 3 commits into from
Feb 13, 2023

Conversation

theodorton
Copy link
Contributor

@theodorton theodorton commented Feb 10, 2023

Motivation

We would like to have consistency when aggregates with dependencies are saved to the database. In a case where two aggregates will be committed to in the same flow, it makes sense to be able to rollback both if one of them fails to commit due to a conflict.

New APIs

@ddes/core

  • added AggregateRoot.build, which accepts the same arguments as AggregateRoot.commit and returns an AggregateCommit

@ddes/postgres

  • added PostgresEventStore.commitInTransaction which will accept a list of AggregateCommits obtained through AggregateRoot.build

Example

const myStore = new PostgresEventStore({})

await retryOnVersionConflict(async () => {
  // Assume currentFooVersion and currentBarVersion is set

  const firstCommit = SomeAggregate.build('foo', currentFooVersion + 1, [{ type: 'SomeEvent' }])
  const secondCommit = OtherAggregate.build('bar', currentBarVersion + 1, [{ type: 'AnotherEvent' }])

  await myStore.commitInTransaction([
    firstCommit,
    secondCommit,
  ])
})

// vs the existing approach
await retryOnVersionConflict(async () => {
  // Assume currentFooVersion and currentBarVersion is set

  await SomeAggregate.commit('foo', currentFooVersion + 1, [{ type: 'SomeEvent' }])
  
  // If this next line fails, the commit above will not be rolled back in the database
  await OtherAggregate.commit('bar', currentBarVersion + 1, [{ type: 'AnotherEvent' }])
})

Copy link
Collaborator

@krijoh92 krijoh92 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM 👍

return commits
}

private async commitOne<TAggregateCommit extends AggregateCommit>(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpicky, but maybe call this insertCommit ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in d5ef9c4

@krijoh92 krijoh92 merged commit c0f0106 into Skalar:master Feb 13, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants