Dynamic Consistency Boundary (DCB)
The Dynamic Consistency Boundary (DCB) pattern allows you to query and enforce consistency across events from multiple streams using tags -- strong-typed identifiers attached to events at append time. This is useful when your consistency boundary doesn't align with a single event stream.
Concept
In traditional event sourcing, consistency is enforced per-stream using optimistic concurrency on the stream version. DCB extends this by letting you:
- Tag events with one or more strong-typed identifiers
- Query events across streams by those tags
- Aggregate tagged events into a view (like a live aggregation, but cross-stream)
- Enforce consistency at save time -- detecting if new matching events were appended since you last read
Registering Tag Types
Tag types are strong-typed identifiers (typically record types wrapping a primitive). Register them during store configuration:
private void ConfigureStore()
{
StoreOptions(opts =>
{
opts.Events.AddEventType<StudentEnrolled>();
opts.Events.AddEventType<AssignmentSubmitted>();
opts.Events.AddEventType<StudentDropped>();
opts.Events.AddEventType<StudentGraded>();
// Register tag types -- each gets its own table (mt_event_tag_student, mt_event_tag_course)
opts.Events.RegisterTagType<StudentId>("student")
.ForAggregate<StudentCourseEnrollment>();
opts.Events.RegisterTagType<CourseId>("course")
.ForAggregate<StudentCourseEnrollment>();
opts.Projections.LiveStreamAggregation<StudentCourseEnrollment>();
});
}Each tag type gets its own table (mt_event_tag_student, mt_event_tag_course, etc.) with a composite primary key of (value, seq_id).
Automatic Tag Type Registration
When you register a SingleStreamProjection<TDoc, TId> or MultiStreamProjection<TDoc, TId> that uses a strong-typed identifier as its TId, Marten will automatically register that type as a tag type with ForAggregate() pointing to TDoc. This means you don't need to call RegisterTagType<TId>() explicitly in most cases:
// The projection's TId (TicketId) is auto-registered as a tag type
opts.Projections.Add<TicketSummaryProjection>(ProjectionLifecycle.Inline);
// No need for: opts.Events.RegisterTagType<TicketId>().ForAggregate<TicketSummary>();Auto-discovery only applies to strong-typed identifiers (e.g., record struct TicketId(Guid Value)). Primitive types like Guid, string, int, long, and short are not auto-registered.
If you explicitly register a tag type before auto-discovery runs, your explicit registration takes precedence. This lets you customize the table suffix when needed:
// Explicit registration with custom table suffix — auto-discovery won't overwrite this
opts.Events.RegisterTagType<TicketId>("custom_ticket")
.ForAggregate<TicketSummary>();
opts.Projections.Add<TicketSummaryProjection>(ProjectionLifecycle.Inline);Every discovered tag type adds a table, with its foreign key and indexes, and a parameter on mt_quick_append_events, whether or not you ever write a tag. If you use strong-typed identifiers but not DCB, turn auto-discovery off:
opts.Events.AutoDiscoverTagTypes = false;Explicit RegisterTagType<T>() calls keep working with auto-discovery off. Turning it off on an existing database leaves any tag tables already there in place, and Marten will not remove them for you.
Registering Tag Types under Trimming or Native AOT
RegisterTagType<TTag>() discovers the primitive inside your tag type by reflecting over its members, and closes a generic registration type at runtime. Both are unsafe under trimming and Native AOT, so those overloads are marked [RequiresUnreferencedCode] and [RequiresDynamicCode], and an AOT-analyzed application sees IL2026/IL3050 warnings where it calls them. For those applications, register the tag type with an explicit unwrapper instead. It is backed by TagTypeRegistration.FromUnwrapper<TTag, TInner>() in JasperFx.Events, and needs no reflection:
// Trim- and AOT-safe: the unwrapper says how to read the stored primitive out of the tag
opts.Events.RegisterTagType<StudentId, Guid>(id => id.Value, "student")
.ForAggregate<StudentCourseEnrollment>();The second type argument is the primitive the tag table stores, typically Guid, string, int or long. The suffix is optional and defaults to the tag type's own name, exactly as it does for the inferring overloads — so for a tag the inferring overload could have registered, the explicit one registers the same inner type and the same table.
If you call an inferring overload anyway and it cannot do its work, it says which line to write. A native image that has no instantiation of TagTypeRegistration<TTag, TInner> — or a trimmed image that has lost the tag's members — throws an InvalidOperationException while the store is being configured, naming the registration for the tag type in question and keeping the original failure as its inner exception:
The tag type Enrollment.StudentId could not be read as a strong-typed identifier. Either it is not
a single-value wrapper, or this image was trimmed and has lost the members that say so. Naming the
inner type and how to read it needs neither:
opts.Events.RegisterTagType<StudentId, Guid>(x => x.Value, "student");That message matters because the [RequiresUnreferencedCode]/[RequiresDynamicCode] warnings only reach an application that is itself AOT-analyzed. A store configured from inside a library gets no warning at build time, so the runtime message is the only thing that names the fix.
Automatic tag type registration uses the inferring path too. It cannot throw — it runs while the store initializes, and a tag type is not worth refusing to start over — so it logs a warning naming the same line, including the projection's ForAggregate<T>(). Under Native AOT, register those identity types explicitly as well rather than relying on it.
WARNING
An empty table suffix is refused. mt_event_tag_ is a real table name, so RegisterTagType<T>("") used to be accepted and would put every tag type registered that way into one shared table. Pass a suffix, or null for the tag type's own name.
Tag Type Requirements
Tag types should be simple wrapper records around a primitive value:
// Strong-typed tag identifiers
public record StudentId(Guid Value);
public record CourseId(Guid Value);Supported inner value types: Guid, string, int, long, short.
Tags work with both Rich and Quick append modes (the default in Marten 9 is QuickWithServerTimestamps). In Rich mode, tags are inserted using pre-assigned sequence numbers. In Quick mode, tags are inserted using a subquery that looks up the sequence from the event's id.
Tagging Events
Use BuildEvent and WithTag to attach tags before appending:
var enrolled = theSession.Events.BuildEvent(new StudentEnrolled("Alice", "Math"));
enrolled.WithTag(studentId, courseId);
theSession.Events.Append(streamId, enrolled);
await theSession.SaveChangesAsync();Events can have multiple tags of different types. Tags are persisted to their respective tag tables in the same transaction as the event.
Tag Rules 9.30
Tagging every event at its call site is a rule nothing enforces, and a forgotten tag is not an error to a tag query -- it is simply absent from the answer. A tag rule states the rule once, and Marten applies it wherever the event is built:
opts.Events.RegisterTagType<InvoiceId>("invoice");
opts.Events.RegisterTagType<LineId>("line");
// Declared on an interface, so it reaches every event that belongs to an invoice
opts.Events.TagWith<IInvoiceEvent>(e => new InvoiceId(e.Invoice));
opts.Events.TagWith<LineInvoiced>(e => new LineId(e.Line));This closes the two gaps that tag inference leaves open. Inference matches a property by its type, so an event that names its identifiers as Guid or string can never be inferred, and it only runs on the IEventBoundary path. A rule applies to ordinary appends, StartStream, aggregate handlers and bulk inserts alike, because it runs where the event is built.
Rules compose the way you would expect:
- returning
nullleaves the event untagged; - a rule declared on a base type or interface applies to every event assignable to it;
- several rules may contribute different tag types to one event;
- a tag type already on the event is left alone, so a rule never fights an explicit
WithTag-- and never adds a second value of one tag type, which HStore mode refuses.
A rule that produces a tag type you never registered throws, rather than writing an event whose tag no query can ever match.
When an application already owns a single place that knows what an event is about, hand that over whole instead of restating it as one registration per tag type:
opts.Events.TagEventsBy(data => data switch
{
LineInvoiced e => [new InvoiceId(e.Invoice), new LineId(e.Line)],
IInvoiceEvent e => [new InvoiceId(e.Invoice)],
_ => Array.Empty<object>()
});Return an empty sequence to leave an event untagged. The rule receives the event body: the stream is assigned after the event is built, so it is not available here.
Querying Events by Tags
Use EventTagQuery to build a query, then execute it with QueryByTagsAsync:
var query = new EventTagQuery().Or<StudentId>(studentId);
var events = await theSession.Events.QueryByTagsAsync(query);Multiple Tags (OR)
// Query for either student
var query = new EventTagQuery()
.Or<StudentId>(student1)
.Or<StudentId>(student2);
var events = await theSession.Events.QueryByTagsAsync(query);Filtering by Event Type
// Query only AssignmentSubmitted events for this student
var query = new EventTagQuery()
.Or<AssignmentSubmitted, StudentId>(studentId);
var events = await theSession.Events.QueryByTagsAsync(query);Events are always returned ordered by sequence number (global append order).
TIP
The read-only tag queries, QueryByTagsAsync, AggregateByTagsAsync and EventsExistAsync, are on IQuerySession.Events as well as on IDocumentSession.Events, so a read-only endpoint can call them through a query session. FetchForWritingByTags needs a document session.
Aggregating by Tags
Build an aggregate from tagged events, similar to AggregateStreamAsync but across streams. First define an aggregate that applies the tagged events:
// Aggregate for DCB
public class StudentCourseEnrollment
{
public Guid Id { get; set; }
public string StudentName { get; set; } = "";
public string CourseName { get; set; } = "";
public List<string> Assignments { get; set; } = new();
public bool IsDropped { get; set; }
public void Apply(StudentEnrolled e)
{
StudentName = e.StudentName;
CourseName = e.CourseName;
}
public void Apply(AssignmentSubmitted e)
{
Assignments.Add(e.AssignmentName);
}
public void Apply(StudentDropped e)
{
IsDropped = true;
}
}Then aggregate across streams by tag query:
var query = new EventTagQuery()
.Or<StudentId>(studentId)
.Or<CourseId>(courseId);
var aggregate = await theSession.Events.AggregateByTagsAsync<StudentCourseEnrollment>(query);Returns null if no matching events are found.
Identity-less Boundary Aggregates
StudentCourseEnrollment above carries a single-stream Id, so it doubles as an ordinary aggregate. A pure boundary aggregate has no single-stream identity at all — it exists only as the projection of the events selected by a tag query, spanning many streams. Mark such a type with [BoundaryAggregate] so the source generator still emits a dispatcher for it even though it has no Id property and no [AggregateIdentity]:
// A *pure* DCB boundary aggregate: Apply methods, but no single-stream identity
// (no Id property, no [AggregateIdentity]). It spans multiple streams by tag, so
// the only thing that makes the source generator emit an evolver for it is the
// [BoundaryAggregate] marker. See marten#4510 / jasperfx#324.
[BoundaryAggregate]
public class SubscriptionState
{
public int EnrollmentCount { get; set; }
public int ProgressCount { get; set; }
public void Apply(Enrolled _) => EnrollmentCount++;
public void Apply(ProgressRecorded _) => ProgressCount++;
}Register it with RegisterTagType<...>().ForAggregate<T>() only — do not add a LiveStreamAggregation<T>() / Snapshot<T>() registration, since those require a stream identity. AggregateByTagsAsync<T> and FetchForWritingByTags<T> then work against the boundary aggregate.
WARNING
The [BoundaryAggregate] marker is required, and it is an explicit opt-in. Without it, an identity-less aggregate gets no source-generated dispatcher and FetchForWritingByTags<T> throws InvalidProjectionException ("No source-generated dispatcher found"). This is deliberate: a no-Id aggregate is far more often a forgotten identity than an intended boundary aggregate, so the marker distinguishes the two. The aggregate's assembly must reference the JasperFx.Events.SourceGenerator analyzer.
Fetch for Writing (Consistency Boundary)
FetchForWritingByTags loads the aggregate and establishes a consistency boundary. At SaveChangesAsync time, Marten checks whether any new events matching the query have been appended since the read, throwing DcbConcurrencyException if so:
// Fetch for writing
await using var session2 = theStore.LightweightSession();
var query = new EventTagQuery().Or<StudentId>(studentId);
var boundary = await session2.Events.FetchForWritingByTags<StudentCourseEnrollment>(query);
// Read current state
var aggregate = boundary.Aggregate; // may be null if no events yet
var lastSequence = boundary.LastSeenSequence;
// Append via boundary
var assignment = session2.Events.BuildEvent(new AssignmentSubmitted("HW1", 95));
assignment.WithTag(studentId, courseId);
boundary.AppendOne(assignment);
// Save -- will throw DcbConcurrencyException if another session
// appended matching events after our read
await session2.SaveChangesAsync();Handling Concurrency Violations
try
{
await session1.SaveChangesAsync();
}
catch (DcbConcurrencyException ex)
{
// Reload and retry -- the boundary's tag query had new matching events
// ex.Query -- the original tag query
// ex.LastSeenSequence -- the sequence at time of read
}TIP
The consistency check only detects events appended after the read that carry a tag value the query reads. Events appended to unrelated tags or streams never cause a violation, and neither does another boundary's save that appends nothing carrying one of those tag values. Since Marten 10 the check also honours the event types a condition names with AndEventsOfType: an event of a type the query does not select does not conflict. See scoping conflicts by event type.
How the boundary check serializes 9.4
Upgrading from 9.3 or earlier
Marten 9.4 added a new schema object — mt_dcb_tag_version — to fix #4591. Deployments with AutoCreate.None must run db-patch / db-apply before deploying 9.4. See Migration Guide → 9.4 schema migration.
Internally, FetchForWritingByTags records the captured version of every tag value referenced by the query in a side table (mt_dcb_tag_version, one row per (tag_table, tag_value, tenant_id)). A version only moves when an event carrying that tag value is appended: every save that appends a tagged event — boundary or otherwise — bumps the row of each tag value its events carry. That's what keeps a plain session.Events.Append(streamId, taggedEvent) from silently committing past an in-flight boundary fetch held by another session.
At SaveChangesAsync time a boundary save emits an INSERT … ON CONFLICT DO UPDATE … WHERE version = $captured RETURNING 1 for each captured row. For a row the save's own events do not carry, the update leaves the version as it is: the statement exists to lock the row and compare it. The row-level lock plus the captured-version predicate is the serialization point. Two concurrent boundary saves over the same tag value take turns; the second waits for the first to commit and then compares against the committed row, so it fails with DcbConcurrencyException only if the first appended an event carrying that tag value. This works at PostgreSQL's default READ COMMITTED isolation; no SERIALIZABLE, no advisory locks.
The rows a save checks and the rows its events bump are locked together, in one sorted order, so two saves that each check a tag value the other one appends to cannot deadlock: one of them commits, and the other fails with DcbConcurrencyException.
Changed in 9.60
Before 9.60 the check also bumped every row it read. Two boundaries reading the same tag value therefore always conflicted, even when neither appended anything the other reads, and two saves that each read a tag the other appended to could deadlock instead of failing cleanly (#5887). If you relied on a boundary save invalidating every concurrent boundary over the same tag value, append an event carrying that tag value.
A save asserts each row once, however many boundaries named it. Fetching one query twice on a session, or fetching two queries that overlap on a tag value, is not a conflict with itself — the oldest captured version of the row is the one enforced, so every read the session made still has to be valid.
A boundary that decides there is nothing to append is not a save at all as far as the side table is concerned. The check guards an append, so a session that fetches a boundary and then calls SaveChangesAsync() without appending anything leaves mt_dcb_tag_version exactly as it found it, and never throws DcbConcurrencyException — even if another session moved the boundary in the meantime. Two sessions can reach the same "nothing to do" conclusion about one boundary and both commit, and a no-op decision never invalidates a concurrent session that does have events to append. The boundary is released by that commit: to act on it afterwards, fetch it again.
The side table grows with distinct boundary-tag values, not with event volume, and is never deleted automatically — the same StudentId or CourseId reuses its row across every save. Avoid using ephemeral or one-shot values as DCB tags if you want to keep the table compact.
Scoping conflicts by event type
A query condition can name event types with AndEventsOfType, and the DCB specification only fails an append when a later event matches the query — event type included. Marten 10 does the same by default: alongside its version per tag value it keeps one per (tag value, event type), and a condition naming event types checks those. Marten 9 kept versions per tag value only, so an event of a type the condition does not name still conflicted when it carried the same tag value — never wrong, but it reports conflicts the specification would not, and under load those cost retries. opts.Events.DcbConflictScope chooses between the two:
var store = StoreOptions(opts =>
{
opts.Events.RegisterTagType<LibraryLoanId>("library_loan");
// Honour AndEventsOfType in the DCB conflict check, as the DCB specification does.
// On a running system, deploy TagValueRecordingEventTypes to every node first.
opts.Events.DcbConflictScope = DcbConflictScope.TagValueAndEventType;
});
await using var session = store.LightweightSession();
// The decision only folds returns...
var query = new EventTagQuery()
.Or(new LibraryLoanId(loanId))
.AndEventsOfType<LibraryBookReturned>();
var boundary = await session.Events.FetchForWritingByTags<LibraryLoanState>(query);
// ...so a reminder for the same loan appended in the meantime by another session
// no longer fails this save with a DcbConcurrencyExceptionDcbConflictScope has three settings:
| Setting | A condition naming event types conflicts with… | Extra version rows written |
|---|---|---|
TagValue (Marten 9 default) | any later event carrying the tag value | none |
TagValueRecordingEventTypes | any later event carrying the tag value | one per (tag value, event type) appended |
TagValueAndEventType (default) | later events of those types carrying the tag value | one per (tag value, event type) appended |
A condition without event types conflicts with any event carrying its tag value under every setting.
TagValueAndEventType checks a version per (tag value, event type), which is only maintained by nodes running TagValueRecordingEventTypes or TagValueAndEventType. No schema change is involved — the extra versions are rows in the same mt_dcb_tag_version table — but switching a running system takes two deployments, and that includes upgrading from Marten 9:
- Deploy
TagValueRecordingEventTypesto every node. Conflicts are still detected per tag value, and every append now also maintains the per-type versions. - Once no node is left on
TagValue, deployTagValueAndEventType.
WARNING
Switching straight from TagValue to TagValueAndEventType with a rolling deployment can miss conflicts. While any node still runs TagValue, its appends do not move the per-type versions, so a node already checking them does not see those appends as conflicts. A deployment that stops every node before starting the new version does not need the intermediate step.
Each appended event carrying a tag writes one extra mt_dcb_tag_version row per (tag value, event type), so the side table holds roughly one row per tag value per event type that has been appended with it.
Tuning the side table for a large tag set 9.47
mt_dcb_tag_version takes an UPDATE on every boundary save, so it is built for PostgreSQL's HOT (Heap-Only Tuple) path: the only column that changes, version, is deliberately left unindexed, so a bump rewrites no index entry. HOT also needs free space in the same heap page, and that is what a lower fillfactor reserves:
// Opt-in. Null (the default) leaves PostgreSQL's default of 100.
opts.Events.DcbTagVersionFillFactor = 70;Most stores should leave this alone. Measured on PostgreSQL 17 over 50,000 bumps, one statement per transaction:
| tag set | default (fillfactor 100) | fillfactor = 70 |
|---|---|---|
| 50 distinct values (one heap page) | 100% HOT, no growth | 100% HOT — no change at all |
| 200,000 distinct values (packed pages) | 92.9% HOT, heap grows | 100% HOT, no growth |
| disk for 200,000 rows | 13 MB | 19 MB (+45%) |
So it buys nothing until the table is large enough for its pages to be genuinely packed, and it costs 45% more disk permanently. Marten cannot know your tag cardinality, which is why there is no default.
WARNING
Two things to know before setting it. Declaring a storage parameter is visible to the schema diff, so an existing deployment will report a pending ALTER TABLE … SET (fillfactor = N). And that ALTER does not rewrite existing pages — the benefit arrives gradually as pages are rewritten, and fully only after a VACUUM FULL or CLUSTER that you run yourself.
Checking Event Existence
If you only need to know whether any events matching a tag query exist -- without loading or deserializing them -- use EventsExistAsync. This is a lightweight SELECT EXISTS(...) query that avoids the overhead of fetching and materializing event data:
[Fact]
public async Task events_exist_returns_true_when_matching_events_found()
{
var studentId = new StudentId(Guid.NewGuid());
var courseId = new CourseId(Guid.NewGuid());
var streamId = Guid.NewGuid();
var enrolled = theSession.Events.BuildEvent(new StudentEnrolled("Alice", "Math"));
enrolled.WithTag(studentId, courseId);
theSession.Events.Append(streamId, enrolled);
await theSession.SaveChangesAsync();
// Check existence -- lightweight, no event loading
var query = new EventTagQuery().Or<StudentId>(studentId);
var exists = await theSession.Events.EventsExistAsync(query);
exists.ShouldBeTrue();
}This is useful for guard clauses and validation logic in DCB workflows where you need to check preconditions before appending new events.
EventsExistAsync is also available in batch queries via batch.Events.EventsExist(query).
How It Works
Storage Modes
DCB tags can be stored two different ways, controlled by opts.Events.DcbStorageMode. The default is DcbStorageMode.TagTables — the behavior shipped in Marten 8. Marten 9.0 adds DcbStorageMode.HStore as an opt-in alternative that stores all tags inline on the event row using PostgreSQL's hstore key-value type.
The mode is chosen per database at creation time. There is no in-place migration between modes — pick one before populating an event store and stick with it.
DcbStorageMode.TagTables (default)
Each registered tag type creates its own PostgreSQL table:
CREATE TABLE IF NOT EXISTS mt_event_tag_student (
value uuid NOT NULL,
seq_id bigint NOT NULL,
CONSTRAINT pk_mt_event_tag_student PRIMARY KEY (value, seq_id),
CONSTRAINT fkey_mt_event_tag_student_seq_id
FOREIGN KEY (seq_id) REFERENCES mt_events(seq_id)
);
CREATE INDEX idx_mt_event_tag_student_seq_id ON mt_event_tag_student USING btree (seq_id);DCB queries probe each referenced tag table through its primary key, one probe per query condition, and combine the matches on seq_id. Strengths: native column types preserve Guid/int/string/long/short semantics, and single-tag EventsExistAsync checks hit a small dedicated table via its primary-key index. Trade-offs: every distinct tag type adds a table, two indexes, and a foreign key.
The foreign key does not cascade. Whenever Marten deletes events — stream compaction, TombstoneStream, archiving under UseArchivedStreamPartitioning, DeleteSingleEventStreamAsync, DeleteAllTenantDataAsync, and removing a tenant under UseTenantPartitionedEvents with RemoveMartenManagedTenantsAsync or RemoveTenantFromShardAsync — it deletes their tag rows first. The index on seq_id keeps the deletes that go by event, and the foreign key's own check on every deleted event, from scanning the whole tag table. The tenant-scoped deletes, DeleteAllTenantDataAsync and the two tenant removals, go by tenant_id instead. Neither the primary key nor the seq_id index leads with tenant_id, so each of them scans the tag table.
A store whose tag tables predate the index gets it from its next schema migration, as a plain CREATE INDEX. That build holds a SHARE lock on the tag table, so tagged appends wait until it finishes, while reads carry on. To avoid the wait on a large tag table, build the index yourself first with CREATE INDEX CONCURRENTLY and the same name and column. Marten then finds it in place and leaves it alone. Under UseArchivedStreamPartitioning the tag table is partitioned, so use the three-step sequence shown for the HStore index below.
Because the primary key is (value, seq_id), one event may carry several values of the same tag type — a HomeworkCopied event naming the student copied from and the student who copied is two student tags on one event, and either one finds it. This is the mode to pick when your events tag that way; HStore cannot represent it.
DcbStorageMode.HStore (opt-in)
Tags are stored inline on a new mt_events.tags hstore column, covered by a single GIN index that handles every registered tag type. The hstore extension is registered automatically as part of schema creation:
opts.Events.DcbStorageMode = DcbStorageMode.HStore;The resulting schema adds one column and one index instead of N per-type tables:
-- Single column on mt_events; tag-type suffix is the hstore key, value is text
ALTER TABLE mt_events ADD COLUMN tags hstore;
CREATE INDEX idx_mt_events_tags ON mt_events USING gin (tags);
-- Auto-registered as part of schema-create:
-- CREATE EXTENSION IF NOT EXISTS hstore;DCB queries become single-table containment lookups using Postgres' @> operator — no JOINs. The same GIN index serves every tag type and every query shape (1 tag, N tags OR'd, with or without an event-type filter).
-- Single tag: e.tags @> hstore('student', 'STU-001')
-- Two tags OR: e.tags @> hstore('student', 'STU-001') OR e.tags @> hstore('course', 'CS-101')Trade-offs:
- All tag values are stored as text — Npgsql automatically converts
Dictionary<string, string>tohstoreviaNpgsqlDbType.Hstore, andGuid/int/long/shortare stringified at the database boundary. Tag-type registration (RegisterTagType<StudentId>("student")) and usage (event.WithTag(new StudentId(...))) are unchanged — only the on-disk representation is different. - The
hstoreextension must be installable on the target database. Most managed Postgres providers ship it; bare-metal installations may needCREATE EXTENSIONprivileges on first run. - The
mt_quick_append_eventsPostgres function takes the tags as onehstore[]parallel to the events and writesmt_events.tagsin its own insert, rather than per-tag-type arrays. Before 10.0 (#5896) Marten wrote them with a follow-upUPDATEper tagged event that found the row by its unindexedid, which made every tagged append scanmt_events. - Each tag type is single-valued per event. An hstore is a map with unique keys, and Marten uses the registered tag's table-suffix as the key, so there is nowhere to put a second value of one tag type. Appending an event that carries two different values of the same tag type throws
MartenNotSupportedExceptionrather than silently keeping one of them — a dropped tag is not an error to a DCB query, it is simply absent from the answer, and that is the one failure a consistency boundary must not have. TagTables has no such restriction (see below). Cross-type merging (e.g. adding aStudentIdtag to an event that already has aRegionIdtag) works correctly in both modes — HStore uses Postgres'hstore || hstoreconcatenation to preserve the existing keys.
Enabling HStore on an existing store 9.29
Switching an existing store to DcbStorageMode.HStore adds two things to mt_events. The tags hstore column is free — a nullable add is metadata-only. The GIN index over it is not: Marten emits a plain CREATE INDEX, which holds ACCESS EXCLUSIVE for the whole build. On a large event table that is a write outage rather than a migration.
Marten can build it for you without blocking writes (9.30+):
opts.Events.DcbStorageMode = DcbStorageMode.HStore;
// Non-blocking, whichever shape mt_events has
opts.Events.BuildHStoreTagIndexConcurrently = true;On an ordinary event table that is CREATE INDEX CONCURRENTLY. Under UseTenantPartitionedEvents, mt_events is a partitioned table and PostgreSQL refuses CONCURRENTLY on a partitioned parent outright (cannot create index on partitioned table ... concurrently), so Marten emits the three-step sequence it does accept instead: the index created on only the parent, one concurrent index per tenant partition, and each attached. The parent index is invalid until the last child is attached, so a run that dies halfway leaves a visible state rather than a silent one, and the next apply repairs it.
The trade-off is that a concurrent build cannot run inside a transaction, so what db-patch and db-dump write out is no longer runnable as a single transactional script. It is still correct applied against a live database — which is what ApplyAllConfiguredChangesToDatabaseAsync and the schema management on startup do.
If you would rather own the index yourself, hand it to the operator instead. Ignore it, and Marten leaves it out of the schema diff in both directions — it will neither create it nor treat one you built yourself as drift:
opts.Events.DcbStorageMode = DcbStorageMode.HStore;
// Marten adds the tags column, but leaves this index alone
opts.Events.IgnoreIndex(EventGraph.HStoreTagIndexName);Apply the schema as usual to get the column, then build the index out of band. On an unpartitioned event table:
CREATE INDEX CONCURRENTLY idx_mt_events_tags ON mt_events USING gin (tags);On a tenant-partitioned one, PostgreSQL's supported sequence is three steps — the parent index is created invalid and flips to valid once every child is attached:
-- 1. metadata only; the parent index is left invalid
CREATE INDEX idx_mt_events_tags ON ONLY mt_events USING gin (tags);
-- 2. per partition, without blocking writes
CREATE INDEX CONCURRENTLY idx_mt_events_tags_<partition> ON mt_events_<partition> USING gin (tags);
-- 3. per partition; after the last one the parent is valid
ALTER INDEX idx_mt_events_tags ATTACH PARTITION idx_mt_events_tags_<partition>;WARNING
Tag queries are correct without the index — they just fall back to a sequential scan, which on a large event table is slow enough to matter. Build it before you rely on DCB queries in production, not after.
Choosing a Storage Mode
Choose on the shape of your data, not on speed: since 10.0 the two modes perform comparably. The differences that matter:
- Pick TagTables when one event carries two values of the same tag type, such as a
HomeworkCopiednaming both students. HStore refuses such an event rather than dropping a tag. - Pick HStore if you would rather keep one GIN index on
mt_eventsthan a table per tag type. It is a little faster for tagged appends. - Stay where you are on an existing store. Neither mode is a reason to migrate.
The harness at src/DcbLoadTest measures both, and src/DcbLoadTest/RESULTS-10.0.md has the full 10.0 results. The numbers below were measured against PostgreSQL 17 with the default QuickWithServerTimestamps append mode; reads use a store of 1,000,000 tagged events.
| Scenario | TagTables | HStore |
|---|---|---|
| append, 10 events × 2 tags per save, sequential (saves/s) | 1,135 | 1,449 |
| same, 16 concurrent writers (saves/s) | 5,319 | 5,758 |
FetchForWritingByTags, 1 tag, ~10 events (p50 ms) | 0.30 | 0.24 |
FetchForWritingByTags, 2 tag types OR'd, ~1,010 events (p50 ms) | 3.93 | 4.98 |
| decision: fetch + append + save, 1 tag (p50 ms) | 0.89 | 0.80 |
Before 10.0
Two bugs made one or the other mode far slower on a large store. Benchmarks on a small store hide both.
- HStore wrote each tagged event's tags with a follow-up
UPDATEthat found the row bymt_events.id. That column has no index unlessEnableUniqueIndexOnEventIdis on, so every tagged append scanned the events table: a 42–60 ms decision at 1M events (#5896). On an earlier version, turn onopts.Events.EnableUniqueIndexOnEventId = true. - TagTables answered a query spanning two or more tag types with
LEFT JOINs under anOR, which reads the whole store: 301 ms at 1M events (#5897). The same query also returned, and folded, an event twice when two values of one tag type both matched it.
Consistency Check 9.4
At SaveChangesAsync time, Marten emits one INSERT … ON CONFLICT DO UPDATE … WHERE version = $captured per distinct (tag_table, tag_value) row the boundary read against the mt_dcb_tag_version side table, together with the bumps of the tag values the save's own events carry, all in one deterministic sort order. The row-level write lock plus the version predicate is the serialization point: concurrent saves over the same row take turns, and a save fails with DcbConcurrencyException when an event carrying one of its tag values was committed after its read. This works at PostgreSQL's default READ COMMITTED isolation — no advisory locks, no SERIALIZABLE transactions. See how the boundary check serializes for the detail.
The check shape no longer depends on DcbStorageMode. Both TagTables and HStore share the same side-table mechanism for the consistency check; the storage mode only affects how tags are physically read at fetch time and written at append time.
Tag Routing
Events appended via IEventBoundary.AppendOne() are automatically routed to streams based on their tags. Each tag value becomes the stream identity, so events with the same tag value end up in the same stream.

