Eventual Consistency in Projections
Chronicle’s materialized projections are eventually consistent: a successful event append stores the event, but the read model may still show the previous state. Design the query and the screen for that gap, or explicitly wait when a caller needs to read its own change. There is no fixed catch-up time.
Understanding Eventual Consistency
Section titled “Understanding Eventual Consistency”An append and a read-model update are separate work. Chronicle stores the event before reporting a successful append. The projection processes it asynchronously and writes the resulting state to its sink. Processing may finish before or after the caller receives the append result; the append does not wait for it.
For example, creating a book can succeed while a query for that book still returns no instance. Show that the command was accepted without claiming the query result is already available.
Asynchronous Processing
Section titled “Asynchronous Processing”Materialized projections consume stored events independently of the append call. The same separation applies to reducers and reactors that run as observers.
Processing Pipeline
Section titled “Processing Pipeline”Benefits of Asynchronous Processing
Section titled “Benefits of Asynchronous Processing”A slow or failed projection does not undo an event already stored in the log. It does delay the view that depends on that projection. This lets appends proceed without waiting for each view, while making observer progress and failures part of operating the application.
Consistency Guarantees
Section titled “Consistency Guarantees”What Chronicle Guarantees
Section titled “What Chronicle Guarantees”Observers process events in order within a partition and retry failed processing. A retry can deliver an event again, so do not treat processing as exactly once. If retries are exhausted, a failed partition needs attention before its read model can catch up. See observer retry configuration.
What Chronicle Does NOT Guarantee
Section titled “What Chronicle Does NOT Guarantee”A successful append does not guarantee an updated materialized view, a maximum delay, or a common position across different projections. Do not rely on processing order across independent partitions. Replaying a projection also takes time; registration or a replay request is not proof that its container is ready for queries.
Handling Eventual Consistency
Section titled “Handling Eventual Consistency”1. Design for Asynchronous Updates
Section titled “1. Design for Asynchronous Updates”Return the append outcome or the new book’s identifier, then let the query show progress toward the
updated view. In this example, the immediate query in CreateBookAndReturn can run before the
projection has created the book:
using Cratis.Chronicle.Events;using Cratis.Chronicle.EventSequences;using Cratis.Chronicle.ReadModels;
[EventType]public record EcBookCreated(string Title, string Author);
public record EcBookInventory(Guid Id, string Title, string Author);
public class EcBookService(IEventLog eventLog, IReadModels readModels){ // Good — fire and forget: don't wait for the projection before returning public async Task<EventSourceId> CreateBook(string title, string author) { var bookId = EventSourceId.New(); await eventLog.Append(bookId, new EcBookCreated(title, author)); return bookId; }
// Problematic — expecting immediate consistency public async Task<EcBookInventory> CreateBookAndReturn(string title, string author) { var bookId = EventSourceId.New(); await eventLog.Append(bookId, new EcBookCreated(title, author));
// The projection may not have run yet — this can return a stale or default instance return await readModels.GetInstanceById<EcBookInventory>(bookId); }}import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.events.EventTypeimport java.util.UUID
@EventTypedata class EcBookCreated(val title: String, val author: String)
data class EcBookInventory(val id: String = "", val title: String = "", val author: String = "")
class EcBookService(private val store: IEventStore) { // Good — fire and forget: don't wait for the projection before returning suspend fun createBook(title: String, author: String): String { val bookId = UUID.randomUUID().toString() store.eventLog.append(bookId, EcBookCreated(title, author)) return bookId }
// Problematic — expecting immediate consistency suspend fun createBookAndReturn(title: String, author: String): EcBookInventory? { val bookId = UUID.randomUUID().toString() store.eventLog.append(bookId, EcBookCreated(title, author))
// The projection may not have run yet — this can return null or a stale instance return store.readModels.getInstanceByKey(EcBookInventory::class, bookId) }}import io.cratis.chronicle.IEventStore;import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.java.BlockingEventStore;import java.util.UUID;
@EventTyperecord EcBookCreated(String title, String author) {}
record EcBookInventory(String id, String title, String author) { EcBookInventory() { this("", "", ""); }}
class EcBookService { private final BlockingEventStore store;
EcBookService(IEventStore store) { this.store = new BlockingEventStore(store); }
// Good — fire and forget: don't wait for the projection before returning String createBook(String title, String author) { var bookId = UUID.randomUUID().toString();
store.getEventLog().append(bookId, new EcBookCreated(title, author));
return bookId; }
// Problematic — expecting immediate consistency EcBookInventory createBookAndReturn(String title, String author) { var bookId = createBook(title, author);
// The projection may not have run yet — this can return null or a stale instance return store.getReadModels().getInstanceByKey(EcBookInventory.class, bookId); }}defmodule MyApp.Events.EcBookCreated do use Chronicle.Events.EventType, id: "ec-book-created"
defstruct [:title, :author]end
defmodule MyApp.ReadModels.EcBookInventory do use Chronicle.ReadModels.ReadModel
defstruct id: "", title: "", author: ""end
defmodule MyApp.EcBookService do alias MyApp.Events.EcBookCreated alias MyApp.ReadModels.EcBookInventory
# Good — fire and forget: don't wait for the projection before returning def create_book(book_id, title, author) do Chronicle.append(book_id, %EcBookCreated{title: title, author: author}) :ok end
# Problematic — expecting immediate consistency def create_book_and_return(book_id, title, author) do create_book(book_id, title, author)
# The projection may not have run yet — this can return nil or a stale instance Chronicle.read_model(EcBookInventory, book_id) endendimport { eventType, Guid, IEventStore } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class EcBookCreated { @field(String) readonly title: string; @field(String) readonly author: string;
constructor(title: string, author: string) { this.title = title; this.author = author; }}
class EcBookInventory { id: string = ''; title: string = ''; author: string = '';}
class EcBookService { constructor(private readonly store: IEventStore) {}
// Good — fire and forget: don't wait for the projection before returning async createBook(title: string, author: string): Promise<string> { const bookId = Guid.create().toString(); await this.store.eventLog.append(bookId, new EcBookCreated(title, author)); return bookId; }
// Problematic — expecting immediate consistency async createBookAndReturn(title: string, author: string): Promise<EcBookInventory | null> { const bookId = Guid.create().toString(); await this.store.eventLog.append(bookId, new EcBookCreated(title, author));
// The projection may not have run yet — this can return null return this.store.readModels.findInstanceById(EcBookInventory, bookId); }}2. Watch Projection Changes
Section titled “2. Watch Projection Changes”In the .NET client, .Watch<TReadModel>() emits read-model changes so the screen can update when the
projection processes the event. Subscribe before appending and keep the subscription alive for as
long as the screen needs updates:
using System.Reactive.Linq;using Cratis.Chronicle.Events;using Cratis.Chronicle.EventSequences;using Cratis.Chronicle.ReadModels;
[EventType]public record EcWatchBookCreated(string Title, string Author);
public record EcWatchBookInventory(Guid Id, string Title, string Author);
public class EcWatchBookService(IEventLog eventLog, IReadModels readModels){ public IObservable<ReadModelChangeset<EcWatchBookInventory>> WatchBookChanges() => readModels.Watch<EcWatchBookInventory>();
public async Task CreateBookAndWatch(string title, string author) { var bookId = EventSourceId.New();
// Subscribe before appending so the update is observed once the projection catches up using var subscription = readModels.Watch<EcWatchBookInventory>() .Where(changeset => changeset.ModelKey.Value == bookId.Value) .Subscribe(changeset => Console.WriteLine($"Book projection updated: {changeset.ReadModel?.Title}"));
await eventLog.Append(bookId, new EcWatchBookCreated(title, author)); }}import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.readModels.ReadModelimport kotlinx.coroutines.flow.collect
@ReadModeldata class WatchAccountInfo(val name: String = "", val balance: Double = 0.0)
suspend fun watchAccountChanges(store: IEventStore) { store.readModels.watch(WatchAccountInfo::class).collect { changeset -> val label = if (changeset.removed) "removed" else "${changeset.readModel?.name}: ${changeset.readModel?.balance}" println("${changeset.modelKey} ${changeset.changeType}: $label") }}import io.cratis.chronicle.EventStore;import io.cratis.chronicle.readModels.ReadModel;
import io.cratis.chronicle.java.ReadModelsJavaBridge;import kotlinx.coroutines.Job;
@ReadModelclass WatchAccountInfo { private String name = ""; private double balance = 0.0;
public WatchAccountInfo() {}
public String getName() { return name; } public void setName(String name) { this.name = name; }
public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; }}
class ProjectionsEventualConsistencyWatch { // Cancel the returned job when observation ends. Job watchAccountChanges(EventStore store) { return ReadModelsJavaBridge.watch(store.getReadModels(), WatchAccountInfo.class, changeset -> { WatchAccountInfo model = changeset.getReadModel(); String label = changeset.getRemoved() || model == null ? "removed" : model.getName() + ": " + model.getBalance(); System.out.println(changeset.getModelKey() + " " + changeset.getChangeType() + ": " + label); }, error -> System.err.println("Watch failed: " + error)); }}defmodule MyApp.Events.EcWatchBookCreated do use Chronicle.Events.EventType, id: "ec-watch-book-created"
defstruct [:title, :author]end
defmodule MyApp.ReadModels.EcWatchBookInventory do use Chronicle.ReadModels.ReadModel
alias MyApp.Events.EcWatchBookCreated
defstruct [:id, :title, :author]
from EcWatchBookCreated, set: [id: :event_source_id, title: :title, author: :author]end
defmodule MyApp.EcWatchBookService do alias Chronicle.ReadModels alias MyApp.Events.EcWatchBookCreated alias MyApp.ReadModels.EcWatchBookInventory
# Subscribes the calling process to live changesets for every instance of # EcWatchBookInventory. Chronicle.ReadModels.watch/2 is Elixir's equivalent # of the C#/TypeScript clients' Watch<TReadModel>(): instead of an # IObservable, the calling process receives # {:chronicle_read_model_changed, EcWatchBookInventory, changeset} messages # until unwatch/1 is called. def watch_book_changes, do: ReadModels.watch(EcWatchBookInventory)
def create_book_and_watch(title, author) do book_id = Base.encode16(:crypto.strong_rand_bytes(8), case: :lower)
# Subscribe before appending so the update is observed once the # projection catches up. {:ok, watcher} = watch_book_changes()
:ok = Chronicle.append(book_id, %EcWatchBookCreated{title: title, author: author})
receive do {:chronicle_read_model_changed, EcWatchBookInventory, %{model_key: ^book_id} = changeset} -> IO.puts("Book projection updated: #{changeset.read_model && changeset.read_model.title}") after 5_000 -> :timeout end
ReadModels.unwatch(watcher) endendimport { eventType, Guid, IEventStore } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class EcWatchBookCreated { @field(String) readonly title: string; @field(String) readonly author: string;
constructor(title: string, author: string) { this.title = title; this.author = author; }}
class EcWatchBookInventory { id: string = ''; title: string = ''; author: string = '';}
class EcWatchBookService { constructor(private readonly store: IEventStore) {}
watchBookChanges() { return this.store.readModels.watch(EcWatchBookInventory); }
async createBookAndWatch(title: string, author: string): Promise<void> { const bookId = Guid.create().toString();
const watcher = this.store.readModels.createWatcher(EcWatchBookInventory); try { // Wait for the kernel's acknowledgment before appending to avoid missing the update. await watcher.subscribed; await this.store.eventLog.append(bookId, new EcWatchBookCreated(title, author)); for await (const changeset of watcher) { if (changeset.key === bookId) { console.log(`Book projection updated: ${changeset.readModel.title}`); break; } } } finally { watcher.dispose(); } }}watchBookChanges() keeps the lazy, pull-based async-iterable API: the stream starts on the first next(), with no client-side buffer or overflow limit. Use createWatcher() when you need to await subscription readiness before appending. Both methods propagate transport errors by default so callers can refresh and re-watch. Only createWatcher() supports resumption through resume: true or a registered onResubscribed callback. Its slow consumers get backpressure after acknowledgment unless they explicitly set maxBuffered; before each acknowledgment, its default 1,024-change limit can fail readiness rather than let backpressure hide the acknowledgment.
The example scopes the subscription to a method. In an application, let the screen or service own its lifetime; returning from that method disposes the subscription and does not wait for an update.
3. Monitor Database Changes
Section titled “3. Monitor Database Changes”Use Chronicle’s watch API for projection changes. If another application writes directly to the sink, check that database’s notification mechanism separately; the projection watch API is not a general feed of external database writes. Polling a query can refresh a screen, but it does not protect a business decision from concurrent changes.
4. Use Command-Query Segregation
Section titled “4. Use Command-Query Segregation”Keep the command’s append outcome distinct from the query’s projected state. Separating those contracts makes the lag visible instead of hiding it behind a command that promises a current view:
using Cratis.Chronicle.Events;using Cratis.Chronicle.EventSequences;using Cratis.Chronicle.ReadModels;
[EventType]public record EcCqsBookCreated(string Title);
public record EcCqsBook(Guid Id, string Title);
// Commands — fire and forget, never return projected statepublic class EcCqsBookCommandHandler(IEventLog eventLog){ public Task Create(EventSourceId bookId, string title) => eventLog.Append(bookId, new EcCqsBookCreated(title));}
// Queries — always read from projectionspublic class EcCqsBookQueryHandler(IReadModels readModels){ public Task<EcCqsBook> GetBook(EventSourceId bookId) => readModels.GetInstanceById<EcCqsBook>(bookId);}import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.events.EventType
@EventTypedata class EcCqsBookCreated(val title: String)
data class EcCqsBook(val id: String = "", val title: String = "")
// Commands — fire and forget, never return projected stateclass EcCqsBookCommandHandler(private val store: IEventStore) { suspend fun create(bookId: String, title: String) { store.eventLog.append(bookId, EcCqsBookCreated(title)) }}
// Queries — always read from projectionsclass EcCqsBookQueryHandler(private val store: IEventStore) { suspend fun getBook(bookId: String): EcCqsBook? = store.readModels.getInstanceByKey(EcCqsBook::class, bookId)}import io.cratis.chronicle.IEventStore;import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.java.BlockingEventStore;
@EventTyperecord EcCqsBookCreated(String title) {}
record EcCqsBook(String id, String title) { EcCqsBook() { this("", ""); }}
// Commands — fire and forget, never return projected stateclass EcCqsBookCommandHandler { private final BlockingEventStore store;
EcCqsBookCommandHandler(IEventStore store) { this.store = new BlockingEventStore(store); }
void create(String bookId, String title) { store.getEventLog().append(bookId, new EcCqsBookCreated(title)); }}
// Queries — always read from projectionsclass EcCqsBookQueryHandler { private final BlockingEventStore store;
EcCqsBookQueryHandler(IEventStore store) { this.store = new BlockingEventStore(store); }
EcCqsBook getBook(String bookId) { return store.getReadModels().getInstanceByKey(EcCqsBook.class, bookId); }}defmodule MyApp.Events.EcCqsBookCreated do use Chronicle.Events.EventType, id: "ec-cqs-book-created"
defstruct [:title]end
defmodule MyApp.ReadModels.EcCqsBook do use Chronicle.ReadModels.ReadModel
defstruct id: "", title: ""end
# Commands — fire and forget, never return projected statedefmodule MyApp.EcCqsBookCommandHandler do alias MyApp.Events.EcCqsBookCreated
def create(book_id, title) do Chronicle.append(book_id, %EcCqsBookCreated{title: title}) endend
# Queries — always read from projectionsdefmodule MyApp.EcCqsBookQueryHandler do alias MyApp.ReadModels.EcCqsBook
def get_book(book_id) do Chronicle.read_model(EcCqsBook, book_id) endendimport { eventType, IEventStore } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class EcCqsBookCreated { @field(String) readonly title: string;
constructor(title: string) { this.title = title; }}
class EcCqsBook { id: string = ''; title: string = '';}
// Commands — fire and forget, never return projected stateclass EcCqsBookCommandHandler { constructor(private readonly store: IEventStore) {}
create(bookId: string, title: string): Promise<void> { return this.store.eventLog.append(bookId, new EcCqsBookCreated(title)).then(() => undefined); }}
// Queries — always read from projectionsclass EcCqsBookQueryHandler { constructor(private readonly store: IEventStore) {}
getBook(bookId: string): Promise<EcCqsBook | null> { return this.store.readModels.findInstanceById(EcCqsBook, bookId); }}Best Practices
Section titled “Best Practices”1. Design for Eventual Consistency
Section titled “1. Design for Eventual Consistency”If a caller must read its own append from a materialized view, use the .NET append result’s
WaitForCompletion() and check its success, timeout, and failures before querying. Waiting does not
make the append and query atomic. Observing appends
explains which observers the wait covers.
For an event-source-keyed instance, a passive projection can compute the answer from history at read time instead. Neither a fresh read nor waiting after an append protects a rule checked before it: use constraints or decision reads for that concurrency boundary.
2. Test Eventual Consistency Scenarios
Section titled “2. Test Eventual Consistency Scenarios”Exercise the screen while a read model is missing or stale, and test what happens when an observer fails or a wait times out. Include a replay in operational checks: a newly registered definition can be valid while its historical rebuild is still running.
Summary
Section titled “Summary”Choose read-model consistency based on what the caller needs to know. For a screen, an accepted command followed by a watched update may be enough. For a response that needs the new stored view, wait and handle failure. Before deploying changed mappings, review the registration lifecycle so you also account for rebuilding existing data.