Table of Contents

Class SqlServerEventStore

Namespace
Excalibur.EventSourcing.SqlServer
Assembly
Excalibur.EventSourcing.SqlServer.dll

SQL Server implementation of IEventStore.

[SuppressMessage("Maintainability", "CA1506", Justification = "The SQL provider integrates its single-append operation context at both atomic commit paths; splitting the commit boundary would obscure the invariant.")]
public sealed class SqlServerEventStore : ITransactionalProjectionEventStore, IEventStoreErasure, ITransactionalEventStore, IEventStore, IServiceProvider, IEventStoreArchive, IEventStoreVersionProbe
Inheritance
SqlServerEventStore
Implements
Inherited Members

Remarks

Provides atomic event appends with optimistic concurrency control. Uses database transactions to ensure consistency.

This class supports two constructor patterns:

  • Simple: Connection string for most users
  • Advanced: Connection factory for multi-database, pooling, or IDb integration

Supports pluggable serialization via IPayloadSerializer for event payloads, with backward compatibility for existing JSON-serialized events.

Constructors

SqlServerEventStore(Func<SqlConnection>, ILogger<SqlServerEventStore>, ITenantContext, ISerializer?, IPayloadSerializer?, string, string, IJsonTypeInfoResolver?)

Initializes a new instance of the SqlServerEventStore class with a connection factory.

public SqlServerEventStore(Func<SqlConnection> connectionFactory, ILogger<SqlServerEventStore> logger, ITenantContext tenantContext, ISerializer? internalSerializer = null, IPayloadSerializer? payloadSerializer = null, string schema = "dbo", string table = "EventStoreEvents", IJsonTypeInfoResolver? eventTypeInfoResolver = null)

Parameters

connectionFactory Func<SqlConnection>

A factory function that creates SqlConnection instances. The caller is responsible for ensuring the factory returns properly configured connections.

logger ILogger<SqlServerEventStore>

The logger instance.

tenantContext ITenantContext

The ambient tenant context. Required: this store partitions rows by tenant, and it resolves that partition from here, so there is no state in which the partition is undecided. A single-tenant host receives the framework default context and operates as the one canonical tenant.

internalSerializer ISerializer

Optional internal serializer for high-performance binary envelope serialization.

payloadSerializer IPayloadSerializer

Optional pluggable serializer for event payloads.

schema string

The schema name for the event store table. Default: "dbo".

table string

The event store table name. Default: "EventStoreEvents".

eventTypeInfoResolver IJsonTypeInfoResolver

An optional source-generated JSON type-info resolver covering the application's domain event types and the runtime types of the values it places in Metadata. Supplied, the store serializes without reflection, which is what a native-AOT host published with reflection-based serialization disabled requires. Omitted, the store serializes through the reflection-based serializer exactly as before, so an existing caller is unaffected. The stored wire format is byte-identical either way.

Remarks

This is the advanced constructor for scenarios that need custom connection management: It does not advertise IEventStoreAuthoritativeReader, because the factory may return a borrowed connection. Use CreateWithOwnedPrimaryConnectionFactory(Func<SqlConnection>, ILogger<SqlServerEventStore>, ITenantContext, ISerializer?, IPayloadSerializer?, string, string, IJsonTypeInfoResolver?) to explicitly supply fresh owned primary connections for independent authoritative rechecks.

  • Multi-database setups with marker interfaces (e.g., IDomainDb, IEventStoreDb)
  • Custom connection pooling
  • Integration with IDb abstraction

Example with IDb:

new SqlServerEventStore(
    () => (SqlConnection)domainDb.Connection,
    logger,
    tenantContext,
    internalSerializer,
    payloadSerializer);

SqlServerEventStore(string, ILogger<SqlServerEventStore>, ITenantContext)

Initializes a new instance of the SqlServerEventStore class.

public SqlServerEventStore(string connectionString, ILogger<SqlServerEventStore> logger, ITenantContext tenantContext)

Parameters

connectionString string

The SQL Server connection string.

logger ILogger<SqlServerEventStore>

The logger instance.

tenantContext ITenantContext

The ambient tenant context. Required: this store resolves the tenant partition it reads and writes from here.

Remarks

This is the simple constructor for most users. Use SqlServerEventStore(Func<SqlConnection>, ILogger<SqlServerEventStore>, ITenantContext, ISerializer?, IPayloadSerializer?, string, string, IJsonTypeInfoResolver?) for advanced scenarios like multi-database setups or custom connection pooling.

SqlServerEventStore(string, ILogger<SqlServerEventStore>, ITenantContext, ISerializer?)

Initializes a new instance of the SqlServerEventStore class with optional internal serializer.

public SqlServerEventStore(string connectionString, ILogger<SqlServerEventStore> logger, ITenantContext tenantContext, ISerializer? internalSerializer)

Parameters

connectionString string

The SQL Server connection string.

logger ILogger<SqlServerEventStore>

The logger instance.

tenantContext ITenantContext

The ambient tenant context. Required: this store resolves the tenant partition it reads and writes from here.

internalSerializer ISerializer

Optional internal serializer for high-performance binary envelope serialization.

Remarks

This is the simple constructor for most users. Use SqlServerEventStore(Func<SqlConnection>, ILogger<SqlServerEventStore>, ITenantContext, ISerializer?, IPayloadSerializer?, string, string, IJsonTypeInfoResolver?) for advanced scenarios like multi-database setups or custom connection pooling.

SqlServerEventStore(string, ILogger<SqlServerEventStore>, ITenantContext, ISerializer?, IPayloadSerializer?)

Initializes a new instance of the SqlServerEventStore class with optional serializers.

public SqlServerEventStore(string connectionString, ILogger<SqlServerEventStore> logger, ITenantContext tenantContext, ISerializer? internalSerializer, IPayloadSerializer? payloadSerializer)

Parameters

connectionString string

The SQL Server connection string.

logger ILogger<SqlServerEventStore>

The logger instance.

tenantContext ITenantContext

The ambient tenant context. Required: this store resolves the tenant partition it reads and writes from here.

internalSerializer ISerializer

Optional internal serializer for high-performance binary envelope serialization.

payloadSerializer IPayloadSerializer

Optional pluggable serializer for event payloads.

Remarks

This is the simple constructor for most users. Use SqlServerEventStore(Func<SqlConnection>, ILogger<SqlServerEventStore>, ITenantContext, ISerializer?, IPayloadSerializer?, string, string, IJsonTypeInfoResolver?) for advanced scenarios like multi-database setups or custom connection pooling.

Methods

AppendAsync(string, string, IEnumerable<IDomainEvent>, long, CancellationToken)

Appends events to the store with optimistic concurrency control.

public ValueTask<AppendResult> AppendAsync(string aggregateId, string aggregateType, IEnumerable<IDomainEvent> events, long expectedVersion, CancellationToken cancellationToken)

Parameters

aggregateId string

The aggregate identifier. Must not be null, empty, or white space.

aggregateType string

The aggregate type name. Must not be null, empty, or white space.

events IEnumerable<IDomainEvent>

The events to append. Must not be null.

expectedVersion long

The version the stream is expected to currently be at, or -1 when the stream does not yet exist. See the version base stated in the remarks below.

cancellationToken CancellationToken

Cancellation token.

Returns

ValueTask<AppendResult>

The result of the append operation, carrying the stream's version after the append in NextExpectedVersion.

Remarks

Version base. Stream versions are zero-based and contiguous. The first event appended to a new stream is version 0, and each subsequent event takes the next integer. A stream that does not yet exist has no current version, which expectedVersion expresses as -1. Appending N events to a new stream therefore leaves it at version N-1: that is the value NextExpectedVersion reports, and the value the next append must pass as expectedVersion — it is the version the stream is now at, not the version the next event will receive. Appending no events leaves the version unchanged and reports back the version it was given.

An identifier that is null, empty, or white space is a usage error, never a legitimate stream: accepting one would fabricate a stream key and write events where no reader will ever look. Every implementation therefore rejects such an argument by throwing, rather than reporting a failed AppendResult — a returned result models a domain or infrastructure outcome, not a caller defect. Implementations validate their arguments before any I/O or concurrency check is attempted.

Outcome or defect. The line between a returned AppendResult and a thrown exception is whether the identical call could ever succeed without a change to the calling program. A version clash could, once the caller reloads, so it is reported as a result carrying IsConcurrencyConflict; an infrastructure fault may be reported as Failed only when non-commit is established. A lost commit acknowledgement with inconclusive recovery is Unknown, even if a later read sees a different stream version or no matching rows. Retry classification does not establish commit certainty. An event type the configured resolver does not declare could not — no retry, reload or reconfiguration reaches it — so it throws, as do a blank identifier, a batch above the provider's atomic limit, and cancellation. Every implementation of this interface answers the same way; a caller may rely on that rather than on which provider is configured.

Cancellation propagates. A cancelled append raises OperationCanceledException rather than reporting a failed result: reporting it as a store failure would invite a caller to retry inside a scope that has already been cancelled. Cancellation after dispatch does not prove rollback. Reconcile outside the cancelled operation using the original tenant, stream, event identities, payloads and expected version; do not regenerate events or rebase the append merely because its acknowledgement was not received.

Confined to the ambient tenant established for this store instance: the appended events join only this tenant's stream for aggregateId, and the optimistic-concurrency check against expectedVersion is evaluated within that same partition — another tenant holding a stream under the same aggregateId can neither cause nor observe a conflict here.

Exceptions

ArgumentException

aggregateId or aggregateType is empty or white space.

ArgumentNullException

aggregateId, aggregateType, or events is null.

EventBatchTooLargeException

events contains more events than the underlying store can append atomically. The exception carries the offending count and the limit, so a caller may split the batch and retry.

EventTypeNotDeclaredException

An event's runtime type is not declared by the type-info resolver the host configured, so it cannot be serialized. Nothing is appended. The identical call cannot succeed until the type is declared, which is why this is thrown rather than reported as a failed AppendResult.

AppendWithOutboxStagingAsync(string, string, IEnumerable<IDomainEvent>, long, Func<IDbTransaction, CancellationToken, ValueTask>, CancellationToken)

Appends events and stages outbox messages within a single atomic database transaction.

public ValueTask<AppendResult> AppendWithOutboxStagingAsync(string aggregateId, string aggregateType, IEnumerable<IDomainEvent> events, long expectedVersion, Func<IDbTransaction, CancellationToken, ValueTask> stageOutbox, CancellationToken cancellationToken)

Parameters

aggregateId string

The aggregate identifier.

aggregateType string

The aggregate type name.

events IEnumerable<IDomainEvent>

The events to append.

expectedVersion long

The expected current version (-1 for a new aggregate).

stageOutbox Func<IDbTransaction, CancellationToken, ValueTask>

A callback that stages outbox messages on the supplied transaction. It is invoked only when the version check succeeds, before the events are appended and before commit. It must not depend on the version or global position the append assigns; neither is available to it.

cancellationToken CancellationToken

Cancellation token.

Returns

ValueTask<AppendResult>

The result of the append operation.

Remarks

The store opens one connection and one transaction, performs the optimistic-concurrency version check, invokes stageOutbox on the same transaction, appends the events, then commits. A failed version pre-check does not invoke stageOutbox. A later conflict can occur after staging; a proven rollback discards both events and staged rows. Lost commit acknowledgement can leave both durable and must be reported as Unknown unless reconciliation establishes the complete operation. Callback faults before commit propagate and abort the store-owned transaction. The callback must not commit it, open independent writes or perform external effects; the supplied transaction does not enforce that discipline by itself.

Staging runs before the events are appended, and the callback must not depend on anything the append produces. A provider with a global event position allocates it from a shared counter whose lock is held until commit, so every appender in the process is blocked for as long as that transaction runs. Staging is one round trip per message, so performing it after the append would place all of those round trips inside that window. The ordering is therefore a throughput property, not a correctness one — atomicity is identical either way — and it is only available because the callback receives the transaction and nothing else. Do not widen the callback to expose the assigned version or position: that would force staging back inside the window and reduce sustained append throughput for every consumer of the provider.

A concurrency conflict is classified the same way whether it is caught by the in-transaction version pre-check or lost to a genuine race that slips past it (two callers both pass the pre-check, then race at insert/commit — the database's own uniqueness constraint on the stream key decides the loser). Either shape yields CreateConcurrencyConflict(long, long?), matching AppendAsync(string, string, IEnumerable<IDomainEvent>, long, CancellationToken)'s contract on the same provider. A changed stream version after a lost commit acknowledgement does not establish a conflict: it may include this append. An inconclusive commit outcome is Unknown. Callback faults before commit propagate as their original exceptions. Cancellation propagates as cancellation, but cancellation after commit dispatch does not establish rollback; callers must reconcile the original operation before retrying or issuing dependent effects.

AppendWithProjectionsAsync(string, string, IReadOnlyList<IDomainEvent>, long, Func<ProjectionTransaction, CancellationToken, ValueTask>, CancellationToken)

Appends events and projection changes in one transaction.

public ValueTask<AppendResult> AppendWithProjectionsAsync(string aggregateId, string aggregateType, IReadOnlyList<IDomainEvent> events, long expectedVersion, Func<ProjectionTransaction, CancellationToken, ValueTask> apply, CancellationToken cancellationToken)

Parameters

aggregateId string

Stream identifier.

aggregateType string

Stream type.

events IReadOnlyList<IDomainEvent>

New events.

expectedVersion long

Expected last persisted version, or -1 for a new stream.

apply Func<ProjectionTransaction, CancellationToken, ValueTask>

Callback before append, using authoritative history and the supplied transaction.

cancellationToken CancellationToken

Cancellation token. Cancellation does not prove rollback after commit dispatch.

Returns

ValueTask<AppendResult>

The confirmed or uncertain append outcome.

CreateWithOwnedPrimaryConnectionFactory(Func<SqlConnection>, ILogger<SqlServerEventStore>, ITenantContext, ISerializer?, IPayloadSerializer?, string, string, IJsonTypeInfoResolver?)

Creates a store whose factory transfers fresh closed primary connections to the store.

public static SqlServerEventStore CreateWithOwnedPrimaryConnectionFactory(Func<SqlConnection> connectionFactory, ILogger<SqlServerEventStore> logger, ITenantContext tenantContext, ISerializer? internalSerializer = null, IPayloadSerializer? payloadSerializer = null, string schema = "dbo", string table = "EventStoreEvents", IJsonTypeInfoResolver? eventTypeInfoResolver = null)

Parameters

connectionFactory Func<SqlConnection>

Factory returning a new closed connection on every invocation, owned and disposed by the store.

logger ILogger<SqlServerEventStore>

The logger instance.

tenantContext ITenantContext

The tenant scope, checked again on each authoritative read.

internalSerializer ISerializer

Optional internal serializer.

payloadSerializer IPayloadSerializer

Optional payload serializer.

schema string

The event store schema.

table string

The event store table.

eventTypeInfoResolver IJsonTypeInfoResolver

Optional source-generated event type resolver.

Returns

SqlServerEventStore

The configured event store.

Remarks

Every connection must route to the same logical primary database as appends, without cached query results. Recovery must preserve acknowledged erasures. Configure authentication on each connection as needed. Authoritative reads suppress ambient transactions and own a separate connection; ensure adequate pool capacity. An endpoint role check cannot identify an unrelated writable copy.

EraseEventsAsync(string, string, Guid, CancellationToken)

Erases all event payloads for the specified aggregate, replacing them with a tombstone marker.

public Task<int> EraseEventsAsync(string aggregateId, string aggregateType, Guid erasureRequestId, CancellationToken cancellationToken)

Parameters

aggregateId string

The aggregate whose events should be erased.

aggregateType string

The aggregate type name.

erasureRequestId Guid

The GDPR erasure request tracking ID for audit purposes.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<int>

The number of events that were erased.

Remarks

Confined to the ambient tenant established for this store instance: tombstones events only in the caller's own tenant's stream for aggregateId, and cannot reach or be triggered by another tenant's stream under the same identifier.

GetArchiveCandidatesAsync(ArchivePolicy, int, CancellationToken)

Finds aggregates with events eligible for archival based on the archive policy.

public Task<IReadOnlyList<ArchiveCandidate>> GetArchiveCandidatesAsync(ArchivePolicy policy, int batchSize, CancellationToken cancellationToken)

Parameters

policy ArchivePolicy

The archive policy criteria.

batchSize int

Maximum number of candidates to return.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<IReadOnlyList<ArchiveCandidate>>

A list of aggregates with archivable events.

Remarks

Discovery is deliberately cross-tenant: one pass enumerates candidates for every tenant, and each returned candidate carries the tenant that owns it. Scoping this enumeration to a single tenant would stall archival for all others, so the tenant term is a result here, never a parameter. Candidates must contain pending work. Apply the policy's retention override and stop each stream's prefix at its first ineligible or unresolved event before applying the candidate batch limit. Read candidate payloads through the same hot store's IEventStoreArchiveReader capability, using the candidate's tenant, aggregate identity, and inclusive version ceiling.

GetMaxVersionAsync(string, string, CancellationToken)

Gets the highest event version stored for the aggregate stream.

public ValueTask<long> GetMaxVersionAsync(string aggregateId, string aggregateType, CancellationToken cancellationToken)

Parameters

aggregateId string

The aggregate identifier.

aggregateType string

The aggregate type name.

cancellationToken CancellationToken

Token to observe for cancellation.

Returns

ValueTask<long>

The highest version present in the stream, or -1 when the stream holds no events. Versions are zero-based, so a stream of n events reports n - 1.

Remarks

Reuses the same indexed MAX(Version) read the append path uses to resolve a concurrency conflict, which already returns -1 for a stream with no events -- the value this capability is specified to return. Runs on its own connection, outside any append transaction.

GetService(Type)

Resolves an optional capability supported by this configured store.

public object? GetService(Type serviceType)

Parameters

serviceType Type

The requested capability type.

Returns

object

The capability, or null if this configuration does not support it.

Remarks

Authoritative reads are available for string constructors and explicitly owned primary factories. Resolve through the final decorated store so tenant, routing, and representation restrictions apply.

IsErasedAsync(string, string, CancellationToken)

Checks whether erasure has been performed for the specified aggregate.

public Task<bool> IsErasedAsync(string aggregateId, string aggregateType, CancellationToken cancellationToken)

Parameters

aggregateId string

The aggregate identifier.

aggregateType string

The aggregate type name.

cancellationToken CancellationToken

Cancellation token.

Returns

Task<bool>

true if the aggregate's events have been erased; otherwise, false.

Remarks

Confined to the ambient tenant established for this store instance: answers for the caller's own tenant's stream, never another tenant's stream under the same identifier.

LoadAsync(string, string, long, CancellationToken)

Loads events for an aggregate from a specific version.

public ValueTask<IReadOnlyList<StoredEvent>> LoadAsync(string aggregateId, string aggregateType, long fromVersion, CancellationToken cancellationToken)

Parameters

aggregateId string

The aggregate identifier. Must not be null, empty, or white space.

aggregateType string

The aggregate type name. Must not be null, empty, or white space.

fromVersion long

The version to start loading from, exclusive: the result begins at the next version after this one. Versions are zero-based, so -1 loads the whole stream. See the version base stated on AppendAsync(string, string, IEnumerable<IDomainEvent>, long, CancellationToken).

cancellationToken CancellationToken

Cancellation token.

Returns

ValueTask<IReadOnlyList<StoredEvent>>

The events for the aggregate from the specified version in order.

Remarks

Confined identically to the zero-argument overload above: none of another tenant's events for this aggregateId, and every one of the caller's own from fromVersion onward.

Exceptions

ArgumentException

aggregateId or aggregateType is empty or white space.

ArgumentNullException

aggregateId or aggregateType is null.

LoadAsync(string, string, CancellationToken)

Loads all events for an aggregate.

public ValueTask<IReadOnlyList<StoredEvent>> LoadAsync(string aggregateId, string aggregateType, CancellationToken cancellationToken)

Parameters

aggregateId string

The aggregate identifier. Must not be null, empty, or white space.

aggregateType string

The aggregate type name. Must not be null, empty, or white space.

cancellationToken CancellationToken

Cancellation token.

Returns

ValueTask<IReadOnlyList<StoredEvent>>

The events for the aggregate in version order.

Remarks

Confined to the ambient tenant established for this store instance: returns none of another tenant's events for this aggregateId, and every one of the caller's own — a store that returns fewer than the caller's own full history satisfies neither this contract nor the aggregate that must replay from it.

Exceptions

ArgumentException

aggregateId or aggregateType is empty or white space.

ArgumentNullException

aggregateId or aggregateType is null.

TombstoneArchivedEventsUpToVersionAsync(KeyedTenantPartition, string, string, long, CancellationToken)

Clears archived payloads from the hot store up to and including the specified version, preserving event identity, ordering, and archive markers.

public Task<int> TombstoneArchivedEventsUpToVersionAsync(KeyedTenantPartition tenant, string aggregateId, string aggregateType, long toVersion, CancellationToken cancellationToken)

Parameters

tenant KeyedTenantPartition

The tenant partition whose payloads are to be cleared. The update is addressed by this term, so a run for one tenant cannot clear another tenant's payloads for the same aggregate identifier.

aggregateId string

The aggregate identifier.

aggregateType string

The aggregate type name.

toVersion long

The version up to which payloads should be cleared (inclusive).

cancellationToken CancellationToken

Cancellation token.

Returns

Task<int>

The number of event payloads cleared.

Remarks

The caller must bound this operation by both the candidate ceiling and the cold store's confirmed durable prefix. Completion of a write attempt alone does not establish that the full submitted range is durable. Preserve hot rows and their global positions so subscribers can hydrate them from cold storage without silently skipping committed events.

The tenant term is required and must be the same one under which the cold write was confirmed. Implementations MUST emit it as a predicate on the deletion; a deletion addressed by aggregate identifier alone spans every tenant sharing that identifier and destroys events this call never archived.