What Building a Postgres CDC Pipeline Taught Me About Feeding Snowflake

Our warehouse used to refresh once a night. A job woke up after hours, exported every customer’s data from the application, loaded it into Snowflake, and left every dashboard a day behind. On a normal night it ran for 64 to 84 minutes.

That worked until users started editing records in the web app and expecting the analytics to agree with what they had just saved. The application’s own reports, served from Postgres, showed the edit straight away. The Snowflake dashboards showed it the next day.

This article covers the two things I built along the way and what each one taught me. The first was the obvious fix: running the batch far more often. The second was a change data capture (CDC) pipeline that turns Postgres row changes into ordered, replayable change records. Together they shaped the design we are building now: a translator that updates only the dimension and fact rows a change affects.

Step one: the obvious fix, and what it cost

Before building anything event-driven, I tried the brute-force answer: replace the nightly job with a loop that exports and reloads everything, then starts again as soon as it finishes.

I measured it in production over three days: 269 cycles, with a median cycle of 15.5 minutes. The export took 10.4 minutes of that and the Snowflake load 5.1. Dashboards went from a day old to about 15 minutes old.

It also brought three cost problems I had not predicted:

The load got slower every day. Each load rebuilt the fact tables and swapped them in, and the swap procedure then dropped and re-added the foreign keys on every table: about 225 ADD CONSTRAINT statements per cycle. In our pre-production environment, the average time for one of those statements went from 5.2 to 14.0 seconds in 24 hours, and production followed the same curve. Snowflake does not enforce foreign keys, so we were paying to maintain metadata nothing checked. I changed the swap to delete and re-insert rows inside one transaction, which took the re-adds per load to zero.

A warehouse nobody was watching was a third of the spend. When I split Snowflake usage by warehouse, 34% of it came from a small warehouse I expected to be almost idle. The cause was a status check. While each load ran, the function orchestrating it asked Snowflake every 30 seconds whether the load had finished. Those checks ran on a different warehouse from the load, so they kept a second warehouse awake for every load. Snowflake bills at least 60 seconds each time a warehouse resumes, so a check every 30 seconds meant it never got to sleep. Pointing the checks at the warehouse the load was already using cut that warehouse’s usage by about a third after the first environment was fixed, and we expect most of the rest to go when production gets the same change.

The pre-production copy cost as much as production. It ran the same loop against a copy of the production data. Moving it to one cycle a day cut its usage by about 96%.

The loop gave us fresh dashboards, but each cycle re-read data that had not changed. A scoped export for one customer’s monthly slice took between 0.1 and 1 minute, compared with 10.4 for a full export. Most of the work in every cycle was repeated work.

Step two: a CDC pipeline, built for an audit trail first

In parallel, I was building a CDC pipeline for a different reason: moving the application’s audit trail off the request path. Every save used to write its audit rows inside the user’s request. We wanted the database’s own change log to produce them instead.

The pipeline:

  • Postgres write-ahead log → AWS DMS Serverless → Kinesis → a consumer Lambda. About 180 tables are replicated.
  • The consumer groups messages by Postgres transaction ID and turns physical row changes into logical ones: this record was created, these fields changed, this record was deleted.
  • It drops updates where nothing it tracks changed. Our models keep history as versioned rows, so one user edit arrives as two physical changes, a close of the old version and an insert of the new one. The consumer pairs them before deciding what happened.
  • Raw messages are archived to S3, and an hourly reconciler replays the archive to fill any gaps.
  • Failures go to a dead-letter queue, and a separate watcher reports them.

That is the first half of the warehouse translator: reading the change, working out what actually changed, and keeping one transaction together. It ran in parallel with the old audit writer for weeks so we could compare the two, and that comparison is where most of the lessons came from.

What broke, and what I learned

Tables created after replication starts are invisible

A daily comparison showed that one table had lost 1,184 audit rows in a single day. There was no error anywhere. The consumer had not dropped them; it had never received them.

The table had been created by a migration after the replication task started. DMS evaluates its table selection rules once, when replication starts, and does not see a later CREATE TABLE unless it captures DDL. DDL capture needs an event trigger that only a superuser can create, and we ran DMS with a least-privilege role, so it was off.

The fix had two parts. After each deploy, a check compares the tables the application expects with the tables DMS reports. If they differ, an automated step stops and resumes the replication, which re-evaluates the rules against the current schema. In pre-production, the whole sequence ran unattended in about six minutes and picked up the missing tables.

Lesson: a wildcard table filter in CDC covers the tables that existed when replication last started, not the ones you add later. Check coverage after every schema change.

An idempotency key that moves with the batch

The consumer keyed each logical change on the stream position of the last physical record in its batch. Replaying the same batch gave the same key, so a unique index made replays safe.

But the same transaction did not always arrive in the same batch. When a create and an edit to one record landed together, the key came from the edit; when the create arrived alone, it came from the create. The unique index saw two different keys and kept both rows, so some records got two “created” entries.

To prove the cause, I wrote a harness that ran the real grouping code over every possible way of cutting one transaction into batches. Single creates, edits and deletes gave the same result every time. Multi-step histories, such as create then edit, did not.

Lesson: “replays are harmless” is true only if the key comes from the change itself, never from where a batch happened to end.

One bad record should not stop the stream

One record type made the consumer throw on a relationship lookup, so every batch containing one failed. I expected the stream to wedge. It did not: Lambda retried with batch bisection, split out the bad records, sent them to the dead-letter queue, and the shard moved on. Our QA environment recovered unattended in 3.5 hours.

The surprise was in monitoring. The queue depth metric read zero the whole time, because the watcher drained the dead-letter queue within seconds of each message arriving. The useful metric was messages sent to the queue, not messages waiting in it.

Lesson: turn on bisect-on-error and a dead-letter queue from day one, and alert on messages arriving in the queue, not on its depth.

The old system was wrong more often than the new one

The first production comparison counted 247 audit rows that the old writer had and the CDC consumer lacked. I reported it as a gap. Then I sorted the rows into categories:

Category Rows What it was
No-op decimal changes 185 The old writer compared 4.00 with 4 as strings and logged changes that never happened. The CDC side read both as numerics, saw them as equal and correctly wrote nothing.
Many-to-many changes 10 Written by an application signal with no matching row change in Postgres.
Timing 18 Written just outside the comparison window.
Real misses 52 The ones that needed fixing.

So 75% of the “gap” was the old system inventing changes.

Lesson: categorise every difference before quoting a number, and don’t assume the system you’re replacing is the correct one.

What this means for the warehouse translator

Each of these lessons changed the translator design:

  • Change → impact map. The translator needs a declarative map from each source table and column to the dimension attributes and fact rows it feeds. The new-table problem showed that any table missing from the map must fail loudly, not pass silently.
  • Dimensions are Type 1 merges on the business key, guarded by the source timestamp, with each batch collapsed to the latest change per key. After the idempotency bug, that key comes from the source change, never from batch boundaries.
  • Facts are updated only where the map says a change reaches them: a measure changed, a foreign key moved, or an attribute copied into the fact changed.
  • Transactions stay together. One user action writes several tables in one Postgres transaction, so the translator holds a micro-batch until the whole transaction has arrived, which the audit consumer already does.
  • Snowflake gets micro-batches, never row-by-row statements: stage the translated operations, then run one merge per target table. The batch window is the dial between freshness and cost, and auto-suspend must be short enough for the warehouse to actually sleep.
  • The full reload stays as a safety net, run in compare mode, until the differences stay at zero. The raw change archive makes a translator bug a replay rather than a loss.

What I learned

Understand what the data is doing before tuning the infrastructure that processes it. The refresh loop showed how much of each cycle was repeated work, and the cost breakdown showed a third of the bill coming from a status check nobody had looked at.

With CDC, most of the hard problems were not in Snowflake. They were in identity and coverage: whether every table is captured, whether a change keeps the same key wherever the batch boundary falls, and whether the old system’s numbers deserve to be the baseline.

References

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.