Feed hooks from your own pipeline
This guide runs FeatureQL inside a pipeline that owns the stream, for a format featuremeshd does not decode, transactional outputs or a paced replay: with embedded serving in your Python consumer, or with a call to featuremeshd over HTTP.
Before you start, have the hook, its statement and its sinks defined and registered ( Hooks ), and know what featuremeshd does that your process will not ( Differences from featuremeshd ). Do not run featuremeshd on the same hook ( One runner per hook ).
1. Choose who writes
The two ways differ in who writes:
| Embedded serving in your Python consumer | Your pipeline calls the statement over featuremeshd's HTTP API | |
|---|---|---|
| Decodes the records | the library, as JSON: hand it records you decoded as dicts | your pipeline |
| Runs the statement | run_event_hook, the hook's calls | POST /v1/featureql, one call |
Writes the index and latest sinks, queues entries, fires the hooks on the statement | the library, before it returns | nothing: the call returns values, fires no hook and writes no sink; your pipeline writes what it needs |
| Commits the offsets | your consumer, after it returns | your pipeline |
A pipeline with transactional outputs runs embedded serving and writes its own outputs ( Hooks and views in Python ).
A pipeline that calls over HTTP sends one call per batch of records, with the statement's inputs, and writes the values it gets back itself. The call is in Call a prepared statement . A pipeline under backpressure calls at its own pace, which no hook setting gives ( Limits ).
The rest of this guide is the embedded way.
2. Connect your consumer
A Python consumer that runs an event hook, its scheduled hooks and the views with embedded serving. client is an embedded ServingClient that has loaded the hook FM.SHOP.ON_PAYMENT ( Hooks and views in Python ).
The library never connects to Kafka, so the connection settings are your consumer's. With confluent_kafka, for SASL/SCRAM over TLS:
import os
KAFKA = {"bootstrap.servers": "broker:9093", "security.protocol": "SASL_SSL",
"sasl.mechanism": "SCRAM-SHA-512", "sasl.username": "hooks",
"sasl.password": os.environ["KAFKA_PASSWORD"], "ssl.ca.location": "/etc/kafka/ca.pem"}
# a local broker without authentication: KAFKA = {"bootstrap.servers": "localhost:9092"} 3. Run the loop
The consumer thread hands batches in and commits; a second thread ticks the queues and the views. They are apart because a drain or a view run can take longer than Kafka lets a consumer go without polling (max.poll.interval.ms, 5 minutes by default): past that, the group takes the consumer's partitions away.
import logging
import signal
import threading
import time
from confluent_kafka import Consumer, KafkaError, KafkaException, TopicPartition
log = logging.getLogger("shop-hooks")
stop = threading.Event()
signal.signal(signal.SIGTERM, lambda *_: stop.set())
consumer = Consumer({**KAFKA, "group.id": "FM.SHOP.ON_PAYMENT", # featuremeshd's group: the hook's name, after its kafka_group_prefix if set
"auto.offset.reset": "latest", # plays the part of START (the hook's own, 'latest' by default, is not read here)
"enable.auto.commit": False, # commit below, once the batch is written
"enable.auto.offset.store": False}) # nothing is stored by polling alone
consumer.subscribe(["payments"])
def run_batch(messages):
for wait in (0.2, 1, 5, None): # your retry, your backoff
try:
return client.run_event_hook("FM.SHOP.ON_PAYMENT", messages)
except RuntimeError:
if wait is None:
raise # stop: nothing past this batch is committed
time.sleep(wait)
last_tick = time.monotonic()
def tick():
global last_tick
while not stop.is_set():
try:
for drained in client.run_due_hooks():
if drained["error"] or drained.get("data_errors"):
log.warning("drain: %s", drained)
for run in client.run_due_materialized_views():
if run["error"] or run["busy"]:
log.warning("view run: %s", run)
last_tick = time.monotonic()
except Exception:
log.exception("tick failed")
stop.wait(1)
ticker = threading.Thread(target=tick, name="hooks-tick", daemon=True)
ticker.start()
try:
while not stop.is_set():
if not ticker.is_alive() or time.monotonic() - last_tick > 900: # above your longest tick
raise RuntimeError("the tick thread is stuck")
messages = []
for m in consumer.consume(num_messages=2000, timeout=0.5):
if m.error() is None:
messages.append(m)
elif m.error().code() != KafkaError._PARTITION_EOF:
raise KafkaException(m.error()) # a real error: stop, do not commit past it
if not messages:
continue
report = run_batch(messages)
if report["data_errors"]:
log.warning("%d data errors, for instance %s", report["data_errors"], report["errors"])
next_offsets = {}
for m in messages:
next_offsets[(m.topic(), m.partition())] = m.offset() + 1
try:
for tp in consumer.commit(offsets=[TopicPartition(t, p, o) for (t, p), o in next_offsets.items()],
asynchronous=False):
if tp.error:
log.warning("not committed: %s", tp)
except KafkaException as error:
log.warning("commit failed: %s", error) # the partitions' next owner reads the batch again
finally:
stop.set()
ticker.join(30) # lets the current drain or view run finish, up to 30 s
consumer.close() - Offsets. Each batch commits, per partition, the offset after its last record, and only once
run_event_hookreturned. A rebalance happens insideconsume(), between two batches: a partition taken away has nothing written but uncommitted, so the loop needs no revoke callback. A batch that outlastsmax.poll.interval.ms(four attempts and 6.2 s of backoff here, plus the batch's own time) loses its partitions: its commit fails, the next owner reads the records again, and the sinks take the same values again. - Reports. A data error never raises: read
data_errorsanderrorsin each report. A drain that stopped short haserror, and is retried by the next tick; a view run that failed or found another holder haserrororbusy. - The tick runs drains, then views, one after the other: a long view run delays the next drain. An entry due at 10:01:00 with
EXPIRE = INTERVAL '2 MINUTES'that waits behind a three-minute view run is dropped. Keep the tick's period plus its longest run well under the shortestEXPIRE, or run views in a thread of their own. The loop stops when the tick thread dies or stops coming round; your supervisor restarts the process.
One ServingClient serves both threads: the engine runs each call outside Python's lock, and the local registry takes one translation at a time.
4. Run it under a supervisor
The loop stops when it meets an error it must not commit past, or when the tick thread dies or stops coming round. Run it under a supervisor that restarts the process, a Kubernetes Deployment for instance. On SIGTERM, it lets the current drain or view run finish, up to 30 seconds, then closes the consumer.
Check the pipeline
- Lag: your broker's tools show the group's lag falling to near zero.
- Reports:
data_errorsstays at zero in the batch reports, and no drain report carries anerror. - Values: a reader of the sinks finds the values for the keys just processed ( Reading back ).
Common failures
- The same records again and again: a batch outlasts
max.poll.interval.ms, loses its partitions, and its commit fails. Lowernum_messages, or raisemax.poll.interval.ms. - Buckets dropped while the loop runs: a view run held the tick past an entry's
EXPIRE. Run views in a thread of their own. - Nothing written for a while, no error: the tick thread is stuck. The loop's check raises after 900 seconds; set it above your longest tick.
Related
- Connect featuremeshd : the other ways to plug featuremeshd into your systems.
- Write results to Kafka : send the values on, from featuremeshd.
- A Python precompute : the short loop on a test stack.