M3-S3 — Aggregation, statistics and composite read models
Section titled “M3-S3 — Aggregation, statistics and composite read models”| Module | M3 — The read side |
| After this session you can | Explain how a statistic, a counter and a joiner or aggregate entity are computed, and spot the designs that make them slow. |
| Time | Facilitated: 51 min · On your own: 51 min |
| Before you start | M3-S2: the list-read pipeline and the profiler. Larkspur Lab with the volume set loaded by the seed (20,000 purchase orders), the API and record-store windows (workbench). |
| Go deeper | Engine: query and aggregation, statistics · Summaries API · Aggregates API |
◆ Orientation (1 min) — Numbers that people decide by
Section titled “◆ Orientation (1 min) — Numbers that people decide by”Leila Amari opens Operations Command every morning. Sara Qasim negotiates contracts from Spend by Supplier. Tariq Saleh’s supplier reviews quote the Supplier Scorecard. These are the numbers Larkspur decides by, and they are computed by the engine you opened in M3-S2, extended with grouping and accumulation, or materialised ahead of time as virtual records. A builder chose their shape in ACD and ACE (ACE M2-S2). A master answers two questions about them that a builder cannot: why is this one slow, and why is that one out of date?
▤ Concept (10 min) — Computed when read, or materialised ahead
Section titled “▤ Concept (10 min) — Computed when read, or materialised ahead”There are two ways the platform produces a number or a combined list, and the difference decides both cost and freshness.
| Computed when read | Materialised ahead | |
|---|---|---|
| What | Statistics (charts, number tiles, lists of totals), counters, entries-list summaries | Virtual entities: proxies, joiners, aggregates |
| When the work happens | Every time someone opens the screen | When a source record changes, and on a rebuild |
| Freshness | Always current | A little behind its sources |
| Cost grows with | How often it is opened, and how much data each opening scans | How often sources change, and how big a rebuild is |
A statistic, step by step
Section titled “A statistic, step by step”A statistic query is a stored definition: a source (an entity, or one of its saved queries), a measure (the field to accumulate, if any), one or more group-by dimensions, an optional date bucketing (by year, quarter, month, week and so on) and an aggregation function: count, sum, minimum, maximum or average. Executing it builds one aggregation pipeline:
- The source query’s criteria are compiled as in M3-S2, with any parameters filled in.
- Relation look-ups are added for every group-by or measure path that crosses a relation
(
value.supplier.:relation.value.country). - The base match always keeps only active records that are not obsolete, plus the criteria. An obsolete record (M2-S3) silently drops out of every statistic until it is upgraded.
- Unwinds expand repeatable fields and blocks and relation results into one row each.
- Date bucketing converts each date to the user’s time zone and formats it into its bucket.
- The group stage accumulates per bucket: a count adds one per row; a sum adds the measure. Category and switch dimensions group on the option id; reference dimensions group on the referenced record and keep it for later.
- After the database, in the service’s memory: references are turned into titles, category ids into labels, numbers rounded to two decimals, and the buckets sorted.
flowchart LR Q["source query<br/>criteria"] --> L["relation<br/>look-ups"] L --> M["active, not obsolete,<br/>+ criteria"] M --> U["unwind<br/>repeatables"] U --> D["date<br/>buckets"] D --> G["group and<br/>accumulate"] G --> R["in memory: titles,<br/>labels, rounding, sort"]
What to notice: the expensive stages are the look-ups and the unwinds, before the group. Everything after the group works on a handful of buckets and costs almost nothing.
Two consequences shape good designs. Grouping by a reference is cheaper than grouping through it.
Group Spend by Supplier by the purchase order’s own supplier reference, and the database groups on
an id already in each record; the supplier’s name is looked up afterwards, once per bucket. Group it by
value.supplier.:relation.value.supplier_name instead, and the database joins every purchase order to
its supplier before grouping. The chart is the same; the cost is not. An unwind multiplies rows.
Summing order lines inside purchase orders through a repeatable block turns 20,000 orders into 60,000
rows before the group.
Counters, dashboards and pages
Section titled “Counters, dashboards and pages”A counter is a count with a criteria tree: it runs the count variant of the list-read pipeline (M3-S2), ending in a count instead of a page. A dashboard and a page hold widgets; each widget runs its own statistic or count when the dashboard or page is opened, independently, with no cache between users or between openings. So the cost of Operations Command is the sum of its widgets, paid on every opening by every person: twelve widgets opened by forty planners at 08:00 is 480 aggregations in a few minutes. Since 1.10 the platform counts aggregations per tenant, which is how you will see it in M9-S1.
Virtual entities: materialised read models
Section titled “Virtual entities: materialised read models”A virtual entity looks like an entity and is read like one, but its records are derived from
other entities’ records and stored as records of their own, flagged as virtual (M2-S3’s virtual
field). ACE taught the three kinds by purpose: a proxy re-exposes one source, a joiner enriches
each primary record with fields from related ones, an aggregate pours records of several unrelated
entities into one shape (ACE M2-S2). Here is how an aggregate is
kept, the most instructive of the three.
Building. For each source, the engine runs a pipeline: the source’s own query criteria and active records, projected to the mapped fields. The primary source starts the pipeline and every other source is appended with a union; the combined rows are then split back per source so each can be mapped by its own rules. Each source record becomes one aggregate record whose id is computed from the aggregate’s name and the source record’s id, so the same source record always maps to the same aggregate record. Each field is filled by its mapping: copied from a source field (with category options translated to the aggregate’s own options), computed by an expression, a fixed value, or left empty; a mapping that fails is logged and left empty, never fatal. Every aggregate record also carries a hidden reference to the source record it came from.
Keeping current. The data service is a consumer of record events (M2-S2). When a source record is created, updated, invalidated or restored, a handler recomputes that one aggregate record, found directly by its computed id, and publishes the usual record events for it, so reactions, search and live push see aggregate records like any others. A rebuild, triggered by changing the aggregate’s definition or options, deletes all its records and recreates them: until it finishes, the aggregate is empty.
Editing. Whether a field of an aggregate record can be edited is derived from its source: only a field copied from a visible, editable source field of the same shape stays editable, and when the source record’s workflow has completed or failed, everything is locked.
Proxies and joiners follow the same principle (derived records, kept by the data service from source events); a joiner’s derived fields come from computed stages that join the related records. For all of them, the lag between a source change and the read model is the time it takes the event to reach the data service’s handler: normally a second or less, and much longer when that queue is backed up or its handler is failing, which is the stale scorecard of M2-S2’s scenario.
The design traps
Section titled “The design traps”| Symptom | Usual cause | Better design |
|---|---|---|
| A chart is slow, and slower every month | Groups through a relation, or has no date limit on its source query, so it scans all history | Group by the reference itself; give the source query a date window |
| A number tile is slow although the entity is small | It counts across a relation, or uses Contains on text | Count on the record’s own fields; copy what you filter on as a mapped field |
| Operations Command is slow at 08:00 only | Many widgets, each an aggregation, opened by everyone at once | Fewer widgets on the landing page; move detail to drill-down pages |
| A statistic ignores some records | They are obsolete after a breaking change | Upgrade the records (M2-S3) |
| An aggregate is empty for a while after a change | Its definition change triggered a full rebuild | Change aggregate definitions in the release window, not mid-morning |
| An aggregate lags or stops updating | The data service’s handler for its source events is slow or failing | Read that queue and its dead letters (M2-S2) |
▶ Guided demo (8 min) — How Spend by Supplier is computed
Section titled “▶ Guided demo (8 min) — How Spend by Supplier is computed”In Larkspur Lab, with the API window and the record store open.
-
Find the statistic’s definition: in the portal, open Procurement › Purchase Orders, open the Spend by Supplier chart’s settings and note its Aggregation function, Field, Group by and Data Source. Then read its id from the address bar.
-
Switch the profiler on (
db.setProfilingLevel(2)onlk-data). -
Execute it through the API and time the call:
Terminal window time curl -s -H "x-app-token: $TOKEN" \"$BASE/api/v2/entities/purchase_orders/statistic-queries/<id>/execute" | jq '.result[0:3]' -
Read the profiled pipeline:
db.system.profile.find({ns: "lk-data.purchase_orders"}).sort({ts: -1}).limit(1).forEach(p => { printjson(p.command.pipeline); printjson({ms: p.millis, examined: p.docsExamined}) }). Find the base match (active, not obsolete), the$lookupintosuppliersthrough Approved Suppliers, the$groupand its accumulator.Screenshot pending The profiled statistic pipeline for Spend by Supplier, with the lookup stage before the group stage highlighted, and the millis and docsExamined values below it What to notice: the look-up comes before the group, so it runs once per purchase order, 20,000 times, to produce a dozen buckets.
-
Switch the profiler off. Keep the definition, the time and the figures: the lab starts from them.
⛏ Lab (23 min) — Diagnose the slow chart
Section titled “⛏ Lab (23 min) — Diagnose the slow chart”Goal. Spend by Supplier made fast without changing what it shows, with before-and-after evidence, and a second finding about the Supplier Scorecard.
Before you start. The demo’s definition, time and figures. Larkspur Lab as Rami Aziz (a lab: you
may change the statistic; the seed’s --reset restores it). A file m3-s3-diagnosis.md.
Measure and explain
- Record the demo’s baseline: response time,
millis,docsExaminedand the number of buckets. - From the pipeline, write which stage does the most work, and why, using the Concept’s trap table.
- Check the source: does the statistic’s Data Source limit purchase orders by date? Count how many
years of orders it scans:
db.purchase_orders.aggregate([{$group: {_id: {$substr: ["$value.order_date", 0, 4]}, n: {$sum: 1}}}]).
Fix and prove
- Edit the statistic: change Group by from the supplier’s name (through the relation) to the purchase order’s own Supplier reference. Save.
- Run the profiler and the API call again, as in the demo. Record the same four figures.
- Compare the two charts’ buckets: the same suppliers and the same totals?
- Add a date window: set the Data Source to the saved query Orders in the last 12 months (seeded). Save, and measure a third time.
The scorecard
- Open Quality and Compliance › Supplier Scorecard and read the definition of the aggregate: its sources and the mapping of Supplier in each.
- In the record store, find one aggregate record and its hidden source reference:
db.supplier_scorecard.findOne({}, {id: 1, "value._sourceEntry": 1, "value.supplier": 1}). - Close a non-conformance in the portal (move Seal hardness out of spec to Closed), then read the matching aggregate record again within a few seconds. Did it change, and how quickly?
- Write the scorecard’s freshness rule in one sentence, and the condition under which it breaks.
- Write the advice for Sara Qasim’s team: the two design rules that made Spend by Supplier fast.
Check.
- Baseline and two re-measurements, each with time,
millis,docsExaminedand bucket count. - The regrouped chart shows the same suppliers and totals as the original.
- The date window reduced
docsExamined, and you said what the chart now excludes. - You found an aggregate record’s source reference and saw it change after the closure.
- The freshness rule names the data service’s event handler and what happens when its queue is backed up.
Pass condition. All five checks hold, and the regrouped pipeline has no $lookup before its
$group.
If something goes wrong
| What you see | What to do |
|---|---|
| The times are all tiny | The volume set is not loaded: the seed’s --volume option adds 20,000 purchase orders. Without it, compare docsExamined and the stages instead of time. |
| The regrouped chart shows ids instead of names | The Group by is a reference, so names are resolved after the group from the title index; if names are missing, the index lags (M3-S4). Wait a minute and repeat. |
| The totals differ after regrouping | A purchase order’s Supplier may be empty; through the relation it dropped out, as a reference it forms a bucket of its own. Note it as a data-quality finding. |
| The aggregate record did not change | The non-conformance did not reach Closed, or the data service’s queue is backed up: check rabbitmqctl list_queues -p lk for the data service’s queue depth. |
| No Orders in the last 12 months query | Create it on Purchase Orders: Order Date greater than @today('-12M'). |
Model answer
Baseline. The pipeline’s base match keeps active, non-obsolete purchase orders (all 20,000, across
five years), then a $lookup (through Approved Suppliers to Suppliers) runs once per purchase order,
then $group on the supplier’s name with $sum of value.total_value. docsExamined ≈ 20,000 plus
the joined suppliers; the look-up is the dominant stage. Four years of history are scanned for a chart
people read for this year.
After regrouping. No $lookup before the $group; the group key is value.supplier.dataEntry; the
names are filled in after the group. Same suppliers and totals (unless some orders lack a supplier,
which now show as their own bucket). Time and millis fall markedly. After the date window,
docsExamined falls to about a fifth: only the last twelve months are scanned, and the chart no longer
shows older spend, which is what its readers use it for (say so in the chart’s description).
Scorecard. Each scorecard record carries value._sourceEntry pointing at the inspection or
non-conformance it came from; closing the non-conformance updates its scorecard record within a second
or two, because the data service handles the record-updated event and recomputes that one record by its
computed id. Rule: “The scorecard is as fresh as the data service’s handling of Quality’s record
events: normally seconds; it lags when that queue backs up, and stops when its handler fails on every
event, until the cause is fixed and the dead letters are replayed.”
Advice. “Group by the reference, not through it: names are added after the group. Give every chart a date window that matches the decision it serves.”
◇ Worked scenario (2 min) — The 08:00 slowdown
Section titled “◇ Worked scenario (2 min) — The 08:00 slowdown”Every weekday at about 08:00, the portal is slow for ten minutes. By 08:15 it is fine. Nothing runs on a schedule at 08:00. Reason it through before you read each step.
Step 1: what happens at 08:00? People arrive, and Operations Command is the landing page of every planner and lead: about forty people open it within minutes.
Step 2: what does opening it cost? The page holds twelve widgets: eight counters, three charts and a list. Each runs its own aggregation on every opening, with no sharing between people. Forty openings of twelve widgets is 480 aggregations, concentrated in a few minutes, on the same data service pods that answer every other request.
Step 3: which widgets dominate? You switch the profiler on in Larkspur Lab, open the page once, and
sort the profiled operations by millis. Two stand out: a counter “Open work orders at sites with a
safety hold”, which counts across the relation to assets, and the chart “Spend this year by category”,
which groups through two relations. Together they are four fifths of the page’s database time.
Step 4: the decision. You do not add hardware first. The counter’s site condition becomes a mapped field on work orders (Site Hold, copied from the asset), so the count runs on the work order’s own field. The chart moves from the landing page to Procurement’s own page, where a handful of people open it. The landing page keeps the counters people act on first thing.
Step 5: the proof. Profiling one opening again shows the page’s database time down by more than half. In M9-S1 you will learn to read the same signal from the platform’s metrics, without a profiler, in production.
✓ Practice (6 min) — Predict the cost and the freshness
Section titled “✓ Practice (6 min) — Predict the cost and the freshness”After a breaking change to Purchase Orders, Spend by Supplier shows about half the usual total, and nobody deleted anything. Why?
Check your answer
The correct answer is C. Open the explanation under each option to see why.
A builder adds eight more counters to Operations Command. What does each person’s opening of the page now cost the platform?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
Tariq Saleh edits the Supplier Scorecard’s mapping at 10:00 on a weekday. Planners report the scorecard is empty until 10:04. What happened?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
Two people close the same non-conformance’s corrective action, one after the other. How many records does the aggregate hold for that non-conformance afterwards?
Check your answer
The correct answer is C. Open the explanation under each option to see why.
A counter “Open work orders” takes two seconds on 300,000 records, while the list of open work orders with the same filter opens in under a second. Why can a count be slower than a page?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
↺ Recap (1 min) — Cost and freshness, on purpose
Section titled “↺ Recap (1 min) — Cost and freshness, on purpose”You can now explain how statistics, counters and dashboards are computed when read, how virtual entities and aggregates are materialised and kept current from events, and diagnose a slow chart or a stale read model to its cause with evidence.
Next. M3-S4 opens the other read model the platform keeps up to date from events: the search indexes, including the title index the statistic used to name its buckets.