Precompute in a Python process

This tutorial runs the hooks of Buckets per key inside your own Python process, with no featuremeshd. Your loop reads the payments from Kafka, hands each batch to the library, and drains the due buckets. The library computes and writes the same values featuremeshd would.

You need Python with the library and its embedded engine ( Install ), the confluent-kafka package, a Kafka broker on localhost:29093 and Redis on localhost:26379. The process runs on your machine, so the definitions reach the stores at localhost.

The definitions

Save this as precompute.fql. It is the index and the minute rollup of Buckets per key , with the queue and the buckets in Redis:

CREATE OR REPLACE FEATURES IN fm.tutorials.py_precompute AS
PERSIST
    stream := SOURCE_STREAM('kafka://localhost:29093' WITH (FORMAT = 'json')),
    payments := EXTERNAL_COLUMNS(payment_id BIGINT, merchant_id BIGINT, amount DOUBLE, event_time TIMESTAMP(3)
        FROM TABLE(stream[tut_py_precompute])),
    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://localhost:26379' KEY 'tut_py_precompute:pay: || merchant_id::VARCHAR || '
        INDEXED ON event_time UNIQUE ON payment_id
        WITH (MODE = 'append', SHAPE = 'sorted_set', FORMAT = 'msgpack', 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://localhost:26379'),
    mm := INPUT(ROW<merchant_id BIGINT, minute TIMESTAMP(3)>),
    mm_pays := EXTERNAL_KV(KEY 'tut_py_precompute: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 INTEGER, 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_LENGTH(minute_pays) AS n, ARRAY_SUM(minute_pays[amount]) AS total),
    minute_ps := PREPARED_STATEMENT(minute_row USING mm),
    per_minute := SINK('redis://localhost:26379'
        KEY 'tut_py_precompute:minute: || mm[merchant_id]::VARCHAR || :' || mm[minute]::VARCHAR
        WITH (MODE = 'latest', FORMAT = 'json', RETENTION = INTERVAL '36500 DAY')),
    minute_queue := SINK('redis://localhost:26379' KEY 'tut_py_precompute:queue'),
    rollup_minute := HOOK(RUN minute_ps ON pay_ps AT minute_close USING (minute_ref) TO per_minute QUEUE minute_queue
        WITH (EXPIRE = INTERVAL '36500 DAY'));

EVERY is left out: in Python, your loop decides when to drain ( The clock ).

Save the reader of the buckets as read.fql:

CREATE OR REPLACE FEATURES IN fm.tutorials.py_precompute AS
PERSIST
    at_minute := INPUT(TIMESTAMP(3)),
    bucket := EXTERNAL_KV(KEY 'tut_py_precompute:minute: || merchant_id::VARCHAR || :' || at_minute::VARCHAR FROM kv
        AS ROW(n BIGINT, total DOUBLE, request_time TIMESTAMP(6), compute_time TIMESTAMP(6), datakey VARCHAR,
            partition INTEGER, offset BIGINT, drain BIGINT)
        WITH (FORMAT = 'json')),
    bucket_value := ROW(bucket[n] AS n, bucket[total] AS total),
    bucket_ps := PREPARED_STATEMENT(bucket_value USING (merchant_id, at_minute));

Load them

Create an embedded client with a local registry, register both files, and load them:

import json
import featuremesh
from confluent_kafka import Consumer, Producer
from featuremesh import RegistryDeployment, ServingClient, ServingDeployment

featuremesh.set_default("registry", RegistryDeployment.LOCAL)
featuremesh.set_default("serving", ServingDeployment.EMBEDDED)
featuremesh.set_default("local.db_path", "tutorial.db")

client = ServingClient()
client.translate(open("precompute.fql").read())
client.translate(open("read.fql").read())
client.query("RECOMPILE SERVING;")
python

translate() registers the features in the local registry file, tutorial.db. RECOMPILE SERVING loads them into the engine of this process ( Hooks and views in Python ).

Send three payments

Merchant 7 pays 10.0 and 3.0 in the minute 15:00. Merchant 9 pays 5.0:

producer = Producer({"bootstrap.servers": "localhost:29093"})
for payment_id, merchant_id, amount, second in [(1, 7, 10.0, 10), (2, 7, 3.0, 40), (3, 9, 5.0, 30)]:
    event_time = f"2025-11-24T15:00:{second:02d}"
    producer.produce("tut_py_precompute", key=str(merchant_id), value=json.dumps(
        {"payment_id": payment_id, "merchant_id": merchant_id, "amount": amount, "event_time": event_time}))
producer.flush()
python

The loop

The loop does what featuremeshd does on its own. It reads a batch, hands it to the event hook, commits the batch's offsets, then drains the scheduled hooks:

HOOK = "FM.TUTORIALS.PY_PRECOMPUTE.ON_PAYMENT"
consumer = Consumer({"bootstrap.servers": "localhost:29093", "group.id": HOOK,
                     "auto.offset.reset": "earliest", "enable.auto.commit": False})
consumer.subscribe(["tut_py_precompute"])
idle = 0
while idle < 5:                                   # stop after 5 seconds without records
    messages = [m for m in consumer.consume(num_messages=500, timeout=1.0) if m.error() is None]
    if messages:
        report = client.run_event_hook(HOOK, messages)
        print(report["records"], "records,", report["writes"], "writes,", report["scheduled"], "scheduled")
        consumer.commit(asynchronous=False)       # once the batch is written
        idle = 0
    else:
        idle += 1
    for drained in client.run_due_hooks():
        if drained.get("fired"):
            print(drained["hook"], "fired", drained["fired"])
consumer.close()
python
  • group.id is the hook's name, as featuremeshd names its consumer group.
  • auto.offset.reset plays the part of the hook's START: the library never connects to Kafka, so it does not read the hook's own.
  • run_event_hook() writes the index and queues the buckets before it returns. The commit comes after, so a crash in between hands the same records in again.
  • run_due_hooks() drains every due queue once. How often you call it is your drain period.

It prints:

3 records, 3 writes, 3 scheduled
FM.TUTORIALS.PY_PRECOMPUTE.ROLLUP_MINUTE fired 2
text

The three payments made three index writes and queued three references. Merchant 7's two payments fall in the same minute, so the queue kept two entries, and the drain ran two calls.

Read the buckets

The reader is an ordinary prepared statement, served by the same client:

result = client.execute_prepared_statement("FM.TUTORIALS.PY_PRECOMPUTE.BUCKET_PS",
    {"input_1": [[7, "2025-11-24 15:00:00"], [9, "2025-11-24 15:00:00"]]})
for merchant_id, at_minute, bucket in result.dataframe.itertuples(index=False):
    print(merchant_id, bucket)
client.close()
python
7 {'n': 2, 'total': 13.0}
9 {'n': 1, 'total': 5.0}
text

A production loop adds retries, a separate thread for the drains, and a clean shutdown: Feed hooks from your own pipeline has one.

What you learned

  • The library runs the same hooks as featuremeshd, from the same definitions.
  • Your process owns the stream and the clock: it consumes, hands batches in, commits, and drains.
  • Commit a batch only after run_event_hook() has returned.
  • A served statement reads back what the hooks wrote, in the same process.

Next