One Engineer, One Million Rows
Correct first, fast later: why gates scale better than headcount
We had a million insurance claims to move into production and an eight-figure contract riding on it. Depending on the week, somewhere between 12 and 22 developers touched the pipeline: contractors, teams working overnight in other time zones, junior engineers, and none of the people who originally built it. When the counts came back short, nobody could say which batch was bad. We read logs instead. About 100,000 lines of them.
I was the lead, brought in mid flight. Days ran from 7 AM to 10 PM. Every fix had to fit a project process shaped by business deadlines and short timelines, so the honest answer is that we patched. Patching was the only thing that fit the window.
This post is the question I kept asking during those weeks: what would it take for one engineer to run this pipeline, correctly? Not a hypothetical rewrite with unlimited time. A realistic design, built from the exact failures we hit.
The pipeline, as it actually ran
Analytics team prepares the data
โ writes it into staging tables and fires a trigger
โ Stage one: stored procedures move staging rows into the live tables
โ Stage two: a Go "data landing" job checks every 10 minutes for new rows
and pushes batches to Azure AI Search (two pods, leader election)
โ staging rows move pending โ processing โ deleted on successThere were two ways data got in. Writes through the API and UI synced fine. Writes through the ETL path are where everything broke.
It was designed for one or two runs a day of about twenty thousand records. Then a client started streaming 10 to 25 records per second, and later asked for a backfill of millions of historical records while the stream kept running.
The knowledge lived in people
Here is what went wrong, all of it real:
- 70,320 rows disappeared from a push of roughly one million. Five batches went in that day. Three reconciled exactly and two did not.
- The wrong identifier landed in the wrong column. In one tenant, claim number was null for every record. In another, claim number held claim ID values, so the UI showed IDs where adjusters expected claim numbers.
- Keys had stray whitespace, so joins only worked with TRIM, and some staging rows arrived with no ID at all.
- 118,000 rows sat in processing with no way out. Uploads were failing 100% of the time for one tenant, and there was no failure path, no retry and no expiry.
- 422 orphaned lookup roles from older builds pointed at nothing.
- Nothing could be reversed. No batch filter, no way to identify which rows came from which push, and no dead letters. When a queue or worker failed, someone eyeballed its logs.
Every one of these was known to somebody on the team. None of them was known to the pipeline.
The rule: correct first, fast later
Speed was never the problem. Load tests moved one million rows in about eighteen seconds. The problem was everything the pipeline assumed: that data arrives tidy, that nobody writes while it reads, that every identifier means what its column name says, and that the search index will simply keep up.
The tolerance for a bad row was zero. These were insurance claims for real people and real money. So the design starts there, and speed comes after.
The gate ladder
Every stage becomes a gate. A gate checks one thing, writes its result, and either passes the batch forward or holds it. A failed gate never loops and never guesses. It stops.
| Gate | What it checks | The real failure it catches |
|---|---|---|
| G0 Receipt | Staging count matches the count and batch number analytics handed over | 70,320 missing rows |
| G1 Contract | Required keys present, trimmed, and claim number does not look like a claim ID | ID swap, nulls, whitespace |
| G2 Isolation | This run claims its rows under a lock and stamps a batch_id on every one | Snapshot race, no way to reverse |
| G3 Reconcile | Expected equals staged equals claimed | Silent drops |
| G4 Business rules | Every lookup resolves and every row belongs to the right tenant | Orphaned roles |
| G5 Promote | One transaction into production. The point of no return | Partial writes |
| G6 Downstream | Retries with backoff, dead letters, nothing stuck in processing | 118,000 stuck rows |
| G7 Verify | Database count equals index count for this batch | Index drift |
G0 through G4 are cheap and run before anything touches production. That is the whole point: push the point of no return as late as possible.
G0 Receipt: start from what you were promised
The analytics team did hand over a count and a batch number. The pipeline just never used them. Make that handoff a row, and refuse to start until staging matches it.
CREATE TABLE etl.batch_manifest (
batch_id uuid PRIMARY KEY,
source_batch_no text NOT NULL,
expected_rows bigint NOT NULL,
received_at timestamptz NOT NULL DEFAULT now(),
status text NOT NULL DEFAULT 'received'
);
-- G0 passes only when staging holds exactly what was promised.
SELECT m.expected_rows, count(s.staging_id) AS staged_rows
FROM etl.batch_manifest m
LEFT JOIN staging.claims s ON s.source_batch_no = m.source_batch_no
WHERE m.batch_id = $1
GROUP BY m.expected_rows;G1 Contract: staging is a contract, not a scratch table
One null staging ID used to stall every job behind it. One wrong column put claim IDs on the screen. Both are contract violations, and both are cheap to detect before promotion.
-- Normalize in the read path so the transform never sees surprises.
CREATE OR REPLACE VIEW staging.claims_clean AS
SELECT
staging_id,
source_batch_no,
TRIM(claim_id) AS claim_id,
NULLIF(TRIM(claim_number), '') AS claim_number,
COALESCE(TRIM(exposure_number), '') AS exposure_number,
loss_date
FROM staging.claims;
-- Contract violations for this batch, each with a reason.
SELECT staging_id,
CASE
WHEN claim_id IS NULL THEN 'missing claim_id'
WHEN claim_number IS NULL THEN 'missing claim_number'
WHEN claim_number = claim_id THEN 'claim_number holds claim_id'
WHEN claim_number !~ $2 THEN 'claim_number format'
END AS reason
FROM staging.claims_clean
WHERE source_batch_no = $1
AND (claim_id IS NULL OR claim_number IS NULL
OR claim_number = claim_id OR claim_number !~ $2);The format check ($2) is the one line that would have caught the identifier swap on the first push. Claim numbers and claim IDs have different shapes. Encode the shape.
G2 Isolation: never delete what you did not process
This is the bug I think about most. The old ETL read everything in staging, copied it to the live tables, then cleared staging. The analytics team was still writing while it ran. Anything that landed after the read was deleted without ever being processed. With one or two records at a time, the window was tiny. A bulk load made it enormous.
Claim specific rows, process exactly those rows, remove exactly those rows.
-- Rows that arrive after this statement are untouched,
-- and a concurrent worker skips rows another worker already holds.
WITH claimed AS (
SELECT staging_id
FROM staging.claims
WHERE batch_id IS NULL AND source_batch_no = $2
ORDER BY staging_id
FOR UPDATE SKIP LOCKED
)
UPDATE staging.claims s
SET batch_id = $1, claimed_at = now()
FROM claimed c
WHERE s.staging_id = c.staging_id;
-- Later, after G7: remove only what this run owned.
DELETE FROM staging.claims WHERE batch_id = $1;Overlapping runs caused lock contention and stuck queries too, so each pipeline also takes an advisory lock. A second run becomes a no op instead of a collision.
// internal/etl/run.go
func (p *Pipeline) RunOnce(ctx context.Context, name string) error {
conn, err := p.pool.Acquire(ctx)
if err != nil {
return err
}
defer conn.Release()
var got bool
if err := conn.QueryRow(ctx,
`SELECT pg_try_advisory_lock(hashtext($1))`, "etl:"+name).Scan(&got); err != nil {
return err
}
if !got {
p.log.Info("run already in progress, skipping", "pipeline", name)
return nil
}
defer conn.Exec(context.Background(), `SELECT pg_advisory_unlock(hashtext($1))`, "etl:"+name)
return p.runGates(ctx, conn)
}G3 Reconcile: the books must balance
Three numbers, one comparison. If expected, staged and claimed are not identical, the batch holds. No judgment call, no log reading.
SELECT
m.expected_rows,
(SELECT count(*) FROM staging.claims WHERE source_batch_no = m.source_batch_no) AS staged,
(SELECT count(*) FROM staging.claims WHERE batch_id = m.batch_id) AS claimed
FROM etl.batch_manifest m
WHERE m.batch_id = $1;G4 Business rules: every reference resolves
The 422 orphaned lookup roles were rows that pointed at nothing. An anti join finds them before they reach production.
SELECT s.staging_id, s.role_code
FROM staging.claim_roles s
LEFT JOIN production.lookup_roles r
ON r.role_code = s.role_code AND r.tenant_id = s.tenant_id
WHERE s.batch_id = $1
AND r.role_code IS NULL;G5 Promote: one transaction, one point of no return
Only now does anything touch production. The upsert, the before images that make reversal possible, and the outbox messages for downstream all commit together or not at all.
Seventeen staging tables with shifting schemas meant hardcoded column lists broke constantly. The load function derives its columns at runtime from information_schema, so a new upstream field flows through as soon as it exists on both sides.
CREATE OR REPLACE FUNCTION etl.upsert_from_staging(
p_table text, p_key text, p_batch uuid
) RETURNS bigint
LANGUAGE plpgsql AS $
DECLARE
v_cols text;
v_updates text;
v_rows bigint;
BEGIN
-- Columns present in BOTH staging and production, in production order.
SELECT
string_agg(quote_ident(p.column_name), ', ' ORDER BY p.ordinal_position),
string_agg(format('%1$I = EXCLUDED.%1$I', p.column_name), ', '
ORDER BY p.ordinal_position)
FILTER (WHERE p.column_name <> p_key)
INTO v_cols, v_updates
FROM information_schema.columns p
JOIN information_schema.columns s
ON s.column_name = p.column_name
AND s.table_schema = 'staging'
AND s.table_name = p_table
WHERE p.table_schema = 'production'
AND p.table_name = p_table;
-- DISTINCT ON keeps the latest version of a key inside one batch.
EXECUTE format(
'INSERT INTO production.%1$I (%2$s)
SELECT DISTINCT ON (%3$I) %2$s
FROM staging.%1$I
WHERE batch_id = $1
ORDER BY %3$I, staging_id DESC
ON CONFLICT (%3$I) DO UPDATE SET %4$s',
p_table, v_cols, p_key, v_updates)
USING p_batch;
GET DIAGNOSTICS v_rows = ROW_COUNT;
RETURN v_rows;
END $;That flexibility cuts both ways. If upstream renames a column, the old one silently stops flowing. So G1 also records the column set on every run and holds the batch when it changes.
-- Columns in staging that are not landing in production.
SELECT s.column_name
FROM information_schema.columns s
LEFT JOIN information_schema.columns p
ON p.table_schema = 'production'
AND p.table_name = s.table_name
AND p.column_name = s.column_name
WHERE s.table_schema = 'staging'
AND s.table_name = 'claims'
AND s.column_name NOT IN ('staging_id', 'batch_id', 'claimed_at', 'source_batch_no')
AND p.column_name IS NULL;The promote step itself:
BEGIN;
-- Before images: what every touched row looked like before this batch.
INSERT INTO etl.row_history (batch_id, record_id, before_image)
SELECT $1, p.claim_id, to_jsonb(p)
FROM production.claims p
JOIN staging.claims s ON s.claim_id = p.claim_id
WHERE s.batch_id = $1;
SELECT etl.upsert_from_staging('claims', 'claim_id', $1);
-- One message per changed record, committed with the data.
INSERT INTO etl.outbox (record_type, record_id, batch_id)
SELECT 'claim', claim_id, $1
FROM staging.claims
WHERE batch_id = $1;
COMMIT;G6 Downstream: nothing waits forever
The 118,000 stuck rows had one root cause: the upload could fail, and nothing handled it. A row entered processing and had no way to leave. Every downstream state needs an exit: succeeded, retrying, or dead lettered with a reason.
The message carries only an ID, and the consumer always reads current state. A retried, duplicated or out of order message can never write stale data.
// internal/searchsync/handler.go
const maxRetries = 2
func (s *Syncer) Handle(ctx context.Context, msg Message) error {
err := s.sync(ctx, msg.RecordID)
if err == nil {
return s.repo.MarkSynced(ctx, msg.ID)
}
if msg.Attempts >= maxRetries {
return s.repo.DeadLetter(ctx, msg.ID, err.Error()) // visible, owned, alerted
}
delay := backoff(msg.Attempts) + jitter()
return s.repo.Retry(ctx, msg.ID, msg.Attempts+1, delay) // back to pending
}
func (s *Syncer) sync(ctx context.Context, id string) error {
rec, err := s.repo.GetClaim(ctx, id)
if errors.Is(err, ErrNotFound) {
return s.index.Delete(ctx, id)
}
if err != nil {
return fmt.Errorf("load %s: %w", id, err)
}
return s.index.MergeOrUpload(ctx, toDocument(rec)) // idempotent by design
}Per record sync also fixes a quieter problem. When indexes updated table by table, a run that stopped halfway left a claim updated and its notes stale. Reading current state per record converges no matter where it was interrupted.
G7 Verify: the batch is done when the index agrees
A batch is not done when the database commits. It is done when every record it changed is searchable.
-- Every outbox message for this batch has left the system one way or another.
SELECT
count(*) FILTER (WHERE status = 'synced') AS synced,
count(*) FILTER (WHERE status = 'dead_letter') AS dead,
count(*) FILTER (WHERE status IN ('pending', 'processing', 'retrying')) AS in_flight
FROM etl.outbox
WHERE batch_id = $1;G7 passes when in flight is zero, dead is zero, and the index document count for the batch matches the database. Only then does staging get cleared.
The same principle applies to full rebuilds. Our reindex deleted the index and repopulated it, which meant hours to days of partial search for real users after every release. Build the new index beside the old one, verify it, then swap an alias.
// internal/searchsync/rebuild.go
func Rebuild(ctx context.Context, s SearchAdmin, src Source, alias string) error {
next := fmt.Sprintf("%s-%d", alias, time.Now().Unix())
if err := s.CreateIndex(ctx, next, ClaimSchema); err != nil {
return err
}
// Keyset pagination with a checkpoint, so a failure resumes instead of restarting.
if err := hydrate(ctx, s, src, next); err != nil {
return fmt.Errorf("hydrate %s: %w", next, err) // old index still serving
}
rows, err := src.Count(ctx)
if err != nil {
return err
}
docs, err := s.DocCount(ctx, next)
if err != nil {
return err
}
if docs != rows {
return fmt.Errorf("verify failed: %d docs vs %d rows", docs, rows)
}
old, _ := s.ResolveAlias(ctx, alias)
if err := s.SwapAlias(ctx, alias, next); err != nil {
return err
}
return s.DeleteIndex(ctx, old) // only after the new one is live
}Hold the batch, not the row
Most pipelines quarantine a bad row and keep going. With zero tolerance, that is the wrong default. A batch with one bad claim is a bad batch, because the analytics team needs to know their export is wrong, not just that one row was skipped.
// internal/etl/contract.go
// Collect every violation, then decide once for the whole batch.
func (p *Pipeline) gateContract(ctx context.Context, b Batch) (GateResult, error) {
violations, err := p.repo.ContractViolations(ctx, b.ID)
if err != nil {
return GateResult{}, err
}
if len(violations) > 0 {
p.repo.Quarantine(ctx, b.ID, violations) // every row, every reason
return Hold("G1", b, len(violations)), nil
}
return Pass("G1", b), nil
}The quarantine list goes back to the analytics team with a row ID and a reason for each problem. The batch stays held, production stays untouched, and the fix happens at the source.
Batch IDs make reversal possible
We could not reverse a bad push because nothing in production said where a row came from. Stamp the batch on every production row, keep the before images from G5, and reversal becomes two statements.
-- Delete what this batch created.
DELETE FROM production.claims p
WHERE p.last_batch_id = $1
AND NOT EXISTS (
SELECT 1 FROM etl.row_history h
WHERE h.batch_id = $1 AND h.record_id = p.claim_id);
-- Restore what this batch changed.
UPDATE production.claims p
SET claim_number = h.before_image->>'claim_number',
status = h.before_image->>'status',
last_batch_id = (h.before_image->>'last_batch_id')::uuid
FROM etl.row_history h
WHERE h.batch_id = $1 AND h.record_id = p.claim_id;Then requeue the affected IDs through G6, and the index follows.
Logs you can query, not read
Eyeballing 100,000 lines per queue is not a logging strategy. Every gate writes one row: which batch, which gate, what it expected, what it found, and why it held.
CREATE TABLE etl.gate_result (
batch_id uuid NOT NULL,
gate text NOT NULL, -- G0 .. G7
status text NOT NULL CHECK (status IN ('passed', 'held', 'failed')),
expected bigint,
actual bigint,
reason text,
checked_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (batch_id, gate)
);
-- "Which batch is bad, and where did it stop?" is now one query.
SELECT m.source_batch_no, g.gate, g.expected, g.actual, g.reason
FROM etl.gate_result g
JOIN etl.batch_manifest m USING (batch_id)
WHERE g.status <> 'passed'
ORDER BY g.checked_at DESC;Wire alerts to three things: a held or failed gate, any dead letter, and a batch older than the agreed cadence that has not reached G7.
Then, and only then, speed
Once the gates hold, speed is easy, because it was always there. Load testing showed the ETL was never the bottleneck.
| Test | Result |
|---|---|
| 10K rows ร 5 tables, 10 parallel runs | 2 to 3 seconds per iteration |
| 100K rows ร 5 tables, single run | 9 seconds |
| 200K rows ร 5 tables (1M rows), single run | about 18 seconds |
| API latency under load | 2.45s โ 2.55 to 2.65s |
The gates add seconds. The missing gates cost weeks. For a large backfill next to live traffic:
- Scale the database and search tier first, and confirm you can scale them back down.
- Pause automated search sync through versioned config or a feature flag.
- Pilot a small, real slice in production during off hours. Our 50K test push needed about ten named people. With gates, it needs one person and a dashboard.
- Hold a 12 to 24 hour cool off and watch the gate results.
- Run the remainder in fixed batches (we settled on 200K), each one through G0 to G7.
One corner we cut: pausing sync meant hand editing a stored procedure in production, which raised a fair compliance objection. It worked, and it was the wrong mechanism. Any switch you expect to flip during an operation belongs in versioned config.
Why one engineer is realistic
Each gate replaces something a person used to have to remember, notice or do by hand.
| What the team did by hand | What the gate does |
|---|---|
| Asked analytics "how many did you send?" | G0 compares the manifest automatically |
| Spotted claim IDs on screen after release | G1 rejects the batch before promotion |
| Coordinated so nobody wrote during a run | G2 claims rows and locks the run |
| Counted rows in three places by query | G3 compares them in one |
| Found orphaned roles in support tickets | G4 finds them in staging |
| Hoped a failed run left nothing behind | G5 commits everything or nothing |
| Cleared stuck processing rows manually | G6 retries or dead letters with a reason |
| Searched the UI to confirm data landed | G7 compares database and index counts |
| Read 100,000 lines of logs | One query on gate_result |
That is the real lesson for leads as much as engineers. When a pipeline is in trouble, the instinct is to add people. But every new person brings their own understanding of how it works, and the pipeline does not enforce any of them. Gates are how you make the pipeline enforce one.
Why this fits any industry
None of these failures were about insurance. They were about a handoff with no receipt, two writers on one table, an identifier nobody validated, and a downstream state with no exit. Orders, patients, shipments and ledgers all have the same shape. The gates transfer unchanged.
If you are about to build one
Start with the decision, not the code.
- Decide your tolerance for bad rows before you write code. If it is zero, hold batches, not rows.
- Turn every handoff into a manifest with a count and a batch number.
- Encode the shape of every identifier. Names lie, formats do not.
- Claim rows explicitly. Never delete what this run did not process.
- Keep the point of no return late, and make it one transaction.
- Give every downstream state an exit: synced, retrying, or dead lettered.
- Stamp batch IDs everywhere so any push can be reversed.
- Log gate results as rows you can query, not lines you have to read.
- Only then, make it fast.
Build order for one engineer
You can't build everything at once, so the order matters. Build the parts that tell you the truth first, and the parts that make it fast last.
- The receipt and the ledger. Create batch_manifest and gate_result before writing any transform. Even with nothing else built, you can already answer "which batch is bad?"
- Contract checks (G1). Encode identifier shapes, required keys and trimming. Hold the batch on any violation and send the quarantine list back to the source.
- Claiming and locking (G2, G3). Stamp batch IDs, claim rows explicitly, take an advisory lock and check that the three counts match.
- One promote transaction (G5). The upsert, before images and outbox commit together. This is the only step that touches production.
- An exit for every downstream state (G6, G7). Retry with backoff, dead letter with a reason, and check the database against the index for each batch.
- Business rules (G4) as you find them. Each incident becomes a new check, not a new page in a runbook.
- Then speed. Batch sizes, parallel runs, scaling. Only tune what the gates prove is slow.
Prove it with a bad batch
Before the first real push, try to break the pipeline on purpose. Each rehearsal should stop at exactly one gate and leave production untouched.
| Rehearsal | Expected result |
|---|---|
| Drop 1,000 rows but keep the original manifest count | G0 holds |
| Put claim IDs in the claim number column | G1 holds and quarantines every row |
| Keep writing to staging during a run | New rows wait for the next batch and G3 balances |
| Kill a pod halfway through search sync | Messages retry and G7 passes after recovery |
| Make every search upload fail | Messages dead letter with a reason and G7 holds |
| Reverse a promoted batch | Production matches the before images and the index follows |
If explaining what happened in a rehearsal means reading logs, that gate isn't finished.
The lines one engineer holds
- No batch reaches production without a manifest.
- No delete without a claim.
- No manual edits to production procedures. Switches live in versioned config.
- No state without an exit.
- No batch is done until the index agrees.
Twenty two people could not hold all of this in their heads, and they should not have had to. One engineer can, because the pipeline holds it for them. A million rows do not care how many people are watching. They care whether every gate stays closed until the batch earns its way through.
We patched our way through because that was what the timeline allowed. The pipeline was fast from day one. Making it something one person could trust would have taken every gate on that list.