Engineering notes

Safe CSV Imports: Preview, Validate and Correct Before Commit

Design bulk imports with explicit field mapping, row-level errors, duplicate rules and a clear boundary between staging and live data.

Bitcave5 min readUpdated

A spreadsheet import can change thousands of records faster than a person can inspect them. In a hypothetical supplier catalogue workflow, the important feature is not the upload button: it is the ability to understand the proposed changes, correct mistakes and explain what was committed. Treat import as a controlled business transaction.

Define the format and mapping contract

Specify encoding, delimiter, header names, required fields and accepted date and decimal formats. Use a proper CSV parser that handles quoted delimiters and embedded line breaks; splitting each line on commas is not a reliable parser. RFC 4180 documents common conventions, while real files still require an explicit supported-format policy.

Preserve identifiers as text where leading zeros matter. Show sample rows and let the user confirm column mapping. Record the mapping version and original file reference so a repeated import can be investigated. File size and row limits should match the processing budget.

Spreadsheet rows moving through a staging checkpoint into accepted and correction trays

Generated editorial illustration; not a record of a live system.

Stage data before changing live records

Parse and validate into an import session with an owner and lifecycle states. Check types, required fields, allowed values, foreign references and tenant permissions. Show proposed creates, updates and rejected rows separately before the commit action.

Distinguish a blank value from a request to clear an existing value. Define what happens to records absent from the file; absence should not silently mean deletion. Cross-row rules, such as duplicate supplier codes within the same file, need validation in addition to checking each row independently.

Choose atomic or partial commit deliberately

Some workflows require every row to succeed together. Others permit valid rows to commit while invalid rows wait for correction. Make that choice visible and keep the resulting counts reconcilable. For large files, use bounded batches with durable progress and a consistent session-level outcome.

Define a stable identity for each intended change so retries do not create duplicates. Check whether destination records changed after preview and surface conflicts rather than overwriting newer work. A transaction protects local database changes; external effects need their own deferred, duplicate-safe handoff.

Make error correction usable and safe

Report row reference, field, rejected value where appropriate and a clear reason. Let users download or inspect only the error subset and preserve the relationship to the original import. Avoid an unstructured wall of stack traces.

When exporting correction files for spreadsheet applications, account for formula interpretation and other output hazards. Do not expose confidential rows to users who lack access. Corrections should be validated through the same rules as the original file, with an audit record of who resubmitted them.

Test replay and reversal before rollout

Test quoted fields, unusual encodings, missing columns, duplicate rows, ambiguous dates, leading zeros and an interrupted batch. Replay the same session and confirm no repeated effect. Change a destination record between preview and commit and verify the conflict path.

If reversal is offered, define its limits when later edits or external actions depend on imported data. Keep committed before/after references where needed, subject to retention rules. Acceptance means users can reconcile accepted, rejected and unresolved rows and explain the live changes; a successful upload response is only the beginning.

Worked example and implementation boundary

A fictional supplier CSV includes code 0012, a quoted name containing a comma, and an ambiguous date 03/04/2026. The parser preserves the code as text and the quoted name as one value. Validation rejects the date until the import contract specifies its interpretation. Preview shows the accepted and rejected rows without changing live data. If a destination record changes before commit, the import raises a conflict rather than overwriting the newer edit. Correcting the rejected subset retains the original session reference.

The file contract here is UTF-8 CSV with exactly two ordered headers and positive integer quantities. Record numbers are logical CSV records, not physical lines. Catch decoding and csv.Error failures in the upload flow. This preview does not authorize a tenant, detect business duplicates, resolve product identifiers or commit changes; those checks belong to the staged server-side workflow. Escape formula-like cells separately when producing spreadsheet exports.

# Python 3: bounded preview only; no database writes.
import csv
import io
import re

def preview_csv(payload: bytes):
    if len(payload) > 2_000_000:
        raise ValueError("File exceeds preview limit")
    text = payload.decode("utf-8-sig", errors="strict")
    reader = csv.DictReader(io.StringIO(text, newline=""), strict=True)
    if reader.fieldnames != ["sku", "quantity"]:
        raise ValueError("Expected unique headers: sku,quantity")
    accepted, errors = [], []
    for index, row in enumerate(reader, start=1):
        if index > 10_000:
            raise ValueError("Too many records")
        sku = (row.get("sku") or "").strip()
        quantity = row.get("quantity") or ""
        if None in row or not sku or len(sku) > 80:
            errors.append((index, "Invalid record shape or SKU"))
        elif not re.fullmatch(r"[1-9][0-9]{0,5}", quantity):
            errors.append((index, "Quantity must be a positive integer"))
        else:
            accepted.append({"record": index, "sku": sku,
                             "quantity": int(quantity)})
    return {"accepted": accepted, "errors": errors}

Trade-offs and limitations

All-or-nothing commit makes a small import easier to reason about but may be unsuitable for a large independent catalogue. Partial commit improves throughput only if users can reconcile accepted, rejected and pending rows and safely replay the remainder.

Common pitfalls

Do not split CSV on commas, infer destructive deletion from an absent row, or lose leading zeros by numeric conversion. An exported correction file must account for spreadsheet formula interpretation and the recipient's data permissions.

Key takeaways

Separate parse, validate, preview and commit. Version the mapping and protect changes between preview and commit. Keep replay identity and a usable error subset so an interrupted import can be explained and corrected.

References and further reading

RFC 4180 — Common Format and MIME Type for CSV Files

Related reading and implementation support

Systems Integration and Workflow Automation

Business API Integration: Design for Failure and Recovery

Related content

Systems Integration and Business Workflow Automation

Connect your applications and automate repeatable processes with clear rules, visible status and a defined way to handle exceptions.

Business API Integration: Design for Failure and Recovery

Connect sales, accounting and operations with clear ownership, bounded retries and a recovery workflow your team can actually use.

Define the implementation boundary

Discuss safe CSV import in the context of your current systems, decision owners and exception paths, then define a bounded first step.

Discuss your project