Page Through Chronicle Materialized Read Models
Chronicle’s Materialized API reads pages of read model instances from their configured storage without replaying events. Use it when a list or data grid needs a window of current stored state rather than every instance at once.
That stored state is called materialized because a projection or reducer has already built it and written it to a sink, Chronicle’s read model storage. It is eventually consistent: an appended event may not have reached the sink when you read. Passive read models have no materialized sink.
Client APIs express paging differently. Elixir’s Chronicle.ReadModels.query/2 uses page/page-size. TypeScript uses skip/take and an AsyncIterable for page observations; Kotlin uses skip/take and Flow. Java exposes blocking reads and callback or publisher observations through ReadModelsJavaBridge. Follow your example’s client tab; the named paging concepts and ASP.NET endpoint below are .NET host code.
What Materialized Access Covers
Section titled “What Materialized Access Covers”GetInstances reads a window once; ObserveInstances keeps sending replacement snapshots of that window. Both use the registered read model’s sink, so you do not need to open its MongoDB collection or SQL table just to page through instances.
The window limits what your consumer receives, but it is not a guarantee about query cost. In .NET, an offset that is not a multiple of the page size can fetch a larger covering range and slice it locally. InstanceCount.Unlimited explicitly requests all instances. Choose a bounded page size for a list that may grow.
Accessing the API
Section titled “Accessing the API”In .NET, reach IMaterializedReadModels through IReadModels.Materialized. The read model must be known to a projection or reducer in the client and have stored instances to retrieve:
using Cratis.Chronicle;
public record MaterializedPaginationOrder(string CustomerName, decimal Total);
public class MaterializedPaginationAccessingApi(IEventStore eventStore){ public async Task<IEnumerable<MaterializedPaginationOrder>> GetOrders() { // Inject IEventStore, then reach through to the Materialized API var instances = await eventStore.ReadModels.Materialized.GetInstances<MaterializedPaginationOrder>(); return instances; }}import io.cratis.chronicle.IEventStore
data class MaterializedPaginationOrder(val customerName: String = "", val total: Double = 0.0)
class MaterializedPaginationAccessingApi(private val eventStore: IEventStore) { // Reach through IEventStore, then the Materialized API suspend fun getOrders(): List<MaterializedPaginationOrder> = eventStore.readModels.materialized.getInstances(MaterializedPaginationOrder::class)}import io.cratis.chronicle.IEventStore;import io.cratis.chronicle.java.ReadModelsJavaBridge;
import java.util.List;
record MaterializedPaginationOrder(String customerName, double total) { MaterializedPaginationOrder() { this("", 0.0); }}
class MaterializedPaginationAccessingApi { private final IEventStore eventStore;
MaterializedPaginationAccessingApi(IEventStore eventStore) { this.eventStore = eventStore; }
// Reach through IEventStore, then the Java bridge for the Materialized API List<MaterializedPaginationOrder> getOrders() { return ReadModelsJavaBridge.getMaterializedInstances(eventStore.getReadModels(), MaterializedPaginationOrder.class, 0, 50); }}defmodule MyApp.ReadModels.MaterializedPaginationOrder do use Cratis.Chronicle.ReadModels.ReadModel
defstruct customer_name: "", total: 0.0end
defmodule MyApp.MaterializedPaginationAccessingApi do alias MyApp.ReadModels.MaterializedPaginationOrder
def get_orders do # Query the materialized read-model container directly, rather than replaying events Cratis.Chronicle.ReadModels.query(MaterializedPaginationOrder) endendimport { IEventStore } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
class MaterializedPaginationOrder { @field(String) readonly customerName: string; @field(Number) readonly total: number;
constructor(customerName: string, total: number) { this.customerName = customerName; this.total = total; }}
class MaterializedPaginationAccessingApi { constructor(private readonly store: IEventStore) {}
// Inject IEventStore, then reach through to the materialized API async getOrders(): Promise<MaterializedPaginationOrder[]> { return this.store.readModels.materialized.getInstances(MaterializedPaginationOrder); }}Getting Instances
Section titled “Getting Instances”Basic Usage
Section titled “Basic Usage”The .NET call defaults to skip: 0 and take: 50, returning up to the first 50 stored instances:
using Cratis.Chronicle;
public class MaterializedPaginationBasicUsage(IEventStore eventStore){ public Task<IEnumerable<MaterializedPaginationOrder>> GetOrders() => eventStore.ReadModels.Materialized.GetInstances<MaterializedPaginationOrder>();}import io.cratis.chronicle.IEventStore
class MaterializedPaginationBasicUsage(private val eventStore: IEventStore) { suspend fun getOrders(): List<MaterializedPaginationOrder> = eventStore.readModels.materialized.getInstances(MaterializedPaginationOrder::class)}import io.cratis.chronicle.IEventStore;import io.cratis.chronicle.java.ReadModelsJavaBridge;
import java.util.List;
class MaterializedPaginationBasicUsage { private final IEventStore eventStore;
MaterializedPaginationBasicUsage(IEventStore eventStore) { this.eventStore = eventStore; }
List<MaterializedPaginationOrder> getOrders() { return ReadModelsJavaBridge.getMaterializedInstances(eventStore.getReadModels(), MaterializedPaginationOrder.class, 0, 50); }}defmodule MyApp.MaterializedPaginationBasicUsage do alias MyApp.ReadModels.MaterializedPaginationOrder
def get_orders do Cratis.Chronicle.ReadModels.query(MaterializedPaginationOrder) endendimport { IEventStore } from '@cratis/chronicle';
class MaterializedPaginationBasicUsage { constructor(private readonly store: IEventStore) {}
async getOrders(): Promise<MaterializedPaginationOrder[]> { return this.store.readModels.materialized.getInstances(MaterializedPaginationOrder); }}Pagination
Section titled “Pagination”For .NET page-based navigation, keep take fixed and increase skip by that amount. These calls read successive windows of 20 instances:
using System.Linq;using Cratis.Chronicle;
public class MaterializedPaginationPagination(IEventStore eventStore){ public async Task GetPages() { // First page of 20 var page1 = await eventStore.ReadModels.Materialized.GetInstances<MaterializedPaginationOrder>(take: 20); Console.WriteLine($"Page 1: {page1.Count()} orders");
// Second page of 20 var page2 = await eventStore.ReadModels.Materialized.GetInstances<MaterializedPaginationOrder>(skip: 20, take: 20); Console.WriteLine($"Page 2: {page2.Count()} orders");
// Third page of 20 var page3 = await eventStore.ReadModels.Materialized.GetInstances<MaterializedPaginationOrder>(skip: 40, take: 20); Console.WriteLine($"Page 3: {page3.Count()} orders"); }}import io.cratis.chronicle.IEventStore
class MaterializedPaginationPagination(private val eventStore: IEventStore) { suspend fun getPages() { // First page of 20 val page1 = eventStore.readModels.materialized.getInstances(MaterializedPaginationOrder::class, take = 20) println("Page 1: ${page1.size} orders")
// Second page of 20 val page2 = eventStore.readModels.materialized.getInstances(MaterializedPaginationOrder::class, skip = 20, take = 20) println("Page 2: ${page2.size} orders")
// Third page of 20 val page3 = eventStore.readModels.materialized.getInstances(MaterializedPaginationOrder::class, skip = 40, take = 20) println("Page 3: ${page3.size} orders") }}import io.cratis.chronicle.IEventStore;import io.cratis.chronicle.java.ReadModelsJavaBridge;
class MaterializedPaginationPagination { private final IEventStore eventStore;
MaterializedPaginationPagination(IEventStore eventStore) { this.eventStore = eventStore; }
void getPages() { // First page of 20 var page1 = ReadModelsJavaBridge.getMaterializedInstances(eventStore.getReadModels(), MaterializedPaginationOrder.class, 0, 20); System.out.println("Page 1: " + page1.size() + " orders");
// Second page of 20 var page2 = ReadModelsJavaBridge.getMaterializedInstances(eventStore.getReadModels(), MaterializedPaginationOrder.class, 20, 20); System.out.println("Page 2: " + page2.size() + " orders");
// Third page of 20 var page3 = ReadModelsJavaBridge.getMaterializedInstances(eventStore.getReadModels(), MaterializedPaginationOrder.class, 40, 20); System.out.println("Page 3: " + page3.size() + " orders"); }}defmodule MyApp.MaterializedPaginationPagination do alias MyApp.ReadModels.MaterializedPaginationOrder
def get_pages do # First page of 20. Pages count from 0. {:ok, page1} = Cratis.Chronicle.ReadModels.query(MaterializedPaginationOrder, page: 0, page_size: 20) IO.puts("Page 1: #{length(page1.instances)} orders")
# Second page of 20 {:ok, page2} = Cratis.Chronicle.ReadModels.query(MaterializedPaginationOrder, page: 1, page_size: 20) IO.puts("Page 2: #{length(page2.instances)} orders")
# Third page of 20 {:ok, page3} = Cratis.Chronicle.ReadModels.query(MaterializedPaginationOrder, page: 2, page_size: 20) IO.puts("Page 3: #{length(page3.instances)} orders") endendimport { IEventStore } from '@cratis/chronicle';
class MaterializedPaginationPagination { constructor(private readonly store: IEventStore) {}
async getPages(): Promise<void> { // First page of 20 const page1 = await this.store.readModels.materialized.getInstances(MaterializedPaginationOrder, 0, 20); console.log(`Page 1: ${page1.length} orders`);
// Second page of 20 const page2 = await this.store.readModels.materialized.getInstances(MaterializedPaginationOrder, 20, 20); console.log(`Page 2: ${page2.length} orders`);
// Third page of 20 const page3 = await this.store.readModels.materialized.getInstances(MaterializedPaginationOrder, 40, 20); console.log(`Page 3: ${page3.length} orders`); }}Pagination Parameters
Section titled “Pagination Parameters”The .NET parameters use strongly typed concepts that convert implicitly from int:
| Parameter | Type | Default | Named Constants |
|---|---|---|---|
skip |
InstanceCountToSkip? |
0 |
InstanceCountToSkip.Zero |
take |
InstanceCount? |
50 |
InstanceCount.Default, InstanceCount.Unlimited |
using Cratis.Chronicle;using Cratis.Chronicle.ReadModels;
public class MaterializedPaginationNamedConstants(IEventStore eventStore){ public Task<IEnumerable<MaterializedPaginationOrder>> GetOrders() => // Using named constants eventStore.ReadModels.Materialized.GetInstances<MaterializedPaginationOrder>( skip: InstanceCountToSkip.Zero, take: InstanceCount.Default);}import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.readModels.ReadModel
@ReadModeldata class NamedConstantsOrder(val status: String = "", val total: Double = 0.0)
/** * `skip` and `take` both default to well-known values (0 and 50) - call without arguments to * use them rather than repeating the numbers yourself. */suspend fun getOrders(store: IEventStore): List<NamedConstantsOrder> = store.readModels.materialized.getInstances(NamedConstantsOrder::class)import io.cratis.chronicle.EventStore;import io.cratis.chronicle.readModels.ReadModel;
import java.util.List;
import io.cratis.chronicle.java.ReadModelsJavaBridge;
@ReadModelclass NamedConstantsOrder { private String status = ""; private double total = 0;
public String getStatus() { return status; } public void setStatus(String status) { this.status = status; }
public double getTotal() { return total; } public void setTotal(double total) { this.total = total; }}
class ReadModelsMaterializedPaginationNamedConstants { // skip: 0, take: 50 are the Kotlin client's built-in defaults - repeat them explicitly since // the Java bridge has no default-argument support. List<NamedConstantsOrder> getOrders(EventStore store) { return ReadModelsJavaBridge.getMaterializedInstances(store.getReadModels(), NamedConstantsOrder.class, 0, 50); }}Elixir does not support this workflow yet.TypeScript does not support this workflow yet.Building a Paged API Endpoint
Section titled “Building a Paged API Endpoint”The ASP.NET endpoint translates a zero-based page number into an offset with page * pageSize. Validate those inputs at your application’s boundary before passing them to the read API.
using Cratis.Chronicle;using Microsoft.AspNetCore.Mvc;
[ApiController][Route("orders")]public class MaterializedPaginationOrdersController(IEventStore eventStore) : ControllerBase{ [HttpGet] public async Task<IEnumerable<MaterializedPaginationOrder>> GetOrders( [FromQuery] int page = 0, [FromQuery] int pageSize = 20) { return await eventStore.ReadModels.Materialized.GetInstances<MaterializedPaginationOrder>( skip: page * pageSize, take: pageSize); }}import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.readModels.ReadModel
@ReadModeldata class PagedEndpointOrder(val status: String = "", val total: Double = 0.0)
/** * A paged read suitable for backing a list endpoint - only the requested page is loaded. */suspend fun getOrders(store: IEventStore, page: Int, pageSize: Int): List<PagedEndpointOrder> = store.readModels.materialized.getInstances(PagedEndpointOrder::class, skip = page * pageSize, take = pageSize)import io.cratis.chronicle.EventStore;import io.cratis.chronicle.readModels.ReadModel;
import java.util.List;
import io.cratis.chronicle.java.ReadModelsJavaBridge;
@ReadModelclass PagedEndpointOrder { private String status = ""; private double total = 0;
public String getStatus() { return status; } public void setStatus(String status) { this.status = status; }
public double getTotal() { return total; } public void setTotal(double total) { this.total = total; }}
class ReadModelsMaterializedPaginationPagedEndpoint { // A paged read suitable for backing a list endpoint - only the requested page is loaded. List<PagedEndpointOrder> getOrders(EventStore store, int page, int pageSize) { return ReadModelsJavaBridge.getMaterializedInstances( store.getReadModels(), PagedEndpointOrder.class, page * pageSize, pageSize); }}defmodule MyApp.MaterializedPaginationOrdersController do alias MyApp.ReadModels.MaterializedPaginationOrder
def get_orders(page \\ 0, page_size \\ 20) do with {:ok, result} <- Cratis.Chronicle.ReadModels.query(MaterializedPaginationOrder, page: page, page_size: page_size ) do {:ok, result.instances} end endendTypeScript does not support this workflow yet.Observing Changes
Section titled “Observing Changes”For a complete live collection with optional client-side filtering, use Observing Read Models. IReadModels.Observe<T>() has no 50-instance default window; Materialized.ObserveInstances below observes only the requested page.
In .NET, ObserveInstances returns an IObservable<IEnumerable<TReadModel>>. A subscription receives the current page, then replacement page snapshots as the sink reports changes. Replace the displayed window with each emission rather than appending the items to it.
using System.Linq;using Cratis.Chronicle;
public record MaterializedPaginationProduct(string Name, decimal Price);
public class MaterializedPaginationObserving(IEventStore eventStore){ public void Run() { var subscription = eventStore.ReadModels.Materialized .ObserveInstances<MaterializedPaginationProduct>(take: 50) .Subscribe(products => { // Called whenever the stored instances change Console.WriteLine($"Products updated: {products.Count()} in view"); });
// Dispose when done to release the change stream subscription.Dispose(); }}import io.cratis.chronicle.IEventStoreimport kotlinx.coroutines.coroutineScopeimport kotlinx.coroutines.launch
data class MaterializedPaginationProduct(val name: String = "", val price: Double = 0.0)
class MaterializedPaginationObserving(private val eventStore: IEventStore) { suspend fun run() = coroutineScope { val subscription = launch { eventStore.readModels.materialized .observeInstances(MaterializedPaginationProduct::class, take = 50) .collect { products -> // Called whenever the stored instances change println("Products updated: ${products.size} in view") } }
// Collect within the caller's scope; cancel that scope when observation ends. subscription.join() }}import io.cratis.chronicle.IEventStore;import io.cratis.chronicle.java.ReadModelsJavaBridge;
import kotlinx.coroutines.Job;
record MaterializedPaginationProduct(String name, double price) {}
class MaterializedPaginationObserving { private final IEventStore eventStore;
MaterializedPaginationObserving(IEventStore eventStore) { this.eventStore = eventStore; }
Job run() { Job subscription = ReadModelsJavaBridge.observeMaterializedInstances( eventStore.getReadModels(), MaterializedPaginationProduct.class, 0, 50, products -> { // Called whenever the stored instances change System.out.println("Products updated: " + products.size() + " in view"); });
// The owner cancels this job when it closes. return subscription; }}defmodule MyApp.MaterializedPaginationObserving do alias Cratis.Chronicle.ReadModels alias MyApp.ReadModels.MaterializedPaginationOrder
def run do {:ok, observer} = ReadModels.observe(MaterializedPaginationOrder, page: 0, page_size: 50)
try do receive_pages() after ReadModels.unobserve(observer) end end
defp receive_pages do receive do {:chronicle_read_model_instances, MaterializedPaginationOrder, page} -> # Receives the initial stored page and each updated page. IO.puts("Orders updated: #{length(page.instances)} in view") receive_pages()
{:chronicle_read_model_observe_error, MaterializedPaginationOrder, reason} -> {:error, reason}
:stop -> :ok end endendimport { IEventStore } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
class MaterializedPaginationProduct { @field(String) readonly name: string; @field(Number) readonly price: number;
constructor(name: string, price: number) { this.name = name; this.price = price; }}
class MaterializedPaginationObserving { constructor(private readonly store: IEventStore) {}
async run(): Promise<void> { // Called whenever the stored instances change for await (const products of this.store.readModels.materialized.observeInstances(MaterializedPaginationProduct, 0, 50)) { console.log(`Products updated: ${products.length} in view`); } }}Observation follows the sink’s notification mechanism:
- MongoDB uses native change streams.
- SQL (PostgreSQL, SQL Server, SQLite) reads the current page on subscription, then polls the stored rows and total count for changes. Pages are ordered by the read model key. Set
Cratis:Chronicle:Sql:LiveQueryPollIntervalSecondsto change the polling interval (default: 2 seconds). Failed polls are retried with backoff.
Several writes between SQL polls can appear as one updated snapshot. Snapshot delivery can also coalesce updates while a slower consumer catches up. Use read model watching when you need projection changesets rather than replacement pages.
Dispose the subscription when its consumer closes. For coroutine or iterator-based clients, cancel or end the observation using that client’s lifetime mechanism.
Observing in a Service
Section titled “Observing in a Service”Let the service that uses the page own the subscription. In this .NET example, disposing the dashboard also disposes its observation:
using Cratis.Chronicle;
public class MaterializedPaginationProductDashboard : IDisposable{ readonly IDisposable _subscription;
public MaterializedPaginationProductDashboard(IEventStore eventStore) { _subscription = eventStore.ReadModels.Materialized .ObserveInstances<MaterializedPaginationProduct>(take: 100) .Subscribe(UpdateView); }
void UpdateView(IEnumerable<MaterializedPaginationProduct> products) { /* ... */ }
public void Dispose() => _subscription.Dispose();}import io.cratis.chronicle.IEventStoreimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launch
/** * Observes a live paginated window of materialized instances for as long as [scope] is active. */class ProductDashboard(store: IEventStore, scope: CoroutineScope) { init { scope.launch { store.readModels.materialized.observeInstances(MaterializedPaginationProduct::class, take = 100) .collect { products -> updateView(products) } } }
private fun updateView(products: List<MaterializedPaginationProduct>) { // ... }}import io.cratis.chronicle.IEventStore;import io.cratis.chronicle.java.ReadModelsJavaBridge;
import kotlinx.coroutines.Job;
import java.util.List;
/** * Observes a live paginated window of materialized instances until {@code close()} releases it. */class ProductDashboard implements AutoCloseable { private final Job subscription;
ProductDashboard(IEventStore store) { subscription = ReadModelsJavaBridge.observeMaterializedInstances( store.getReadModels(), MaterializedPaginationProduct.class, 0, 100, this::updateView); }
private void updateView(List<MaterializedPaginationProduct> products) { // ... }
@Override public void close() { subscription.cancel(null); }}defmodule MyApp.MaterializedPaginationProductDashboard do use GenServer
alias Cratis.Chronicle.ReadModels alias MyApp.ReadModels.MaterializedPaginationOrder
def start_link(opts \\ []), do: GenServer.start_link(__MODULE__, opts)
@impl true def init(_opts) do case ReadModels.observe(MaterializedPaginationOrder, page: 0, page_size: 100) do {:ok, observer} -> {:ok, %{observer: observer, orders: []}} {:error, reason} -> {:stop, reason} end end
@impl true def handle_info({:chronicle_read_model_instances, MaterializedPaginationOrder, page}, state) do # Update the dashboard on the initial page and every subsequent snapshot. {:noreply, %{state | orders: page.instances}} end
def handle_info({:chronicle_read_model_observe_error, MaterializedPaginationOrder, reason}, state) do {:stop, reason, state} end
@impl true def terminate(_reason, state), do: ReadModels.unobserve(state.observer)endimport { IEventStore } from '@cratis/chronicle';
class MaterializedPaginationProductDashboard { constructor(private readonly store: IEventStore) {}
async start(updateView: (products: MaterializedPaginationProduct[]) => void): Promise<void> { for await (const products of this.store.readModels.materialized.observeInstances(MaterializedPaginationProduct, 0, 100)) { updateView(products); } }}When to Use the Materialized API
Section titled “When to Use the Materialized API”Choose a materialized read when the screen needs a bounded window of stored state. Choose a materialized observation when that window should update without the application repeatedly issuing reads; the sink may still poll internally.
For a small list that needs every instance, observe the complete collection. If the screen needs a field filter or a user-selected sort order, query the sink directly instead of fetching pages and filtering each page afterward. Filtering after paging does not produce a page of matching results.
Comparison with On-Demand GetInstances
Section titled “Comparison with On-Demand GetInstances”In .NET, the difference is whether you need the complete collection or a stored window:
ReadModels.GetInstances<T>() |
ReadModels.Materialized.GetInstances<T>() |
|
|---|---|---|
| Data source | The sink for a materialized read model; event replay for a passive one or when you pass an event count | Materialized sink |
| Consistency | Eventual for stored state; passive reads fold the event log on demand | Eventual; no fixed delay is guaranteed |
| Result size | All instances from the read | A skip/take window |
| Filtering/sorting | Client-side after retrieval | No query parameters for either; use the sink directly |
Related Topics
Section titled “Related Topics”- Consistency Models — Understanding strong vs. eventual consistency
- Getting a Single Instance — Read current state for one key
- Getting a Collection of Instances — Retrieve all instances, from stored state or event replay
- Watching Read Models — Observe event-log-sourced read model changesets
- Projections — How read models are produced from events
- Reducers — Imperative state-building from events
- MongoDB Sink — How read model instances are stored in MongoDB
- SQL Sink — How read model instances are stored in a SQL database