Skip to content

M3-S3 — Aggregation, statistics and composite read models

Section titled “M3-S3 — Aggregation, statistics and composite read models”
ModuleM3 — The read side
After this session you canExplain how a statistic, a counter and a joiner or aggregate entity are computed, and spot the designs that make them slow.
TimeFacilitated: 51 min · On your own: 51 min
Before you startM3-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 deeperEngine: 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 readMaterialised ahead
WhatStatistics (charts, number tiles, lists of totals), counters, entries-list summariesVirtual entities: proxies, joiners, aggregates
When the work happensEvery time someone opens the screenWhen a source record changes, and on a rebuild
FreshnessAlways currentA little behind its sources
Cost grows withHow often it is opened, and how much data each opening scansHow often sources change, and how big a rebuild is

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:

  1. The source query’s criteria are compiled as in M3-S2, with any parameters filled in.
  2. Relation look-ups are added for every group-by or measure path that crosses a relation (value.supplier.:relation.value.country).
  3. 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.
  4. Unwinds expand repeatable fields and blocks and relation results into one row each.
  5. Date bucketing converts each date to the user’s time zone and formats it into its bucket.
  6. 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.
  7. 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.

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.

SymptomUsual causeBetter design
A chart is slow, and slower every monthGroups through a relation, or has no date limit on its source query, so it scans all historyGroup by the reference itself; give the source query a date window
A number tile is slow although the entity is smallIt counts across a relation, or uses Contains on textCount on the record’s own fields; copy what you filter on as a mapped field
Operations Command is slow at 08:00 onlyMany widgets, each an aggregation, opened by everyone at onceFewer widgets on the landing page; move detail to drill-down pages
A statistic ignores some recordsThey are obsolete after a breaking changeUpgrade the records (M2-S3)
An aggregate is empty for a while after a changeIts definition change triggered a full rebuildChange aggregate definitions in the release window, not mid-morning
An aggregate lags or stops updatingThe data service’s handler for its source events is slow or failingRead 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.

  1. 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.

  2. Switch the profiler on (db.setProfilingLevel(2) on lk-data).

  3. 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]'
  4. 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 $lookup into suppliers through Approved Suppliers, the $group and 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.

  5. 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

  1. Record the demo’s baseline: response time, millis, docsExamined and the number of buckets.
  2. From the pipeline, write which stage does the most work, and why, using the Concept’s trap table.
  3. 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

  1. Edit the statistic: change Group by from the supplier’s name (through the relation) to the purchase order’s own Supplier reference. Save.
  2. Run the profiler and the API call again, as in the demo. Record the same four figures.
  3. Compare the two charts’ buckets: the same suppliers and the same totals?
  4. 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

  1. Open Quality and Compliance › Supplier Scorecard and read the definition of the aggregate: its sources and the mapping of Supplier in each.
  2. 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}).
  3. 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?
  4. Write the scorecard’s freshness rule in one sentence, and the condition under which it breaks.
  5. 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, docsExamined and 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 seeWhat to do
The times are all tinyThe 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 namesThe 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 regroupingA 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 changeThe 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 queryCreate 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”
PracticeChoose one answer.

After a breaking change to Purchase Orders, Spend by Supplier shows about half the usual total, and nobody deleted anything. Why?

  1. Explanation for A

    ✗ Incorrect

    Not this one: statistics are computed when read, with no cache between openings. See A statistic, step by step.

  2. Explanation for B

    ✗ Incorrect

    Not this one: obsolescence, not the look-up, removed them before grouping. See A statistic, step by step.

  3. Explanation for C

    ✓ Correct

    Correct: every statistic keeps only active, non-obsolete records, so un-upgraded records drop out. See A statistic, step by step.

Check your answer

The correct answer is C. Open the explanation under each option to see why.

PracticeChoose one answer.

A builder adds eight more counters to Operations Command. What does each person’s opening of the page now cost the platform?

  1. Explanation for A

    ✓ Correct

    Correct: each widget runs its own count or statistic on every opening, with no sharing. See Counters, dashboards and pages.

  2. Explanation for B

    ✗ Incorrect

    Not this one: counters are computed when the page is read, every time. See Counters, dashboards and pages.

  3. Explanation for C

    ✗ Incorrect

    Not this one: widgets run independently; nothing merges them. See Counters, dashboards and pages.

Check your answer

The correct answer is A. Open the explanation under each option to see why.

PracticeChoose one answer.

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?

  1. Explanation for A

    ✗ Incorrect

    Not this one: editing an aggregate does not lock its sources. See Virtual entities.

  2. Explanation for B

    ✓ Correct

    Correct: a definition change rebuilds the whole aggregate, which is empty until the rebuild ends. See Virtual entities.

  3. Explanation for C

    ✗ Incorrect

    Not this one: obsolescence comes from breaking changes to an entity’s structure, not a rebuild. See Virtual entities.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

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?

  1. Explanation for A

    ✗ Incorrect

    Not this one: an update recomputes the existing aggregate record, it does not add one. See Virtual entities.

  2. Explanation for B

    ✗ Incorrect

    Not this one: aggregates are kept current from source events, not rebuilt nightly. See Virtual entities.

  3. Explanation for C

    ✓ Correct

    Correct: the deterministic id makes each refresh address the same record directly. See Virtual entities.

Check your answer

The correct answer is C. Open the explanation under each option to see why.

PracticeChoose one answer.

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?

  1. Explanation for A

    ✓ Correct

    Correct: the count ends in a count over all matching rows; a page sorts and limits. See Counters, dashboards and pages.

  2. Explanation for B

    ✗ Incorrect

    Not this one: a counter runs the count variant of the list-read pipeline. See Counters, dashboards and pages.

  3. Explanation for C

    ✗ Incorrect

    Not this one: counts are computed by the data service on every runtime. See Counters, dashboards and pages.

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.