Sinks and reading back
A sink says where and how a hook, a materialized view or a logger writes, and serving reads what it holds back as an ordinary source.
SINK('<url>' [KEY <expression> | TABLE '<name>' [KEY (<column>, …)]] [INDEXED ON <field> UNIQUE ON <field>]
[WITH (MODE = …, SHAPE = …, FORMAT = …, RETENTION = …, WATERMARK_KEY = …, PASSWORD = SECRET(…))]) A hot sink, a queue or a view's sink has one writer. A second hook or view naming it is refused at registration (UE/SINK-SHARED), and so is a hook or view naming a logger's sink. Loggers are the exception: several can share one cold sink, each writing under its own path ( Feature logging ). The check is on the sink feature, not on what it points at ( Limits ).
Modes
MODE | Keeps | Written by |
|---|---|---|
latest | one value per key, the newest: for a hook, the one with the newest request_time; for a view, the last run's | hooks and views: Redis, PostgreSQL, MySQL/MariaDB |
append | one member or row per identity. On Redis, the event index: a sorted set per KEY, scored by INDEXED ON, one member per UNIQUE ON value. On a table, one row per KEY columns plus UNIQUE ON | hooks: Redis (SHAPE = 'sorted_set'), PostgreSQL, MySQL/MariaDB. Loggers: files and object stores, every row |
replace | the last run's rows, swapped whole at each run | views: PostgreSQL, MySQL/MariaDB, object stores and file:// |
- Hot for hooks, cold for loggers. A hook writes the stores serving reads. Files, object stores and
stdout://are a logger's. - Whole values. A write replaces its key's whole value, or its member's or row's. A retried record writes again what its statement computes then, which differs when a source it reads changed: a replay never adds a row, and it does not restore the values computed before.
- Keys. A table sink names its key columns, taken from the statement's inputs (a
ROWinput's fields) or its output. A RedisKEYis an expression over the same. - A hash tag in every Redis key. An event index writes two keys, the sorted set and
<key>:ids, in one script. On Redis Cluster they must share a slot, so the registry requires a hash tag in theKEYof every Redis sink a hook or view writes:'shop:pay:{' || MERCHANT_ID::VARCHAR || '}'. On a single Redis the braces do nothing. - The event index on Redis. Each member is the row in the sink's
FORMAT(MessagePack in the tutorials), scored by itsINDEXED ONtime in seconds.<key>:idsmaps eachUNIQUE ONvalue to that score.UNIQUE ONmakes a replayed record replace its member rather than add a second one. A member is unique within its key only. - An index in a table is an
appendtable sink: one row perKEYcolumns plus theUNIQUE ONfield, which are the table's primary key, trimmed byRETENTIONon theINDEXED ONtime. A history in PostgreSQL rather than Redis:
PAY_HISTORY := SINK('postgresql://hooks@db:5432/app' TABLE 'pay_history' KEY (merchant_id)
INDEXED ON event_time UNIQUE ON payment_id
WITH (MODE = 'append', RETENTION = INTERVAL '30 DAYS', PASSWORD = SECRET('env', 'PG_PASSWORD'))),
-- CREATE TABLE pay_history (merchant_id BIGINT NOT NULL, event_time TIMESTAMP(3), payment_id BIGINT NOT NULL,
-- amount NUMERIC(12, 2), request_time TIMESTAMP(6), compute_time TIMESTAMP(6), datakey TEXT,
-- "partition" INTEGER, "offset" BIGINT, drain BIGINT, PRIMARY KEY (merchant_id, payment_id)); To read it, start from SHOW CREATE SINK PAY_HISTORY READER, which prints a point lookup, and turn it into a read over merchant_id and a range of event_time ( Long horizons ).
Which write lands
| Writer and mode | A write lands | On the same time or identity |
|---|---|---|
hook, latest | when its request_time is not older than the stored one. Redis compares in a script, a table in the upsert | it replaces: the last write wins ( Which write lands ) |
hook, append | always, replacing the member or row of the same identity whole | the last write wins, whatever its INDEXED ON value or its request_time |
view, latest or replace | when its run is newer than the run the sink published ( How a run lands ) | a run number is never reused |
| queue entry | by its due time and the hook's POLICY ( WITH ) | one pending entry per reference |
appendhas no fence. A replay of an event rewrites its member or row from what the statement computes then. A corrected payload under the same identity is overwritten by an older record replayed later ( Late, corrected and missing events ).- An identity is scoped to its key: the Redis key, or the table's
KEYcolumns. An event that moves to another key, such as another merchant, gets a member there and leaves the old one. - A Kafka tombstone removes nothing. A record with no value is a decode error, not a removal.
Retention
RETENTION removes a row once its time is older than the store's clock minus the retention. The time is the INDEXED ON field for an append member or row, and request_time for any other row (for a view, its slot).
| Store | How rows expire |
|---|---|
| Redis value | with PEXPIREAT |
| Redis index | trimmed inside each write to its key: expired members go with their <key>:ids entries. Both keys expire at the newest member's time plus the retention, so an idle key's index disappears on its own |
| Table | rows deleted by a periodic sweep of featuremeshd ( retention_sweep_every ), so a row can outlive its retention by up to one sweep period. A reader that needs an exact window filters on the time |
A view's watermark never expires ( Materialized views ).
Properties
Clause or WITH | Sinks | Values | Default |
|---|---|---|---|
KEY <expression> | Redis | the key, with a {hash tag} | required |
TABLE '<name>' KEY (…) | PostgreSQL, MySQL/MariaDB | the table, and its key columns | TABLE required; KEY required for latest |
INDEXED ON … UNIQUE ON … | hooks' append sinks | the time field and the identity field | required for append, refused otherwise |
MODE | Redis | 'append', 'latest' | 'append' |
| PostgreSQL, MySQL/MariaDB | 'append', 'latest', 'replace' (views) | 'append' | |
| object stores, files | 'append' (loggers), 'replace' (views) | 'append' | |
SHAPE | Redis | 'sorted_set' for append, 'string' for latest | follows MODE |
FORMAT | Redis | 'json', 'msgpack' | required |
| object stores, files | 'parquet', 'jsonl' | 'parquet' | |
RETENTION | hot sinks | a fixed INTERVAL in days, hours, minutes or seconds: INTERVAL '30 DAYS' is accepted, months and years are refused | none: rows stay |
WATERMARK_KEY | a view's Redis latest sink | the key of the view's watermark | required there, refused elsewhere |
PASSWORD | hot sinks, queues | a SECRET(…) | none |
COMPRESSION, ROLL_SECONDS, ROLL_MB | Parquet and file sinks (loggers, views) | see Feature logging |
A sink takes its password as a source does: SINK('postgresql://fm@db:5432/fm' TABLE '…' WITH (PASSWORD = SECRET('env', 'PG_PASSWORD'))), for a table and for a queue. When featuremeshd reads it is in Credentials . Sinks and queues connect over TLS as the sources of their store do:
| Store | When the URL says nothing | Other settings | Private CA |
|---|---|---|---|
| PostgreSQL | sslmode=verify-full: TLS, the certificate and name checked against the system's roots | require (TLS, certificate not checked), disable (plain text, for a local database) | sslrootcert=/path/ca.crt |
| MySQL, MariaDB | sslmode=required: TLS, the certificate and name checked against the system's roots | preferred (TLS without a certificate check when the server offers it, plain text when it does not: not for credentials over a network you do not trust), disabled (plain text) | sslrootcert=/path/ca.pem |
| Redis | plain text with redis:// | rediss://: TLS, the certificate checked against the system's roots | set in featuremeshd's environment ( Rotate credentials and certificates ) |
Queues
A queue is a bare hot sink: a TABLE without KEY columns, or a constant Redis KEY prefix, plus PASSWORD if it needs one. MODE, SHAPE, FORMAT, RETENTION, INDEXED ON, UNIQUE ON, KEY columns and WATERMARK_KEY are refused (UE/HOOK-QUEUE-OPTIONS).
MINUTE_QUEUE := SINK('postgresql://fm@postgres:5432/fm' TABLE 'minute_queue'
WITH (PASSWORD = SECRET('env', 'PG_PASSWORD'))),
MINUTE_QUEUE := SINK('mysql://fm@mariadb:3306/fm' TABLE 'minute_queue'
WITH (PASSWORD = SECRET('env', 'MYSQL_PASSWORD'))),
MINUTE_QUEUE := SINK('rediss://redis:6380' KEY 'minute_queue'
WITH (PASSWORD = SECRET('env', 'REDIS_PASSWORD'))), - A Redis prefix needs no hash tag. FeatureMesh wraps it in braces, so the queue's keys
{minute_queue}:due,:entries,:metaand:leaseshare one slot of a cluster. A prefix that already holds braces is kept as written. - The queue's table is created for you. featuremeshd creates a missing queue table when it starts draining, if its credentials allow
CREATE, because the engine owns the queue's format.SHOW CREATE HOOKprints the statements that create it, for you to run or adapt:
SHOW CREATE HOOK FM.TUTORIALS.HOOK_REF.ROLLUP_MINUTE;| OUTPUT VARCHAR |
|---|
| -- The queue of FM.TUTORIALS.HOOK_REF.ROLLUP_MINUTE, FM.TUTORIALS.HOOK_REF.MINUTE_QUEUE. CREATE TABLE IF NOT EXISTS minute_queue ( ref_hash BYTEA PRIMARY KEY, reference BYTEA, due_time BIGINT, token BYTEA, claim_time BIGINT, holder TEXT, lease_number BIGINT, identity TEXT ); CREATE INDEX IF NOT EXISTS minute_queue_due ON minute_queue (due_time); |
- What a queue holds. A table's rows hold the reference encoded, under
ref_hash, and itsdue_timein epoch seconds. A Redis queue keeps{<prefix>}:due, a sorted set of hashes scored by due time, and{<prefix>}:entries, their references. Entries are not keyed by a readable reference.SHOW SERVING STATUSgives a queue's depth, its due entries and the oldest one's age ( Status ).
FeatureMesh creates nothing else you did not name. A sink's table is your schema, read by your readers, so it is never created for you.
The write layout
The rows a writer lands have its keys, its value's fields, then the layout's columns:
| Column | Holds |
|---|---|
| the keys | table sinks: the KEY columns |
| the value's fields | one per field of the statement's ROW output (a scalar: one, named as the feature); a view's columns |
request_time | the call's REQUEST_TIME(): an event hook's record's Kafka timestamp, a scheduled hook's drain time, a hook ON a statement's trigger's; a view's slot |
compute_time | when the value was computed. NULL in a tombstone |
datakey | the definition that wrote it: its name and a hash of its compiled version, FM.SHOP.ON_PAYMENT@78667480d51269c7 |
partition, offset | hooks: the stream record behind the row, its trigger's for a hook ON a statement. NULL for a scheduled hook |
drain | hooks: a scheduled hook's drain number, shared by every reference of that drain. NULL otherwise |
run | views: the run that wrote it |
Readers name the fields, in any order. A row's identity is its key, not these columns: a topic has no column, every reference of a drain has the same drain, and a retried drain has a new one.
Tables
A table sink's table is yours to create before its writer runs. The registry does not check it: a missing column fails the write with the store's error, and the hook is STALLED until the table has it. Check the table against the columns SHOW CREATE SINK … READER prints. The columns are named, in any order:
Writer, MODE | Primary key, or unique key | Columns |
|---|---|---|
hook, latest | the KEY columns (the upsert needs it) | keys, value fields, request_time, compute_time, datakey, partition, offset, drain |
hook, append | the KEY columns and the UNIQUE ON field | the same |
view, latest | the KEY columns | the view's columns, request_time, compute_time, datakey, run |
view, replace | none needed | the same |
- Nullable. Leave every column but the keys and
request_timenullable. A tombstone sets the others toNULL, and the layout columns a writer does not fill areNULL. - Types. Times are
TIMESTAMP(6)in PostgreSQL andDATETIME(6)in MySQL/MariaDB.datakeyis text,partitionan integer, andoffset,drainandrunbig integers. The value's columns take the types the statement writes ( Keep money exact ). - Quoted.
partitionandoffsetare quoted, with double quotes in PostgreSQL and backticks in MySQL/MariaDB. - Privileges. Grant
SELECT,INSERT,UPDATEandDELETEon the table, and on a view's watermark table. - A key column is the input's. A
KEYcolumn named like a field of the statement's output is refused at registration (SINK-KEY-AMBIGUOUS): the table would hold one of the two. Drop the field from the output, since the key comes from the input, or rename one of them.
For minute buckets whose amounts are DOUBLE:
-- PostgreSQL
CREATE TABLE per_minute (
merchant_id BIGINT NOT NULL,
minute TIMESTAMP(3) NOT NULL,
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)
);
-- MySQL/MariaDB: the same columns, with
-- minute DATETIME(3), total DOUBLE, request_time DATETIME(6), compute_time DATETIME(6),
-- `partition` INT, `offset` BIGINT A view's table and its watermark table are in Materialized views .
Reading back
Hooks and views only write. A read is an ordinary feature over an ordinary source, declared against the layout above, and FeatureMesh never links it to the sink. SHOW CREATE SINK … READER prints that declaration for the sink as its writer is compiled now: paste it, rename, and drop the columns you do not need.
For the event index, read as a history : EXTERNAL_KV(KEY … FROM … AS ARRAY<ROW<…>> INDEXED ON event_time WITH (FORMAT = 'msgpack')), the layout's columns included, its clauses in that order:
SHOW CREATE SINK FM.TUTORIALS.HOOK_REF.PAY_INDEX READER;| OUTPUT VARCHAR |
|---|
| -- Reads FM.TUTORIALS.HOOK_REF.PAY_INDEX, written by FM.TUTORIALS.HOOK_REF.ON_PAYMENT (key columns, the value's fields, then request_time, compute_time, datakey, partition, offset, drain). CREATE OR REPLACE FEATURES IN FM.TUTORIALS.HOOK_REF AS PERSIST PAY_INDEX_KV := SOURCE_KV('redis://redis:6379'), PAY_INDEX_READ := EXTERNAL_KV(KEY ('pay:{' || FM.TUTORIALS.HOOK_REF.MERCHANT_ID::VARCHAR || '}') FROM PAY_INDEX_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]; |
For a table:
SHOW CREATE SINK FM.TUTORIALS.HOOK_REF.PER_MINUTE READER;| OUTPUT VARCHAR |
|---|
| -- Reads FM.TUTORIALS.HOOK_REF.PER_MINUTE, written by FM.TUTORIALS.HOOK_REF.ROLLUP_MINUTE (key columns, the value's fields, then request_time, compute_time, datakey, partition, offset, drain). -- A key whose call raised holds a tombstone, request_time and no compute_time: it reads as NULL. CREATE OR REPLACE FEATURES IN FM.TUTORIALS.HOOK_REF AS PERSIST PER_MINUTE_DB := SOURCE_DB('postgresql://fm@postgres:5432/fm' WITH (tables = ARRAY['per_minute'], password = SECRET('env', 'PG_PASSWORD'))), PER_MINUTE_MERCHANT_ID := INPUT(BIGINT), PER_MINUTE_MINUTE := INPUT(TIMESTAMP(3)), PER_MINUTE_STORED := EXTERNAL_COLUMNS("merchant_id" BIGINT BIND TO PER_MINUTE_MERCHANT_ID, "minute" TIMESTAMP(3) BIND TO PER_MINUTE_MINUTE, "n_doubled" BIGINT, "request_time" TIMESTAMP(6), "compute_time" TIMESTAMP(6), "datakey" VARCHAR, "partition" INTEGER, "offset" BIGINT, "drain" BIGINT FROM TABLE(PER_MINUTE_DB[per_minute])), PER_MINUTE_READ := IF(PER_MINUTE_STORED[compute_time] IS NULL, NULL, PER_MINUTE_STORED); |
A Redis latest value is read as a ROW, without INDEXED ON and without [value], through the same tombstone check. A view's reader also checks the run ( Reading a view ).
What a reader sees, for a latest sink read as READ := IF(STORED[compute_time] IS NULL, NULL, STORED), and for an event index:
| The store holds | latest: READ | latest: STORED[source_status] | Event index |
|---|---|---|---|
| a value | the value | OK | the members, OK |
| nothing: never written, expired or deleted | NULL | MISS | [], OK: an empty history is never MISS |
| a tombstone | NULL | OK, with request_time set and compute_time NULL | |
| the store is down or slow | the call fails (SERVING-SOURCE-UNAVAILABLE, SERVING-SOURCE-TIMEOUT); a guarded read gives NULL and the call is PARTIAL | UNAVAILABLE, TIMEOUT | the same |
- The fallback is the reader's. An outage is never read as "no activity" unless the reader says so. By default it fails the call. Reading
source_statusguards the read, and the feature chooses ( Serving errors and fallbacks ). In an index, a key with no events and a key never written are both[]. A reader that tells the cases apart:
SCORE_OR_REVIEW := CASE
WHEN STORED[source_status] NOT IN ('OK', 'MISS') THEN 'REVIEW' -- the store did not answer
WHEN STORED[compute_time] IS NULL THEN 'NO_VALUE' -- a miss, or a tombstone
ELSE STORED[tier] END,
- Freshness is the reader's rule. A hook has no watermark. How old a value may be, and which
datakeyit may come from, the reader decides over the value'srequest_timeanddatakey.
Related
- Hooks :
TOandQUEUE. - Delivery and failures : which write lands, tombstones.
- Materialized views : how a view's run lands in its sinks.
- Feature logging : cold sinks.
- Limits .