Ingestion is a contract, not a connector
Choosing how data enters your platform is choosing the guarantees you will live with afterwards. Every ingestion pattern encodes a position on four questions: how fresh the data can be, whether history is complete, whether records can be duplicated, and what happens when the source is unavailable. A nightly batch answers those questions cheaply and honestly; a streaming pipeline answers them expensively and usually still needs a reconciliation job for the cases it cannot cover.
The mistake is picking a pattern by technology availability rather than by consumer need. A dashboard that refreshes hourly does not justify a CDC pipeline, and a compliance feed that must capture every update in under a second cannot be served by a nightly dump. Write the consumer's freshness and completeness requirements first, then choose the pattern that satisfies them at the lowest operational cost.
After this lesson you should be able to name the pattern that fits a requirement, describe the failure mode each pattern exposes, and design the reconciliation step that closes the gaps every pattern leaves open.
Four families, four sets of trade-offs
Most production ingestion falls into four families, often used together. Full or incremental batch extraction reads the source on a schedule and is trivial to reason about but limited by the schedule. Streaming ingestion reads a continuous feed and gives low latency at the cost of state and offset management. Change data capture reads the database's transaction log and reconstructs row-level history without touching the source workload, at the cost of log-format coupling. API and file ingestion covers everything else â third-party systems that offer no log and no direct table access.
| Pattern | Freshness | Historical completeness | Source impact | Primary risk |
|---|---|---|---|---|
| Nightly full extract | Up to 24 hours | Only current state | Full scan load | No history of intra-day changes |
| Incremental batch | Minutes to hours | Only rows changed since watermark | Row or timestamp scan | Missed updates when timestamps skip |
| Streaming from a queue | Sub-second | Depends on retention | Low | Lag growth during outages |
| Change data capture | Seconds | Full row-level history | Reads the log | Schema drift and transaction boundaries |
| API polling with cursor | Minutes | Depends on API support | Rate limits | Pagination errors, throttling |
| Webhook push | Seconds | None unless persisted | None | Duplicates and unacknowledged retries |
| File drop with watcher | When the file lands | Whatever the file contains | None | Partial files, naming races |
Two patterns deserve particular care. Incremental batch using a updated_at watermark silently loses rows when clocks move backwards, when updates happen in the same microsecond, or when a row is updated and its timestamp is not; a monotonic id plus a created-or-updated predicate is safer, and reading soft-deleted rows is easy to forget. File watching has a matching trap: a producer writing a file in place will be picked up half-written, so always watch for a completed marker, a rename into place, or a stable size across two checks.
Batch loads that can be re-run
The discipline that makes batch ingestion safe is idempotency. If the same logical day can be loaded twice without changing the result, every failure becomes a retry instead of an investigation. Write to a staging location keyed by the logical date, validate, then publish atomically.
import pandas as pd
import pyarrow.parquet as pq
import pyarrow as pa
from datetime import date, timedelta
def extract_incremental(engine, since_id: int, batch_size: int = 50_000):
"""Read rows with a monotonic id greater than the watermark."""
last = since_id
while True:
df = pd.read_sql(
"SELECT id, payload, updated_at, is_deleted FROM events "
"WHERE id > %s ORDER BY id LIMIT %s",
engine,
params=(last, batch_size),
)
if df.empty:
break
last = int(df["id"].max())
yield df
def load_day(df: pd.DataFrame, root: str, logical_day: date) -> None:
"""Write a partitioned, overwrite-safe parquet stage for one day."""
table = pa.Table.from_pandas(df, preserve_index=False)
path = f"{root}/dt={logical_day.isoformat()}"
pq.write_table(table, path + "/part-0.parquet") # deterministic path
# Re-running the same day rewrites the same file: converges by construction.
def publish(engine, watermark: int) -> None:
"""Advance the watermark only after the stage is committed."""
engine.execute("UPDATE ingest_state SET last_id = %s WHERE source = 'events'",
(watermark,))
engine = create_engine("postgresql://warehouse/prod")
watermark = read_watermark(engine, "events")
for chunk in extract_incremental(engine, watermark):
load_day(chunk, "s3://lake/staging/events", date.today())
watermark = int(chunk["id"].max())
publish(engine, watermark)
Note what the watermark update is not doing: it is not advanced inside the loop. If a load fails halfway, the next run resumes from the last committed position rather than from a partial batch, which means the failure mode is a bounded replay rather than missing rows. The staging path is deterministic so that replay overwrites rather than appends.
Change data capture without breaking the source
CDC reads the database's write-ahead log and converts physical row changes into a stream of before-and-after images. Its appeal is that extraction cost does not depend on table size and the source is not queried at all; its complexity is that you now depend on log retention, replica slots, and a decoder that must survive DDL changes.
from confluent_kafka import Consumer, KafkaProducer
import json, os
def run_cdc_consumer():
consumer = Consumer({
"bootstrap.servers": os.environ["KAFKA_BROKERS"],
"group.id": "orders-cdc",
"auto.offset.reset": "earliest",
"enable.auto.commit": False,
"isolation.level": "read_committed",
})
producer = KafkaProducer(
bootstrap_servers=os.environ["KAFKA_BROKERS"],
acks="all",
enable_idempotence=True,
value_serializer=lambda v: json.dumps(v, default=str).encode("utf-8"),
)
consumer.subscribe(["dbserver1.public.orders"])
try:
while True:
msg = consumer.poll(1.0)
if msg is None:
continue
if msg.error():
continue
payload = json.loads(msg.value())
change = {
"op": payload["op"], # c=create u=update d=delete
"table": f"{payload['source']['schema']}.{payload['source']['table']}",
"ts_ms": payload["ts_ms"],
"before": payload.get("before"),
"after": payload.get("after"),
"lsn": msg.key().decode() if msg.key() else None,
}
# Tombstones and deletes must be applied, not filtered away.
producer.send("cdc.orders", key=change["after"]["id"] if change["after"]
else change["before"]["id"], value=change)
producer.flush()
consumer.commit(message=msg)
finally:
consumer.close()
The line that matters is the commit position. Committing after the downstream ack gives at-least-once, so your apply step must be an upsert keyed on the primary key â including deletes, which arrive as tombstones and are the change most often dropped by a filter that only looks at the new image. Retention is the other constraint: if CDC lags past the log's retention window, the only recovery is a full resnapshot of the table.
API sync: cursors, webhooks, and backfills
Third-party APIs rarely offer a log, so you synthesise one. Use an opaque cursor rather than a timestamp where the API provides it, page until the cursor stops rather than assuming one response equals one page, and record the cursor in the same transaction that commits the data so a crash cannot advance it past unwritten records. Respect rate-limit headers and back off on 429 with jitter instead of hammering.
Webhooks invert the direction and bring their own problems: the provider retries until it receives a 2xx, which means duplicates are guaranteed rather than possible. Deduplicate on a delivery id, acknowledge quickly, and move the work to a queue so your endpoint never does processing inside the request handler. For both webhooks and polling, schedule a periodic reconciliation job that compares source and target counts or checksums â it is the only defence against a silently missed update.
Choosing under real constraints
With the families understood, selection becomes a short argument rather than a debate about tools. Start from the consumer: what freshness does the decision actually require, must history be reconstructable, and what is the cost of a missed record. Then check the source: does it expose a log, a table, a cursor, or only a file, because that single fact eliminates most of the remaining options. Finally price the operation: who is on call when it breaks, and can that team debug a rebalanced consumer group at midnight.
Most platforms converge on the same shape. Batch extraction covers the long tail of sources that offer nothing better. Streaming from a queue covers the handful of high-value, low-latency feeds. CDC covers the core operational tables where intra-day history matters. A reconciliation job sits over all three, because each family leaves a different hole and only an independent comparison closes them. Resist the urge to convert everything to streaming; the operational cost is real and the consumer rarely needs it.
đĄDesign the reconciliation first
Before choosing a pattern, write down how you would detect and repair a missing record. If the answer requires reading the entire source again, budget for that full pass now and schedule it, because the incident where you need it will not be the moment you want to design it.
Common Mistakes
Extracting incrementally on updated_at and missing rows that share a timestamp
Fix: Use a monotonic key with an inclusive bound and a tie-breaker, and test for skipped ids
Watching a file path and reading the file while it is still being written
Fix: Watch for a rename or a success marker, or require a stable size across two polls
Treating webhook deliveries as exactly-once
Fix: Deduplicate on the provider's delivery id and process asynchronously behind a queue
Advancing a CDC watermark before downstream commits
Fix: Commit offsets only after the apply step succeeds, and keep a resnapshot runbook for log expiry
Best Practices
- Write to deterministic staging paths so a re-run overwrites instead of duplicating
- Store watermarks and cursors transactionally with the data they describe
- Keep an independent reconciliation job for every ingestion path, including streaming ones
- Quarantine unparseable records with their raw payload rather than dropping them
- Document freshness and completeness targets for each source so consumers know what to expect
Interview Questions
Q1: When would you choose CDC over batch extraction?
When you need low latency, row-level history, or must avoid scanning a large source table; the trade-off is coupling to log retention and format.
Q2: Why are webhook duplicates guaranteed?
Providers retry until they receive a successful acknowledgement, so a timed-out but applied request will be delivered again.
Q3: What is the failure mode of timestamp-based incremental loads?
Clock skew, identical timestamps, and updates that do not change the tracked column all cause silently skipped rows.
Q4: How do you recover a CDC pipeline after log retention expires?
You cannot replay from the log; take a fresh snapshot of the table and resume capture from the new snapshot's position.
Key Takeaways
- Choose ingestion from consumer freshness and completeness requirements, not from tool familiarity
- Each family has a characteristic gap: batches miss intra-day history, APIs miss silent updates, CDC needs log retention
- Idempotent staging paths and transactional watermarks make retries safe
- Deduplicate webhooks and CDC applies on a key, and apply deletes explicitly
- A scheduled reconciliation job is what turns best-effort ingestion into trustworthy ingestion