Data Ingestion and Source System Integration Questions
Getting data out of heterogeneous source systems and landing it reliably: APIs, operational databases, file drops, webhooks, message queues and third-party SaaS. Covers connector selection and design (managed platforms versus Debezium, DMS or Kafka Connect versus building your own), pull versus push and polling versus webhook patterns, incremental extraction and high-watermark strategy including what to do when a source offers no native change capture, authentication and credential rotation against third-party APIs, source-side rate limits and quotas, schema drift and contract breakage at the source boundary, backfill and replay of history, ingestion-time data-quality gates, reconciliation after a source outage, and negotiating with source-system owners. The scope stops at the boundary: once data has landed, transforming it, the architecture of the pipeline that carries it, stream-processing mechanics, and pipeline monitoring are all covered separately.
You are ingesting data from multiple third-party APIs that use OAuth2 and rotating API keys. Describe how you would securely store and refresh credentials, handle a token-refresh failure without losing data, enforce each source's rate limits, and design retry and backoff so ingestion stays reliable and auditable.
Sample Answer
Direct answer
Credential management for many third-party connectors comes down to three disciplines: store every credential in a secrets manager and never in connector configuration files, refresh OAuth2 tokens proactively before they expire rather than reactively after a call fails, and treat a refresh failure as a distinct, alertable condition rather than letting it silently degrade into skipped syncs. Rate limits and retry behavior then have to be tracked per source, since every third-party API enforces its own limit differently.
Structured elaboration
Secure storage
- Store client IDs, client secrets, and refresh tokens in a dedicated secrets manager (a cloud provider's secrets service or an equivalent), never in a connector's plain configuration file or in version control.
- Scope access narrowly: the connector process should have permission to read only the credentials it needs, not every secret in the organization's store, so a compromised connector cannot pivot to unrelated systems.
Refreshing tokens without losing data
- Refresh proactively, ahead of expiry (for example, when a token has less than 10 minutes of validity left), rather than waiting for a call to fail with a 401 and refreshing reactively; this avoids losing an in-flight batch to an expired token mid-pull.
- If a refresh does fail (the refresh token itself is invalid or revoked), do not let ingestion silently stop: raise a distinct, named alert ("source X requires re-authorization") rather than letting the connector fail the same generic way it would for a transient network error, since these need different human responses.
- Persist enough state that a connector recovering from a refresh failure resumes from its last successful checkpoint rather than needing a full re-pull once access is restored.
Enforcing each source's rate limit
- Each third-party API documents its own limit differently (requests per second, per minute, per day, sometimes per specific endpoint); track each source's limit as explicit configuration rather than a single global assumption.
- A token-bucket (a counter that starts at some capacity, refills by a fixed amount on a fixed schedule such as once per second, and is spent one token per request, so you physically cannot send faster than the refill rate once the initial balance is used up) or sliding-window (which instead counts how many requests actually landed in the trailing N-second window and blocks new ones once that count hits the cap) limiter per source, refilled or evaluated at that source's documented rate, keeps you comfortably under the cap without needing to guess a safe interval empirically.
Retry and backoff, and making it auditable
- Exponential backoff with jitter on 429s and 5xxs, capped so a persistent failure surfaces as an alert instead of retrying forever.
- Log every token refresh, every rate-limit-triggered backoff, and every retry with enough context (which source, which credential, timestamp) that an audit can reconstruct exactly what happened to a given source's access over time, which matters both for debugging and for satisfying a security review.
Worked example
A connector integrates with 12 different third-party sources, each with its own OAuth2 app registration and its own rate limit. Credentials for all 12 live in a secrets manager, tagged by source, with the connector's service identity granted read access only to that tag group. A background refresh job checks each source's token expiry every 5 minutes and refreshes any token with under 10 minutes of remaining validity, well before any extraction job would hit it expired. When source #7's refresh token is revoked (an admin at the third-party company deauthorized the app), the refresh job's next attempt fails distinctly, raising a "source 7 needs re-authorization" alert rather than the generic "sync failed" alert every other source's transient hiccup produces, so the on-call engineer knows immediately this needs a human to click through an OAuth consent screen again, not a routine retry.
Trade-offs & pitfalls
- Reactive-only token refresh (refresh on the first 401) is simpler to implement but risks losing an in-flight extraction to a mid-batch expiry, especially for a slow, long-running pull; proactive refresh is worth the extra complexity for anything beyond a trivial connector.
- Logging refresh and retry events "for audit" is only useful if the logs are actually structured and queryable; a wall of unstructured text log lines does not satisfy a real security audit request.
- A single global rate limiter across all sources under-utilizes fast sources and still risks exceeding a slow source's limit; per-source limiting is more code but is the only version that is actually correct.
- Storing a refresh token is itself a long-lived secret with real blast radius if leaked; rotate the underlying OAuth application's credentials periodically even if no incident has occurred, not only in response to one.
Explain log aggregation as a source-ingestion pattern: what is typically collected, which agents commonly do the collecting (for example Filebeat, Fluentd, or Logstash), and how a log stream differs from a structured event stream. Describe how you would handle log rotation, multi-line log entries, and backpressure when logs are shipped to a central broker.
Sample Answer
Direct answer
Log aggregation collects unstructured or semi-structured text output that applications and infrastructure already emit (request logs, error traces, system events) using a lightweight agent running alongside the source, and ships it to a central broker for downstream processing. It differs from a structured event stream in one fundamental way: a log line is written for a human to read, with no guaranteed schema, while a structured event is deliberately designed as data, with a defined shape a consumer can rely on; that difference shapes everything about how you have to handle log ingestion.
Structured elaboration
What is typically collected
- Application logs (request/response traces, error stack traces, application-level warnings), system logs (OS and infrastructure-level events), and access logs (web server or load balancer request records).
Common collection agents
- Filebeat: a lightweight, low-resource agent focused specifically on tailing log files and forwarding them, commonly paired with the Elastic stack.
- Fluentd (and its lighter sibling Fluent Bit): a more general-purpose log collector and router with a large plugin ecosystem for routing to many different destinations.
- Logstash: a heavier-weight collector with built-in parsing and transformation capability, often used when logs need real processing before landing, not just forwarding.
How a log stream differs from a structured event stream
- Schema: a structured event has a defined, versioned shape a consumer can validate against; a log line is free text whose format can change any time a developer changes a log statement, with no contract and often no warning.
- Intent: a log line is written primarily for a human debugging an issue in the moment; a structured event is written primarily for a downstream SYSTEM to consume programmatically. Extracting reliable structured data out of logs (parsing timestamps, fields, and values out of free text) is a real engineering task in a way that reading an already-structured event is not.
- Volume characteristics: logs are often far higher-volume and noisier than a purpose-built event stream, since every application already emits a lot of log output that was never designed with ingestion cost in mind.
Handling log rotation
- A log agent needs to track its read position (an inode and offset, not just a filename) so it correctly continues reading a rotated file's new incarnation without either re-reading already-shipped lines or silently skipping lines written in the brief window around rotation.
Handling multi-line log entries
- A single logical log entry (a stack trace spanning many lines, for example) needs to be recognized and grouped correctly by the agent before shipping, using a pattern (a line starting with a timestamp signals a new entry, everything after it until the next timestamp belongs to the same entry) rather than treating every physical line as a separate record, which would shred a stack trace into meaningless individual fragments.
Handling backpressure
- When the central broker cannot keep up with the volume an agent is producing, the agent needs a bounded local buffer (disk-backed, ideally, so a restart does not lose buffered lines) and a policy for what happens when that buffer fills: block and slow the source application (risky, since logging should rarely be allowed to affect application performance), drop the oldest or newest lines (a real, explicit data-loss decision that should be a deliberate choice, not a default nobody decided on), or sample.
Worked example
An application server emits a Java stack trace as 15 separate physical lines when an exception occurs. A naive line-by-line log shipper would forward each of those 15 lines as 15 unrelated log entries, destroying the ability to read the actual stack trace as a coherent unit downstream. Configuring the collection agent (Filebeat or Fluentd, either supports this) with a multi-line pattern, "a new entry starts only on a line matching a timestamp pattern, otherwise append to the previous entry," correctly reassembles the full 15-line trace into one shipped log entry, matching how a human reading the raw file would naturally interpret it.
Trade-offs & pitfalls
- Treating log data as if it had the same reliability as a structured event stream is a common mistake; a developer can change a log line's format in a routine code change with zero awareness that a downstream parser depends on its exact shape, and that parser will then silently misparse or drop fields with no warning from anywhere in the chain.
- Getting multi-line grouping wrong in either direction is costly: too aggressive grouping merges genuinely separate log entries into one garbled record, too conservative grouping shreds a single logical entry (like a stack trace) into fragments; test the pattern against real production log samples, not synthetic ones.
- A backpressure policy of "just buffer more" without a bound eventually exhausts local disk on the source host, which then risks affecting the actual application, the opposite of what a good logging design should ever do.
- Retention and cost for raw log volume can dwarf structured event costs at real scale, since logs are typically far higher-volume and lower information-density per byte; a deliberate retention and sampling policy matters more here than for most other source types.
After a regional outage at one of your source systems, the warehouse shows lower totals than the source of record. Some records were replayed during recovery, some were skipped, and the source-side logs from the outage window are incomplete. Walk through how you would safely replay the missing window from the source without double-counting the records that already made it through, and what you would change so an outage like this does not create the same class of gap next time.
Sample Answer
Direct answer
Safely replaying the missing window means treating the outage window as a specific, bounded time range to re-extract from the source, applying every replayed record through the same idempotent write path normal ingestion uses so already-landed records are harmlessly overwritten rather than duplicated, and cross-checking the result against an independent total (the source's own reported total, if one exists) before declaring the gap closed. Preventing a repeat means the outage revealed a real gap in what the ingestion pipeline durably records about its own progress during a failure, and that gap is what needs fixing, not just the one bad day's numbers.
Structured elaboration
Determining exactly what is missing
- Establish the outage window's precise start and end from your own ingestion checkpoints and monitoring, not from the source's incomplete logs, since those are exactly what is unreliable here.
- Compare your landed record IDs against the source's current state for that window (a re-query, not the old logs) to build an authoritative list of what is actually missing, rather than assuming the whole window needs a full re-pull.
Replaying without double-counting
- Route every replayed record through the same idempotent upsert path (keyed on the record's own stable ID) that normal ingestion uses, so a record that already landed correctly during the chaotic recovery is simply overwritten with itself, not duplicated.
- Never insert replayed records as new rows into the destination without going through that same conflict-safe write path; a "just for this replay" bespoke insert script is exactly how a well-intentioned fix creates the duplicates it was meant to prevent.
Verifying the fix
- Reconcile against an independent total where one exists: if the source has its own authoritative count or sum for the window (a billing system's own reported revenue, for example), compare your landed total against it, not just against your own row count.
- Spot-check a sample of individual records from the window against the source directly, since an aggregate total matching does not guarantee every individual record is correct, only that errors did not happen to cancel out.
Preventing the same class of gap next time
- The actual root cause here is that your OWN ingestion checkpoint/logging was not durable or granular enough to reconstruct exactly what was captured during the outage; fix that specifically, for example by persisting a checkpoint after every small batch rather than only at the end of a run, so a future outage leaves a precise, trustworthy record of exactly where things stopped.
- Add a lightweight, ongoing reconciliation check (comparing your ingested totals against the source's own reported totals on some regular cadence) so a gap like this is caught within hours, not discovered by a finance team noticing the numbers do not match.
Worked example
A payments source has a 6-hour outage; during automated recovery, some transactions are re-sent and land twice under the pipeline's normal ingestion (no duplicate, because ingestion already upserts on transaction ID), but a smaller set of transactions that occurred right at the very start of the outage were never captured at all, since the pipeline's checkpoint had not yet been durably written when the outage began. The precise gap is identified by querying the source for all transaction IDs in the outage window and diffing against what already landed, rather than trusting the source's own (incomplete) outage-window logs. The missing transactions are replayed through the normal idempotent ingestion path, and the day's total is reconciled against the payment processor's own settlement report for that window, confirming an exact match before the incident is closed. Going forward, the checkpoint is changed to persist after every 1,000-record batch instead of only at the end of a full run, so a future outage at the same point in processing would leave a checkpoint precise enough to know exactly what needs replaying without needing this kind of forensic reconciliation at all.
Trade-offs & pitfalls
- Re-pulling the ENTIRE outage window "to be safe," rather than precisely the missing subset, is simpler to reason about but multiplies load on a source that may still be recovering from the outage that caused this in the first place; a precise, diffed gap is worth the extra care.
- Reconciling only against your own row counts, with no independent total from the source, means a systematic error (every record shifted by the same wrong amount, for example) can pass a naive check that only confirms "the right number of rows landed."
- The prevention step is easy to skip once the immediate incident is resolved and the pressure is off; without it, this exact incident recurs at the next outage, just with a different specific set of missing records.
- A replay that bypasses the normal ingestion write path "because it is faster for this one-off fix" is the single most common way a well-intentioned incident response creates a second incident.
Design a batch ingestion pipeline that moves daily 100 GB file drops delivered to an SFTP endpoint into an S3-based data lake, and from there into a partitioned Parquet dataset. Cover transfer and verification, schema and checksum validation, making the commit atomic, your partitioning strategy, metadata-catalog updates, retry and backoff, and cost.
Sample Answer
Direct answer
The pipeline needs to treat the SFTP (SSH File Transfer Protocol) transfer, the validation, and the commit into the partitioned dataset as three distinct, separately-verifiable steps, because collapsing them (writing directly into the final partitioned location as bytes arrive) is exactly what turns a partial or corrupted transfer into bad data a downstream query can already see.
Structured elaboration
Transfer and verification
- Pull the file from SFTP into a staging location first, never directly into the final partitioned dataset, so a failed or partial transfer never becomes visible to a downstream reader.
- Verify the transfer completed correctly using a checksum: if the SFTP source can provide one (many partner feeds publish a companion checksum file), compare against it; otherwise compute your own checksum on the staged file and compare its size against what the source reports, at minimum.
Schema and checksum validation
- Validate the staged file's schema against what you expect before touching the partitioned dataset at all: column presence, types, and a row-count sanity check against recent history for this same daily drop.
- A checksum mismatch or a schema-validation failure halts the pipeline at this stage, before anything downstream is touched, rather than partially loading a suspect file.
Atomic commit
- Write the converted, partitioned Parquet output to a temporary path, then atomically move or rename it into the final partition location only once the write is fully complete and verified, so a reader never sees a partially-written partition.
- On object stores without a true atomic rename across prefixes, achieve the same effect by writing to a versioned or staged prefix and updating a pointer (a manifest or a catalog entry) only after the write finishes, rather than writing in place.
Partitioning strategy
- Partition by the file's own delivery date, since that is the natural, stable grain at which this daily file arrives, and keep the partition scheme simple and predictable so downstream consumers can reason about "yesterday's partition" without needing pipeline-internal knowledge.
Metadata-catalog updates
- Register the new partition with your catalog (Glue, Hive metastore, or equivalent) only after the atomic commit succeeds, so the catalog and the actual data on disk never disagree about what partitions exist.
Retry and backoff
- Retry a failed SFTP transfer with backoff, since transient network issues on a large 100 GB transfer are common; but do not retry a checksum or schema-validation failure blindly, since that is very likely a genuine problem with the source file that a retry will just reproduce identically.
Cost
- Compress and use a columnar format (Parquet) for the final dataset to reduce both storage cost and downstream query cost; keep the raw staged copy for a bounded retention window (long enough to support reprocessing after a bug fix) rather than indefinitely, since 100 GB/day of uncompressed staged copies adds up fast.
Worked example
A 100 GB file lands on the SFTP endpoint overnight. The transfer job pulls it into a staging bucket, verifying the transferred byte count and checksum against the source's own manifest; a mismatch (a partial transfer from a dropped connection) triggers an automatic retry of just the transfer, not the whole pipeline. Once verified, a validation pass checks the file's schema against the expected columns and confirms the row count falls within the normal range for this daily drop (catching, for example, a file that is unexpectedly only 10% of its usual size, a signal the partner's own export may have failed partway). The conversion job then writes partitioned Parquet output to a temporary prefix, and only after that write completes and is itself verified does a final atomic operation move it into the dated partition and register it with the metadata catalog, so a downstream query against "today's partition" either sees the complete, correct data or does not see the partition at all, never a partial one.
Trade-offs & pitfalls
- Writing directly into the final partitioned location "to save a copy step" is the single most common way this kind of pipeline produces a partial-partition incident; the staging-then-atomic-commit pattern costs extra storage and time but is what actually prevents that class of failure.
- Retrying a checksum failure automatically, without distinguishing it from a transient transfer failure, wastes time re-downloading a file that is going to fail the checksum identically every time if the source file itself is genuinely corrupted.
- Keeping the raw staged copy indefinitely "just in case" quietly becomes a real cost line at 100 GB/day; define and enforce a retention window deliberately rather than letting it default to forever.
- A catalog update that happens BEFORE the underlying data write is fully durable is a subtle but real bug: a reader could see a partition registered in the catalog moments before the actual files are consistently readable from the object store, depending on the store's consistency model.
Write a Python function that streams a newline-delimited JSON (NDJSON) file and writes out a CSV with columns id, timestamp, value. The function must not load the whole file into memory, must skip and log any invalid JSON line rather than crashing, and must preserve the original read order. Use only the standard library.
Sample Answer
Direct answer
The key is to iterate the input as a file object (or any line-yielding iterable), which reads and processes one line at a time rather than materializing the whole file, wrapping each line's JSON parse in a per-line try/except so one bad line is logged and skipped without stopping the run or losing the rows that come after it. Below is the complete function plus the fixture and driver used to verify it, so the worked example is something a reader can run, not just read.
Structured elaboration
import csv
import json
import sys
def ndjson_to_csv(infile, outfile, logfile=sys.stderr):
writer = csv.writer(outfile)
writer.writerow(["id", "timestamp", "value"])
n_ok = 0
n_skipped = 0
for lineno, line in enumerate(infile, start=1): # iterating a file object streams line-by-line
line = line.strip()
if not line:
continue
try:
rec = json.loads(line)
except json.JSONDecodeError as e:
print(f"line {lineno}: skipped, invalid JSON ({e})", file=logfile)
n_skipped += 1
continue
try:
row = [rec["id"], rec["timestamp"], rec["value"]]
except KeyError as e:
print(f"line {lineno}: skipped, missing field {e}", file=logfile)
n_skipped += 1
continue
writer.writerow(row)
n_ok += 1
return n_ok, n_skipped
for lineno, line in enumerate(infile, ...) is the memory-bounded part: a file object (or a generator, as the second test below confirms) yields one line at a time under Python's own iterator protocol, so the function never holds more than one line in memory regardless of the input's total size. Each line gets its OWN try/except for JSON parsing and its own check for the required fields, so a single malformed line is logged with its line number and reason and then skipped, while every well-formed line before and after it is still processed and written in its original order, since nothing about a skip disturbs the loop's forward progress. The implementation imports only csv, json, and sys, all standard library, exactly as asked.
Worked example
import io
lines = [
'{"id": 1, "timestamp": "2026-07-01T00:00:00Z", "value": 10}', # line 1: valid
'{"id": 2, "timestamp": "2026-07-01T00:01:00Z", "value": 20}', # line 2: valid
'', # line 3: blank
'not-json-at-all', # line 4: invalid JSON
'{"id": 3, "value": 30}', # line 5: valid JSON, missing timestamp
'{"id": 5, "timestamp": "2026-07-01T00:04:00Z", "value": 50}', # line 6: valid
'{"id": 6, "timestamp" "2026-07-01T00:05:00Z", "value": 60}', # line 7: malformed JSON
'{"id": 7, "timestamp": "2026-07-01T00:06:00Z", "value": 70}', # line 8: valid
]
ndjson_text = "\n".join(lines) + "\n"
print("--- Streaming NDJSON -> CSV over a mixed-validity input ---")
infile = io.StringIO(ndjson_text)
outfile = io.StringIO()
logfile = io.StringIO()
n_ok, n_skipped = ndjson_to_csv(infile, outfile, logfile=logfile)
print(f"lines converted: {n_ok}, lines skipped: {n_skipped}")
print("log output:")
print(logfile.getvalue().rstrip())
print("\nCSV output:")
print(outfile.getvalue().rstrip())
print("\n--- Memory-boundedness check: process a 200,000-line generator, never a list ---")
def gen_lines(n):
for i in range(n):
yield '{"id": %d, "timestamp": "2026-07-01T00:00:00Z", "value": %d}\n' % (i, i)
class FakeFile:
"""Wraps a generator so iterating it never requires the whole thing in memory."""
def __init__(self, gen):
self.gen = gen
def __iter__(self):
return self.gen
n = 200000
outfile2 = io.StringIO()
logfile2 = io.StringIO()
n_ok2, n_skipped2 = ndjson_to_csv(FakeFile(gen_lines(n)), outfile2, logfile=logfile2)
print(f"processed {n_ok2} generated lines via a plain generator (never a list); skipped {n_skipped2}")
Actual output from running the above:
--- Streaming NDJSON -> CSV over a mixed-validity input ---
lines converted: 4, lines skipped: 3
log output:
line 4: skipped, invalid JSON (Expecting value: line 1 column 1 (char 0))
line 5: skipped, missing field 'timestamp'
line 7: skipped, invalid JSON (Expecting ':' delimiter: line 1 column 24 (char 23))
CSV output:
id,timestamp,value
1,2026-07-01T00:00:00Z,10
2,2026-07-01T00:01:00Z,20
5,2026-07-01T00:04:00Z,50
7,2026-07-01T00:06:00Z,70
--- Memory-boundedness check: process a 200,000-line generator, never a list ---
processed 200000 generated lines via a plain generator (never a list); skipped 0
The 8-line fixture deliberately mixes a blank line (silently skipped, not logged, since a blank line is not an error), completely invalid JSON, valid JSON missing the required timestamp field, and malformed JSON (a missing colon), alongside four genuinely valid lines with ids 1, 2, 5, and 7. The output confirms all three distinct invalid cases are individually caught and logged with the correct reason and line number, the four valid rows appear in the CSV in their original order with none skipped or reordered, and the blank line produces neither an output row nor a log entry. The second run feeds the function a plain Python generator producing 200,000 lines on the fly, never a pre-built list, and confirms all 200,000 are processed correctly, which is the concrete proof that "does not load the whole file into memory" actually holds and is not just true by accident on a small test fixture.
Trade-offs & pitfalls
- The blank-line handling (
if not line: continue) has to come before the JSON parse attempt, not after; parsing an empty string as JSON raises the sameJSONDecodeErrora genuinely malformed line does, which would misleadingly count trailing blank lines as "invalid JSON" in the skip log rather than silently ignoring them as intended. - Catching
KeyErrorfor missing required fields is deliberately a SEPARATE except block from the JSON-parse except block; collapsing them into one broadexcept Exceptionwould still work but would make the log message less useful for debugging, since "invalid JSON" and "valid JSON, wrong shape" are different problems with different fixes on the source side. csv.writeronoutfilestill buffers its own output somewhat depending on the underlying file object's buffering, and a genuinely huge output file may want an explicit periodic flush; this was not needed for correctness in the test above but is worth naming for a production version writing to a slow destination.- This implementation assumes one JSON object per line, the NDJSON convention; a file with pretty-printed, multi-line JSON objects (each individual record spanning several lines) would need a different, stateful parsing approach entirely, since a single line would no longer be a complete parseable unit.
Unlock Full Question Bank
Get access to all 26 Data Ingestion and Source System Integration interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.