Buckets per key

This tutorial computes each merchant's total per minute, then per hour, and stores them in PostgreSQL tables for anything to read: serving, a dashboard, a batch job. A bucket is computed once, after it closes, however many payments it had. You then send late payments, one counted and one too late to count.

You need a test featuremeshd, Kafka, Redis and PostgreSQL ( Tutorial settings ). The index works as in A rolling window .

The tables

The buckets land in two PostgreSQL tables you create, keyed by merchant and minute, and by merchant and hour. Their last columns hold what featuremeshd writes beside each value ( Sinks and reading back ). Run this in PostgreSQL. It also drops the queue tables of an earlier run:

Postgres
DROP TABLE IF EXISTS tut_hook_per_minute;
DROP TABLE IF EXISTS tut_hook_per_hour;
DROP TABLE IF EXISTS tut_hook_minute_queue;
DROP TABLE IF EXISTS tut_hook_hour_queue;
CREATE TABLE tut_hook_per_minute (merchant_id BIGINT, minute 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, minute));
CREATE TABLE tut_hook_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 index, and what each payment schedules

FeatureQL
CREATE OR REPLACE FEATURES IN FM.TUTORIALS.HOOK_BUCKETS 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_buckets])
    ),
    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
    ),
    minute_ref := ROW(
        merchant_id AS merchant_id,
        DATE_TRUNC(event_time, 'minute') AS minute
    ),
    minute_close := (DATE_TRUNC(event_time, 'minute') + INTERVAL '70 SECOND')::TIMESTAMP(0),
    pay_ps := PREPARED_STATEMENT(
        pay_row
        USING (payment_id, merchant_id, amount, event_time)
        CAPTURE (minute_ref, minute_close)
    ),
    pay_index := SINK(
        'redis://host.docker.internal:26379'
        KEY 'tut_hook_buckets: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
    )
;
Result
feature_name VARCHARstatus VARCHARmessage VARCHAR
FM.TUTORIALS.HOOK_BUCKETS.AMOUNTCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.EVENT_TIMECREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.MERCHANT_IDCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.MINUTE_CLOSECREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.MINUTE_REFCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.ON_PAYMENTCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.PAYMENTSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.PAYMENT_IDCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.PAY_INDEXCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.PAY_PSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.PAY_ROWCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.STREAMCREATEDFeature created as not exists

The event hook writes each payment to the merchant's index, as in A rolling window . Its statement also captures two values per payment. A capture is a feature listed in the statement's CAPTURE: computed in the same call, and not returned to the caller.

  • MINUTE_REF is the bucket the payment falls in: a row of the merchant and the minute.
  • MINUTE_CLOSE is when that bucket becomes due: the end of the minute, plus 10 seconds for payments a few seconds late. It is a TIMESTAMP(0), whole seconds, as a due time must be.

The rollups

FeatureQL
CREATE OR REPLACE FEATURES IN FM.TUTORIALS.HOOK_BUCKETS AS
PERSIST
    kv := SOURCE_KV('redis://host.docker.internal:26379'),
    mm := INPUT(ROW<merchant_id BIGINT, minute TIMESTAMP(3)>),
    mm_pays := EXTERNAL_KV(
        KEY 'tut_hook_buckets:pay:{' || mm[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],
    minute_pays := mm_pays.CARRY(mm[minute] AS m).TRANSFORM(
        RETURN amount
        WHERE event_time >= m AND event_time < m + INTERVAL '1 MINUTE'
    ),
    minute_row := ROW(
        ARRAY_COUNT(minute_pays) AS n,
        ARRAY_SUM(minute_pays[amount]) AS total
    ),
    hour_ref := ROW(
        mm[merchant_id] AS merchant_id,
        DATE_TRUNC(mm[minute], 'hour') AS hour
    ),
    hour_close := (DATE_TRUNC(mm[minute], 'hour') + INTERVAL '65 MINUTE')::TIMESTAMP(0),
    minute_ps := PREPARED_STATEMENT(
        minute_row
        USING mm
        CAPTURE (hour_ref, hour_close)
    ),
    minute_log := LOGGER(ON minute_ps TO SINK('stdout://')),
    per_minute := SINK(
        'postgresql://featuremesh@host.docker.internal:25432/featuremesh?sslmode=disable'
        TABLE 'tut_hook_per_minute' KEY (MERCHANT_ID, MINUTE)
        WITH (
            MODE = 'latest',
            RETENTION = INTERVAL '36500 DAY',
            PASSWORD = SECRET('env', 'FEATUREMESH_DEMOS_PG_PASSWORD')
        )
    ),
    minute_queue := SINK(
        'postgresql://featuremesh@host.docker.internal:25432/featuremesh?sslmode=disable'
        TABLE 'tut_hook_minute_queue'
        WITH (
            PASSWORD = SECRET('env', 'FEATUREMESH_DEMOS_PG_PASSWORD')
        )
    ),
    rollup_minute := HOOK(
        RUN minute_ps
        ON pay_ps
        AT minute_close
        USING (minute_ref)
        TO per_minute
        QUEUE minute_queue
        WITH (
            EVERY = INTERVAL '1 HOUR',
            EXPIRE = INTERVAL '36500 DAY'
        )
    ),
    hh := INPUT(ROW<merchant_id BIGINT, hour TIMESTAMP(3)>),
    hh_pays := EXTERNAL_KV(
        KEY 'tut_hook_buckets: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_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_hour_queue'
        WITH (
            PASSWORD = SECRET('env', 'FEATUREMESH_DEMOS_PG_PASSWORD')
        )
    ),
    rollup_hour := HOOK(
        RUN hour_ps
        ON minute_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_BUCKETS.HHCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.HH_PAYSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.HOUR_CLOSECREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.HOUR_PAYSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.HOUR_PSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.HOUR_QUEUECREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.HOUR_REFCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.HOUR_ROWCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.KVCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.MINUTE_LOGCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.MINUTE_PAYSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.MINUTE_PSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.MINUTE_QUEUECREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.MINUTE_ROWCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.MMCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.MM_PAYSCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.PER_HOURCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.PER_MINUTECREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.ROLLUP_HOURCREATEDFeature created as not exists
FM.TUTORIALS.HOOK_BUCKETS.ROLLUP_MINUTECREATEDFeature created as not exists

  • ROLLUP_MINUTE is a scheduled hook: ON PAY_PS AT MINUTE_CLOSE USING (MINUTE_REF). Each call of PAY_PS queues its MINUTE_REF, due at its MINUTE_CLOSE. The queue keeps one entry per reference, so the payments of one merchant in one minute fold into one entry.
  • QUEUE MINUTE_QUEUE is where the queue lives, here a PostgreSQL table. featuremeshd creates the table if it is missing ( Queues ). The queue survives restarts.
  • When an entry falls due, a drain runs MINUTE_PS once for it. Its input MM is the reference row. The call reads the merchant's index and keeps the members of that minute: the bucket's whole value, whatever arrived in between.
  • PER_MINUTE and PER_HOUR are sinks on the two tables created above.
  • MINUTE_PS captures the hour in turn, so ROLLUP_HOUR, ON MINUTE_PS, is scheduled by each minute run: buckets chain. HOUR_PS reads the hour from the index, not from the minute buckets.
  • EXPIRE drops an entry whose due time is older than EXPIRE when a drain reads it, instead of running it. EVERY is the drainer's period. The tutorial sets both long ( Tutorial settings ).

Payments in, buckets out

Merchant 7 pays twice in the minute 15:00 and once in 15:01. Merchant 9 pays once in 15:00:

FeatureQL
TEST SERVING PRODUCE 'FM.TUTORIALS.HOOK_BUCKETS.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:01:20", "partition": 0, "value": {"payment_id": 3, "merchant_id": 7, "amount": 4.0, "event_time": "2025-11-24T15:01:20"}}

Drain the minute rollup. TEST SERVING DRAIN runs the due entries at once, and answers with what it did:

FeatureQL
TEST SERVING DRAIN 'FM.TUTORIALS.HOOK_BUCKETS.ROLLUP_MINUTE';
Result
HOOK VARCHARDRAINS BIGINTFIRED BIGINTEXPIRED BIGINTDELETED BIGINTDATA_ERRORS BIGINT
FM.TUTORIALS.HOOK_BUCKETS.ROLLUP_MINUTE13030

Four payments made three buckets, so the drain ran three calls (FIRED) and removed three entries (DELETED). Each bucket holds its whole value:

Postgres
SELECT merchant_id, minute::text AS minute, n, total FROM tut_hook_per_minute ORDER BY merchant_id, minute
Result
MERCHANT_ID BIGINTMINUTE VARCHARN BIGINTTOTAL DOUBLE
72025-11-24 15:00:00213
72025-11-24 15:01:0014
92025-11-24 15:00:0015

MINUTE_LOG logs each call a drain runs. CALL_DETAILS names the hook and the drain behind the call. The result lists the fields of CALL_DETAILS to look at, not the whole logged row:

FeatureQL
SHOW SERVING LOGS LIKE 'FM.TUTORIALS.HOOK_BUCKETS.MINUTE_LOG' LIMIT 1;
Result
CALL_DETAILS FIELD VARCHARVALUE VARCHAR
status"OK"
path"FM.TUTORIALS.HOOK_BUCKETS.ROLLUP_MINUTE"
source.drain != nulltrue
source.partitionnull
source.offsetnull

The minute runs queued two hour buckets, one per merchant:

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

Postgres
SELECT merchant_id, hour::text AS hour, n, total FROM tut_hook_per_hour ORDER BY merchant_id, hour
Result
MERCHANT_ID BIGINTHOUR VARCHARN BIGINTTOTAL DOUBLE
72025-11-24 15:00:00317
92025-11-24 15:00:0015

Fifty payments, one computation

Merchant 11 pays 50 times in the minute 15:02, once a second: payments 100 to 149, 1.0 each, from 15:02:00 to 15:02:49, produced as above.

FeatureQL
TEST SERVING DRAIN 'FM.TUTORIALS.HOOK_BUCKETS.ROLLUP_MINUTE';
Result
HOOK VARCHARDRAINS BIGINTFIRED BIGINTEXPIRED BIGINTDELETED BIGINTDATA_ERRORS BIGINT
FM.TUTORIALS.HOOK_BUCKETS.ROLLUP_MINUTE11010

The fifty payments queued one entry, so the drain ran one call. The bucket counts every payment:

Postgres
SELECT merchant_id, minute::text AS minute, n, total FROM tut_hook_per_minute WHERE merchant_id = 11
Result
merchant_id BIGINTminute VARCHARn BIGINTtotal DOUBLE
112025-11-24 15:02:005050

A minute with ten thousand payments would also cost one computation.

A late payment

Merchant 7 paid 2.0 at 15:00:50, and the record reaches the topic at 15:05:

FeatureQL
TEST SERVING PRODUCE 'fm.tutorials.hook_buckets.payments'
{"key": "7", "time": "2025-11-24T15:05:00", "partition": 0, "value": {"payment_id": 5, "merchant_id": 7, "amount": 2.0, "event_time": "2025-11-24T15:00:50"}}

The payment queues its minute again, with the minute's own due time, 15:01:10, already past. The next drain runs it:

FeatureQL
TEST SERVING DRAIN 'FM.TUTORIALS.HOOK_BUCKETS.ROLLUP_MINUTE';
Result
HOOK VARCHARDRAINS BIGINTFIRED BIGINTEXPIRED BIGINTDELETED BIGINTDATA_ERRORS BIGINT
FM.TUTORIALS.HOOK_BUCKETS.ROLLUP_MINUTE11010

Postgres
SELECT merchant_id, minute::text AS minute, n, total FROM tut_hook_per_minute WHERE merchant_id = 7 ORDER BY minute
Result
merchant_id BIGINTminute VARCHARn BIGINTtotal DOUBLE
72025-11-24 15:00:00315
72025-11-24 15:01:0014

The 15:00 bucket was computed again, whole: three payments, 15.

A payment too late to count

In production, EXPIRE is minutes to hours. Give the minute rollup an EXPIRE of one day. The queue and its entries stay:

FeatureQL
CREATE OR REPLACE FEATURES IN FM.TUTORIALS.HOOK_BUCKETS AS
PERSIST
    rollup_minute := HOOK(
        RUN minute_ps
        ON pay_ps
        AT minute_close
        USING (minute_ref)
        TO per_minute
        QUEUE minute_queue
        WITH (
            EVERY = INTERVAL '1 HOUR',
            EXPIRE = INTERVAL '1 DAY'
        )
    )
;
Result
feature_name VARCHARstatus VARCHARmessage VARCHAR
FM.TUTORIALS.HOOK_BUCKETS.ROLLUP_MINUTEREPLACEDFeature was replaced

Merchant 7 paid 6.0 at 15:01:30. Its bucket was due on 2025-11-24, more than a day before the drain:

FeatureQL
TEST SERVING PRODUCE 'fm.tutorials.hook_buckets.payments'
{"key": "7", "time": "2025-11-24T15:10:00", "partition": 0, "value": {"payment_id": 6, "merchant_id": 7, "amount": 6.0, "event_time": "2025-11-24T15:01:30"}}

FeatureQL
TEST SERVING DRAIN 'FM.TUTORIALS.HOOK_BUCKETS.ROLLUP_MINUTE';
Result
HOOK VARCHARDRAINS BIGINTFIRED BIGINTEXPIRED BIGINTDELETED BIGINTDATA_ERRORS BIGINT
FM.TUTORIALS.HOOK_BUCKETS.ROLLUP_MINUTE10100

The drain dropped the entry unrun (EXPIRED). The 15:01 bucket keeps its first value, without the late payment:

Postgres
SELECT merchant_id, minute::text AS minute, n, total FROM tut_hook_per_minute WHERE merchant_id = 7 ORDER BY minute
Result
merchant_id BIGINTminute VARCHARn BIGINTtotal DOUBLE
72025-11-24 15:00:00315
72025-11-24 15:01:0014

A drain reads the time T on the queue store's clock. An entry due at due runs if T ≤ due + EXPIRE, and is dropped otherwise. For the 10:00 minute, due is 10:01:10. With EXPIRE = INTERVAL '2 MINUTE':

A payment of 10:00:59QueuedNext drainBucket
arrives at 10:00:59due 10:01:1010:01:12computed with it
arrives at 10:03:05due 10:01:10, already past10:03:08computed again, with it
arrives at 10:03:05due 10:01:10, already past10:03:11dropped: the bucket keeps its first value

A missing row and a dropped entry look alike from the table. entries_expired, in SHOW SERVING STATUS, counts the dropped entries ( Status and writes ).

What you learned

  • A capture schedules a bucket from each payment; a scheduled hook runs it once it is due.
  • The queue keeps one entry per reference: fifty payments in a minute cost one computation.
  • A bucket is computed whole, from the index, every time it runs.
  • A late payment queues its bucket again, and the next drain computes it again, while within EXPIRE.
  • Past EXPIRE, the entry is dropped and the bucket keeps its first value.

Next