StateViewSlice
For a short summary of StateViewSlice, see Reventless Components Overview.
This component follows the Reventless Component Structure Pattern, using separate files for interface definitions (StateViewSlice.res), builder logic (StateViewSlice_Builder.res), and callback/handler logic (StateViewSlice_Callback.res).
Overview
The StateViewSlice is a DCB (Dynamic Consistency Boundary) component that projects events from a shared DcbEventLog into a QueryDb-backed read model. It implements the projection pattern where events are transformed into state updates.
Purpose and Responsibilities
- Responsibility: Listen to events from DcbEventLog and project them into a QueryDb for efficient reading
- In: Events from DcbEventLog (subscribed via EventCollector)
- Out: State updates to QueryDb
- Key Feature: Complements StateChangeSlice by providing read-optimized views of the event-sourced state
Relationship with DCB
StateViewSlice works alongside StateChangeSlice in the DCB architecture:
Component Spec
A StateViewSlice is split into two files:
<Name>.res— the spec (@@reventless.spec): the localconsumedEventandstate@schematypes.<Name>_Projection.res— the projection (@@reventless.projection): a singlelet project = ({event}) => [...]function receiving aconsumedenvelope{event, meta, recordedAt}.
The spec file. @@reventless.spec injects name, module Id (the row key, a plain
string unless the view declares module Id = OrderId), moduleUrl,
let config = config(), and let subIdConfig = None:
@@reventless.spec
@schema
type consumedEvent =
| Created({id: string, name: string})
| Updated({id: string, name: string})
| Deleted({id: string})
@schema
type state = {name: string}
The projection file. @@reventless.projection injects open Reventless.Projection
(so Set, Update, UpdateWithDefault, Delete are in scope unqualified) and
brings the spec module into scope. project receives a consumed envelope
{event, meta, recordedAt}; destructure ({event}) when you only need the
payload. meta is Reventless.Message.meta (producer info incl. meta.time, the
producer timestamp, and meta.user) and recordedAt: string is the storage
timestamp:
@@reventless.projection
let project = ({event}) =>
switch event {
| Created({id, name}) => [Set(id, {name: name})]
| Updated({id, name}) => [Update(id, state => {...state, name})]
| Deleted({id}) => [Delete(id)]
}
There is no DcbEventLogSpec reference — the slice declares its own local
consumedEvent union.
Spec Fields Explained
In the spec file (@@reventless.spec injects name, module Id, moduleUrl):
| Field | Type | Description |
|---|---|---|
consumedEvent | @schema type | The local subset of event variants this slice projects |
state | @schema type | State type for the read model (schema auto-generated) |
In the _Projection.res file:
| Field | Type | Description |
|---|---|---|
project | Reventless.StateViewSlice.consumed<consumedEvent> => array<Projection.action<state>> | Function to transform a consumed event envelope into state actions |
At run time
Event Processing Flow
Projection Actions
In the _Projection.res file, @@reventless.projection injects
open Reventless.Projection, so the action constructors (Set, Update,
UpdateWithDefault, Delete) are in scope unqualified:
@@reventless.projection
let project = ({event}) =>
switch event {
| ItemCreated({itemId, name}) => [Set(itemId, {name, createdAt: Date.now()})]
| ItemRenamed({itemId, newName}) => [Update(itemId, state => {...state, name: newName})]
| ItemDeleted({itemId}) => [Delete(itemId)]
| StockAdjusted({itemId, delta}) =>
// UpdateWithDefault handles case where item doesn't exist yet
[UpdateWithDefault(itemId, {count: 0}, state => {...state, count: state.count + delta})]
}
Key Design Annotations
StateViewSlice supports the same PPX annotations on @schema type state as ReadModel. Annotations on state fields automatically generate let makeId, let subIdConfig, and let config. These annotations go on the spec file's @schema type state:
@@reventless.spec
@schema
type state = {
@id orderId: string, // generates: let makeId
@subId lineItemId: string, // generates: let subIdConfig — enables sort key queries
@index categoryId: string, // generates: let config with a secondary index
@resolves({table: "Products", field: "product"}) productId: string,
quantity: int,
}
@schema
type consumedEvent =
| LineItemAdded({orderId: string, lineItemId: string, productId: string, categoryId: string, quantity: int})
| LineItemRemoved({orderId: string, lineItemId: string})
The project function lives in the sibling _Projection.res file, where
@@reventless.projection injects open Reventless.Projection (so Set,
Update, UpdateWithDefault, and Delete are in scope unqualified):
@@reventless.projection
let project = ({event}) =>
switch event {
| LineItemAdded({orderId, lineItemId, productId, categoryId, quantity}) =>
[Set(lineItemId, {orderId, lineItemId, productId, categoryId, quantity})]
| LineItemRemoved({lineItemId}) => [Delete(lineItemId)]
}
For the full annotation reference, see PPX annotations.
Recording When a Row Reached Each State
A view's lifecycle field says which state a row is in. Declare a trail field beside it and the projection machinery also records when it got there — every state entered, with the instant, in the order it happened:
@schema
type lifecycle =
| Placed
| Shipped
| Cancelled
@schema
type state = {
@id orderId: string,
lifecycle: lifecycle,
trail: Reventless.Lifecycle.Trail.t<lifecycle>,
}
That is the whole of the domain's work. The projection writes trail: [] in the
action that creates the row and never touches the field again:
let project = ({event}) =>
switch event {
| OrderPlaced({orderId}) => [Set(orderId, {orderId, lifecycle: Placed, trail: []})]
// No `shippedAt` to remember — the trail's `Shipped` entry is the date.
| OrderShipped({orderId}) => [Update(orderId, state => {...state, lifecycle: Shipped})]
| OrderCancelled({orderId}) => [Update(orderId, state => {...state, lifecycle: Cancelled})]
}
Whenever an action changes the lifecycle field, {state, at} is appended, with
at taken from the event envelope's own meta.time — never a clock, so a
rebuild reproduces the trail exactly. A state a row never reached has no entry.
Four things worth knowing:
- Which field is the lifecycle is the usual rule:
@lifecycle, else a field literally namedlifecycleholding an enum. A view with no lifecycle field records nothing. - The trail is ordered, not keyed by state. A lifecycle that revisits a state
— a reopened order back to
Placed— carries both visits, at their own instants. - On the wire an entry is
{"state": "Placed", "at": "…"}, andstateemits the same GraphQL enum the lifecycle field emits. - It replaces per-state timestamp fields. Adding a state costs no new field,
no schema change and no projection edit — which is what a
shippedAtbeside acancelledAtthat nobody remembered to add cost before.
Sub-state rows (a view with @subId, projected with UpdateMultiState) are the
one exception: pairing a before-row with an after-row needs the sub-id, which is
not resolved until the action is applied, so those actions record no entry.
The Dates the Trail Derives
Beside the trail, and from it alone, every save also writes a few plain dates, so a client does not have to walk the list:
- for each state the row entered: the latest entry, the first entry, and the number of visits;
- for the row: when it entered the state it is in now.
They are a pure function of the trail and are rewritten on every save of the row,
not only on a transition. Nothing is declared for them. Over GraphQL they read as
one object beside the trail, named <trailField>Entered, with one entry per
lifecycle state (lower-case first letter) and current:
{
Ordering_Orders(first: 10) {
edges {
node {
orderId
lifecycle
trailEntered {
placed { latest first visits }
shipped { latest first visits }
current
}
}
}
}
}
A state the row never entered reads null; a reopened order reads placed { visits: 2 } with first and latest apart. The object is absent when the trail
field is @internal, and a lifecycle state named Current is refused when the
API is generated, because its key would collide with current. A live update
carries the row with the same object, built from the same attributes, so a row
updated live does not keep the dates it was fetched with.
Filtering and Sorting by a State's Date
Reading the dates costs nothing. Filtering and sorting by them on the server is an opt-in, written on the trail field:
@schema
type state = {
@id orderId: string,
lifecycle: lifecycle,
@trail({index: [Placed, Shipped]})
trail: Reventless.Lifecycle.Trail.t<lifecycle>,
}
| Annotation | The view's filter input and orderBy gain |
|---|---|
@trail({index: [Placed, Shipped]}) | For each named state: entered<State> (latest entry), entered<State>First and visits<State>, each with Eq, From and To and each an order field. Also everything the next row gives. |
@trail({index: true}) | enteredCurrent with Eq, From, To and as an order field, and <lifecycleField>Eq (lifecycleEq, shelfStatusEq, …). |
So orders that have been Placed for more than three days, oldest first is one
request, with the bound an absolute instant the client computes:
{
Ordering_Orders(
filter: { lifecycleEq: "Placed", enteredCurrentTo: "2026-11-19T00:00:00.000Z" }
orderBy: { field: enteredCurrent, direction: ASC }
first: 20
) {
edges { node { orderId trailEntered { current } } }
}
}
Three rules:
- A state's date covers only the rows that entered that state. Filtering or
sorting by
enteredShipped,enteredShippedFirstorvisitsShippedleaves out every row that never shipped, on every backend.enteredCurrentcovers every row with a trail. - The unqualified name is the latest visit.
enteredPlacedanswers "since when in that state";enteredPlacedFirstis the first time. For a state entered once they are the same instant. - Dates compare as ISO instants, counts as numbers. There is no operator relative to now and no stored duration: a client sends an absolute bound and computes a duration from two dates.
The PPX refuses a state the lifecycle does not declare, naming the ones it does;
@trail on a field that is not typed Reventless.Lifecycle.Trail.t<…>; and a
second @trail on one record. The state check runs when the lifecycle enum is
declared in the same file.
What the Opt-in Costs on DynamoDB
On the in-memory, SQLite and Postgres backends the opt-in only widens the filter input. On DynamoDB it provisions global secondary indexes:
- One per named state, sorted by that state's latest entry. It is sparse: a row that never entered the state is not in it.
- The lifecycle index, keyed by the lifecycle field and sorted by when the row
entered its current state. A request that names
<lifecycleField>Eqis aQueryon it, withenteredCurrentFrom/Toas the key condition andorderBy: enteredCurrentread in index order.
A range on, or an order by, entered<State> queries that state's index; any
other filter stays a filter on the page read. A caller that @owner scopes keeps
the owner index for the read.
Two limits:
- DynamoDB allows 20 global secondary indexes on a table. A view whose
@index,@ownerand@trailannotations ask for more is refused when the table is declared, with each index and the annotation it came from. Name fewer states. - Each per-state index, and each lifecycle state, is one partition. A
partition takes about 1,000 writes per second, and a throttled index throttles
the table's own writes; it shows as write throttling on the index in CloudWatch.
A view writing past that would need the index sharded (keyed by
hash(id) mod N, a read querying all N and merging them, a rebuild re-keying the rows), which@traildoes not offer today.
Creating the indexes is slow once, as with any new GSI: the deploy that first
adds the annotation waits for them to become ACTIVE.
Rows Saved Before the Opt-in
A row saved before the derived dates existed carries its trail and none of the
dates, so every entry of its trailEntered reads null and it is missing from the new indexes until
it is written again. The rows that have sat longest in a state are the ones
nothing writes again, so backfill them once with views:rederive, which computes
each row's dates from its trail with the function a save uses:
# A deployed stack, from the deployment's platform project (AWS credentials from
# the ambient chain). A dry run is the default: it prints, per table, the rows to change.
AWS_REGION=eu-west-1 SEED_STACK=alpha pnpm run views:rederive
AWS_REGION=eu-west-1 SEED_STACK=alpha pnpm run views:rederive -- --apply
# A local SQLite store, from platform-local. The in-memory backend needs none.
pnpm run views:rederive
pnpm run views:rederive -- --apply
It finds the stack's view tables by their tags, sets or removes only the derived attributes, and skips a row that was written while it ran (that row's own save already derived them). A second run finds nothing to change.
What the Schema Says About a Trail
The view's JSON Schema, which a client reads from the component definitions,
says what the trail offers on the trail's own property, under
x-reventless-trail:
"trail": {
"type": "array",
"x-reventless-trail": {
"lifecycle": "lifecycle",
"entered": "trailEntered",
"index": ["Placed", "Shipped", "Cancelled"]
}
}
| Member | Says |
|---|---|
lifecycle | The lifecycle field the trail's entries name. |
entered | The API field the derived dates read as. Its presence is how a client knows the platform derives them; a platform that predates them writes no x-reventless-trail. |
index | The states of @trail({index: […]}), as declared. Absent: nothing is filtered or sorted on the server. An empty list is @trail({index: true}), the lifecycle index alone. |
From index a client builds the names of the previous sections by rule: for each
listed state entered<State>, entered<State>First and visits<State>, and for
any index at all enteredCurrent and <lifecycle>Eq. The key is absent when
the view has no lifecycle field or the trail is @internal.
Comparison with ReadModel
| Aspect | ReadModel | StateViewSlice |
|---|---|---|
| Event Source | Multiple EventTopics | Single DcbEventLog |
| Mappings | Complex mapping system | Single projection function |
| Spec | Reventless.ReadModel.Spec | Custom Spec with project function |
| Key annotations | @id, @subId, @index, @resolves on state fields | Same — identical PPX annotation support |
| Use Case | General-purpose read models | DCB-specific view projections |
Comparison with StateChangeSlice
| Aspect | StateChangeSlice | StateViewSlice |
|---|---|---|
| Purpose | Handle commands and decide on events | Project events into read model |
| Input | Commands from CommandTopic | Events from DcbEventLog EventTopic |
| Output | Appends events to DcbEventLog | Updates QueryDb state |
| Pattern | Decision/command pattern | Projection pattern |
Best Practices
1. Use UpdateWithDefault for Optional Creation
// Good: handles both new and existing rows
let project = ({event}) =>
switch event {
| ItemAdjusted({itemId, delta}) => [
UpdateWithDefault(itemId, {count: 0}, state => {...state, count: state.count + delta}),
]
}
// Avoid: Update on a row that may not exist yet is a no-op
let project = ({event}) =>
switch event {
| ItemAdjusted({itemId, delta}) => [Update(itemId, state => {...state, count: state.count + delta})]
}
2. Keep Projections Idempotent
// Good: setting an absolute value is idempotent on replay
let project = ({event}) =>
switch event {
| QuantitySet({itemId, qty}) => [Update(itemId, state => {...state, qty})]
}
// Be careful: relative deltas can double-count if events are re-delivered
3. Denormalize Only What This View Can Maintain
A projection sees one row at a time, found by the view's @id. So it can keep a
copy of another entity's value current only if every event that changes the
original also names the row holding the copy. Copy a value that fails that test
and nothing ever refreshes it: it is not a cache, it is a value frozen by
accident, and the row ends up carrying two answers with nothing saying which one
is current.
Values the projection computes itself always pass — a running total is derived from the very events the view consumes.
// Good: pre-aggregated from the events this view already consumes
type state = {
@id itemId: string,
itemName: string,
totalQuantity: int,
}
// Good: frozen on purpose, because these are the terms of a transaction
type state = {
@id orderId: string,
// What the product was called and cost when the order was placed. The view
// must not go and ask the catalog what it costs now — a later price change
// did not change this sale.
productName: string,
unitPrice: Reventless.Money.t,
}
// Avoid: a copy this view has no way to refresh
type state = {
@id productId: string,
categoryId: string,
// Keyed by `productId`, so a `CategoryRenamed` would have to rewrite every row
// filed under that category — which a single-key projection cannot do. And a
// rename is a correction to a label, which is exactly the case where the new
// value should be what everyone reads.
categoryName: string,
}
Where the value is a live classification rather than a recorded fact, carry the reference and let the reader resolve it:
type state = {
@id productId: string,
// `@index` so the server can answer "the products in this category";
// `@groupBy` sections the list by it.
@index @groupBy categoryId: string,
}
Resolving a reference at read time is not a join in the projection. Two doors do
it: @resolves({table, field}) puts the target row on this view's GraphQL type
(see Key Design Annotations above), and the
{list}Refs(ids) query generated for every view answers {id, label, retired}
for ids a client already holds.
4. Match consumedEvent Exhaustively
// consumedEvent lists exactly the events this view reads, so the switch is exhaustive.
// For an event that should not change state, return [] (or [Ignore]).
let project = ({event}) =>
switch event {
| KnownEvent1({id}) => [Update(id, state => state)]
| KnownEvent2({id}) => [Delete(id)]
| NoteAdded(_) => [] // no state change
}
Pulumi Outputs
type outputs = {
resources: array<Reventless.Adapter.resource>,
queryDb: QueryDb.outputs,
}
The StateViewSlice creates its own QueryDb:
- DynamoDB table for state storage
- AppSync resolvers for querying
- Related IAM roles and policies
Related Components
- DcbEventLog - Shared event log for DCB slices
- StateChangeSlice - Processes commands and appends events
- QueryDb - Read model storage
- ReadModel - General-purpose read model component
- Plugin - Hosts DCB slices and creates shared infrastructure
- EventCollector - Consumes events for projection