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:
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;| ACCOUNT_ID BIGINT | EVENT_ID BIGINT | AGE_DAYS BIGINT | AMOUNT DOUBLE | KIND VARCHAR |
|---|---|---|---|---|
| 1 | 1 | 1 | 10.0 | purchase |
| 1 | 2 | 3 | 25.0 | refund |
| 1 | 3 | 40 | 20.0 | purchase |
| 2 | 4 | 2 | 30.0 | purchase |
The features
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
);| feature_name VARCHAR | status VARCHAR | message VARCHAR |
|---|---|---|
| FM.TUTORIALS.HISTORY.ACCOUNTS | CREATED | Feature created as not exists |
| FM.TUTORIALS.HISTORY.ACCOUNT_ID | CREATED | Feature created as not exists |
| FM.TUTORIALS.HISTORY.EVENTS | CREATED | Feature created as not exists |
| FM.TUTORIALS.HISTORY.EVENT_ID | CREATED | Feature created as not exists |
| FM.TUTORIALS.HISTORY.EVT | CREATED | Feature created as not exists |
| FM.TUTORIALS.HISTORY.IN_LAST_30D | CREATED | Feature created as not exists |
| FM.TUTORIALS.HISTORY.LAST_30D | CREATED | Feature created as not exists |
| FM.TUTORIALS.HISTORY.POSTGRES_CONN | CREATED | Feature created as not exists |
| FM.TUTORIALS.HISTORY.REQ_TS | CREATED | Feature created as not exists |
Read it from the bottom up:
LAST_30Dis a row of three aggregates. Each isRELATED(aggregate ON condition): the aggregate over the events for which the condition holds, computed for each account.IN_LAST_30Dis that condition, written once and shared: the event belongs to the account, and it happened in the 30 days beforeREQ_TS.EVTmaps the table's columns. The table is keyed byevent_id(BIND TO EVENT_ID);account_idis just a column, annotated#ACCOUNTSso that FeatureQL knows it holds an account key.REQ_TSis an input like any other: the time the window ends at. Making it an input, rather than callingNOW()inside the feature, keeps the feature deterministic: the sameREQ_TSgives 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:
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)
;| ACCOUNT_ID BIGINT | LAST_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_IDis the accounts to compute.REQ_TSis 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 thatRELATED()aggregates over: all the rows of the table.NESTEDmakes 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:
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())
);| feature_name VARCHAR | status VARCHAR | message VARCHAR |
|---|---|---|
| FM.TUTORIALS.HISTORY.LAST_30D_PS | CREATED | Feature 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:
FM.TUTORIALS.HISTORY.LAST_30D_PS{"input_1": [[1], [2], [3]]} | ACCOUNT_ID BIGINT | REQ_TS VARCHAR | LAST_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
A rolling window reads the same kind of window from a Redis index that an event hook keeps up to date.
Database sources shows where this aggregation runs, and how to keep it in the serving engine.
What a prepared statement may read shows the features a prepared statement refuses over these events.
Choosing a pattern compares the storages a history can live in.