Long horizons

This tutorial computes a merchant's 7-day total at the moment of the request. Reading the whole window from the event index would fetch every payment of the week. Reading only hour buckets would miss the hour still open. The read combines both: hour buckets for the whole hours, the index for the two edges.

You need a test featuremeshd, Kafka, Redis and PostgreSQL ( Tutorial settings ). Complete Buckets per key first.

The buckets

The hour buckets land in a PostgreSQL table you create. Run this in PostgreSQL. It also drops the queue table of an earlier run:

Postgres
DROP TABLE IF EXISTS tut_hook_horizon_per_hour;
DROP TABLE IF EXISTS tut_hook_horizon_queue;
CREATE TABLE tut_hook_horizon_per_hour (merchant_id BIGINT, hour TIMESTAMP(3), n BIGINT, total DOUBLE PRECISION, request_time TIMESTAMP(6), compute_time TIMESTAMP(6), datakey TEXT, "partition" INTEGER, "offset" BIGINT, drain BIGINT, PRIMARY KEY (merchant_id, hour));
Result

The features, the hooks and the sink on that table:

FeatureQL
CREATE OR REPLACE FEATURES IN FM.TUTORIALS.HOOK_HORIZON 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_horizon])
    ),
    payment_id := INPUT(BIGINT),
    merchant_id := INPUT(BIGINT),
    amount := INPUT(DOUBLE),
    event_time := INPUT(TIMESTAMP(3)),
    pay_row := ROW(
        event_time AS event_time,
        payment_id AS payment_id,
        amount AS amount
    ),
    hour_ref := ROW(
        merchant_id AS merchant_id,
        DATE_TRUNC(event_time, 'hour') AS hour
    ),
    hour_close := (DATE_TRUNC(event_time, 'hour') + INTERVAL '65 MINUTE')::TIMESTAMP(0),
    pay_ps := PREPARED_STATEMENT(
        pay_row
        USING (payment_id, merchant_id, amount, event_time)
        CAPTURE (hour_ref, hour_close)
    ),
    pay_index := SINK(
        'redis://host.docker.internal:26379'
        KEY 'tut_hook_horizon:pay:{' || merchant_id::VARCHAR || '}'
        INDEXED ON event_time UNIQUE ON payment_id
        WITH (
            FORMAT = 'msgpack',
            MODE = 'append',
            SHAPE = 'sorted_set',
            RETENTION = INTERVAL '36500 DAY'
        )
    ),
    on_payment := HOOK(
        RUN pay_ps
        ON payments AS p
        USING (p[payment_id], p[merchant_id], p[amount], p[event_time])
        TO pay_index
    ),
    kv := SOURCE_KV('redis://host.docker.internal:26379'),
    hh := INPUT(ROW<merchant_id BIGINT, hour TIMESTAMP(3)>),
    hh_pays := EXTERNAL_KV(
        KEY 'tut_hook_horizon:pay:{' || hh[merchant_id]::VARCHAR || '}'
        FROM kv
        AS ARRAY<
            ROW<
                event_time TIMESTAMP(3),
                payment_id BIGINT,
                amount DOUBLE,
                request_time TIMESTAMP(6),
                compute_time TIMESTAMP(6),
                datakey VARCHAR,
                partition INT,
                offset BIGINT,
                drain BIGINT
            >
        > INDEXED ON event_time
        WITH (
            FORMAT = 'msgpack'
        )
    )[value],
    hour_pays := hh_pays.CARRY(hh[hour] AS h).TRANSFORM(
        RETURN amount
        WHERE event_time >= h AND event_time < h + INTERVAL '1 HOUR'
    ),
    hour_row := ROW(
        ARRAY_COUNT(hour_pays) AS n,
        ARRAY_SUM(hour_pays[amount]) AS total
    ),
    hour_ps := PREPARED_STATEMENT(hour_row USING hh),
    per_hour := SINK(
        'postgresql://featuremesh@host.docker.internal:25432/featuremesh?sslmode=disable'
        TABLE 'tut_hook_horizon_per_hour' KEY (MERCHANT_ID, HOUR)
        WITH (
            MODE = 'latest',
            RETENTION = INTERVAL '36500 DAY',
            PASSWORD = SECRET('env', 'FEATUREMESH_DEMOS_PG_PASSWORD')
        )
    ),
    hour_queue := SINK(
        'postgresql://featuremesh@host.docker.internal:25432/featuremesh?sslmode=disable'
        TABLE 'tut_hook_horizon_queue'
        WITH (
            PASSWORD = SECRET('env', 'FEATUREMESH_DEMOS_PG_PASSWORD')
        )
    ),
    rollup_hour := HOOK(
        RUN hour_ps
        ON pay_ps
        AT hour_close
        USING (hour_ref)
        TO per_hour
        QUEUE hour_queue
        WITH (
            EVERY = INTERVAL '1 HOUR',
            EXPIRE = INTERVAL '36500 DAY'
        )
    )
;
Result
feature_name VARCHARstatus VARCHARmessage VARCHAR
FM.TUTORIALS.HOOK_HORIZON.AMOUNTCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.EVENT_TIMECREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.HHCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.HH_PAYSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.HOUR_CLOSECREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.HOUR_PAYSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.HOUR_PSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.HOUR_QUEUECREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.HOUR_REFCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.HOUR_ROWCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.KVCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.MERCHANT_IDCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.ON_PAYMENTCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.PAYMENTSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.PAYMENT_IDCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.PAY_INDEXCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.PAY_PSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.PAY_ROWCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.PER_HOURCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.ROLLUP_HOURCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.STREAMCREATEDFeature created as not exists

The index and an hour rollup work as in Buckets per key . Here each payment schedules its hour directly, due 65 minutes after the hour starts: 5 minutes for late records.

The read

FeatureQL
CREATE OR REPLACE FEATURES IN FM.TUTORIALS.HOOK_HORIZON AS
PERSIST
    pg := SOURCE_DB(
        'postgresql://featuremesh@host.docker.internal:25432/featuremesh?sslmode=disable'
        WITH (
            TABLES = ARRAY('tut_hook_horizon_per_hour'),
            PASSWORD = SECRET('env', 'FEATUREMESH_DEMOS_PG_PASSWORD')
        )
    ),
    merchants := ENTITY(),
    hours := ENTITY(),
    w_merchant := INPUT(BIGINT#merchants),
    w_at := INPUT(TIMESTAMP),
    hour_key := INPUT(VARCHAR#hours),
    hour_buckets := EXTERNAL_COLUMNS(
        datakey VARCHAR#hours BIND TO hour_key,
        merchant_id BIGINT#merchants,
        hour TIMESTAMP(3),
        total DOUBLE
        FROM TABLE(pg[tut_hook_horizon_per_hour])
    ),
    w_start := w_at - INTERVAL '7 DAY',
    w_first := DATE_TRUNC(w_start, 'hour') + INTERVAL '1 HOUR',
    w_cut := DATE_TRUNC(w_at - INTERVAL '10 MINUTE', 'hour'),
    w_buckets := RELATED(
        SUM(hour_buckets[total]) ON hour_buckets[merchant_id] = w_merchant
        AND hour_buckets[hour] >= w_first
        AND hour_buckets[hour] < w_cut
    ),
    w_pays := EXTERNAL_KV(
        KEY 'tut_hook_horizon:pay:{' || KEY_TO_SCALAR(w_merchant)::VARCHAR
        || '}'
        FROM kv
        AS ARRAY<
            ROW<
                event_time TIMESTAMP(3),
                payment_id BIGINT,
                amount DOUBLE,
                request_time TIMESTAMP(6),
                compute_time TIMESTAMP(6),
                datakey VARCHAR,
                partition INT,
                offset BIGINT,
                drain BIGINT
            >
        > INDEXED ON event_time
        WITH (
            FORMAT = 'msgpack'
        )
    )[value],
    w_edges := w_pays.CARRY(w_start AS s, w_first AS f, w_cut AS c, w_at AS t).TRANSFORM(
        RETURN amount
        WHERE (event_time > s AND event_time < f)
        OR (event_time >= c AND event_time <= t)
    ),
    sum_7d := COALESCE(w_buckets, 0e0)
    + COALESCE(ARRAY_SUM(w_edges[amount]), 0e0),
    sum_7d_ps := PREPARED_STATEMENT(sum_7d USING (w_merchant, w_at))
;
Result
feature_name VARCHARstatus VARCHARmessage VARCHAR
FM.TUTORIALS.HOOK_HORIZON.HOURSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.HOUR_BUCKETSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.HOUR_KEYCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.MERCHANTSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.PGCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.SUM_7DCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.SUM_7D_PSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.W_ATCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.W_BUCKETSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.W_CUTCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.W_EDGESCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.W_FIRSTCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.W_MERCHANTCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.W_PAYSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_HORIZON.W_STARTCREATEDFeature created as not exists

The window (W_AT - 7 days, W_AT] splits in three:

PartRead fromHow
The partial first hour, (W_START, W_FIRST)the indexa range of members
The whole hours, [W_FIRST, W_CUT)the bucketsone query, RELATED(SUM(...))
The rest, [W_CUT, W_AT]the indexa range of members

The bounds, as the reader computes them:

  • W_START is W_AT - INTERVAL '7 DAY', excluded.
  • W_FIRST is DATE_TRUNC(W_START, 'hour') + INTERVAL '1 HOUR', always after W_START. When W_START is a whole hour, 16:00, W_FIRST is 17:00. The first hour, (16:00, 17:00), then comes from the index, and a payment at exactly 16:00 is left out.
  • W_CUT is DATE_TRUNC(W_AT - INTERVAL '10 MINUTE', 'hour'): the end of the last hour that ended at least 10 minutes before the request. These 10 minutes are the lag tolerance.
Request atW_CUTThe 15:00 hour comes from
16:0515:00the index
16:1016:00its bucket, due at 16:05: the rollup has 5 minutes to write it
16:3016:00its bucket

An hour that ended within the tolerance is read from the index. A bucket the rollup has not written yet is then not missed, as long as the rollup writes each bucket within the tolerance.

HOUR_BUCKETS is a table with one row per merchant and hour, read over a range of hours: why it declares an entity of its own, HOURS, is in A table keyed by several columns, read over a range .

Payments in, sums out

Merchant 7 pays 10.0, 3.0 and 4.0 in the 15:00 hour. Merchant 9 pays 5.0:

FeatureQL
TEST SERVING PRODUCE 'FM.TUTORIALS.HOOK_HORIZON.PAYMENTS'
{"key": "7", "time": "2025-11-24T15:00:10", "partition": 0, "value": {"payment_id": 1, "merchant_id": 7, "amount": 10.0, "event_time": "2025-11-24T15:00:10"}}
{"key": "9", "time": "2025-11-24T15:00:30", "partition": 0, "value": {"payment_id": 4, "merchant_id": 9, "amount": 5.0, "event_time": "2025-11-24T15:00:30"}}
{"key": "7", "time": "2025-11-24T15:00:40", "partition": 0, "value": {"payment_id": 2, "merchant_id": 7, "amount": 3.0, "event_time": "2025-11-24T15:00:40"}}
{"key": "7", "time": "2025-11-24T15:21:20", "partition": 0, "value": {"payment_id": 3, "merchant_id": 7, "amount": 4.0, "event_time": "2025-11-24T15:21:20"}}

At 15:30, the 15:00 hour is an edge, read from the index. At 16:30, it is past the tolerance and comes from its bucket, which the rollup has not written yet: the sum finds nothing.

Prepared
FM.TUTORIALS.HOOK_HORIZON.SUM_7D_PS
Call 1
{"input_1": [[7, "2025-11-24 15:30:00"], [7, "2025-11-24 16:30:00"], [9, "2025-11-24 16:30:00"]]}
W_MERCHANT BIGINTW_AT VARCHARSUM_7D_PS DOUBLE
72025-11-24 15:30:0017.0
72025-11-24 16:30:000.0
92025-11-24 16:30:000.0

The buckets fall due at 16:05. The drain writes them:

FeatureQL
TEST SERVING DRAIN 'FM.TUTORIALS.HOOK_HORIZON.ROLLUP_HOUR';
Result
HOOK VARCHARDRAINS BIGINTFIRED BIGINTEXPIRED BIGINTDELETED BIGINTDATA_ERRORS BIGINT
FM.TUTORIALS.HOOK_HORIZON.ROLLUP_HOUR12020

Once the buckets are written, every read agrees with the index. A week later, at 15:10 on 2025-12-01, only the payment of 15:21:20 remains, in the window's partial first hour:

Prepared
FM.TUTORIALS.HOOK_HORIZON.SUM_7D_PS
Call 1
{"input_1": [[7, "2025-11-24 15:30:00"], [7, "2025-11-24 16:30:00"], [9, "2025-11-24 16:30:00"], [7, "2025-12-01 15:10:00"]]}
W_MERCHANT BIGINTW_AT VARCHARSUM_7D_PS DOUBLE
72025-11-24 15:30:0017.0
72025-11-24 16:30:0017.0
72025-12-01 15:10:004.0
92025-11-24 16:30:005.0

A late payment

Merchant 7 paid 5.0 at 15:20, and the record reaches the topic at 16:20, after the hour's bucket was written:

FeatureQL
TEST SERVING PRODUCE 'fm.tutorials.hook_horizon.payments'
{"key": "7", "time": "2025-11-24T16:20:00", "partition": 0, "value": {"payment_id": 5, "merchant_id": 7, "amount": 5.0, "event_time": "2025-11-24T15:20:00"}}

Prepared
FM.TUTORIALS.HOOK_HORIZON.SUM_7D_PS
Call 1
{"input_1": [[7, "2025-11-24 15:30:00"], [7, "2025-11-24 16:30:00"]]}
w_merchant BIGINTw_at VARCHARsum_7d_ps DOUBLE
72025-11-24 15:30:0022.0
72025-11-24 16:30:0017.0

The read at 15:30 takes the hour from the index, so it counts the late payment at once: 22.0. The read at 16:30 takes the hour from the bucket computed before the payment arrived, and misses it: 17.0. The payment queued its hour again, due at 16:05, already past. The next drain computes the hour again:

FeatureQL
TEST SERVING DRAIN 'FM.TUTORIALS.HOOK_HORIZON.ROLLUP_HOUR';
Result
HOOK VARCHARDRAINS BIGINTFIRED BIGINTEXPIRED BIGINTDELETED BIGINTDATA_ERRORS BIGINT
FM.TUTORIALS.HOOK_HORIZON.ROLLUP_HOUR11010

Prepared
FM.TUTORIALS.HOOK_HORIZON.SUM_7D_PS
Call 1
{"input_1": [[7, "2025-11-24 15:30:00"], [7, "2025-11-24 16:30:00"]]}
w_merchant BIGINTw_at VARCHARsum_7d_ps DOUBLE
72025-11-24 15:30:0022.0
72025-11-24 16:30:0022.0

Both reads agree again. A payment later than the rollup's EXPIRE would be missing from its bucket for good, and from this read too.

What you learned

  • A long window reads whole hours from buckets, and only its two edges from the index.
  • The lag tolerance gives the rollup time to write a bucket before reads count on it.
  • A late payment is missing from the reads that take its hour from the bucket, until the next drain computes the bucket again.

Next