Cratis Chronicle sinks: choose an output target
A Cratis Chronicle sink receives the state produced by a projection or reducer and either stores it as a read model or publishes it as a new event. Use a read-model sink when queries need current state. Use an event-sequence sink when downstream consumers need events derived from that state.
MongoDB is the default read-model sink; SQL is another storage option. Graph projections write to graph sinks, described below. Publishing events is a separate target choice, with its own destination rules and replay behavior.
The SQL registration examples are specific to .NET hosting. The Kernel host registers the storage implementation; the client host selects the default read-model sink. These examples do not establish equivalent configuration APIs in other clients.
Target schemas and event publication
Section titled “Target schemas and event publication”The target schema describes the output’s shape; the sink determines what happens to it. A read-model target can keep the same schema when you switch its storage from MongoDB to SQL. An event target instead names the event type and generation that consumers will receive.
The Kernel represents target shape through IHaveTargetSchema. A ReadModelDefinition resolves its latest registered read-model schema; an EventTypeSchema resolves the schema for its explicitly registered event type and generation. Resolving a schema does not register a generation, select a sink, or authorize publication.
An event-sequence sink definition adds the exact registered event type and generation, the destination sequence, and whether the event type is public. Omitting the destination selects the outbox, never the event log. A definition whose sink type and event-target metadata disagree is rejected rather than falling back to a read model or the event log. Older kernels that do not recognize the EventSequence sink type reject it as an unknown sink.
What the event-sequence sink does
Section titled “What the event-sequence sink does”The event-sequence sink turns accumulated state into a new event. This accumulation is called a fold: the engine reads current state with FindOrDefault, applies the source event or batch, and hands the changeset to ApplyChanges. The sink publishes the result as the target event type, with the target key as the event source id. The source event’s subject, correlation, causation and identity travel with it, and a causation link identifies the producing observer and processing step.
The published event is also the durable state for its key. The sink reads back its own last publication as the next fold’s input, excluding events written by another observer or an ordinary append. State and publication commit in the same append, avoiding a separate state write that could succeed while publication fails.
Each processing step has a deterministic publication identity scoped to store, namespace, destination, observer, replay occurrence, target key and input position. In-memory, MongoDB and SQL storage use that identity to make the append idempotent: an identical retry returns the committed event instead of appending another instance. Reusing the identity with different content fails with EventPublicationConflict.
A rejected append reports a failed partition with the key, input position and reason. State removal also fails explicitly because deleting a read model cannot retract a published fact. A step that produces no change publishes nothing; its progress remains in the observer’s offset.
Replay and public history
Section titled “Replay and public history”Changing a projection mapping triggers replay: Chronicle runs through the source history again, starting with empty state and appending new event instances to the destination. This run is a new replay occurrence. Consumers receive new publications; replay does not overwrite, remove or replace older public history. Marking an event public does not change its schema-migration requirements.
The occurrence is part of the publication identity, so a replay can publish a new instance for the same source event while an identical retry inside that occurrence reuses the committed one. A restarted replay resumes the same occurrence, identified by its persisted replay context rather than its start time.
For reducers, changing batch boundaries on resume can give the same input position different output content. That step fails with a publication conflict instead of appending a duplicate; replay identity does not resolve that batching difference.
Publishing from a .NET client
Section titled “Publishing from a .NET client”Point IProjectionFor<T> or IReducerFor<T> at an [EventType] record instead of a read model, and Chronicle publishes the projected state as that event.
For example, a [Public] OrderShipped event record can be the generic argument of an IProjectionFor<OrderShipped> whose definition builds it From<OrderPacked>; the projection’s output is appended to the outbox.
Registration sends the event type, its schema and an EventSequence sink instead of registering a read-model collection. The destination is the outbox unless the target event type carries [PublishTo("sequence")]. Put that attribute on the target, not the projection or reducer: [EventSequence] selects the sequence an observer reads from, which is a separate choice.
An outbox target must be public through [Public] or an [EventStore] declaration naming the connected event store. A private outbox target fails registration in the client with PrivateEventTypeCannotBePublishedToOutbox; the Kernel independently checks the declaration with PrivateEventCannotBePublishedToOutbox. The Kernel also enforces visibility on every append; see Public events. Selecting the event log as the destination fails with EventLogIsNotAPublicationTarget.
Reactors can still append to the outbox through IEventStore.GetEventSequence(EventSequenceId.Outbox); they do not need an event target to do so.
The projection declaration projection OrderShippedPublisher => OrderShipped can name a registered event target. The separate event ... to outbox syntax is not implemented. Use the registered target’s sink configuration to select its destination.
Compliance decision
Section titled “Compliance decision”An event target whose schema carries compliance metadata ([PII]) is rejected at sink creation with EventSequenceTargetCarriesCompliance. The published event becomes the next fold’s input, so protection and release must account for both publication and reuse. This sink does not support that combination.
Pipeline bookkeeping is separate from event content. The sink strips initialization flags, watermarks and subject tracking before publishing.
Current limits
Section titled “Current limits”Only one projection or reducer may publish a given event type to a given destination sequence, across generations. Registration rejects a second publisher with EventPublisherConflict. Use distinct target event types or destinations for independent folds.
Event targets do not provide read-model enumeration, observation, or revert-container browsing. The sink also has no child-key reverse lookup, so child lookups that depend on it cannot find a root key. To consume the output, read or observe the destination event sequence instead of treating the target as a read-model collection.
Event-target preview, code generators emitting IProjectionFor<TEvent>, and Workbench authoring for event targets are not implemented. The sink exposes no read-model instances for the Workbench to list. A schema contract or a compiled target name does not provide those authoring surfaces.
MongoDB Sink
Section titled “MongoDB Sink”The default sink. Read model instances are stored as MongoDB documents, one document per instance. The container name defaults to the read model type name (camelCase), controlled by the INamingPolicy in use.
No separate sink selection is needed when your Kernel is configured with MongoDB storage.
What a MongoDB convention pack reaches
Section titled “What a MongoDB convention pack reaches”A MongoDB convention pack configures how the MongoDB driver maps documents to your types. It does not configure how Chronicle returns a read model. This distinction matters if a custom serializer or property rename works in a direct database query but not in a command receiving a Chronicle read model.
Whether you provide a pack through Arc’s ICanProvideMongoDBConventionPacks or call ConventionRegistry.Register yourself, it enters the driver’s global convention registry and configures its class maps:
| Path a read model takes | Does the convention pack apply |
|---|---|
Your own IMongoCollection<T> query |
Yes — the driver builds the instance from a class map |
| Chronicle’s read model APIs — by key, materialized, snapshots, watching | No |
A read model injected into a command’s validator, Provide(), or Handle() |
No |
| The document the sink writes | No |
Chronicle returns read models as JSON and materializes them with System.Text.Json, without consulting BsonClassMap. Arc’s Chronicle command-parameter resolver uses the same read-model API, so MongoDB conventions such as IgnoreExtraElements do not affect that instance. The sink writes projected state rather than using a class map of your type; a convention pack does not change its stored document either.
Use the convention registration in Get started when your own driver queries need to map a type onto Chronicle’s stored element names.
SQL Sink
Section titled “SQL Sink”The SQL sink gives each read model type its own table, with columns derived from the read model’s schema:
- Each scalar property becomes a typed column, and the read model key becomes the table’s primary key.
- Each collection and nested object becomes a single JSON column —
jsonbon PostgreSQL,nvarchar(max)on SQL Server, andTEXTon SQLite.
A composite key uses a legacy primary-key value with its parts joined by _. When enumerating instances, the sink reconstructs the key object only when that value is unambiguous and matches the declared types; otherwise the instance is returned without its key and the Kernel logs a warning. The sink also attempts to store an encoded key in an internal shadow column for exact composite-key lookups. That encoding does not replace the primary-key format, which can still collide as tracked in #5335.
A read model whose identifier is spelled ID (or any casing other than Id or id) gets a key column spelled exactly like the property. Tables created by earlier releases keep the synthesized Id key they were created with, and the sink reads their layout once, when it first uses the table.
Updates from the projection engine touch only the columns that changed. Tables are created automatically on first use via IReadModelMigrator. You do not need to write migrations by hand.
Declared top-level scalar indexes are ensured idempotently. Populated primary tables use background
online builds (CONCURRENTLY on PostgreSQL and ONLINE = ON on SQL Server); empty and replay-shadow
tables can build synchronously. Per-table locks serialize builders across kernels without waiting
on a competing builder. SQL Server uses online builds on supported editions (Enterprise, Azure SQL,
and Managed Instance); other editions, or error 1712, fall back to a normal background build that
can block database writes while it runs. Other build failures are logged.
Ordinary activation does not prune undeclared indexes. When an already-cached read-model definition
changes, reconciliation removes undeclared chronicle_idx_* indexes, preserving custom indexes.
SQL Server indexed strings use an explicit MaxLength, StringLength, or Length bound up to 850 characters,
or 450 characters if the indexed property has no bound. Unindexed, unbounded strings remain
NVARCHAR(MAX); larger declared bounds remain unbounded and receive an index diagnostic. This
mapping does not change event schemas, read-model generations, or request a replay. Existing SQL
column types are not changed automatically: explicitly replay the model to apply a new column type.
Writes exceeding a bounded column’s length fail rather than truncate the value, causing the projection’s
partition to fail. SQL Server string comparisons use the database collation (commonly case-insensitive);
PostgreSQL btree keys remain subject to its approximately 2.7 KB entry limit.
Join lookups and child removals select candidate rows in SQL before materializing documents. JSON predicates deliberately admit a superset of matches; Chronicle’s existing path walker and value comparison still determine which rows and children are actually updated.
With SQL configured as the Kernel storage provider, you can store both events and read models without a MongoDB instance.
Null nested objects
Section titled “Null nested objects”When a projection sets a nested object property to null (for example, an event property mapped
to it carries null), the SQL sink stores SQL NULL in that object’s JSON column, and reads return
the property as null, the same as MongoDB. Removing a nested object with RemovedWith works
differently: it stores the JSON literal null in the column, which also reads back as null. A later change to one of the
object’s properties creates the object again. An empty object is still stored as {} and read back
as an empty object. Collection columns keep their existing storage.
Kernels before this change stored a null nested object as {}. Keep the following in mind when you upgrade:
- Existing rows are not converted. A stored
{}can mean either an empty object or anullwritten by an older kernel, and Chronicle cannot tell them apart, so it never rewrites them in bulk. To correct a read model, replay it once every kernel writing to it runs the new version; this needs the event history that produced the rows. - Older kernels read the new
NULLvalues correctly. Until every kernel in a cluster is upgraded, an older kernel still writes{}, and rolling back to an older version brings those writes back. - If you query the tables directly,
column IS NULLmatches only objects set tonullby the new kernel on SQLite, PostgreSQL and SQL Server alike. It does not match{}, and it does not match a JSONnullliteral ('null'::jsonbon PostgreSQL, the textnullon SQL Server and SQLite). To match{}usecolumn = '{}'::jsonbon PostgreSQL andcolumn = '{}'on SQL Server and SQLite.
Decimal columns
Section titled “Decimal columns”Decimal-formatted read-model properties use NUMERIC on PostgreSQL, DECIMAL(38,18) on SQL Server, and invariant decimal text in SQLite TEXT columns. MongoDB stores them as Decimal128. Double and float properties keep their floating-point storage types.
SQLite sink paging sorts decimal keys numerically before applying page limits, with the original
key text as a stable tie-breaker. Scalar decimal joins narrow candidates by exact canonical equality,
including equal values with different scales. Declared decimal indexes target the registered ordering
column, ascending or descending, and a top-level decimal inside a composite [CompositeIndex] is keyed by that column
too, so both order and range-scan numerically. The previous Chronicle non-unique TEXT index is replaced on upgrade; custom and
unique indexes are preserved. Decimals nested inside JSON objects are not covered yet.
These operations use the SQL shadow-column contract.
Original decimal digits and scale remain unchanged and internal columns never appear in documents.
Ad-hoc SQL over the original TEXT column still compares lexicographically, not numerically. Use the registered ordering column for numeric sorting, and an encoded decimal comparison key for equality or ranges, not an ordinary decimal string. Arbitrary EF decimal expressions are not translated to this contract automatically. Existing TEXT tables gain ordering support without replay or rewriting stored values. Legacy REAL-affinity tables still require replay for exact values and dependable numeric comparisons.
Existing SQL column types are not altered in place. Replay the read model to create a table with the new mapping. SQL Server values are rounded to scale 18 with midpoints rounded away from zero; only integer parts exceeding 20 digits are refused. Existing DECIMAL(18,2) columns round further; see Exact decimal values for limits and upgrade requirements.
Enabling the SQL Sink
Section titled “Enabling the SQL Sink”After registering SQL storage in the Kernel host as described under Prerequisites, set DefaultSinkTypeId in the .NET client host’s ChronicleOptions:
using Microsoft.Extensions.Hosting;using Cratis.Chronicle.Sinks;
public static class SinksSqlRegistration{ public static void Configure(string[] args) { var builder = Host.CreateApplicationBuilder(args);
builder.AddCratisChronicle(configureOptions: options => { options.DefaultSinkTypeId = WellKnownSinkTypes.SQL; }); }}import io.cratis.chronicle.ChronicleOptionsimport io.cratis.chronicle.connection.ChronicleConnectionStringimport io.cratis.chronicle.sinks.WellKnownSinkTypes
fun optionsWithSqlSinkEnabled(): ChronicleOptions = ChronicleOptions( connectionString = ChronicleConnectionString.parse("chronicle://localhost:35000"), defaultSinkTypeId = WellKnownSinkTypes.SQL)import io.cratis.chronicle.ChronicleOptions;import io.cratis.chronicle.connection.ChronicleConnectionString;import io.cratis.chronicle.sinks.WellKnownSinkTypes;
class SinksIndexEnableSqlSink { ChronicleOptions configure() { return new ChronicleOptions( ChronicleConnectionString.Companion.parse("chronicle://localhost:35000"), "Unknown", WellKnownSinkTypes.SQL); }}defmodule MyApp.Application do use Application
@impl true def start(_type, _args) do children = [ {Cratis.Chronicle.Client, connection_string: "chronicle://localhost:35000", event_store: "my-store", default_sink_type_id: :sql, otp_app: :my_app} ]
Supervisor.start_link(children, strategy: :one_for_one, name: MyApp.Supervisor) endendimport { ChronicleOptions, WellKnownSinks } from '@cratis/chronicle';
function createSinksSqlOptions(): ChronicleOptions { return ChronicleOptions.fromConnectionString('chronicle://localhost:35000', { defaultSinkTypeId: WellKnownSinks.SQL });}Or in appsettings.json:
{ "Cratis": { "Chronicle": { "DefaultSinkTypeId": "SQL" } }}Prerequisites
Section titled “Prerequisites”The SQL sink is provided by the Cratis.Chronicle.Storage.Sql NuGet package. Add it to your Kernel host project and register it in the IChronicleBuilder:
siloBuilder.AddChronicleToSilo(chronicle =>{ chronicle.WithSql(options);});Kotlin does not support this workflow yet.Java does not support this workflow yet.Elixir does not support this workflow yet.TypeScript does not support this workflow yet.Continue with the hosting configuration for the full Kernel setup.
Graph sinks
Section titled “Graph sinks”A graph projection writes nodes and edges instead of read model instances. It uses a graph sink, which implements IGraphSink instead of ISink. The graph sink types are:
| Sink type | Description |
|---|---|
InMemoryGraph |
Keeps the graph in memory. It is the executable reference for the graph sink semantics: operations, watermarks and replay. Use it for development and tests. |
Neo4j |
The default graph sink type, DefaultGraphSinkTypeId. It stores the graph in Neo4j, with a database per event store and namespace. See Neo4j graph sink. A graph sink type that is not available fails with UnknownSink. |
A Kernel can serve several Neo4j servers through named sinks, one graph in each.
Named sinks
Section titled “Named sinks”By default every read model is stored through the Kernel’s own storage connection, and every graph in the Kernel’s neo4j server. A named sink is a sink type with a connection of its own, configured in the Kernel’s sinks section. With named sinks a Kernel can store one read model in MongoDB and another in PostgreSQL, keep read models on a different server than the events, or project graphs into more than one Neo4j server.
Two implicit defaults always exist, so nothing changes for a Kernel without a sinks section:
- the default sink for read models: the client’s
DefaultSinkTypeIdon the Kernel’sstorageconnection; - the default sink for graphs:
Neo4jon the Kernel’sneo4jsection.
sinks.readModels and sinks.graphs replace those defaults with a named sink. The configuration’s type decides how a read model is stored: a read model naming a SQL sink is stored in SQL even when the client’s DefaultSinkTypeId is MongoDB. The Kernel’s named sinks do not depend on its event storage: a Kernel on MongoDB can store read models in PostgreSQL, and a Kernel on SQL can store read models in MongoDB.
Choosing a named sink in the client
Section titled “Choosing a named sink in the client”Put [Sink] on a read model type to store it in a named sink. It works for model-bound read models and for read models filled by a projection or a reducer:
using Cratis.Chronicle.Sinks;
[Sink("reporting")]public record OrderTotals(string CustomerId, decimal Total);Put it on a graph projection, or on the nodes and edges of a model-bound graph, to choose the sink of a graph:
using Cratis.Chronicle.Projections.Graphs;using Cratis.Chronicle.Sinks;
[Graph("People")][Sink("people")]public class PeopleGraph : IGraphProjection{ public void Define(IGraphProjectionBuilder builder) { // Nodes and edges of the graph. }}All nodes and edges of a model-bound graph must name the same sink; a graph whose elements name different sinks fails to register with GraphHasConflictingSinks.
To name a sink for everything without [Sink], set DefaultSinkName and DefaultGraphSinkName in the client options. Both are empty by default, which leaves the choice to the Kernel:
using Microsoft.Extensions.Hosting;
public static class SinksDefaultSinkName{ public static void Configure(string[] args) { var builder = Host.CreateApplicationBuilder(args);
builder.AddCratisChronicle(configureOptions: options => { options.DefaultSinkName = "reporting"; options.DefaultGraphSinkName = "people"; }); }}A passive read model has no sink, so [Passive] cannot be combined with [Sink]; the analyzer reports it as CHR0069. Event targets ignore sink names, because they publish to an event sequence.
Moving a read model to another sink - a different [Sink], client default or Kernel default - rebuilds it there: the Kernel replays the projections and reducers that fill it into the new sink, as it does when their definitions change. The observers.definitionEvolution policy applies, so a Manual policy recommends the replay instead. A read model whose sink is unchanged is not replayed.
The Kernel refuses a read model that names a sink it has no configuration for, with UnknownSinkName naming the read model and the sink. A read model naming a graph sink, or a graph naming a read-model sink, is refused with SinkConfigurationIsForAnotherKindOfReadModel.
Choosing a Sink
Section titled “Choosing a Sink”First decide whether consumers need current state or new events. For current state, choose a storage sink to match the database your application will query. For events, choose an event target and account for its publication and replay rules.
| Output you need | Sink | What to plan for |
|---|---|---|
| Read-model documents queried with MongoDB tooling | MongoDB | MongoDB storage and driver mapping for direct queries |
| Read-model rows queried with SQL tooling | SQL | PostgreSQL, SQL Server or SQLite storage and the column mappings above |
| New events derived from accumulated state | EventSequence | A registered event target, an allowed destination and consumers that account for replay publications |
DefaultSinkTypeId applies to all materialized read models registered by the client. To store some read models elsewhere, configure named sinks in the Kernel and choose them with [Sink]. Event targets use their explicit EventSequence sink instead of these defaults.
Once you have chosen read-model storage, follow the querying guide to retrieve state. For event output, use Public events to understand visibility before selecting an outbox target.