{"id":"6b093dc091bd8fbaf2a0c8c0","slug":"event-sourced-account","title":"Event-sourced bank account","summary":"An account aggregate whose state comes only from replaying events, an event store with optimistic concurrency and a repository that saves only new facts. Queries about past state come for free.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"architecture","status":"published","difficulty":"hard","topics":["event-sourcing","cqrs"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["event-sourcing","aggregate","event-store","optimistic-concurrency","ddd"],"languages":[{"lang":"typescript","runner":"browser","starter":"type AccountEvent =\n  | { type: 'AccountOpened'; accountId: string; owner: string }\n  | { type: 'MoneyDeposited'; amount: number }\n  | { type: 'MoneyWithdrawn'; amount: number }\n  | { type: 'AccountClosed' };\n\n/**\n * Event-sourced aggregate: its state exists only as the result of applying events.\n * Commands validate (errors in this order: 'Account is closed', 'Amount must be positive', 'Insufficient funds',\n * 'Balance must be zero to close'), then RECORD an event: apply it and keep it as uncommitted.\n * apply() never validates – it only changes state and increments `version`.\n */\nclass BankAccount {\n  id = '';\n  owner = '';\n  balance = 0;\n  closed = false;\n  /** Number of events applied so far (committed and uncommitted). */\n  version = 0;\n\n  static open(id: string, owner: string): BankAccount {\n    throw new Error('Not implemented');\n  }\n\n  /** Rebuilds the state by replaying events; the result has no uncommitted events. */\n  static fromHistory(events: AccountEvent[]): BankAccount {\n    throw new Error('Not implemented');\n  }\n\n  deposit(amount: number): void {\n    throw new Error('Not implemented');\n  }\n\n  withdraw(amount: number): void {\n    throw new Error('Not implemented');\n  }\n\n  close(): void {\n    throw new Error('Not implemented');\n  }\n\n  /** A copy of the events recorded since the last markCommitted(). */\n  uncommittedEvents(): AccountEvent[] {\n    throw new Error('Not implemented');\n  }\n\n  markCommitted(): void {\n    throw new Error('Not implemented');\n  }\n}\n\nclass ConcurrencyError extends Error {\n  constructor(message: string) {\n    super(message);\n    this.name = 'ConcurrencyError';\n  }\n}\n\n/** Append-only streams of events, one per account. */\nclass InMemoryEventStore {\n  /** Appends when the stream currently has exactly `expectedVersion` events, otherwise throws ConcurrencyError. */\n  append(streamId: string, events: AccountEvent[], expectedVersion: number): void {\n    throw new Error('Not implemented');\n  }\n\n  /** A copy of the stream ([] when it does not exist). */\n  load(streamId: string): AccountEvent[] {\n    throw new Error('Not implemented');\n  }\n}\n\nclass AccountRepository {\n  constructor(private readonly store: InMemoryEventStore) {}\n\n  /** Appends only the uncommitted events (expected version = version before them), then marks them committed. */\n  save(account: BankAccount): void {\n    throw new Error('Not implemented');\n  }\n\n  /** Replays the stream; an empty stream → Error('Account not found: <id>'). */\n  load(id: string): BankAccount {\n    throw new Error('Not implemented');\n  }\n}\n","testCount":9,"tests":"const opened = (id = 'ACC-1', owner = 'Ann') => ({ type: 'AccountOpened', accountId: id, owner });\nconst deposited = (amount) => ({ type: 'MoneyDeposited', amount });\nconst withdrawn = (amount) => ({ type: 'MoneyWithdrawn', amount });\n\ntest('opening and transactions are recorded as events', () => {\n  const account = BankAccount.open('ACC-1', 'Ann');\n  account.deposit(100);\n  account.withdraw(30);\n  expect(account.balance).toBe(70);\n  expect(account.version).toBe(3);\n  expect(account.uncommittedEvents()).toEqual([opened(), deposited(100), withdrawn(30)]);\n});\n\ntest('rules are checked before recording and a rejected command records nothing', () => {\n  const account = BankAccount.open('ACC-1', 'Ann');\n  account.deposit(50);\n  expect(() => account.withdraw(500)).toThrow('Insufficient funds');\n  expect(() => account.deposit(0)).toThrow('Amount must be positive');\n  expect(() => account.withdraw(-5)).toThrow('Amount must be positive');\n  expect(account.uncommittedEvents()).toHaveLength(2);\n  expect(account.balance).toBe(50);\n  expect(account.version).toBe(2);\n});\n\ntest('state is rebuilt by replaying the history', () => {\n  const account = BankAccount.fromHistory([opened('ACC-7', 'Bob'), deposited(200), withdrawn(50), deposited(25)]);\n  expect(account.id).toBe('ACC-7');\n  expect(account.owner).toBe('Bob');\n  expect(account.balance).toBe(175);\n  expect(account.version).toBe(4);\n  expect(account.uncommittedEvents()).toEqual([]);\n});\n\ntest('replaying does not re-validate past events', () => {\n  // An overdraft that the bank allowed in the past – today's rules would reject it, but it happened.\n  const account = BankAccount.fromHistory([opened(), deposited(50), withdrawn(80)]);\n  expect(account.balance).toBe(-30);\n});\n\ntest('a temporal query replays a prefix of the stream', () => {\n  const stream = [opened(), deposited(100), withdrawn(40), deposited(10)];\n  expect(BankAccount.fromHistory(stream.slice(0, 3)).balance).toBe(60);\n  expect(BankAccount.fromHistory(stream).balance).toBe(70);\n});\n\ntest('the event store appends with optimistic concurrency', () => {\n  const store = new InMemoryEventStore();\n  store.append('S', [opened()], 0);\n  store.append('S', [deposited(10), deposited(20)], 1);\n  expect(store.load('S')).toHaveLength(3);\n  expect(() => store.append('S', [deposited(5)], 1)).toThrow(ConcurrencyError);\n  const copy = store.load('S');\n  copy.push(deposited(999));\n  expect(store.load('S')).toHaveLength(3);\n  expect(store.load('missing')).toEqual([]);\n});\n\ntest('the repository saves only new events and loads the account back', () => {\n  const store = new InMemoryEventStore();\n  const repository = new AccountRepository(store);\n  const account = BankAccount.open('ACC-1', 'Ann');\n  account.deposit(100);\n  repository.save(account);\n  expect(store.load('ACC-1')).toHaveLength(2);\n  expect(account.uncommittedEvents()).toEqual([]);\n  const loaded = repository.load('ACC-1');\n  expect(loaded.balance).toBe(100);\n  loaded.withdraw(20);\n  repository.save(loaded);\n  expect(store.load('ACC-1')).toEqual([opened(), deposited(100), withdrawn(20)]);\n  expect(repository.load('ACC-1').version).toBe(3);\n});\n\ntest('concurrent changes to the same account are detected', () => {\n  const repository = new AccountRepository(new InMemoryEventStore());\n  const account = BankAccount.open('ACC-1', 'Ann');\n  account.deposit(100);\n  repository.save(account);\n  const a = repository.load('ACC-1');\n  const b = repository.load('ACC-1');\n  a.withdraw(70);\n  b.withdraw(50);\n  repository.save(a);\n  expect(() => repository.save(b)).toThrow(ConcurrencyError);\n  expect(repository.load('ACC-1').balance).toBe(30);\n});\n\ntest('a closed account rejects money and closing needs a zero balance', () => {\n  const repository = new AccountRepository(new InMemoryEventStore());\n  const account = BankAccount.open('ACC-1', 'Ann');\n  account.deposit(10);\n  expect(() => account.close()).toThrow('Balance must be zero to close');\n  account.withdraw(10);\n  account.close();\n  expect(account.closed).toBe(true);\n  expect(() => account.deposit(5)).toThrow('Account is closed');\n  repository.save(account);\n  expect(repository.load('ACC-1').closed).toBe(true);\n  expect(() => repository.load('missing')).toThrow('Account not found: missing');\n});\n"},{"lang":"javascript","runner":"browser","starter":"// Events: { type: 'AccountOpened', accountId, owner } | { type: 'MoneyDeposited', amount }\n//       | { type: 'MoneyWithdrawn', amount } | { type: 'AccountClosed' }\n\n/**\n * Event-sourced aggregate: its state exists only as the result of applying events.\n * Commands validate (errors in this order: 'Account is closed', 'Amount must be positive', 'Insufficient funds',\n * 'Balance must be zero to close'), then RECORD an event: apply it and keep it as uncommitted.\n * Applying an event never validates – it only changes state and increments `version`.\n */\nclass BankAccount {\n  id = '';\n  owner = '';\n  balance = 0;\n  closed = false;\n  /** Number of events applied so far (committed and uncommitted). */\n  version = 0;\n\n  static open(id, owner) {\n    throw new Error('Not implemented');\n  }\n\n  /** Rebuilds the state by replaying events; the result has no uncommitted events. */\n  static fromHistory(events) {\n    throw new Error('Not implemented');\n  }\n\n  deposit(amount) {\n    throw new Error('Not implemented');\n  }\n\n  withdraw(amount) {\n    throw new Error('Not implemented');\n  }\n\n  close() {\n    throw new Error('Not implemented');\n  }\n\n  /** A copy of the events recorded since the last markCommitted(). */\n  uncommittedEvents() {\n    throw new Error('Not implemented');\n  }\n\n  markCommitted() {\n    throw new Error('Not implemented');\n  }\n}\n\nclass ConcurrencyError extends Error {\n  constructor(message) {\n    super(message);\n    this.name = 'ConcurrencyError';\n  }\n}\n\n/** Append-only streams of events, one per account. */\nclass InMemoryEventStore {\n  /** Appends when the stream currently has exactly `expectedVersion` events, otherwise throws ConcurrencyError. */\n  append(streamId, events, expectedVersion) {\n    throw new Error('Not implemented');\n  }\n\n  /** A copy of the stream ([] when it does not exist). */\n  load(streamId) {\n    throw new Error('Not implemented');\n  }\n}\n\nclass AccountRepository {\n  constructor(store) {\n    this.store = store;\n  }\n\n  /** Appends only the uncommitted events (expected version = version before them), then marks them committed. */\n  save(account) {\n    throw new Error('Not implemented');\n  }\n\n  /** Replays the stream; an empty stream → Error('Account not found: <id>'). */\n  load(id) {\n    throw new Error('Not implemented');\n  }\n}\n","testCount":9,"tests":"const opened = (id = 'ACC-1', owner = 'Ann') => ({ type: 'AccountOpened', accountId: id, owner });\nconst deposited = (amount) => ({ type: 'MoneyDeposited', amount });\nconst withdrawn = (amount) => ({ type: 'MoneyWithdrawn', amount });\n\ntest('opening and transactions are recorded as events', () => {\n  const account = BankAccount.open('ACC-1', 'Ann');\n  account.deposit(100);\n  account.withdraw(30);\n  expect(account.balance).toBe(70);\n  expect(account.version).toBe(3);\n  expect(account.uncommittedEvents()).toEqual([opened(), deposited(100), withdrawn(30)]);\n});\n\ntest('rules are checked before recording and a rejected command records nothing', () => {\n  const account = BankAccount.open('ACC-1', 'Ann');\n  account.deposit(50);\n  expect(() => account.withdraw(500)).toThrow('Insufficient funds');\n  expect(() => account.deposit(0)).toThrow('Amount must be positive');\n  expect(() => account.withdraw(-5)).toThrow('Amount must be positive');\n  expect(account.uncommittedEvents()).toHaveLength(2);\n  expect(account.balance).toBe(50);\n  expect(account.version).toBe(2);\n});\n\ntest('state is rebuilt by replaying the history', () => {\n  const account = BankAccount.fromHistory([opened('ACC-7', 'Bob'), deposited(200), withdrawn(50), deposited(25)]);\n  expect(account.id).toBe('ACC-7');\n  expect(account.owner).toBe('Bob');\n  expect(account.balance).toBe(175);\n  expect(account.version).toBe(4);\n  expect(account.uncommittedEvents()).toEqual([]);\n});\n\ntest('replaying does not re-validate past events', () => {\n  // An overdraft that the bank allowed in the past – today's rules would reject it, but it happened.\n  const account = BankAccount.fromHistory([opened(), deposited(50), withdrawn(80)]);\n  expect(account.balance).toBe(-30);\n});\n\ntest('a temporal query replays a prefix of the stream', () => {\n  const stream = [opened(), deposited(100), withdrawn(40), deposited(10)];\n  expect(BankAccount.fromHistory(stream.slice(0, 3)).balance).toBe(60);\n  expect(BankAccount.fromHistory(stream).balance).toBe(70);\n});\n\ntest('the event store appends with optimistic concurrency', () => {\n  const store = new InMemoryEventStore();\n  store.append('S', [opened()], 0);\n  store.append('S', [deposited(10), deposited(20)], 1);\n  expect(store.load('S')).toHaveLength(3);\n  expect(() => store.append('S', [deposited(5)], 1)).toThrow(ConcurrencyError);\n  const copy = store.load('S');\n  copy.push(deposited(999));\n  expect(store.load('S')).toHaveLength(3);\n  expect(store.load('missing')).toEqual([]);\n});\n\ntest('the repository saves only new events and loads the account back', () => {\n  const store = new InMemoryEventStore();\n  const repository = new AccountRepository(store);\n  const account = BankAccount.open('ACC-1', 'Ann');\n  account.deposit(100);\n  repository.save(account);\n  expect(store.load('ACC-1')).toHaveLength(2);\n  expect(account.uncommittedEvents()).toEqual([]);\n  const loaded = repository.load('ACC-1');\n  expect(loaded.balance).toBe(100);\n  loaded.withdraw(20);\n  repository.save(loaded);\n  expect(store.load('ACC-1')).toEqual([opened(), deposited(100), withdrawn(20)]);\n  expect(repository.load('ACC-1').version).toBe(3);\n});\n\ntest('concurrent changes to the same account are detected', () => {\n  const repository = new AccountRepository(new InMemoryEventStore());\n  const account = BankAccount.open('ACC-1', 'Ann');\n  account.deposit(100);\n  repository.save(account);\n  const a = repository.load('ACC-1');\n  const b = repository.load('ACC-1');\n  a.withdraw(70);\n  b.withdraw(50);\n  repository.save(a);\n  expect(() => repository.save(b)).toThrow(ConcurrencyError);\n  expect(repository.load('ACC-1').balance).toBe(30);\n});\n\ntest('a closed account rejects money and closing needs a zero balance', () => {\n  const repository = new AccountRepository(new InMemoryEventStore());\n  const account = BankAccount.open('ACC-1', 'Ann');\n  account.deposit(10);\n  expect(() => account.close()).toThrow('Balance must be zero to close');\n  account.withdraw(10);\n  account.close();\n  expect(account.closed).toBe(true);\n  expect(() => account.deposit(5)).toThrow('Account is closed');\n  repository.save(account);\n  expect(repository.load('ACC-1').closed).toBe(true);\n  expect(() => repository.load('missing')).toThrow('Account not found: missing');\n});\n"},{"lang":"python","runner":"browser","starter":"from dataclasses import dataclass\n\n\n@dataclass(frozen=True)\nclass AccountOpened:\n    account_id: str\n    owner: str\n\n\n@dataclass(frozen=True)\nclass MoneyDeposited:\n    amount: int\n\n\n@dataclass(frozen=True)\nclass MoneyWithdrawn:\n    amount: int\n\n\n@dataclass(frozen=True)\nclass AccountClosed:\n    pass\n\n\nclass ConcurrencyError(Exception):\n    pass\n\n\nclass BankAccount:\n    \"\"\"Event-sourced aggregate: its state exists only as the result of applying events.\n    Commands validate (ValueError, in this order: 'Account is closed', 'Amount must be positive',\n    'Insufficient funds', 'Balance must be zero to close'), then RECORD an event: apply it and keep it\n    as uncommitted. Applying an event never validates – it only changes state and increments `version`.\"\"\"\n\n    def __init__(self):\n        self.id = \"\"\n        self.owner = \"\"\n        self.balance = 0\n        self.closed = False\n        self.version = 0  # number of events applied so far (committed and uncommitted)\n\n    @classmethod\n    def open(cls, account_id: str, owner: str) -> \"BankAccount\":\n        raise NotImplementedError\n\n    @classmethod\n    def from_history(cls, events) -> \"BankAccount\":\n        \"\"\"Rebuilds the state by replaying events; the result has no uncommitted events.\"\"\"\n        raise NotImplementedError\n\n    def deposit(self, amount: int) -> None:\n        raise NotImplementedError\n\n    def withdraw(self, amount: int) -> None:\n        raise NotImplementedError\n\n    def close(self) -> None:\n        raise NotImplementedError\n\n    def uncommitted_events(self) -> list:\n        \"\"\"A copy of the events recorded since the last mark_committed().\"\"\"\n        raise NotImplementedError\n\n    def mark_committed(self) -> None:\n        raise NotImplementedError\n\n\nclass InMemoryEventStore:\n    \"\"\"Append-only streams of events, one per account.\"\"\"\n\n    def append(self, stream_id: str, events: list, expected_version: int) -> None:\n        \"\"\"Appends when the stream has exactly expected_version events, otherwise raises ConcurrencyError.\"\"\"\n        raise NotImplementedError\n\n    def load(self, stream_id: str) -> list:\n        \"\"\"A copy of the stream ([] when it does not exist).\"\"\"\n        raise NotImplementedError\n\n\nclass AccountRepository:\n    def __init__(self, store: InMemoryEventStore):\n        self.store = store\n\n    def save(self, account: BankAccount) -> None:\n        \"\"\"Appends only the uncommitted events (expected version = version before them), then marks them committed.\"\"\"\n        raise NotImplementedError\n\n    def load(self, account_id: str) -> BankAccount:\n        \"\"\"Replays the stream; an empty stream → LookupError('Account not found: <id>').\"\"\"\n        raise NotImplementedError\n","testCount":9,"tests":"def test_opening_and_transactions_are_recorded_as_events():\n    account = BankAccount.open(\"ACC-1\", \"Ann\")\n    account.deposit(100)\n    account.withdraw(30)\n    assert account.balance == 70, f\"got {account.balance}\"\n    assert account.version == 3, f\"got version {account.version}\"\n    got = account.uncommitted_events()\n    assert got == [AccountOpened(\"ACC-1\", \"Ann\"), MoneyDeposited(100), MoneyWithdrawn(30)], f\"got {got}\"\n\n\ndef test_rules_are_checked_before_recording_and_a_rejected_command_records_nothing():\n    account = BankAccount.open(\"ACC-1\", \"Ann\")\n    account.deposit(50)\n    with raises(ValueError, match=\"Insufficient funds\"):\n        account.withdraw(500)\n    with raises(ValueError, match=\"Amount must be positive\"):\n        account.deposit(0)\n    with raises(ValueError, match=\"Amount must be positive\"):\n        account.withdraw(-5)\n    assert len(account.uncommitted_events()) == 2\n    assert account.balance == 50 and account.version == 2\n\n\ndef test_state_is_rebuilt_by_replaying_the_history():\n    account = BankAccount.from_history([AccountOpened(\"ACC-7\", \"Bob\"), MoneyDeposited(200), MoneyWithdrawn(50), MoneyDeposited(25)])\n    assert (account.id, account.owner, account.balance, account.version) == (\"ACC-7\", \"Bob\", 175, 4)\n    assert account.uncommitted_events() == []\n\n\ndef test_replaying_does_not_revalidate_past_events():\n    # An overdraft that the bank allowed in the past – today's rules would reject it, but it happened.\n    account = BankAccount.from_history([AccountOpened(\"ACC-1\", \"Ann\"), MoneyDeposited(50), MoneyWithdrawn(80)])\n    assert account.balance == -30, f\"got {account.balance}\"\n\n\ndef test_a_temporal_query_replays_a_prefix_of_the_stream():\n    stream = [AccountOpened(\"ACC-1\", \"Ann\"), MoneyDeposited(100), MoneyWithdrawn(40), MoneyDeposited(10)]\n    assert BankAccount.from_history(stream[:3]).balance == 60\n    assert BankAccount.from_history(stream).balance == 70\n\n\ndef test_the_event_store_appends_with_optimistic_concurrency():\n    store = InMemoryEventStore()\n    store.append(\"S\", [AccountOpened(\"S\", \"Ann\")], 0)\n    store.append(\"S\", [MoneyDeposited(10), MoneyDeposited(20)], 1)\n    assert len(store.load(\"S\")) == 3\n    with raises(ConcurrencyError):\n        store.append(\"S\", [MoneyDeposited(5)], 1)\n    copy = store.load(\"S\")\n    copy.append(MoneyDeposited(999))\n    assert len(store.load(\"S\")) == 3, \"load() must return a copy\"\n    assert store.load(\"missing\") == []\n\n\ndef test_the_repository_saves_only_new_events_and_loads_the_account_back():\n    store = InMemoryEventStore()\n    repository = AccountRepository(store)\n    account = BankAccount.open(\"ACC-1\", \"Ann\")\n    account.deposit(100)\n    repository.save(account)\n    assert len(store.load(\"ACC-1\")) == 2\n    assert account.uncommitted_events() == []\n    loaded = repository.load(\"ACC-1\")\n    assert loaded.balance == 100\n    loaded.withdraw(20)\n    repository.save(loaded)\n    got = store.load(\"ACC-1\")\n    assert got == [AccountOpened(\"ACC-1\", \"Ann\"), MoneyDeposited(100), MoneyWithdrawn(20)], f\"got {got}\"\n    assert repository.load(\"ACC-1\").version == 3\n\n\ndef test_concurrent_changes_to_the_same_account_are_detected():\n    repository = AccountRepository(InMemoryEventStore())\n    account = BankAccount.open(\"ACC-1\", \"Ann\")\n    account.deposit(100)\n    repository.save(account)\n    a, b = repository.load(\"ACC-1\"), repository.load(\"ACC-1\")\n    a.withdraw(70)\n    b.withdraw(50)\n    repository.save(a)\n    with raises(ConcurrencyError):\n        repository.save(b)\n    assert repository.load(\"ACC-1\").balance == 30\n\n\ndef test_a_closed_account_rejects_money_and_closing_needs_a_zero_balance():\n    repository = AccountRepository(InMemoryEventStore())\n    account = BankAccount.open(\"ACC-1\", \"Ann\")\n    account.deposit(10)\n    with raises(ValueError, match=\"Balance must be zero to close\"):\n        account.close()\n    account.withdraw(10)\n    account.close()\n    assert account.closed is True\n    with raises(ValueError, match=\"Account is closed\"):\n        account.deposit(5)\n    repository.save(account)\n    assert repository.load(\"ACC-1\").closed is True\n    with raises(LookupError, match=\"Account not found: missing\"):\n        repository.load(\"missing\")\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic abstract class AccountEvent { }\n\npublic sealed class AccountOpened : AccountEvent\n{\n    public AccountOpened(string accountId, string owner) { AccountId = accountId; Owner = owner; }\n    public string AccountId { get; }\n    public string Owner { get; }\n}\n\npublic sealed class MoneyDeposited : AccountEvent\n{\n    public MoneyDeposited(decimal amount) { Amount = amount; }\n    public decimal Amount { get; }\n}\n\npublic sealed class MoneyWithdrawn : AccountEvent\n{\n    public MoneyWithdrawn(decimal amount) { Amount = amount; }\n    public decimal Amount { get; }\n}\n\npublic sealed class AccountClosed : AccountEvent { }\n\npublic class ConcurrencyException : Exception\n{\n    public ConcurrencyException(string message) : base(message) { }\n}\n\n/// <summary>\n/// Event-sourced aggregate: its state exists only as the result of applying events.\n/// Commands validate (InvalidOperationException, in this order: \"Account is closed\", \"Amount must be positive\",\n/// \"Insufficient funds\", \"Balance must be zero to close\"), then RECORD an event: apply it and keep it as uncommitted.\n/// Applying an event never validates – it only changes state and increments Version.\n/// </summary>\npublic class BankAccount\n{\n    public string Id { get; private set; }\n    public string Owner { get; private set; }\n    public decimal Balance { get; private set; }\n    public bool IsClosed { get; private set; }\n\n    /// <summary>Number of events applied so far (committed and uncommitted).</summary>\n    public int Version { get; private set; }\n\n    public static BankAccount Open(string id, string owner) { throw new NotImplementedException(); }\n\n    /// <summary>Rebuilds the state by replaying events; the result has no uncommitted events.</summary>\n    public static BankAccount FromHistory(IEnumerable<AccountEvent> events) { throw new NotImplementedException(); }\n\n    public void Deposit(decimal amount) { throw new NotImplementedException(); }\n    public void Withdraw(decimal amount) { throw new NotImplementedException(); }\n    public void Close() { throw new NotImplementedException(); }\n\n    /// <summary>A copy of the events recorded since the last MarkCommitted().</summary>\n    public IReadOnlyList<AccountEvent> GetUncommittedEvents() { throw new NotImplementedException(); }\n\n    public void MarkCommitted() { throw new NotImplementedException(); }\n}\n\n/// <summary>Append-only streams of events, one per account.</summary>\npublic class InMemoryEventStore\n{\n    /// <summary>Appends when the stream has exactly expectedVersion events, otherwise throws ConcurrencyException.</summary>\n    public void Append(string streamId, IEnumerable<AccountEvent> events, int expectedVersion) { throw new NotImplementedException(); }\n\n    /// <summary>A copy of the stream (empty when it does not exist).</summary>\n    public IReadOnlyList<AccountEvent> Load(string streamId) { throw new NotImplementedException(); }\n}\n\npublic class AccountRepository\n{\n    private readonly InMemoryEventStore store;\n\n    public AccountRepository(InMemoryEventStore store) { this.store = store; }\n\n    /// <summary>Appends only the uncommitted events (expected version = version before them), then marks them committed.</summary>\n    public void Save(BankAccount account) { throw new NotImplementedException(); }\n\n    /// <summary>Replays the stream; an empty stream → KeyNotFoundException(\"Account not found: id\").</summary>\n    public BankAccount Load(string id) { throw new NotImplementedException(); }\n}\n","testCount":9},{"lang":"java","runner":"judge0","starter":"import java.util.ArrayList;\nimport java.util.List;\n\nabstract class AccountEvent { }\n\nfinal class AccountOpened extends AccountEvent {\n    final String accountId;\n    final String owner;\n    AccountOpened(String accountId, String owner) { this.accountId = accountId; this.owner = owner; }\n}\n\nfinal class MoneyDeposited extends AccountEvent {\n    final long amount;\n    MoneyDeposited(long amount) { this.amount = amount; }\n}\n\nfinal class MoneyWithdrawn extends AccountEvent {\n    final long amount;\n    MoneyWithdrawn(long amount) { this.amount = amount; }\n}\n\nfinal class AccountClosed extends AccountEvent { }\n\nclass ConcurrencyException extends RuntimeException {\n    ConcurrencyException(String message) { super(message); }\n}\n\n/**\n * Event-sourced aggregate: its state exists only as the result of applying events.\n * Commands validate (in this order: \"Account is closed\" – IllegalStateException, \"Amount must be positive\" –\n * IllegalArgumentException, \"Insufficient funds\", \"Balance must be zero to close\" – IllegalStateException),\n * then RECORD an event: apply it and keep it as uncommitted.\n * Applying an event never validates – it only changes state and increments the version.\n */\nclass BankAccount {\n    private String id;\n    private String owner;\n    private long balance;\n    private boolean closed;\n    private int version; // number of events applied so far (committed and uncommitted)\n\n    String id() { return id; }\n    String owner() { return owner; }\n    long balance() { return balance; }\n    boolean isClosed() { return closed; }\n    int version() { return version; }\n\n    static BankAccount open(String id, String owner) { throw new UnsupportedOperationException(\"Not implemented\"); }\n\n    /** Rebuilds the state by replaying events; the result has no uncommitted events. */\n    static BankAccount fromHistory(List<AccountEvent> events) { throw new UnsupportedOperationException(\"Not implemented\"); }\n\n    void deposit(long amount) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    void withdraw(long amount) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    void close() { throw new UnsupportedOperationException(\"Not implemented\"); }\n\n    /** A copy of the events recorded since the last markCommitted(). */\n    List<AccountEvent> uncommittedEvents() { throw new UnsupportedOperationException(\"Not implemented\"); }\n\n    void markCommitted() { throw new UnsupportedOperationException(\"Not implemented\"); }\n}\n\n/** Append-only streams of events, one per account. */\nclass InMemoryEventStore {\n    /** Appends when the stream has exactly expectedVersion events, otherwise throws ConcurrencyException. */\n    void append(String streamId, List<AccountEvent> events, int expectedVersion) { throw new UnsupportedOperationException(\"Not implemented\"); }\n\n    /** A copy of the stream (empty when it does not exist). */\n    List<AccountEvent> load(String streamId) { throw new UnsupportedOperationException(\"Not implemented\"); }\n}\n\nclass AccountRepository {\n    private final InMemoryEventStore store;\n\n    AccountRepository(InMemoryEventStore store) { this.store = store; }\n\n    /** Appends only the uncommitted events (expected version = version before them), then marks them committed. */\n    void save(BankAccount account) { throw new UnsupportedOperationException(\"Not implemented\"); }\n\n    /** Replays the stream; an empty stream → NoSuchElementException(\"Account not found: id\"). */\n    BankAccount load(String id) { throw new UnsupportedOperationException(\"Not implemented\"); }\n}\n","testCount":9},{"lang":"go","runner":"judge0","starter":"package main\n\nimport \"errors\"\n\n// Event is a fact that happened to an account.\ntype Event interface{ isAccountEvent() }\n\n// The events of an account.\ntype AccountOpened struct{ AccountID, Owner string }\ntype MoneyDeposited struct{ Amount int }\ntype MoneyWithdrawn struct{ Amount int }\ntype AccountClosed struct{}\n\nfunc (AccountOpened) isAccountEvent()  {}\nfunc (MoneyDeposited) isAccountEvent() {}\nfunc (MoneyWithdrawn) isAccountEvent() {}\nfunc (AccountClosed) isAccountEvent()  {}\n\n// ErrConcurrency is returned by Append when the stream is not at the expected version.\nvar ErrConcurrency = errors.New(\"concurrency conflict\")\n\n// BankAccount is an event-sourced aggregate: its state exists only as the result of applying events.\n// Commands validate (errors in this order: \"account is closed\", \"amount must be positive\", \"insufficient funds\",\n// \"balance must be zero to close\"), then RECORD an event: apply it and keep it as uncommitted.\n// Applying an event never validates – it only changes state and increments the version.\ntype BankAccount struct {\n\tid, owner string\n\tbalance   int\n\tclosed    bool\n\tversion   int // number of events applied so far (committed and uncommitted)\n}\n\nfunc (a *BankAccount) ID() string    { return a.id }\nfunc (a *BankAccount) Owner() string { return a.owner }\nfunc (a *BankAccount) Balance() int  { return a.balance }\nfunc (a *BankAccount) Closed() bool  { return a.closed }\nfunc (a *BankAccount) Version() int  { return a.version }\n\n// Open records AccountOpened.\nfunc Open(id, owner string) *BankAccount { return &BankAccount{} } // TODO\n\n// FromHistory rebuilds the state by replaying events; the result has no uncommitted events.\nfunc FromHistory(events []Event) *BankAccount { return &BankAccount{} } // TODO\n\nfunc (a *BankAccount) Deposit(amount int) error  { return nil } // TODO\nfunc (a *BankAccount) Withdraw(amount int) error { return nil } // TODO\nfunc (a *BankAccount) Close() error              { return nil } // TODO\n\n// UncommittedEvents returns a copy of the events recorded since the last MarkCommitted.\nfunc (a *BankAccount) UncommittedEvents() []Event { return nil } // TODO\n\n// MarkCommitted forgets the uncommitted events.\nfunc (a *BankAccount) MarkCommitted() {} // TODO\n\n// EventStore keeps append-only streams of events, one per account.\ntype EventStore struct {\n\t// TODO\n}\n\n// NewEventStore creates an empty store.\nfunc NewEventStore() *EventStore { return &EventStore{} }\n\n// Append adds events when the stream has exactly expectedVersion events, otherwise returns ErrConcurrency.\nfunc (s *EventStore) Append(streamID string, events []Event, expectedVersion int) error { return nil } // TODO\n\n// Load returns a copy of the stream (empty when it does not exist).\nfunc (s *EventStore) Load(streamID string) []Event { return nil } // TODO\n\n// AccountRepository saves and loads accounts through the event store.\ntype AccountRepository struct{ store *EventStore }\n\n// NewAccountRepository creates a repository.\nfunc NewAccountRepository(store *EventStore) *AccountRepository { return &AccountRepository{store: store} }\n\n// Save appends only the uncommitted events (expected version = version before them), then marks them committed.\nfunc (r *AccountRepository) Save(a *BankAccount) error { return nil } // TODO\n\n// Load replays the stream; an empty stream → error \"account not found: <id>\".\nfunc (r *AccountRepository) Load(id string) (*BankAccount, error) { return nil, nil } // TODO\n","testCount":9}],"questionCount":null,"xp":40,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:24.935Z","requestedLang":"en","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"A cooperative bank must answer not only \"how much is in the account\" but also \"how much was there on 3 March at 2 p.m.\" and \"who changed it and when\". A table with a "},{"type":"text","text":"balance","marks":[{"type":"code"}]},{"type":"text","text":" column cannot tell – every update overwrites the past. With "},{"type":"text","text":"event sourcing","marks":[{"type":"bold"}]},{"type":"text","text":" the source of truth is a sequence of events ("},{"type":"text","text":"AccountOpened","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"MoneyDeposited","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"MoneyWithdrawn","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"AccountClosed","marks":[{"type":"code"}]},{"type":"text","text":"), and the current state is the result of replaying them."}]},{"type":"heading","attrs":{"level":2,"id":"task"},"content":[{"type":"text","text":"Task"}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The ","marks":[{"type":"bold"}]},{"type":"text","text":"BankAccount","marks":[{"type":"code"}]},{"type":"text","text":" aggregate","marks":[{"type":"bold"}]},{"type":"text","text":":"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"open(id, owner)","marks":[{"type":"code"}]},{"type":"text","text":" creates the account by recording "},{"type":"text","text":"AccountOpened","marks":[{"type":"code"}]},{"type":"text","text":";"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"the commands "},{"type":"text","text":"deposit(amount)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"withdraw(amount)","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"close()","marks":[{"type":"code"}]},{"type":"text","text":" first check the rules and then "},{"type":"text","text":"record","marks":[{"type":"bold"}]},{"type":"text","text":" an event: apply it to the state and add it to the uncommitted list;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"errors in this order: "},{"type":"text","text":"Account is closed","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Amount must be positive","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Insufficient funds","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Balance must be zero to close","marks":[{"type":"code"}]},{"type":"text","text":"; a rejected command records nothing;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"applying an event ("},{"type":"text","text":"apply","marks":[{"type":"code"}]},{"type":"text","text":") "},{"type":"text","text":"validates nothing","marks":[{"type":"bold"}]},{"type":"text","text":" – it only changes state and increments "},{"type":"text","text":"version","marks":[{"type":"code"}]},{"type":"text","text":" (the number of applied events);"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"fromHistory(events)","marks":[{"type":"code"}]},{"type":"text","text":" rebuilds the state from history – with no uncommitted events;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"uncommittedEvents()","marks":[{"type":"code"}]},{"type":"text","text":" returns a copy, "},{"type":"text","text":"markCommitted()","marks":[{"type":"code"}]},{"type":"text","text":" clears it."}]}]}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"InMemoryEventStore","marks":[{"type":"code"}]},{"type":"text","text":" – one append-only stream of events per account:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"append(streamId, events, expectedVersion)","marks":[{"type":"code"}]},{"type":"text","text":" appends only when the stream has exactly "},{"type":"text","text":"expectedVersion","marks":[{"type":"code"}]},{"type":"text","text":" events, otherwise it raises a concurrency error ("},{"type":"text","text":"ConcurrencyError","marks":[{"type":"code"}]},{"type":"text","text":"/"},{"type":"text","text":"ConcurrencyException","marks":[{"type":"code"}]},{"type":"text","text":", in Go "},{"type":"text","text":"ErrConcurrency","marks":[{"type":"code"}]},{"type":"text","text":");"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"load(streamId)","marks":[{"type":"code"}]},{"type":"text","text":" returns a copy of the stream (empty when it does not exist)."}]}]}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"AccountRepository(store)","marks":[{"type":"code"}]},{"type":"text","text":":"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"save(account)","marks":[{"type":"code"}]},{"type":"text","text":" appends only the uncommitted events with the expected version = the account's version minus the number of new events, then marks them committed;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"load(id)","marks":[{"type":"code"}]},{"type":"text","text":" rebuilds the account; an empty stream is the error "},{"type":"text","text":"Account not found: <id>","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Among other things the tests check that a history with an old overdraft (a withdrawal bigger than the balance, allowed before the rules changed) replays without errors, that past state comes from replaying a prefix of the stream, and that two parallel saves of the same account end with a conflict. Names per language: "},{"type":"text","text":"from_history","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"uncommitted_events","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"ValueError","marks":[{"type":"code"}]},{"type":"text","text":"/"},{"type":"text","text":"LookupError","marks":[{"type":"code"}]},{"type":"text","text":" (Python); "},{"type":"text","text":"GetUncommittedEvents","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"IsClosed","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"KeyNotFoundException","marks":[{"type":"code"}]},{"type":"text","text":" (C#); "},{"type":"text","text":"NoSuchElementException","marks":[{"type":"code"}]},{"type":"text","text":" (Java); in Go the functions "},{"type":"text","text":"Open","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"FromHistory","marks":[{"type":"code"}]},{"type":"text","text":", methods returning "},{"type":"text","text":"error","marks":[{"type":"code"}]},{"type":"text","text":" and lower-case messages."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[],"articles":[{"id":"6b08bd3380884893657cc94c","slug":"event-sourcing","title":"Event sourcing: store the facts, not just the latest state"},{"id":"6b08bd3e80884893657cca2e","slug":"vertical-slice-architecture","title":"Vertical slice architecture: code by feature, not by layer"},{"id":"6b08bd3a80884893657cc9aa","slug":"mediator","title":"Mediator: components talk through a coordinator"},{"id":"6b08bd3280884893657cc942","slug":"event-driven-architecture","title":"Event-driven architecture: who publishes, who listens and what can go wrong"},{"id":"6b08bd3180884893657cc924","slug":"cqrs","title":"CQRS: one model for changing, another for reading"},{"id":"6b08bd3080884893657cc910","slug":"command","title":"Command: a request wrapped in an object"}],"topicsInfo":[{"slug":"event-sourcing","title":"Event Sourcing","group":"architecture","icon":"scroll-text"},{"slug":"cqrs","title":"CQRS","group":"architecture","icon":"split"}],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:24.937Z","updatedAt":"2026-11-27T08:22:24.937Z"}