Scoring each event
This tutorial scores every payment as it arrives on a Kafka topic, and stores the score for serving to read back. It is the simplest precompute: the work happens when the event arrives, not when serving is called. You then see what happens to a record that does not decode, to a call that fails, and to two records with the same time. The last part stores a decision per payment, over the payments of A rolling window .
You need a test featuremeshd, Kafka, Redis and PostgreSQL ( Tutorial settings ). A rolling window introduces streams and event hooks.
The hook
Each merchant has a tier in a PostgreSQL table, tut_hook_merchants: merchant 7 is high, merchant 9 is low. Create it in PostgreSQL:
DROP TABLE IF EXISTS tut_hook_merchants;
CREATE TABLE tut_hook_merchants (merchant_id BIGINT PRIMARY KEY, tier TEXT NOT NULL);
INSERT INTO tut_hook_merchants VALUES (7, 'high'), (9, 'low');A payment's score is its amount, times 3 for a high merchant:
CREATE OR REPLACE FEATURES IN FM.TUTORIALS.HOOK_SCORING AS
PERSIST
stream := SOURCE_STREAM(
'kafka://host.docker.internal:29093'
WITH (
FORMAT = 'json'
)
),
payments := EXTERNAL_COLUMNS(
payment_id BIGINT,
merchant_id BIGINT,
amount DOUBLE,
event_time TIMESTAMP(3)
FROM TABLE(stream[tut_hook_scoring])
),
pg := SOURCE_DB(
'postgresql://featuremesh@host.docker.internal:25432/featuremesh?sslmode=disable'
WITH (
TABLES = ARRAY('tut_hook_merchants'),
PASSWORD = SECRET('env', 'FEATUREMESH_DEMOS_PG_PASSWORD')
)
),
payment_id := INPUT(BIGINT),
merchant_id := INPUT(BIGINT),
amount := INPUT(DOUBLE),
merchant := EXTERNAL_COLUMNS(
merchant_id BIGINT BIND TO merchant_id,
tier VARCHAR
FROM TABLE(pg[tut_hook_merchants])
),
tier := merchant[tier],
score := ROW(
payment_id AS payment_id,
amount
* CASE
WHEN tier = 'high' THEN 3e0
ELSE 1e0
END AS score,
tier AS tier
),
score_ps := PREPARED_STATEMENT(
score
USING (payment_id, merchant_id, amount)
),
score_log := LOGGER(ON score_ps TO SINK('stdout://')),
score_last := SINK(
'redis://host.docker.internal:26379'
KEY 'tut_hook_scoring:last:{' || merchant_id::VARCHAR || '}'
WITH (
FORMAT = 'json',
MODE = 'latest'
)
),
on_payment := HOOK(
RUN score_ps
ON payments AS p
USING (p[payment_id], p[merchant_id], p[amount])
TO score_last
)
;| feature_name VARCHAR | status VARCHAR | message VARCHAR |
|---|---|---|
| FM.TUTORIALS.HOOK_SCORING.AMOUNT | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_SCORING.MERCHANT | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_SCORING.MERCHANT_ID | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_SCORING.ON_PAYMENT | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_SCORING.PAYMENTS | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_SCORING.PAYMENT_ID | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_SCORING.PG | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_SCORING.SCORE | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_SCORING.SCORE_LAST | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_SCORING.SCORE_LOG | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_SCORING.SCORE_PS | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_SCORING.STREAM | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_SCORING.TIER | CREATED | Feature created as not exists |
SCORE_PSis the statement you would serve. It reads the merchant's tier from PostgreSQL, like any serving call.3e0and1e0areDOUBLEliterals, asAMOUNTis;3.0would be aDECIMAL. The tutorials useDOUBLEamounts to stay short; for money, see Keep money exact .ON_PAYMENTrunsSCORE_PSon each record, and writes the result toSCORE_LAST.SCORE_LASTis keyed by merchant, withMODE = 'latest': it keeps each merchant's newest score. To look a score up by payment instead, key the sink byPAYMENT_ID. Each payment then has its own key, kept for the sink'sRETENTION.SCORE_LOGis a logger on the statement. It logs the hook's calls as it logs serving calls.
The hook starts once its definition is served:
RECOMPILE SERVING;| FEATURE VARCHAR | KIND VARCHAR | STATUS VARCHAR | MESSAGE VARCHAR | SINCE VARCHAR |
|---|---|---|---|---|
| FM.TUTORIALS.HOOK_SCORING.PG | SOURCE_DB | LOADED | ||
| FM.TUTORIALS.HOOK_SCORING.SCORE_LOG | LOGGER | LOADED | ||
| FM.TUTORIALS.HOOK_SCORING.SCORE_PS | PREPARED_STATEMENT | LOADED | ||
| FM.TUTORIALS.HOOK_SCORING.STREAM | SOURCE_STREAM | LOADED |
Records in, scores out
Merchant 7 pays 10.0, then merchant 9 pays 4.0:
TEST SERVING PRODUCE 'FM.TUTORIALS.HOOK_SCORING.PAYMENTS'
{"key": "7", "time": "2025-11-24T15:00:00", "partition": 0, "value": {"payment_id": 1, "merchant_id": 7, "amount": 10.0, "event_time": "2025-11-24T15:00:00"}}TEST SERVING PRODUCE 'FM.TUTORIALS.HOOK_SCORING.PAYMENTS'
{"key": "9", "time": "2025-11-24T15:00:05", "partition": 0, "value": {"payment_id": 2, "merchant_id": 9, "amount": 4.0, "event_time": "2025-11-24T15:00:05"}}Each record is one call. In a hook, REQUEST_TIME() is the record's Kafka timestamp, not the payload's event_time ( Values of the call ). The logger kept the newest call:
SHOW SERVING LOGS LIKE 'FM.TUTORIALS.HOOK_SCORING.SCORE_LOG' LIMIT 1;| RECORD FIELD VARCHAR | VALUE VARCHAR |
|---|---|
| "fm.tutorials.hook_scoring.merchant_id" | 9 |
| "fm.tutorials.hook_scoring.score_ps" | {"payment_id": 2, "score": 4.0, "tier": "low"} |
Its CALL_DETAILS say which hook ran the call (path) and which record was behind it (source, the record's partition and offset):
SHOW SERVING LOGS LIKE 'FM.TUTORIALS.HOOK_SCORING.SCORE_LOG' LIMIT 1;| CALL_DETAILS FIELD VARCHAR | VALUE VARCHAR |
|---|---|
| status | "OK" |
| path | "FM.TUTORIALS.HOOK_SCORING.ON_PAYMENT" |
| source.partition | 0 |
| source.offset != null | true |
| source.drain | null |
Merchant 7's stored value holds the score's fields, then the layout columns every stored value has. request_time is the record's time:
EVAL "local v = cjson.decode(redis.call('GET', KEYS[1])) return {string.format('%.1f', v.score), v.tier, v.request_time}" 1 tut_hook_scoring:last:{7}| SCORE VARCHAR | TIER VARCHAR | REQUEST_TIME VARCHAR |
|---|---|---|
| 30.0 | high | 2025-11-24T15:00:00.000000 |
Reading it back
FeatureMesh does not link a read to a sink: you declare the read. SHOW CREATE SINK … READER prints the declaration for the sink as it is written now, for you to paste:
SHOW CREATE SINK FM.TUTORIALS.HOOK_SCORING.SCORE_LAST READER;| OUTPUT VARCHAR |
|---|
| -- Reads FM.TUTORIALS.HOOK_SCORING.SCORE_LAST, written by FM.TUTORIALS.HOOK_SCORING.ON_PAYMENT (key columns, the value's fields, then request_time, compute_time, datakey, partition, offset, drain). -- A key whose call raised holds a tombstone, request_time and no compute_time: it reads as NULL. CREATE OR REPLACE FEATURES IN FM.TUTORIALS.HOOK_SCORING AS PERSIST SCORE_LAST_KV := SOURCE_KV('redis://host.docker.internal:26379'), SCORE_LAST_STORED := EXTERNAL_KV(KEY ('tut_hook_scoring:last:{' || FM.TUTORIALS.HOOK_SCORING.MERCHANT_ID::VARCHAR || '}') FROM SCORE_LAST_KV AS ROW(payment_id BIGINT, score DOUBLE, tier VARCHAR, request_time TIMESTAMP(6), compute_time TIMESTAMP(6), datakey VARCHAR, partition INTEGER, offset BIGINT, drain BIGINT) WITH (FORMAT = 'json')), SCORE_LAST_READ := IF(SCORE_LAST_STORED[compute_time] IS NULL, NULL, SCORE_LAST_STORED); |
Paste it, keep the fields you need, and serve them with a statement:
CREATE OR REPLACE FEATURES IN FM.TUTORIALS.HOOK_SCORING AS
PERSIST
score_last_kv := SOURCE_KV('redis://host.docker.internal:26379'),
score_last_stored := EXTERNAL_KV(
KEY 'tut_hook_scoring:last:{' || merchant_id::VARCHAR || '}'
FROM score_last_kv
AS ROW<
payment_id BIGINT,
score DOUBLE,
tier VARCHAR,
request_time TIMESTAMP(6),
compute_time TIMESTAMP(6),
datakey VARCHAR,
partition INT,
offset BIGINT,
drain BIGINT
>
WITH (
FORMAT = 'json'
)
),
score_last_read := IF(
score_last_stored[compute_time] IS NULL,
NULL,
ROW(
score_last_stored[payment_id] AS payment_id,
score_last_stored[score] AS score
)
),
read_ps := PREPARED_STATEMENT(score_last_read USING merchant_id)
;| feature_name VARCHAR | status VARCHAR | message VARCHAR |
|---|---|---|
| FM.TUTORIALS.HOOK_SCORING.READ_PS | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_SCORING.SCORE_LAST_KV | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_SCORING.SCORE_LAST_READ | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_SCORING.SCORE_LAST_STORED | CREATED | Feature created as not exists |
SCORE_LAST_READ is NULL when the stored value has no compute_time. That is how a removed value, a tombstone, reads; you meet one below.
FM.TUTORIALS.HOOK_SCORING.READ_PS{"input_1": [[7], [9]]} | merchant_id BIGINT | read_ps VARCHAR |
|---|---|
| 7 | {payment_id: 1, score: 30.0} |
| 9 | {payment_id: 2, score: 4.0} |
A record that does not decode
Merchant 9 sends a payment whose amount is not a number:
TEST SERVING PRODUCE 'fm.tutorials.hook_scoring.payments'
{"key": "9", "time": "2025-11-24T15:00:20", "partition": 0, "value": {"payment_id": 3, "merchant_id": 9, "amount": "ten", "event_time": "2025-11-24T15:00:20"}}The hook skips it. SHOW SERVING WRITES lists the hook's recent writes and errors, oldest first. The last one is the error, with no sink and no key:
SHOW SERVING WRITES LIKE 'FM.TUTORIALS.HOOK_SCORING.ON_PAYMENT' LIMIT 1;| HOOK VARCHAR | SINK VARCHAR | ACTION VARCHAR | KEY VARCHAR | REQUEST_TIME VARCHAR | VALUE VARCHAR | PARTITION BIGINT | OFFSET VARCHAR | AT VARCHAR | CALL VARCHAR |
|---|---|---|---|---|---|---|---|---|---|
| FM.TUTORIALS.HOOK_SCORING.ON_PAYMENT | (empty) | ERROR | (empty) | * | * | 0 | * | * | * |
Nothing was written, so merchant 9 still reads the score of payment 2:
FM.TUTORIALS.HOOK_SCORING.READ_PS{"input_1": [[9]]} | merchant_id BIGINT | read_ps VARCHAR |
|---|---|
| 9 | {payment_id: 2, score: 4.0} |
A call that fails
A record can decode and still make its call fail. Here the statement also captures the amount in cents, as a BIGINT, for its logger:
-- ACK-KZVQ: an amount too large for cents fails the call
CREATE OR REPLACE FEATURES IN FM.TUTORIALS.HOOK_SCORING AS
PERSIST
amount_cents := (amount * 100e0)::BIGINT,
score_ps := PREPARED_STATEMENT(
score
USING (payment_id, merchant_id, amount)
CAPTURE (amount_cents)
)
;| feature_name VARCHAR | status VARCHAR | message VARCHAR |
|---|---|---|
| FM.TUTORIALS.HOOK_SCORING.AMOUNT_CENTS | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_SCORING.SCORE_PS | REPLACED | Feature was replaced |
The cast to BIGINT fails for an amount too large for it. The registry refuses such an operation when the statement is created, unless the statement handles it or acknowledges it. The comment ACK-KZVQ accepts that a payment with such an amount fails its call ( Runtime errors in a prepared statement ).
Merchant 7 sends a payment with a corrupt amount, 1e17:
TEST SERVING PRODUCE 'fm.tutorials.hook_scoring.payments'
{"key": "7", "time": "2025-11-24T15:00:30", "partition": 0, "value": {"payment_id": 4, "merchant_id": 7, "amount": 1e17, "event_time": "2025-11-24T15:00:30"}}The call fails, and the hook goes on. It also removes merchant 7's score, and stores a tombstone in its place:
SHOW SERVING WRITES LIKE 'FM.TUTORIALS.HOOK_SCORING.ON_PAYMENT' LIMIT 2;| HOOK VARCHAR | SINK VARCHAR | ACTION VARCHAR | KEY VARCHAR | REQUEST_TIME VARCHAR | VALUE VARCHAR | PARTITION BIGINT | OFFSET VARCHAR | AT VARCHAR | CALL VARCHAR |
|---|---|---|---|---|---|---|---|---|---|
| FM.TUTORIALS.HOOK_SCORING.ON_PAYMENT | (empty) | ERROR | (empty) | * | * | 0 | * | * | {"id":"FM.TUTORIALS.HOOK_SCORING.SCORE_PS","inputs":{"input_1":[[4,7,100000000000000000]]}} |
| FM.TUTORIALS.HOOK_SCORING.ON_PAYMENT | FM.TUTORIALS.HOOK_SCORING.SCORE_LAST | DELETE | tut_hook_scoring:last:{7} | * | * | 0 | * | * | {"id":"FM.TUTORIALS.HOOK_SCORING.SCORE_PS","inputs":{"input_1":[[4,7,100000000000000000]]}} |
Both rows name the call that failed in CALL: send it to the statement again to reproduce the error.
Serving now reads a miss for merchant 7:
FM.TUTORIALS.HOOK_SCORING.READ_PS{"input_1": [[7], [9]]} | merchant_id BIGINT | read_ps VARCHAR |
|---|---|
| 7 | NULL |
| 9 | {payment_id: 2, score: 4.0} |
The score of payment 1 is gone on purpose. Payment 4 should have replaced it, so keeping it would serve a value the newest payment should have changed. An older payment arriving later cannot bring it back either: a latest value, a tombstone included, is replaced only by a record at least as new ( Tombstones ).
Two records at the same time
On a topic with LogAppendTime, the broker gives every record of a produce batch the same timestamp. Here merchant 9 pays twice, at the same Kafka time:
TEST SERVING PRODUCE 'fm.tutorials.hook_scoring.payments'
{"key": "9", "time": "2025-11-24T15:01:00", "partition": 0, "value": {"payment_id": 5, "merchant_id": 9, "amount": 1.0, "event_time": "2025-11-24T15:00:58"}}
{"key": "9", "time": "2025-11-24T15:01:00", "partition": 0, "value": {"payment_id": 6, "merchant_id": 9, "amount": 2.0, "event_time": "2025-11-24T15:00:57"}}FM.TUTORIALS.HOOK_SCORING.READ_PS{"input_1": [[9]]} | merchant_id BIGINT | read_ps VARCHAR |
|---|---|
| 9 | {payment_id: 6, score: 2.0} |
With equal times, the last record written wins: in a batch, the one of the higher offset, payment 6. Its event_time is earlier than payment 5's, and it does not matter: the order is the topic's ( Which write lands ).
A decision per payment
A decision often needs the payment's recent history, the payment itself included: how many payments the merchant made in the ten minutes up to this one. This part adds to the index of A rolling window , its PAY_PS and its PAYS.
Split it in two. The event hook writes the index, as before. A second hook, ON the event hook's statement, decides:
CREATE OR REPLACE FEATURES IN FM.TUTORIALS.HOOK_WINDOW AS
PERSIST
pays_at_event := pays.CARRY(event_time AS t).TRANSFORM(
RETURN amount
WHERE event_time > t - INTERVAL '10 MINUTE' AND event_time <= t
),
decision := ROW(
payment_id AS payment_id,
ARRAY_COUNT(pays_at_event) AS n_10m,
COALESCE(ARRAY_SUM(pays_at_event[amount]), 0e0) AS total_10m
),
decide_ps := PREPARED_STATEMENT(
decision
USING (payment_id, merchant_id, event_time)
),
decisions := SINK(
'redis://host.docker.internal:26379'
KEY 'tut_hook_window:decision:{' || payment_id::VARCHAR || '}'
WITH (
FORMAT = 'json',
MODE = 'latest',
RETENTION = INTERVAL '36500 DAY'
)
),
on_indexed := HOOK(
RUN decide_ps
ON pay_ps
USING (payment_id, merchant_id, event_time)
TO decisions
)
;| feature_name VARCHAR | status VARCHAR | message VARCHAR |
|---|---|---|
| FM.TUTORIALS.HOOK_WINDOW.DECIDE_PS | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_WINDOW.DECISION | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_WINDOW.DECISIONS | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_WINDOW.ON_INDEXED | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_WINDOW.PAYS_AT_EVENT | CREATED | Feature created as not exists |
ON_INDEXED has no AT, so it runs at once, after the event hook has written its whole batch. It sees every payment of the batch in the index. On that tutorial's payments (merchant 7 at 15:00, 15:06 and 15:12, merchant 9 at 15:05), each payment's decision is its count and its total:
EVAL "local out = {} for i = 1, 4 do local v = cjson.decode(redis.call('GET', KEYS[i])) out[i] = string.format('%d %.1f', v.n_10m, v.total_10m) end return out" 4 tut_hook_window:decision:{1} tut_hook_window:decision:{2} tut_hook_window:decision:{3} tut_hook_window:decision:{4}| PAYMENT_1 VARCHAR | PAYMENT_2 VARCHAR | PAYMENT_3 VARCHAR | PAYMENT_4 VARCHAR |
|---|---|---|---|
| 1 10.0 | 1 5.0 | 2 14.0 | 2 5.0 |
The window is the payment's own, by event time: (event_time - 10 minutes, event_time]. Payment 3, at 15:06, counts 15:00 and itself. Payment 4, at 15:12, counts 15:06 and itself. A batch-mate with a later event_time is left out, and one with the same event_time is counted.
A window read inside SCORE_PS itself would miss the payment and its batch-mates, which are not indexed yet when it runs ( What a call sees ).
What you learned
- An event hook stores one value per key, with
MODE = 'latest': the newest record's. - You read a sink back with a reader you declare, printed by
SHOW CREATE SINK … READER. - A record that does not decode is skipped, and changes nothing.
- A call that fails leaves a tombstone: serving reads a miss, not an outdated value.
- With equal times, the record of the higher offset wins.
- A hook
ONa statement runs after its batch is written, so a decision sees the payment in the index.
Next
- Buckets per key computes totals per minute, once per bucket.
- Late, corrected and missing events covers what a score and a decision can miss.
- Write results to Kafka sends each score to a topic through the logger.
- Delivery and failures lists every failure and what it does.
- Choosing a pattern says when a decision belongs to your own pipeline.