A real-time market indicator goes wrong in three predictable ways
Computing "the median price per square metre in the centre zone over the last ten minutes" looks like a query. It becomes a systems problem the moment the data comes from a queue: the same event can arrive twice, events arrive in a different order from the one in which they happened, and some arrive hours late because an agency synchronised its management system at the end of the day. A calculation that ignores these three things produces a number that oscillates and cannot be explained. This article deals with them one at a time, with a listing you can run.
I chose not to show code for Kafka or Flink: they were not available on the test machine, and a listing that was not run is not worth as much as one that was. Instead I show the logic those systems implement, in plain TypeScript, and the part that can really be tried, aggregation over time windows, in SQL with PostgreSQL 17. The concepts are those of the Flink and Kafka documentation, which I will cite where needed.
Three facts about time that the code must know
Before the code, the definitions. In a stream of events there are two different clocks, and confusing them is the source of almost all defects:
- Event time: when the fact happened (the sale was recorded at 10:04). It is a datum of the event.
- Processing time: when your system sees it. It depends on the network, the queues, the restarts.
- Watermark: a statement by the system, "event time has reached t, I no longer expect events older than t". It is what allows a window to be closed and the result to be produced.
The third concept is the one that causes the most confusion. The Flink documentation defines it like this: a Watermark(t) declares that event time has reached t in that stream, so no more elements with a timestamp less than or equal to t should arrive. The important word is "should": the watermark is a bet on delay, not a guarantee, and an event that arrives after the watermark has passed its time is called late. The design question is how long to wait before betting. Wait little and you lose data; wait long and your indicator arrives late.
Windows, watermark, duplicates and late events in one listing
The listing processes nine arrivals on a single zone. The stream contains three cases built on purpose: a
duplicate (e2 arrives twice, as can happen with "at least once" delivery), an event out of
order but tolerable (e4 has time 8 and arrives after one with time 12) and an event that is too
late (e8, time 6, arrives when the 0-10 window is already closed). Windows last 10 minutes,
and the watermark is the maximum event time seen, minus 3 minutes of tolerance.
interface Evento { id: string; zona: string; prezzoMq: number; ts: number } // ts = minutes from the start
const FINESTRA = 10; // minutes
const RITARDO_AMMESSO = 3; // minutes of tolerance before closing a window
// ARRIVAL order (not order of occurrence): there is a duplicate (e2) and a badly late event (e8).
const arrivi: Evento[] = [
{ id: 'e1', zona: 'centro', prezzoMq: 3100, ts: 1 },
{ id: 'e2', zona: 'centro', prezzoMq: 3300, ts: 4 },
{ id: 'e2', zona: 'centro', prezzoMq: 3300, ts: 4 }, // duplicate ("at least once" delivery)
{ id: 'e3', zona: 'centro', prezzoMq: 3000, ts: 9 },
{ id: 'e5', zona: 'centro', prezzoMq: 2900, ts: 12 },
{ id: 'e4', zona: 'centro', prezzoMq: 3200, ts: 8 }, // late but allowed: the 0-10 window is still open
{ id: 'e6', zona: 'centro', prezzoMq: 3050, ts: 15 }, // brings the watermark to 12: closes 0-10
{ id: 'e8', zona: 'centro', prezzoMq: 9999, ts: 6 }, // too late: the 0-10 window is already closed
{ id: 'e7', zona: 'centro', prezzoMq: 3150, ts: 21 }, // watermark at 18: closes 10-20
];
const mediana = (v: number[]) => {
const s = [...v].sort((a, b) => a - b);
const m = s.length >> 1;
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
};
const viste = new Set<string>();
const aperte = new Map<number, number[]>(); // window start -> prices
let massimo = -Infinity;
const chiuse = new Set<number>();
let duplicati = 0;
let tardivi = 0;
function chiudiMature(filigrana: number) {
for (const [inizio, prezzi] of [...aperte].sort((a, b) => a[0] - b[0])) {
if (inizio + FINESTRA <= filigrana) {
console.log(`finestra [${inizio},${inizio + FINESTRA}) chiusa a filigrana=${filigrana}: n=${prezzi.length} mediana=${mediana(prezzi)} euro/mq`);
aperte.delete(inizio);
chiuse.add(inizio);
}
}
}
for (const e of arrivi) {
if (viste.has(e.id)) { duplicati++; continue; }
viste.add(e.id);
const inizio = Math.floor(e.ts / FINESTRA) * FINESTRA;
if (chiuse.has(inizio)) { tardivi++; console.log(`scartato ${e.id}: finestra ${inizio} gia' chiusa`); continue; }
aperte.set(inizio, [...(aperte.get(inizio) ?? []), e.prezzoMq]);
massimo = Math.max(massimo, e.ts);
chiudiMature(massimo - RITARDO_AMMESSO);
}
console.log(`duplicati scartati=${duplicati}, tardivi scartati=${tardivi}, finestre ancora aperte=${aperte.size}`);
// Output:
// finestra [0,10) chiusa a filigrana=12: n=4 mediana=3150 euro/mq
// scartato e8: finestra 0 gia' chiusa
// duplicati scartati=1, tardivi scartati=1, finestre ancora aperte=2
Three lines do the work. The Set called viste discards the duplicate by
identifier: deduplication by id is what makes processing idempotent, and it is a concrete need
because a send can be repeated after an error or a restart (it depends on the client's configuration: check
it in its documentation), and the duplicate must not count twice. The assignment
Math.floor(e.ts / FINESTRA) puts the event in the window of its event time, not of its arrival
time, and that is why e4 (time 8) ends up in the 0-10 window even though it arrives after
e5. The chiudiMature call closes the windows whose end is beyond the watermark.
The output shows the result. The 0-10 window closes when e6 arrives (time 15), because the
watermark rises to 12; it contains four events, and its median is 3,150 euros per square metre, computed on
3,100, 3,300, 3,000 and 3,200. The event e8, which arrives after the closing, is dropped, and
with it its value 9,999: had we accepted it, the median would have gone from 3,150 to 3,200 (a contained
change), whereas the mean would have risen from 3,150 to about 4,520: a good reason to use the median in
market indicators. The two windows left open will not close until an event with a later time arrives: in a
real system an inactivity mechanism is advisable, because a zone with no events would otherwise never
publish its last result.
Dropping the late event is a choice, not the only one. You can send the late event to a separate queue and correct the result already published (at the price of an indicator that changes after someone has read it), or recompute every night with all the data that has arrived and leave the real-time stream as a provisional estimate. The first approach is simple and can lose information; the second is more complete and more expensive. There is no right answer: it depends on what the reader of the indicator does.
Storage: windows in SQL with date_bin
Once computed, the results (and often the raw data too) end up in a database. For those using PostgreSQL,
the date_bin function (available from version 14) groups timestamps into fixed-width bins
anchored to an origin. TimescaleDB, the time-series extension, offers time_bucket, which the
documentation describes as similar to date_bin but also capable of intervals of months or
more. The listing creates 200 test sales and computes the median per ten-minute window.
SET timezone = 'UTC';
SET client_min_messages = warning;
DROP TABLE IF EXISTS vendita;
CREATE TABLE vendita (zona text, chiusa_il timestamptz, prezzo_mq numeric);
INSERT INTO vendita
SELECT (ARRAY['centro','periferia'])[1 + g % 2],
timestamptz '2026-11-12 08:00+00' + (g * interval '47 seconds'),
2000 + (g * 37) % 900
FROM generate_series(1, 200) AS g;
-- date_bin (PostgreSQL 14+) groups into 10-minute bins anchored to an origin.
SELECT date_bin('10 minutes', chiusa_il, timestamptz '2026-11-12 08:00+00') AS finestra,
zona,
count(*) AS n,
percentile_cont(0.5) WITHIN GROUP (ORDER BY prezzo_mq) AS mediana_mq
FROM vendita
WHERE zona = 'centro'
GROUP BY 1, 2
ORDER BY 1
LIMIT 4;
-- Output:
-- finestra | zona | n | mediana_mq
-- ------------------------+--------+---+------------
-- 2026-11-12 08:00:00+00 | centro | 6 | 2259
-- 2026-11-12 08:10:00+00 | centro | 6 | 2703
-- 2026-11-12 08:20:00+00 | centro | 7 | 2284
-- 2026-11-12 08:30:00+00 | centro | 6 | 2691
-- (4 rows)
The origin passed as the third argument (08:00 UTC) is the point from which the bins are
counted: if you forget it, each session might align them differently. For the median we use
percentile_cont(0.5) WITHIN GROUP, which computes the exact percentile (with interpolation),
and not the mean: on the test data it does not change much, but on real data with outliers the difference
shows. In the first command I forced the time zone to UTC because without it the printed window depends on
the server's configuration. The data is generated by a formula, so the numbers (2,259, 2,703...) serve to
verify that the mechanism runs, not to describe a market.
A note on cost, without numbers because they depend on your load: this aggregation recomputes everything on every request. When there are many windows, it pays to compute them once at closing and save them in a table (which is what the stream of the first listing does), leaving the query for recent data. TimescaleDB's continuous aggregates are for this, but I did not try them here.
Partitions and keys: where order comes from
According to the Apache Kafka documentation, events with the same key end up in the same partition, and a consumer reads the events of a partition in exactly the order in which they were written. For a stream of price changes the natural key is the property identifier (not the zone): that way all the changes to the same listing stay in order and deduplication by id can be local to the partition. Choosing the zone as the key seems convenient for zone calculations, but concentrates the traffic of the most active zones on a few partitions and leaves the others almost empty. The per-zone calculation is then done with a second step that groups the events from the different partitions.
Where it sits in the series
The data entering this pipeline originates from the entry boundary described in the architecture article; the readings of building sensors, which arrive with the same characteristics (duplicates, delays), are in smart building IoT; and a continuously updated market indicator is the fuel of the automated valuation model, with that article's caution about time: a model must be evaluated on the future, not on the past. Readings that arrive with duplicates and delays also feed the maintenance agent described in the article on property management with agents. The same median, computed per zone instead of per time window, is in the article on H3 geographic indexing. The delivery of the alerts generated by these events, with outbox and offsets, is in the article on listing events.
What you can do now
You can distinguish event time from processing time and explain what a watermark declares and what it
bets. You can write a windowed aggregation that deduplicates, tolerates disorder within a threshold and
drops (or diverts) late events, and you can compute the same windows in SQL with date_bin.
You have a rule for the partition key: choose the one that guarantees the order you need, not the one with
which it is most convenient to aggregate. What remains to be measured, on your load, is how much delay to
tolerate and how much it costs to keep the window state: these are numbers only your data can give.
In this series, the previous article is Mortgage Applications: States, Amortization and Deadlines.
Sources
- Apache Flink, Timely Stream Processing (Event Time and Watermarks) - the definition of Watermark(t) and the distinction between event time and processing time, accessed on 2026-11-12
- Apache Kafka, Introduction - events with the same key in the same partition and read order per partition, accessed on 2026-11-12
- PostgreSQL 17, Date/Time Functions and Operators (date_bin) - the function that groups into time bins with an explicit origin, accessed on 2026-11-12
- TimescaleDB, time_bucket() - the relationship with date_bin and the support for intervals of months or more, accessed on 2026-11-12
The TypeScript listing was run with Node 24 and the SQL one with PostgreSQL 17 on 2026-11-12. Kafka, Flink and TimescaleDB were not run: of them we report only what the documentation says, on the date indicated.

Commenti
Caricamento commenti...
Sign in to comment