Aggregating a key's recent history

Many real-time features summarize what happened to a key recently: the purchases of a customer in the last 30 days, the failed logins of an account in the last hour, the refunds of a merchant this week. The rows live in an operational database, one per event, and the feature is an aggregate over the rows of one key within a window that ends at the time of the request.

This page builds such a feature end to end over PostgreSQL: the events table, the features, a free-form query, and a prepared statement that takes the time of the call.

The events

One row per event, indexed by account and time. The fixture dates them relative to now, so account 1 has two events in the last 30 days (a purchase and a refund) and one older; account 2 has one; account 3 has none:

Postgres
SELECT account_id, event_id, EXTRACT(DAY FROM (now() AT TIME ZONE 'UTC') - event_ts)::BIGINT AS age_days, amount, kind
FROM serving_slt_history_events;
Result
ACCOUNT_ID BIGINTEVENT_ID BIGINTAGE_DAYS BIGINTAMOUNT DOUBLEKIND VARCHAR
11110.0purchase
12325.0refund
134020.0purchase
24230.0purchase

The features

FeatureQL
CREATE OR REPLACE FEATURES IN FM.TUTORIALS.HISTORY AS
PERSIST
    POSTGRES_CONN := SOURCE_DB(
        'postgresql://featuremesh@host.docker.internal:25432/featuremesh?sslmode=disable'
        WITH (
            password = SECRET('env', 'FEATUREMESH_DEMOS_PG_PASSWORD'),
            tables = ARRAY['serving_slt_history_events'],
            timeout = '2s'
        )
    ),
    ACCOUNTS := ENTITY(),
    EVENTS := ENTITY(),
    ACCOUNT_ID := INPUT(BIGINT#ACCOUNTS),
    EVENT_ID := INPUT(BIGINT#EVENTS),
    REQ_TS := INPUT(TIMESTAMP),
    EVT := EXTERNAL_COLUMNS(
        event_id BIGINT#EVENTS BIND TO EVENT_ID,
        account_id BIGINT#ACCOUNTS,
        event_ts TIMESTAMP,
        amount DOUBLE,
        kind VARCHAR
        FROM TABLE(FM.TUTORIALS.HISTORY.POSTGRES_CONN[serving_slt_history_events])
    ),
    IN_LAST_30D := EVT[account_id] = ACCOUNT_ID AND EVT[event_ts] > REQ_TS - INTERVAL '30 days',
    LAST_30D := ROW(
        RELATED(COUNT() ON IN_LAST_30D) AS n_events,
        RELATED(SUM(EVT[amount]) ON IN_LAST_30D) AS total,
        RELATED(COUNT_IF(EVT[kind] = 'refund') ON IN_LAST_30D) AS n_refunds
    );
Result
feature_name VARCHARstatus VARCHARmessage VARCHAR
FM.TUTORIALS.HISTORY.ACCOUNTSCREATEDFeature created as not exists
FM.TUTORIALS.HISTORY.ACCOUNT_IDCREATEDFeature created as not exists
FM.TUTORIALS.HISTORY.EVENTSCREATEDFeature created as not exists
FM.TUTORIALS.HISTORY.EVENT_IDCREATEDFeature created as not exists
FM.TUTORIALS.HISTORY.EVTCREATEDFeature created as not exists
FM.TUTORIALS.HISTORY.IN_LAST_30DCREATEDFeature created as not exists
FM.TUTORIALS.HISTORY.LAST_30DCREATEDFeature created as not exists
FM.TUTORIALS.HISTORY.POSTGRES_CONNCREATEDFeature created as not exists
FM.TUTORIALS.HISTORY.REQ_TSCREATEDFeature created as not exists

Read it from the bottom up:

  • LAST_30D is a row of three aggregates. Each is RELATED(aggregate ON condition): the aggregate over the events for which the condition holds, computed for each account.
  • IN_LAST_30D is that condition, written once and shared: the event belongs to the account, and it happened in the 30 days before REQ_TS.
  • EVT maps the table's columns. The table is keyed by event_id (BIND TO EVENT_ID); account_id is just a column, annotated #ACCOUNTS so that FeatureQL knows it holds an account key.
  • REQ_TS is an input like any other: the time the window ends at. Making it an input, rather than calling NOW() inside the feature, keeps the feature deterministic: the same REQ_TS gives the same answer, so a test pins it and a past call can be replayed. The prepared statement below binds it to the time of the call.

A free-form query

A query binds every input itself:

FeatureQL
RETURN
    fm.tutorials.history.account_id,
    fm.tutorials.history.last_30d
FOR CROSS
    fm.tutorials.history.account_id := BIND_VALUES(ARRAY(1, 2, 3)),
    fm.tutorials.history.req_ts := BIND_VALUES(
        ARRAY(@eval_as_literal(CURRENT_TIMESTAMP()))
    ),
    NESTED fm.tutorials.history.event_id := @BIND_KEYSET(fm.tutorials.history.evt)
;
Result
ACCOUNT_ID BIGINTLAST_30D ROW(n_events BIGINT, total DOUBLE, n_refunds BIGINT)
1{n_events: 2, total: 35.0, n_refunds: 1}
2{n_events: 1, total: 30.0, n_refunds: 0}
3{n_events: 0, total: NULL, n_refunds: 0}

  • ACCOUNT_ID is the accounts to compute.
  • REQ_TS is the end of the window. @eval_as_literal(NOW()) is the time the query is compiled.
  • NESTED EVENT_ID := @BIND_KEYSET(EVT) names the events that RELATED() aggregates over: all the rows of the table. NESTED makes them a nested domain of each account rather than one more axis of the cross product, so the result has one row per account, not one per account and event.

Account 3 has no event: COUNT() is 0 and SUM() is NULL, as in SQL.

A prepared statement

In production, a caller sends account IDs and nothing else. The prepared statement binds the rest:

FeatureQL
CREATE OR REPLACE FEATURE FM.TUTORIALS.HISTORY.LAST_30D_PS AS
PREPARED_STATEMENT(
    FM.TUTORIALS.HISTORY.LAST_30D
    USING (FM.TUTORIALS.HISTORY.ACCOUNT_ID, FM.TUTORIALS.HISTORY.REQ_TS := REQUEST_TIME())
);
Result
feature_name VARCHARstatus VARCHARmessage VARCHAR
FM.TUTORIALS.HISTORY.LAST_30D_PSCREATEDFeature created as not exists

  • REQ_TS := REQUEST_TIME() binds the end of the window to the time of each call (see call binders ). The caller cannot send it.
  • The events need no binding. In a prepared statement, the rows a RELATED() aggregates over are always the whole table. The key in the condition, EVT[account_id] = ACCOUNT_ID, is what limits the read to the caller's accounts.

After RECOMPILE SERVING, a call carries only input_1, the accounts:

Prepared
FM.TUTORIALS.HISTORY.LAST_30D_PS
Call 1
{"input_1": [[1], [2], [3]]}
ACCOUNT_ID BIGINTREQ_TS VARCHARLAST_30D_PS ROW
1*{n_events: 2, total: 35.0, n_refunds: 1}
2*{n_events: 1, total: 30.0, n_refunds: 0}
3*{n_events: 0, total: NULL, n_refunds: 0}

REQ_TS comes back with each row: it is the time the server received the call.

What you learned

  • A feature over a key's recent history is a RELATED() aggregate, with a condition on the key and the window.
  • The end of the window is an input, so the feature stays deterministic, and a test or a replay can pin it.
  • A prepared statement binds that input to REQUEST_TIME(), and the caller sends only keys.

What's next