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:

Postgres
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');
Result

A payment's score is its amount, times 3 for a high merchant:

FeatureQL
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
    )
;
Result
feature_name VARCHARstatus VARCHARmessage VARCHAR
FM.TUTORIALS.HOOK_SCORING.AMOUNTCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_SCORING.MERCHANTCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_SCORING.MERCHANT_IDCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_SCORING.ON_PAYMENTCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_SCORING.PAYMENTSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_SCORING.PAYMENT_IDCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_SCORING.PGCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_SCORING.SCORECREATEDFeature created as not exists
FM.TUTORIALS.HOOK_SCORING.SCORE_LASTCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_SCORING.SCORE_LOGCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_SCORING.SCORE_PSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_SCORING.STREAMCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_SCORING.TIERCREATEDFeature created as not exists

  • SCORE_PS is the statement you would serve. It reads the merchant's tier from PostgreSQL, like any serving call. 3e0 and 1e0 are DOUBLE literals, as AMOUNT is; 3.0 would be a DECIMAL. The tutorials use DOUBLE amounts to stay short; for money, see Keep money exact .
  • ON_PAYMENT runs SCORE_PS on each record, and writes the result to SCORE_LAST.
  • SCORE_LAST is keyed by merchant, with MODE = 'latest': it keeps each merchant's newest score. To look a score up by payment instead, key the sink by PAYMENT_ID. Each payment then has its own key, kept for the sink's RETENTION.
  • SCORE_LOG is a logger on the statement. It logs the hook's calls as it logs serving calls.

The hook starts once its definition is served:

FeatureQL
RECOMPILE SERVING;
Result
FEATURE VARCHARKIND VARCHARSTATUS VARCHARMESSAGE VARCHARSINCE VARCHAR
FM.TUTORIALS.HOOK_SCORING.PGSOURCE_DBLOADED
FM.TUTORIALS.HOOK_SCORING.SCORE_LOGLOGGERLOADED
FM.TUTORIALS.HOOK_SCORING.SCORE_PSPREPARED_STATEMENTLOADED
FM.TUTORIALS.HOOK_SCORING.STREAMSOURCE_STREAMLOADED

Records in, scores out

Merchant 7 pays 10.0, then merchant 9 pays 4.0:

FeatureQL
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"}}

FeatureQL
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:

FeatureQL
SHOW SERVING LOGS LIKE 'FM.TUTORIALS.HOOK_SCORING.SCORE_LOG' LIMIT 1;
Result
RECORD FIELD VARCHARVALUE 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):

FeatureQL
SHOW SERVING LOGS LIKE 'FM.TUTORIALS.HOOK_SCORING.SCORE_LOG' LIMIT 1;
Result
CALL_DETAILS FIELD VARCHARVALUE VARCHAR
status"OK"
path"FM.TUTORIALS.HOOK_SCORING.ON_PAYMENT"
source.partition0
source.offset != nulltrue
source.drainnull

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:

Redis
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}
Result
SCORE VARCHARTIER VARCHARREQUEST_TIME VARCHAR
30.0high2025-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:

FeatureQL
SHOW CREATE SINK FM.TUTORIALS.HOOK_SCORING.SCORE_LAST READER;
Result
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:

FeatureQL
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)
;
Result
feature_name VARCHARstatus VARCHARmessage VARCHAR
FM.TUTORIALS.HOOK_SCORING.READ_PSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_SCORING.SCORE_LAST_KVCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_SCORING.SCORE_LAST_READCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_SCORING.SCORE_LAST_STOREDCREATEDFeature 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.

Prepared
FM.TUTORIALS.HOOK_SCORING.READ_PS
Call 1
{"input_1": [[7], [9]]}
merchant_id BIGINTread_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:

FeatureQL
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:

FeatureQL
SHOW SERVING WRITES LIKE 'FM.TUTORIALS.HOOK_SCORING.ON_PAYMENT' LIMIT 1;
Result
HOOK VARCHARSINK VARCHARACTION VARCHARKEY VARCHARREQUEST_TIME VARCHARVALUE VARCHARPARTITION BIGINTOFFSET VARCHARAT VARCHARCALL VARCHAR
FM.TUTORIALS.HOOK_SCORING.ON_PAYMENT(empty)ERROR(empty)**0***

Nothing was written, so merchant 9 still reads the score of payment 2:

Prepared
FM.TUTORIALS.HOOK_SCORING.READ_PS
Call 1
{"input_1": [[9]]}
merchant_id BIGINTread_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:

FeatureQL
-- 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)
    )
;
Result
feature_name VARCHARstatus VARCHARmessage VARCHAR
FM.TUTORIALS.HOOK_SCORING.AMOUNT_CENTSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_SCORING.SCORE_PSREPLACEDFeature 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:

FeatureQL
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:

FeatureQL
SHOW SERVING WRITES LIKE 'FM.TUTORIALS.HOOK_SCORING.ON_PAYMENT' LIMIT 2;
Result
HOOK VARCHARSINK VARCHARACTION VARCHARKEY VARCHARREQUEST_TIME VARCHARVALUE VARCHARPARTITION BIGINTOFFSET VARCHARAT VARCHARCALL 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_PAYMENTFM.TUTORIALS.HOOK_SCORING.SCORE_LASTDELETEtut_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:

Prepared
FM.TUTORIALS.HOOK_SCORING.READ_PS
Call 1
{"input_1": [[7], [9]]}
merchant_id BIGINTread_ps VARCHAR
7NULL
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:

FeatureQL
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"}}

Prepared
FM.TUTORIALS.HOOK_SCORING.READ_PS
Call 1
{"input_1": [[9]]}
merchant_id BIGINTread_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:

FeatureQL
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
    )
;
Result
feature_name VARCHARstatus VARCHARmessage VARCHAR
FM.TUTORIALS.HOOK_WINDOW.DECIDE_PSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_WINDOW.DECISIONCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_WINDOW.DECISIONSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_WINDOW.ON_INDEXEDCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_WINDOW.PAYS_AT_EVENTCREATEDFeature 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:

Redis
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}
Result
PAYMENT_1 VARCHARPAYMENT_2 VARCHARPAYMENT_3 VARCHARPAYMENT_4 VARCHAR
1 10.01 5.02 14.02 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 ON a statement runs after its batch is written, so a decision sees the payment in the index.

Next