A PostgreSQL replica holds invoices and their lines, with a foreign key from invoice_lines to invoices. A queue consumer (Kafka or RabbitMQ) feeds it, one message per invoice and one per line. Some messages were lost. Lost invoice messages leave the invoice missing, and its lines were rejected by the foreign key when they arrived. Lost line messages leave the invoice there with a line missing.

This is a lab example with generic data (10,000 invoices, 30,000 lines, from SQL Server) and dbSlice by Thinwork. There was no broker in the lab: the lost messages were simulated directly in the PostgreSQL database. Four small job files cover it. None holds a password: they only name saved connection profiles.

The four jobs

  • fk-invoices-check.json, fk-lines-check.json: "tipo": "status". Compare the whole table and only read.
  • fk-invoices-load.json, fk-lines-load.json: "tipo": "insert". Copy only the keys missing in the target.

Windows:

dbSlice.exe fk-invoices-check.json check-invoices.log dbSlice.exe fk-invoices-load.json load-invoices.log 

Linux (Docker edition) runs the jobs through the jobs API with curl and jq. The token goes only in the Authorization: Bearer header (dbs_xxxxxxxx_...).

What the checks found

OK Comparison completed in 0.4s: 9,975 matched, 25 missing in destination, 0 missing in source. 0 with different column values. OK Comparison completed in 0.8s: 29,885 matched, 115 missing in destination, 0 missing in source. 0 with different column values. 

115 lines = 75 (the 3 lines of each of the 25 missing invoices) + 40 (lost line messages).

Children first: it fails

FAILED 23503: insert or update on table "invoice_lines" violates foreign key constraint "invoice_lines_invoice_id_fkey" inserted : 0 

Nothing was written. The exit code is non-zero, and on Linux the API reports "status": "failed", so a script stops at the first error. The DETAIL is redacted by the PostgreSQL driver (Npgsql) by default; the constraint name already points to the parent table.

Parents first, then children

OK Done: 10,000 read, 25 inserted, 0 upsert/update in 0.6s OK Done: 30,000 read, 115 inserted, 0 upsert/update in 0.7s 

The second checks: 10,000 and 30,000 matched, 0 / 0 / 0. Invoices with a line missing went from 40 to 0. Linux returned the same counts.

The insert job never inserts a key that already exists, so running it again does not duplicate.

The full article has the job files, the Linux steps and the script: dbslice.net. Previous in the series: catch up a PostgreSQL replica after a network outage.

dbSlice is our own product, so take this with that in mind.

Originally published at dbslice.net.