cancel
Showing results for 
Search instead for 
Did you mean: 
Community Articles
Dive into a collaborative space where members like YOU can exchange knowledge, tips, and best practices. Join the conversation today and unlock a wealth of collective wisdom to enhance your experience and drive success.
cancel
Showing results for 
Search instead for 
Did you mean: 

Lakebase Change Data Feed exports whole schemas: feed it one event table instead

rajavemuri
New Contributor II

Environment: a Lakebase project with Lakebase Change Data Feed (Public Preview) streaming into Unity Catalog, and a scheduled job on serverless compute that reads the history table.

The scope problem. The feed is configured per schema, and every current and future table in that schema is included. The setup page shows how to set REPLICA IDENTITY FULL on every table in public and adds an event trigger that sets it on each new table, and the quickstart starts the feed on public. For an app database, that path exports the session and credential tables along with everything else. Two more things follow from the same page. Full replica identity makes Postgres log the whole old row on every update and delete, busy tables included. And adding, dropping or retyping a column re-reads the table from Postgres and rewrites its history table, so every migration that touches a column rewrites that table's history in Delta.

What we did instead. We created a schema that holds one table, append-only in normal use, with deletes and redactions only for erasure, gave that table full replica identity, and started the feed on that schema alone. Triggers on the app tables write to it. A new table or column in public can't start flowing by accident, and the app's own tables keep their default replica identity.

A trimmed version of our setup:

CREATE SCHEMA lakehouse_export;
REVOKE ALL ON SCHEMA lakehouse_export FROM PUBLIC;

CREATE TABLE lakehouse_export.decision_event (
    id text PRIMARY KEY DEFAULT gen_random_uuid()::text,
    occurred_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    organization_id text NOT NULL,
    project_id text,
    subject_type text NOT NULL,
    subject_id text,
    event_type text NOT NULL,
    from_state text,
    to_state text,
    actor_kind text NOT NULL CHECK (actor_kind IN ('human', 'ai', 'system', 'unknown')),
    actor_id text,
    payload jsonb
);
ALTER TABLE lakehouse_export.decision_event REPLICA IDENTITY FULL;

CREATE FUNCTION lakehouse_export.capture_proposal() RETURNS trigger
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
BEGIN
    BEGIN
        INSERT INTO lakehouse_export.decision_event
            (organization_id, project_id, subject_type, subject_id, event_type,
             from_state, to_state, actor_kind, actor_id)
        VALUES (NEW.organization_id, NEW.project_id, 'proposal', NEW.id,
            CASE WHEN TG_OP = 'INSERT' THEN 'proposed' ELSE 'status_changed' END,
            CASE WHEN TG_OP = 'UPDATE' THEN OLD.status END, NEW.status,
            CASE WHEN NEW.reviewed_by IS NOT NULL THEN 'human' ELSE 'system' END,
            NEW.reviewed_by);
    EXCEPTION WHEN OTHERS THEN
        -- Fail open: a capture error must not roll back the business write.
        RAISE WARNING 'decision_event capture failed, SQLSTATE %', SQLSTATE;
    END;
    RETURN NULL;
END $$;
REVOKE ALL ON FUNCTION lakehouse_export.capture_proposal() FROM PUBLIC;

CREATE TRIGGER decision_event_proposal_insert AFTER INSERT ON public.proposal
    FOR EACH ROW EXECUTE FUNCTION lakehouse_export.capture_proposal();
CREATE TRIGGER decision_event_proposal_status AFTER UPDATE OF status ON public.proposal
    FOR EACH ROW WHEN (OLD.status IS DISTINCT FROM NEW.status)
    EXECUTE FUNCTION lakehouse_export.capture_proposal();

public.proposal stands in for an app table with id, organization_id, project_id, status and reviewed_by columns.

We chose triggers over writing events from app code because the status column we track is written in 25 places in our code, and a trigger catches every writer. The WHEN clause keeps updates that don't change the status out of the feed. The exception block makes capture fail open. When a capture error is caught, the business write still commits, but that change gets no event, and the warning in the Postgres log is the only trace. Treat the history as best-effort, not complete. The warning carries only the SQLSTATE, because the error message can contain row data. The cost is work inside the business transaction. Past about 64 captured rows in one transaction, Postgres starts paying subtransaction overhead for those blocks. Erasure goes the other way in our version. A trigger on the parent tables deletes or redacts the matching events with no exception block, so if the purge fails, the delete fails too. Those deletes and redactions reach Delta as new change rows. The current-state rebuild below drops deleted events and keeps redacted values, but the history table still holds the earlier rows until it is replaced from the current source rows. Our job doesn't shorten retention or run VACUUM, so plan erasure on the Delta side separately.

Checked on Lakebase. In an empty database on a throwaway branch of a Lakebase project (Postgres 17.11), the example above wrote two events for an insert followed by a status change. An update that left the status alone and a repeat of the same status wrote none. An insert with a NULL organization_id, which makes the capture fail, logged SQLSTATE 23502 while the app row still committed. public.proposal kept its default replica identity.

On the Delta side. The feed writes lb_decision_event_history with _pg_change_type, _pg_lsn, _pg_xid, _timestamp and _sort_by on every row. The first task of our job rebuilds the current state from the whole history:

CREATE OR REPLACE TABLE decision_event_current USING DELTA AS
WITH ranked AS (
  SELECT *, ROW_NUMBER() OVER (
    PARTITION BY id ORDER BY _sort_by DESC, _pg_lsn DESC,
      CASE _pg_change_type WHEN 'delete' THEN 3 WHEN 'update_postimage' THEN 2 ELSE 1 END DESC
  ) AS change_rank
  FROM lb_decision_event_history
  WHERE _pg_change_type IN ('insert', 'update_postimage', 'delete')
)
SELECT id, occurred_at, organization_id, project_id, subject_type, subject_id,
  event_type, from_state, to_state, actor_kind, actor_id, payload
FROM ranked
WHERE change_rank = 1 AND _pg_change_type <> 'delete';

Preimages are filtered out before ranking, and a delete removes the row. The column list matches the example table; ours selects five more. We rebuild from the whole history on every run rather than keeping offsets, because a re-snapshot rewrites the history table. Later tasks build summary tables from decision_event_current, such as what happened to each proposal, decisions per project per day, and what still waits for review.

A schedule, not a table-update trigger. The job runs every 6 hours (0 0 0/6 * * ? in Quartz cron). Triggered by updates to the history table, it would have run close to hourly and paid for a refresh each time. Across four runs of the whole job (current state, summary tables and grants), a run cost 0.13 to 0.16 DBU and took 6 to 8 minutes. Every run scans the full history, so the cost grows with what the history table holds. Measure it on your own volume.

Limits. Lakebase Change Data Feed is in Public Preview. One export table means you design the event's shape yourself and keep the triggers in step with the app's tables. The feed doesn't support partitioned tables, and you can't put row filters or column masks on the history table, so filter in the tables you build from it.

How are others rebuilding downstream tables after a Change Data Feed re-snapshot?

The Delta job is at https://github.com/Fabric-Pro/fabric-oss/tree/master/deployment/databricks/decision-replay, and the full capture migration is at https://github.com/Fabric-Pro/fabric-oss/blob/master/packages/database/prisma/migrations/20261024120.... Longer write-up: https://www.techfabric.com/blog/exporting-ai-decision-history-from-lakebase-through-one-event-table

Drafted with AI assistance; I reviewed it before posting.

0 REPLIES 0