Skip to content

Tag Chronicle events and observer definitions

Tags in Cratis Chronicle serve two different tasks: event tags help you select stored events or filter delivery, while descriptive tags label observer and read-model definitions. Use named event tags when you need to find the events from a particular batch, run or session.

Plain tags are strings such as analytics or customer.registration. Event types can declare them through attributes, and an append can add more at runtime. Reactors, reducers and projections are observers: they process appended events. Tags on their definitions describe their responsibility; they do not select the events they process. Read-model definitions can carry descriptive tags too.

In .NET, [Tag] and [Tags] are interchangeable ways to declare plain tags. You can mix the two attributes; Chronicle merges their tags.

A named tag keeps a name and value separate, such as import-batch = 4711. Use this form for a runtime identifier rather than encoding it into a plain tag.

Choose static tags for categories that belong to every event of a type. Add dynamic tags when the category depends on the operation appending the event.

Declare tags on the event type so appends include them without repeating them at each call site:

using Cratis.Chronicle;
using Cratis.Chronicle.Events;
[EventType]
[Tag("analytics", "user-action")]
public record TaggingUserLoggedIn(string UserId, DateTimeOffset LoggedInAt);
// [Tags] (plural) is equivalent to [Tag] — use whichever reads more naturally
[EventType]
[Tags("analytics", "user-action")]
public record TaggingUserLoggedInAlternate(string UserId, DateTimeOffset LoggedInAt);
// Mixing [Tag] and [Tags] on the same type merges all the tags
[EventType]
[Tag("security")]
[Tags("audit")]
public record TaggingUserPasswordChanged(string UserId, DateTimeOffset ChangedAt);

View C# snippet source on GitHub

When appending events, you can provide additional tags that will be merged with any static tags:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
public class TaggingUserLoginService(IEventLog eventLog)
{
public Task RecordLogin(EventSourceId eventSourceId) =>
// The event will end up with four tags: ["analytics", "user-action", "production", "critical"]
eventLog.Append(
eventSourceId,
new TaggingUserLoggedIn("user123", DateTimeOffset.UtcNow),
tags: ["production", "critical"]);
}

View C# snippet source on GitHub

In this example, the event will have four tags: ["analytics", "user-action", "production", "critical"].

A handler can read the combined static and dynamic tags from EventContext, which carries the event’s metadata:

using System.Linq;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reducers;
public record TaggingUserAnalytics(int LoginCount, int CriticalLoginCount);
public class TaggingUserAnalyticsReducer : IReducerFor<TaggingUserAnalytics>
{
public TaggingUserAnalytics LoggedIn(TaggingUserLoggedIn @event, TaggingUserAnalytics? current, EventContext context)
{
var analytics = current ?? new TaggingUserAnalytics(0, 0);
// Access tags from the event context
var isCritical = context.Tags.Any(tag => tag.Value == "critical");
return analytics with
{
LoginCount = analytics.LoginCount + 1,
CriticalLoginCount = analytics.CriticalLoginCount + (isCritical ? 1 : 0)
};
}
}

View C# snippet source on GitHub

A plain tag such as checkout or audit identifies a category. A named tag identifies which import batch, workflow run or checkout session produced an event. Keeping import-batch and 4711 separate lets you query the name with any value, or just the values you need, without parsing a string such as import-batch:4711.

You supply named tags with AppendWithNamedTags (or AppendManyWithNamedTags for a batch). Unlike plain tags, there is no attribute that declares them on an event type.

using Cratis.Chronicle;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
[EventType]
[Tag("catalog")]
public record TaggingCatalogItemImported(string Sku, string Title);
public class TaggingCatalogImportService(IEventLog eventLog)
{
public Task<AppendResult> Import(EventSourceId itemId, string sku, string title, string batchId) =>
// Plain tags: ["catalog", "import"]
// Named tags: import-batch = <batchId>, source-system = erp
eventLog.AppendWithNamedTags(
itemId,
new TaggingCatalogItemImported(sku, title),
namedTags: [new NamedTag("import-batch", batchId), new NamedTag("source-system", "erp")],
tags: ["import"]);
}

View C# snippet source on GitHub

Named tags and plain tags are stored separately. The [Tag] attribute and the tags values above still produce plain tags, and a named tag never appears in the plain tag list. Appending with Tags covers batch appends and how per-event and call-level named tags combine.

Names and values compare exactly, using ordinal, case-sensitive matching. Import-Batch and import-batch are different names. A name cannot be empty or whitespace; a value can be empty and can contain separators such as :, . or , because Chronicle does not parse it.

One name can have several values on the same event. Each distinct name/value pair is a separate tag, and exact duplicates are kept once.

Named tags come back on the EventContext next to the plain tags:

using System.Linq;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Reactors;
public class TaggingCatalogImportTracker : IReactor
{
public Task Imported(TaggingCatalogItemImported @event, EventContext context)
{
// Names and values compare exactly (ordinal, case-sensitive).
// A name can carry more than one value, so read every match.
var batchIds = context.NamedTags
.Where(tag => tag.Name.Value == "import-batch")
.Select(tag => tag.Value)
.ToArray();
Console.WriteLine($"{@event.Sku} imported in batch(es) {string.Join(", ", batchIds)}");
return Task.CompletedTask;
}
}

View C# snippet source on GitHub

The Chronicle server’s event sequence service answers named-tag queries through two operations: QueryEventsWithNamedTags returns a page of events, and SequenceHistogramWithNamedTags returns event counts over time. Each criterion takes one of three forms:

Criterion Matches events that carry
Name only The name, with any value
Name and a value Exactly that name and value
Name and a set of values The name with any of those values

An event matches when it satisfies any one of the criteria. The named-tag criteria then combine with every other filter on the query: event source, event source type, event stream type, correlation ID, event types, plain tags, and the occurred date range. A named-tag query needs at least one criterion, and a criterion with an empty set of values is rejected. Neither case turns into a query that returns everything.

MongoDB, SQL (SQLite, PostgreSQL, and SQL Server), and in-memory storage support named-tag appends and queries. SQL stores them in a companion table named __cratis_named_tags in each event-store namespace database. That name is reserved for Chronicle. If a conflicting table already exists, every event-sequence operation in that namespace fails with NamedTagsTableCollision on first access (migration is lazy) and continues to fail until the conflicting table is renamed.

Label an observer definition when you want to describe its domain, purpose or owner. These labels stay on the definition rather than becoming event metadata.

Apply one label to the observer:

using Cratis.Chronicle;
using Cratis.Chronicle.Reactors;
[Tag("Notifications")]
public class TaggingOrderConfirmationReactor : IReactor;

View C# snippet source on GitHub

Both [Tag] and [Tags] accept several labels:

using Cratis.Chronicle;
using Cratis.Chronicle.Reactors;
[Tag("Notifications", "Customer", "Email")]
public class TaggingCustomerNotificationReactor : IReactor;
// [Tags] (plural) is equivalent — use whichever reads more naturally
[Tags("Notifications", "Customer", "Email")]
public class TaggingCustomerNotificationReactorAlternate : IReactor;

View C# snippet source on GitHub

Repeat the attribute when separate lines make the labels easier to read:

using Cratis.Chronicle;
using Cratis.Chronicle.Reactors;
[Tag("Integration")]
[Tag("ExternalAPI")]
[Tag("Inventory")]
public class TaggingInventorySyncReactor : IReactor;

View C# snippet source on GitHub

Mixing [Tag] and [Tags] still produces one combined set of labels:

using Cratis.Chronicle;
using Cratis.Chronicle.Reactors;
[Tag("Notifications", "SMS")]
[Tags("Customer")]
public class TaggingSmsNotificationReactor : IReactor;
// Or mix single and multiple attributes the other way around
[Tag("Integration")]
[Tags("ExternalAPI", "Inventory")]
public class TaggingInventorySyncReactorMixed : IReactor;

View C# snippet source on GitHub

Put labels on a read-model definition to describe the data it holds:

using Cratis.Chronicle;
[Tag("Reporting", "Analytics")]
public record TaggingConceptsSalesReport(decimal TotalSales, int OrderCount);

View C# snippet source on GitHub

Choose stable names that describe a category someone will search for, and use the same spelling for related events or definitions. Dot notation, such as customer.registration and customer.profile, can make a naming convention readable; it does not turn a plain tag into a structured query.

Keep runtime identifiers in named tags. A batch number or session ID is a value to match, not a new category. Add labels only when they help a reader distinguish the event or definition.

The following examples organize plain tags by different responsibilities. Choose the categories that match how your team finds and maintains its events and definitions.

using Cratis.Chronicle;
[Tag("Sales")]
[Tag("Inventory")]
[Tag("Customer")]
[Tag("Shipping")]
public record TaggingByDomainExample;

View C# snippet source on GitHub

using Cratis.Chronicle;
[Tag("Analytics")]
[Tag("Reporting")]
[Tag("Integration")]
[Tag("Alerting")]
[Tag("Monitoring")]
[Tag("Automation")]
public record TaggingByPurposeExample;

View C# snippet source on GitHub

using Cratis.Chronicle;
[Tag("Notifications")]
[Tag("ExternalAPI")]
[Tag("MessageQueue")]
[Tag("FileSystem")]
public record TaggingByIntegrationTypeExample;

View C# snippet source on GitHub

using Cratis.Chronicle;
[Tag("Email")]
[Tag("SMS")]
[Tag("Push")]
[Tag("Webhook")]
public record TaggingByCommunicationChannelExample;

View C# snippet source on GitHub

using Cratis.Chronicle;
[Tag("Customer")]
[Tag("Operations")]
[Tag("Finance")]
[Tag("Support")]
[Tag("Executive")]
public record TaggingByStakeholderExample;

View C# snippet source on GitHub

using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
[EventType]
public record TaggingDynamicTagsEventOccurred(string Data);
public class TaggingDynamicTagsService(IEventLog eventLog)
{
public Task RecordProductionCritical(EventSourceId eventSourceId) =>
eventLog.Append(eventSourceId, new TaggingDynamicTagsEventOccurred("production issue"), tags: ["production", "critical"]);
public Task RecordDevelopmentTest(EventSourceId eventSourceId) =>
eventLog.Append(eventSourceId, new TaggingDynamicTagsEventOccurred("test run"), tags: ["development", "testing"]);
public Task RecordBatchMigration(EventSourceId eventSourceId) =>
eventLog.Append(eventSourceId, new TaggingDynamicTagsEventOccurred("batch migration"), tags: ["migration", "batch-process"]);
}

View C# snippet source on GitHub

To restrict which events a reducer or reactor receives, configure event-tag filtering. The filter reads tags stored with each event, not the labels on the observer definition.

Chronicle does not use observer labels to activate, select or group observers. For examples focused on reactor definitions, continue with tagging reactors. To carry a batch or session identifier into an append, see appending with named tags.