Your CSV Import Failed Halfway. Can You Run It Again Safely?
The import ran for an hour. Then the connection dropped.
The destination contains some of the records, the script has no trustworthy completion marker, and someone asks whether it is safe to restart. That question exposes a design decision that should have been made before the first row was written.
Streaming and batching help move data efficiently. Recovery needs another property: a defined outcome when the same input is processed again. Before tuning an import for throughput, make its retry behavior explicit.
1. Define what a repeated record means
Consider an illustrative order export with source_order_id, customer_id, amount, and updated_at. What should happen if tomorrow’s file contains an order that was imported today?
- Ignore it: appropriate only when an existing record is already authoritative.
- Update it: useful for snapshots, with a rule for deciding which version wins.
- Reject it: appropriate when duplicates indicate an upstream contract violation.
These choices affect correctness. An “upsert” does not decide which one the business needs. If an older file arrives after a newer file, blindly updating every matching order could replace current values with stale ones.
Write down the identity key and version rule first. If two source systems can issue the same order number, identity may need to include both the source system and its order ID.
2. Treat CSV as a data contract
A file extension does not establish an encoding, delimiter, timestamp format, or interpretation of an empty field. Define those inputs alongside the required columns and duplicate policy.
Python’s CSV documentation recommends opening CSV file objects with newline=''. Use a CSV parser rather than splitting text on commas: quoted values can contain delimiters and line breaks.
import csv
with open("orders.csv", encoding="utf-8", newline="") as stream:
reader = csv.DictReader(stream)
required = {"source_order_id", "customer_id", "amount", "updated_at"}
if not required.issubset(reader.fieldnames or []):
raise ValueError("Missing required columns")
for record_number, row in enumerate(reader, start=1):
validate_and_stage(record_number, row)
Here, validate_and_stage is an application function you must implement. Header checks are only the beginning: validate required values, types, ranges, and timestamp conventions before accepting a record. Keep financial values out of binary floating-point conversions when exact decimal arithmetic is required.
Notice the name record_number. With multiline fields, a record counter is not a physical line number. Record useful parser diagnostics separately so someone can locate the original problem.
3. Give the input and each attempt separate identities
Use an import-run ID for operational tracking, and identify the input independently. Otherwise, the same file renamed and uploaded twice can look like two unrelated datasets.
A file checksum can help identify identical bytes. Python’s hashlib module provides SHA-256 and incremental hashing, so a digest can be calculated in chunks without reading the entire file into memory.
Pair that digest with the source identity and importer version. A digest identifies bytes, not business meaning: two differently formatted exports can describe the same orders. It also does not prove that a file came from a trusted sender.
Keep the source immutable while hashing and importing. Working from a controlled copy or an immutable object avoids identifying one version of a file and then reading another.
4. Load into staging before changing business tables
A staging table gives an import somewhere to be inspected before it affects the application’s authoritative records. Include the run ID, source record number, business key, parsed values, and validation status.
For large PostgreSQL loads, COPY can be useful for moving data into staging. Its role is loading data; your validation and merge rules still need to be defined. In particular, COPY FROM appends rows to the target table, so rerunning it needs an explicit staging cleanup or run-isolation policy.
Keep rejected records separate, with a reason that an operator can act on. Decide whether any rejection should block the whole import or whether a documented partial result is acceptable. A log line saying “skipped bad row” is not enough to establish which business data was excluded.
5. Enforce identity in the database
A Python check that asks whether a record already exists can race with another worker making the same check. Put the agreed identity rule in a unique constraint as well.
PostgreSQL’s INSERT documentation describes ON CONFLICT, which can apply an explicit alternative when an insert conflicts with a suitable uniqueness constraint. For immutable order records, the policy might look like this:
INSERT INTO orders (source_system, source_order_id, amount)
SELECT source_system, source_order_id, amount
FROM validated_orders_stage
WHERE import_run_id = :run_id
ON CONFLICT (source_system, source_order_id) DO NOTHING;
The example assumes a corresponding unique constraint; :run_id represents a bound parameter whose syntax depends on your database client. “Do nothing” is deliberate here. A mutable snapshot needs a different policy, including how to handle newer versions and ties.
Make staging keys non-null and resolve duplicates within the input before merging. Do not let file order accidentally decide which conflicting version survives.
6. Commit progress with the data it describes
The dangerous sequence is to save a checkpoint and then fail before committing the corresponding records. A restart can skip data that never reached the destination.
When the destination and progress table share a database, update them in the same database transaction:
BEGIN
apply the validated batch
record the batch checkpoint
COMMIT
After a crash, either both changes are committed or neither is. The checkpoint should identify the immutable input and importer version, not merely say “row 50,000.”
Database transactions do not automatically cover external effects. If processing an order also sends an email or calls another service, replaying a batch needs a separate delivery and deduplication design. Do not describe a database upsert as an end-to-end “exactly once” guarantee.
7. Reconcile the result and rehearse failure
Publish a run summary with parsed, accepted, rejected, inserted, updated, and unchanged counts. Define which counts overlap. For a record-level classification, parsed records should equal accepted plus rejected records; blank-record handling should also be documented.
Compare key sets and business totals where appropriate. Equal row counts alone cannot reveal that the wrong orders were loaded. For updates, the destination table’s net growth will not equal the number of accepted input records.
Before relying on the importer, test a repeated file, a renamed copy, conflicting duplicates, a malformed field, and an older snapshot arriving late. Terminate a test run between batches and restart it. Verify the business result, not just the process exit code.
A dependable import has an answer to three questions: what was accepted, what changed, and what happens if we run it again. Once those answers are measurable, performance tuning has a much firmer foundation.
Need help with a data import or migration? Contact Comquest to review the data contract, failure modes, and verification plan.