Data ScienceNovember 22, 2026

Deterministic CDC Replays for Postgres JSONB Using Stable Event Hashes

S

Written by

Sage Stream

The bug that started it all

I hit a really annoying problem while building a real-time analytics pipeline from Postgres: a Change Data Capture (CDC) job would occasionally produce different event payloads for the “same” underlying database change.

At first it sounded impossible—CDC is supposed to reflect changes deterministically. But the culprit turned out to be subtle: I was capturing rows that included jsonb, and my downstream event deduplication logic relied on an event hash. Some JSON objects were semantically identical but serialized differently (key order differences, whitespace differences, etc.), so the same logical change could generate multiple different hashes across replays.

That broke “at-least-once” delivery assumptions and made data observability painful: I could not confidently replay from a checkpoint and get the same stream again.

So I built a small, deterministic event construction pattern for Postgres jsonb changes using a stable JSON normalization step and a stable event hash.


The goal

Given a Postgres row change that includes jsonb, I wanted to guarantee:

  1. Deterministic event payloads across replays (same database state ⇒ same payload).
  2. Deterministic event IDs via a stable hash.
  3. Safe idempotency downstream: duplicates become harmless.

To make this concrete, I used:

  • A Postgres trigger to write CDC-like “events” into a table (so the example is runnable).
  • A Python consumer that:
    • normalizes the JSONB data in a deterministic way,
    • builds an event payload,
    • computes a stable SHA-256 hash.

Setup: a table with JSONB + an events outbox

1) Postgres schema

-- Enable uuid generation (optional) create extension if not exists "pgcrypto"; -- A sample table with jsonb create table if not exists app_orders ( order_id uuid primary key default gen_random_uuid(), customer_id uuid not null, status text not null, attributes jsonb not null default '{}'::jsonb, updated_at timestamptz not null default now() ); -- An "outbox" table that holds CDC-like events create table if not exists order_events_outbox ( event_id uuid primary key default gen_random_uuid(), order_id uuid not null, -- We store the "raw" JSONB snapshot for hashing determinism later attributes jsonb not null, status text not null, customer_id uuid not null, event_time timestamptz not null default now(), -- This is where observability can track whether processing succeeded processed_at timestamptz ); -- Trigger function writes outbox events on update create or replace function emit_order_update_event() returns trigger language plpgsql as $$ begin if (new.attributes is distinct from old.attributes) or (new.status is distinct from old.status) then insert into order_events_outbox(order_id, attributes, status, customer_id) values (new.order_id, new.attributes, new.status, new.customer_id); end if; return new; end; $$; drop trigger if exists trg_order_update on app_orders; create trigger trg_order_update after update on app_orders for each row execute function emit_order_update_event();

What this does (and why):

  • app_orders.attributes is jsonb, which is great for flexibility but can serialize differently.
  • Instead of trying to “hash whatever comes out,” I write the raw JSONB into an outbox table.
  • The consumer later turns that JSONB into a deterministic normalized form and hashes it.

Reproducing the nondeterminism

To see the problem clearly, I inserted the “same” JSON content with different key ordering, updated the row, and then compared hashes.

2) Insert sample data + create the two equivalent JSONB variants

-- Create one order insert into app_orders(order_id, customer_id, status, attributes) values ( 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'PLACED', '{"tier":"gold","region":"us-east"}'::jsonb ); -- Update with same semantic JSON but different key order update app_orders set attributes = '{"region":"us-east","tier":"gold"}'::jsonb, updated_at = now() where order_id = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';

Logically, those JSON objects are equal as data. But if you stringify them naively, you might get different byte representations—and that changes hashes.

So I normalized JSON deterministically in the consumer before hashing.


The deterministic event pattern

The key idea

Stable event hash = hash of a canonical representation.

For JSON, “canonical” typically means:

  • keys are sorted consistently,
  • numeric/string/bool/null types are preserved,
  • nested objects are handled recursively.

In Python, I used json.dumps(..., sort_keys=True, separators=(',', ':')) after parsing the JSON into a standard Python structure.


Python consumer: canonicalize JSONB → stable payload → stable hash

1) Consumer code (step-by-step)

import json import hashlib import psycopg def canonical_json(value) -> str: """ Convert a JSON-like Python structure into a deterministic string: - sort keys - remove whitespace - keep types stable """ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False) def stable_event_hash(event_payload: dict) -> str: """ Build a deterministic event string and hash it. """ canonical = canonical_json(event_payload) return hashlib.sha256(canonical.encode("utf-8")).hexdigest() def build_event_payload(row: dict) -> dict: """ Create the exact payload we want to hash. Important: JSONB values are already parsed by psycopg into Python types (dict/list/scalars). We normalize only the parts that can vary in ordering. """ # attributes is the jsonb column; it should be a Python dict already attrs = row["attributes"] # If attributes can contain nested dicts, canonicalization will recurse via dumps(sort_keys=True) payload = { "event_type": "order_update", "order_id": str(row["order_id"]), "customer_id": str(row["customer_id"]), "status": row["status"], "attributes": attrs, "event_time": row["event_time"].isoformat(), # deterministic timestamp representation } return payload def run_once(dsn: str): with psycopg.connect(dsn, row_factory=dict_row) as conn: with conn.cursor() as cur: cur.execute(""" select event_id, order_id, customer_id, status, attributes, event_time from order_events_outbox where processed_at is null order by event_time asc limit 100 """) rows = cur.fetchall() for row in rows: event_payload = build_event_payload(row) event_id = stable_event_hash(event_payload) # Observability hook: print hash and canonical payload canonical_str = canonical_json(event_payload) print("event_hash:", event_id) print("canonical_payload:", canonical_str) # Mark processed in the outbox (in real systems, you'd write to a sink first) cur.execute(""" update order_events_outbox set processed_at = now() where event_id = %s """, (row["event_id"],)) conn.commit() if __name__ == "__main__": # Example DSN: "postgresql://user:pass@localhost:5432/postgres" run_once("postgresql://user:pass@localhost:5432/postgres")

2) Why each part matters

  • canonical_json(...):
    • sort_keys=True ensures {"a":1,"b":2} hashes the same as {"b":2,"a":1}.
    • separators=(',', ':') removes whitespace so formatting differences don’t leak into hashes.
  • build_event_payload(...):
    • It constructs a payload with a fixed field set and fixed types.
    • It uses isoformat() for timestamps so the representation is consistent.
  • stable_event_hash(...):
    • hashes the canonical string, not a raw Python dict string or a nondeterministic JSON representation.

Wiring it to real replays (checkpoint + idempotency)

In a proper streaming setup, you typically replay from a checkpoint and reprocess the same logical changes. The stable hash becomes your idempotency key.

Example: store processed hashes

Here’s a tiny table for deduplication:

create table if not exists processed_event_hashes ( event_hash text primary key, first_seen_at timestamptz not null default now() );

Then in the Python processing loop, you’d do:

cur.execute(""" insert into processed_event_hashes(event_hash) values (%s) on conflict (event_hash) do nothing """, (event_id,)) # If rowcount == 0, it was a duplicate replay

That makes replays safe: even if the outbox emits events multiple times, the sink only processes unique logical events.


Data observability: catching “non-canonical” payload drift

Once you have stable hashing, observability becomes more actionable. Instead of “events differ mysteriously,” you can detect drift.

I added two metrics-style prints (in real life you’d push to Prometheus/Datadog):

  • the stable event_hash
  • the canonical payload string

When a replay diverges, you’ll see either:

  • different hashes (payload changed), or
  • same hash (payload truly identical).

This is the fastest way I’ve found to isolate whether the issue is:

  • upstream extraction (different data),
  • normalization (hashing logic),
  • or downstream schema evolution.

End-to-end test

After running the SQL updates and then the Python consumer, you should see:

  • the same stable event_hash for semantically identical attributes,
  • even if key order differed in the original JSONB.

That’s the core win: deterministic CDC replays based on data semantics, not serialization quirks.


Conclusion

I learned that “CDC determinism” can still fail in practice when JSONB is involved, because semantically identical data can serialize differently across reads and replays. By normalizing JSON deterministically (sorted keys, stable separators) and hashing a canonical event payload, I got stable event IDs that make reprocessing idempotent and data observability much more trustworthy.