Skip to content

Make InMemory event store thread-safe#279

Open
artnim wants to merge 2 commits into
PapstIO:mainfrom
artnim:fix-inmemory-thread-safety
Open

Make InMemory event store thread-safe#279
artnim wants to merge 2 commits into
PapstIO:mainfrom
artnim:fix-inmemory-thread-safety

Conversation

@artnim

@artnim artnim commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

Problem

InMemoryEventStore and InMemoryEventStream are not safe for concurrent use:

  • InMemoryEventStore.CreateAsync does a check-then-add (ContainsKey + Add) on a plain Dictionary — concurrent creates corrupt the dictionary (InvalidOperationException: Operations that change non-concurrent collections must have exclusive access…), and once corrupted every subsequent store call fails. Two racing creates for the same id can also both succeed.
  • InMemoryEventStream.AppendAsync computes Version + 1 by enumerating the live List and then Adds to it — concurrent appends lose events, assign duplicate versions, or corrupt the list.
  • InMemoryTransactionalBatch.CommitAsync appends to the same raw list unguarded.

This bites in practice when the store backs an ASP.NET Core test host (WebApplicationFactory): background services or notification handlers append events on thread-pool threads while the test thread seeds streams. We hit it as a flaky CI failure in a downstream project — one corruption cascaded into three failing tests.

Fix

  • InMemoryEventStore: ConcurrentDictionary + TryAdd, making creation atomic (exactly one winner, the rest get EventStreamAlreadyExistsException).
  • InMemoryEventStream: a Lock guards all reads and writes of the event list; appends compute the version inside the lock, and the List* methods materialize a snapshot under the lock so enumeration never observes a mutating list.
  • InMemoryTransactionalBatch: commits under the owning stream's lock, so batched version computation stays consistent with concurrent direct appends.

No public API changes; Lock is fine since the package targets net10.0.

Tests

First commit adds the failing tests (concurrent creates corrupt the store; concurrent appends lose events/duplicate versions — reproduced 3/3 runs before the fix), second commit makes them pass. A third test pins the exactly-one-winner contract for same-id concurrent creates. Full solution builds; Papst.EventStore.Tests, CodeGeneration.Tests, and the InMemory tests all pass (the Cosmos/MongoDB integration suites need their emulators and were not run locally).

artnim added 2 commits July 14, 2026 15:51
InMemoryEventStore uses a plain Dictionary with a check-then-add in
CreateAsync, and InMemoryEventStream computes Version + 1 by enumerating
its live List on append. Under concurrent use (e.g. an application host
appending events on background threads while a test seeds streams) the
collections corrupt, events get lost, or versions duplicate.

Claude-Session: https://claude.ai/code/session_01J2j9sfE7zpM2mJq4dsz6m4
- InMemoryEventStore: replace the plain Dictionary and its check-then-add
  with a ConcurrentDictionary.TryAdd, making concurrent CreateAsync calls
  safe and stream creation atomic (exactly one caller wins, the rest get
  EventStreamAlreadyExistsException).
- InMemoryEventStream: guard the event list with a Lock. Appends compute
  Version + 1 and add inside the lock, so concurrent appends can no longer
  corrupt the list, lose events, or assign duplicate versions. Reads
  (Version, LatestSnapshotVersion, GetLatestSnapshot, ListAsync*) take the
  same lock; the List* methods materialize a snapshot so enumeration does
  not observe a mutating list.
- InMemoryTransactionalBatch: commit under the owning stream's lock.

Claude-Session: https://claude.ai/code/session_01J2j9sfE7zpM2mJq4dsz6m4
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.

1 participant