Read one Cratis Chronicle read model by key
Read a single Cratis Chronicle read model by key when you already know which instance the caller needs. An ordinary key lookup returns stored state for a materialized model and rebuilds a passive model from events. The model’s definition determines the path, so the same call can have different freshness and processing costs.
A materialized model has an observer that writes state to a sink, its storage destination. A passive model is computed on demand instead. Neither plain read protects a later append; use a decision-consistent read when a command must detect competing writes.
How it works
Section titled “How it works”The client sends the read model type and key to the kernel. The kernel resolves the read model’s definition and takes one of two paths:
- For a materialized read model, the kernel looks up the stored instance and releases compliance-protected values before returning it. There is no event-history replay, but the instance is only as current as its observer.
- For a passive read model, the read processes the relevant events through the projection or reducer that owns it. It does not wait for materialization, but the work grows with the history being processed.
The materialized path is also the only one that sees the whole picture for a projection that joins across event sources or resolves keys from other events. Replay walks one event source, so it cannot reconstruct state that was built from events belonging to a different key.
Reads during a replay
Section titled “Reads during a replay”For MongoDB, SQL, and in-memory sinks, a materialized lookup by key reads the primary container, not the shadow container a replay is rebuilding. You keep seeing the pre-replay state until promotion completes. A key absent from the primary returns the normal not-found result, even if the replay has already created it. Projection processing still reads its own replay state.
If a MongoDB lookup overlaps the promotion’s rename window and cannot distinguish a missing key from a replaced container, it retries up to three attempts with short pauses. If promotion still prevents a reliable answer, it fails explicitly rather than reporting a missing instance. A missing primary beside a promoting collection is logged as a warning; if a promotion was interrupted, the warning can persist until promotion is recovered. Retry the lookup after promotion completes.
The event-sequence sink has no shadow container: its primary lookup returns the latest durable publication, including facts already published during a replay.
Read by key
Section titled “Read by key”The read model type must already be registered by the client, either as a model-bound projection, a declarative projection, or the read model produced by a reducer.
AccountInfo? account = await eventStore.ReadModels.GetInstanceById<AccountInfo>(accountId);
if (account is not null){ Console.WriteLine($"{account.Name}: {account.Balance:C}");}val account = store.readModels.getInstanceByKey(AccountInfo::class, accountId)
if (account != null) { println("${account.name}: ${account.balance}")}import io.cratis.chronicle.IEventStore;import io.cratis.chronicle.java.BlockingEventStore;import io.cratis.chronicle.readModels.ReadModel;
@ReadModelrecord AccountInfo(String name, double balance) { AccountInfo() { this("", 0.0); }}
class ReadModelLookup { void printAccount(IEventStore store, String accountId) { var account = new BlockingEventStore(store) .getReadModels() .getInstanceByKey(AccountInfo.class, accountId);
if (account != null) { System.out.println(account.name() + ": " + account.balance()); } }}alias MyApp.ReadModels.AccountInfo
{:ok, account} = Chronicle.ReadModels.get_instance_by_id(AccountInfo, account_id)
if account do IO.puts("#{account.name}: #{account.balance}")end// Canonical read-by-key API. Use when the instance is known to exist.const account = await store.readModels.getInstanceById(AccountInfo, accountId);console.log(`${account.name}: ${account.balance}`);
// To detect a missing key, use the TypeScript nullable convenience API instead.const optionalAccount = await store.readModels.findInstanceById(AccountInfo, accountId);if (optionalAccount !== null) { console.log(`${optionalAccount.name}: ${optionalAccount.balance}`);}Use the read model’s key, not an arbitrary field value. If the caller needs to search by another field, see Querying Read Models before reading a collection and filtering it.
Read one stream instance
Section titled “Read one stream instance”For a model declaring [EventStream<TSource>(stream)], use the .NET overload GetInstanceById<T>(EventSourceId, EventStreamId). The model remains keyed by source ID; the second argument selects the stream instance, such as one account’s month of transactions. The declaration makes the model passive and supplies the event source type and stream type.
Events written without that source type are not included. A key-only read refuses with ReadModelRequiresStreamScope rather than mixing streams. This is still a plain read, with no append guard. See Read models scoped to one event stream for the monthly-limit example and the meaning of the default stream ID.
Missing instances
Section titled “Missing instances”Handle the client’s not-found result before using the instance. In .NET this is null. A missing instance is not, by itself, a projection failure, nor does it prove that the source has no events: a materialized model may not have caught up yet.
For a materialized model, a missing key can also mean that no instance was created or that one was removed. Chronicle does not fall back to replay when the stored lookup finds nothing, which would risk recreating a removed instance.
If the read model type itself is unknown, that is a configuration error, not a missing instance. The kernel rejects the lookup with an error naming the requested read model identifier. Use the registered identifier rather than its container name, and register the projection, reducer, or read model before querying it.
Choosing which you get
Section titled “Choosing which you get”Because the read model’s definition decides the path, choose when you design the read model rather than when you query it.
Leave the read model materialized — the default — when:
- The same data is read often, or read from lists, dashboards, and user interfaces.
- The event history for a key can grow long.
- A brief lag between an append and the read reflecting it is acceptable.
- The projection joins events across event sources.
Mark the read model passive when:
- A caller needs state computed from the source’s events rather than an observer’s stored result.
- You append an event and immediately need to read the state it creates.
- The event history for each key stays short.
- The read model is queried rarely relative to how often its events are appended.
If the state determines whether an append is allowed, choosing passive is only the freshness decision. Use decision-consistent reads to guard the append, or a constraint for a rule the kernel checks on every append. For stored reads that must include your own write, see Read model consistency.
Related topics
Section titled “Related topics”- Getting a Collection of Instances - Read or replay every instance of a read model
- Getting Snapshots - Inspect how one instance evolved over time
- Watching Read Models - React to read model changes as they happen
- Materialized Read Models - Page through sink-stored read models
- Passive projections - Keep a read model out of the sink so it is computed on demand