Quick Answers
How do you resume a failed CSV import safely?
Keep a persistent import job, identify the original file, and save a checkpoint alongside each committed record or batch. On restart, use the same job and file, skip completed records, and enforce a database uniqueness rule on the business records.
Is saving the last imported row number enough?
No. If the data write and checkpoint update happen separately, a crash can leave them out of sync. Save both in the same database transaction, and verify that the file has not changed before using the checkpoint.
What prevents duplicate records when the same file is uploaded again?
A stable business identifier enforced by a database unique constraint. An import job ID identifies a processing attempt; a customer ID or order ID identifies the actual record. You need to distinguish the two.
Should every failed CSV row be retried automatically?
No. Temporary failures may succeed on retry. Missing values, malformed CSV and conflicting records need correction or review. Repeatedly retrying unchanged invalid data will not fix it.
The Import Failed. What Actually Reached the Database?
Imagine importing a CSV containing 10,000 customers. The worker stops after processing part of the file.
The dashboard says “Import failed.” It does not tell you whether the final customer was saved before the process stopped.
You restart the import from the beginning. If the application creates a new database ID for every row without checking the source customer ID, previously imported customers may appear again.
Starting from a remembered row number is not necessarily safer. That number might have been saved before the corresponding customer record was committed.
This is an illustrative scenario, but it exposes the central problem:
A resumable import must keep the saved data and its progress record consistent.
The solution needs more than a retry button.
Use Three Separate Identities
A reliable CSV import distinguishes the job, the file and the business record.
| Identity | Example | Purpose |
| Import job ID | customer-import-001 | Identifies the job being resumed |
| File fingerprint | SHA-256 of the uploaded bytes | Detects whether the input has changed |
| Business record ID | CUST-1042 | Identifies the customer across rows and uploads |
These identities solve different problems.
The job ID lets the worker retrieve its progress. The fingerprint prevents that progress from being applied to a different file. The business ID prevents a new upload from creating another copy of an existing customer.
A file fingerprint alone cannot recognise the same customer in two different exports. A row number cannot do that either.
For a multi-tenant application, the uniqueness rule may need to include the tenant and source system:
UNIQUE (tenant_id, source_system, external_customer_id)
Choose that identity from your business rules. Names are usually unsuitable, and email addresses should not automatically be treated as permanent customer identifiers.
Commit the Record and Checkpoint Together
Consider these two unsafe sequences.
Sequence A:
- Insert the customer.
- Commit the insertion.
- Save the checkpoint.
If the process stops between steps two and three, the customer exists but the checkpoint still points to the previous record.
Sequence B:
- Save the checkpoint.
- Insert the customer.
- Commit the insertion.
If the process stops after step one, a retry may skip a customer that was never saved.
Instead, use one transaction:
BEGIN;
-- Insert the business record, or verify an existing matching record.
-- Update the import checkpoint.
COMMIT;
SQLite’s atomic-commit behaviour means the changes within that transaction commit together or do not commit. The database write and checkpoint must be in the same transactional database for this approach.
This does not make external actions, such as sending an email, part of the transaction. We will return to that limitation later.
Decide What a Duplicate Means Before Writing Code
Two rows with the same identifier are not always interchangeable.
Suppose the database contains:
Customer ID: CUST-1042
Name: Ada
Email: ada@example.com
A retry containing the same values can be treated as already applied.
A row with the same ID but a different email needs a policy. Should the importer update it, reject it, or send it for review?
For the example below, the rules are deliberately conservative:
| Situation | Behaviour |
| New customer ID | Insert the customer |
| Existing ID with identical values | Accept as already present |
| Existing ID with different values | Stop and report a conflict |
| Missing required value | Stop at that record |
| Changed file under the same job ID | Reject the resume attempt |
This makes the sample suitable for an insert-only customer import. It is not a customer-update synchronisation tool.
Avoid using a broad “ignore errors” instruction as a substitute for these rules. SQLite’s INSERT OR IGNORE, for example, can suppress certain constraint failures beyond the duplicate you intended to handle.
A Working Python Example With SQLite
The following example uses Python’s standard-library CSV parser and SQLite.
It reads a small CSV into memory so that the bytes being hashed are exactly the bytes being parsed. It then processes records sequentially, saving one record and its checkpoint per transaction.
Scope: One organisation, one customer-ID namespace, a local database and a single-worker workflow. Large-file processing and distributed workers need additional design.
Create customers.csv:
customer_id,name,email
C1,Ada,ada@example.com
C2,Lin,lin@example.com
C3,Sam,sam@example.com
Save this code as resume_csv.py:
import csvimport hashlibimport ioimport sqlite3from contextlib import closing, contextmanagerfrom pathlib
import Path@contextmanagerdef transaction(db): db.execute("BEGIN IMMEDIATE") try: yield db.execute("COMMIT") except BaseException: if db.in_transaction: db.execute("ROLLBACK") raisedef import_customers(csv_path, db_path, job_id, after_write=None): # Small-file demo: hash and parse the same in-memory snapshot. raw = Path(csv_path).read_bytes() fingerprint = hashlib.sha256(b"customers-v1\0" + raw).hexdigest() reader = csv.reader( io.StringIO(raw.decode("utf-8-sig"), newline=""), strict=True, ) if next(reader, None) != ["customer_id", "name", "email"]:
Run the import:
python -c "from resume_csv import import_customers; print(import_customers('customers.csv', 'customers.db', 'customer-import-001'))"
For the example CSV, the function returns:
3
Run the same command again. It returns 3, while the database still contains three customers.
The return value describes the number of CSV data records reached. It is not an insertion count: an identical duplicate row can be processed without inserting another customer.
Why the Example Can Resume Safely
The importer checks the file fingerprint before using the saved checkpoint.
Each pending record is handled inside an explicit transaction. The customer insertion and checkpoint update are committed together. If the transaction fails, the checkpoint does not advance past that record.
The customer primary key provides a separate protection across jobs. Uploading identical customer data under a new job ID does not create another copy.
The customers-v1 prefix also binds the job to an importer version. If parsing or mapping rules change, change that version and handle old jobs deliberately.
The sample only checks the header, field count and non-empty values. Add your application’s actual validation rules, including length limits and permitted formats, before using it with production data.
Count CSV Records, Not Physical Lines
A CSV field can contain a quoted line break:
customer_id,name,email
C1,"Ada
Lovelace",ada@example.com
C2,Lin,lin@example.com
That file contains two customer records, even though it occupies more than two physical data lines.
The example uses csv.reader and counts the records it yields. It does not split the file on newline characters.
Python’s CSV documentation also specifies newline=”” when working with file objects. This lets the parser handle CSV newline conventions correctly.
On resume, this implementation parses the file from the beginning and skips committed records. It avoids repeating database changes, but it does not avoid rereading earlier CSV content.
Test the Failure Between the Write and Checkpoint
A successful second run is useful, but the more important test interrupts the first run at the dangerous point.
The after_write argument exists only to inject that failure.
Save this as check_resume.py beside resume_csv.py:
import sqlite3import tempfilefrom pathlib import Pathfrom resume_csv import import_customersdef fail_on_second_record(row_no): if row_no == 2: raise RuntimeError("Simulated worker failure")with tempfile.TemporaryDirectory() as directory: source = Path(directory) / "customers.csv" database = Path(directory) / "customers.db" source.write_text( "customer_id,name,email\n" "C1,Ada,ada@example.com\n" "C2,Lin,lin@example.com\n" "C3,Sam,sam@example.com\n", encoding="utf-8", ) try: import_customers( source, database, "job-1", after_write=fail_on_second_record, )
Run it with:
python check_resume.py
The second record’s insertion rolls back with the injected failure. The next attempt resumes from the first uncommitted record.
Verification Performed for This Example
The importer passed 10 automated tests using an on-disk SQLite database, running on Python 3.12.14 and SQLite 3.53.1.
| Test | Observed result |
| Run the same completed job again | Customer count stayed unchanged |
| Import identical customers under a new job ID | No duplicate customers |
| Raise an exception after insertion but before checkpoint update | Current record and progress rolled back |
| Exit a separate worker process at that same point using os._exit | Restart recovered and completed the import |
| Change the file while retaining the job ID | Resume rejected |
| Repeat a customer ID with different values | Import stopped with a conflict |
| Parse a quoted multiline field | Checkpoint counted logical records |
| Encounter a missing required value | Checkpoint stayed at the preceding record |
| Repeat an identical customer inside the file | One customer stored; both records accounted for |
| Encounter an unterminated quoted CSV field | Parser error stopped processing |
These checks establish behaviour for the demonstrated workflow. They are not a throughput benchmark, a power-loss test or a distributed-worker test.
Retry Temporary Failures and Correct Data Errors Differently
A failed worker does not always mean a failed row.
For a temporary operational failure, investigate the cause and rerun the unchanged file with the same job ID. Examples include a worker restart or a temporary database-lock problem.
For invalid source data, correct the input and create a new job ID. This example intentionally rejects changed bytes under an existing job.
Previously inserted customers with identical values will be recognised during the new job. If the corrected file changes an already stored customer, the insert-only policy reports a conflict. Handle that through an explicit update or reconciliation workflow.
Do not delete the fingerprint check to make a corrected file “resume.” Inserting, removing or reordering rows changes the meaning of the old checkpoint.
What If Valid Rows Should Continue After an Error?
The sample stops at the first invalid record. That keeps a single checkpoint easy to interpret.
If your product must continue past rejected rows, use a persistent row-outcome ledger. Record the source row identity, outcome and error reason, then give rejected rows a separate correction workflow.
A progress counter alone is no longer enough. It must be possible to distinguish:
- Successfully applied records.
- Identical records already present.
- Explicitly rejected records.
- Records not yet attempted.
Store the accepted write or rejection outcome together with the corresponding progress update. A rejected record must remain visible in the final import report.
What Changes for Large Files and Production Workloads?
The transaction pattern remains useful, but this small-file implementation needs adaptation.
| Requirement | Production consideration |
| Large uploads | Store an immutable file version and stream it; avoid reading the entire upload into memory |
| Faster processing | Commit bounded batches with their checkpoints, then measure throughput and recovery behaviour |
| Efficient restarts | Consider staging parsed records or creating verified record-boundary checkpoints |
| Multiple workers | Use explicit job ownership or partitioned work with separate progress tracking |
| Multiple tenants | Scope jobs, file access and business uniqueness to the authorised tenant |
| Operational visibility | Persist job status, counts, failure reasons and retry history |
| Data protection | Limit upload access, avoid sensitive payloads in logs and define retention |
| Changed import rules | Version schemas and mapping logic; provide a deliberate migration or restart policy |
A single “highest completed row” is unsafe for parallel processing when lower rows may still be unfinished. Use per-record or per-partition state, or track the highest contiguous completed position.
SQLite allows one write transaction at a time. Its locking behaviour is part of why the sequential example is straightforward; moving the code to another database requires reviewing that database’s isolation and concurrency behaviour.
Preventing recurring import failures can also reduce support and repair work. For the wider operational picture, see our guide to reducing software maintenance costs.
Keep External Side Effects Out of the Database Guarantee
Suppose the import also sends a welcome email.
If the email is sent before the database commits, a rollback can leave the email delivered while the customer record remains uncommitted. A retry may send it again.
If it is sent after the commit, a process failure can leave the customer saved but the email unsent.
The database transaction does not resolve that gap.
For external actions, use a separate delivery workflow with persistent state. Where appropriate, write an outbox entry in the same transaction as the customer, then have a worker deliver it with retry and duplicate-handling rules.
An outbox still needs a strategy for ambiguous delivery and repeated attempts. Do not describe the complete import-and-notification workflow as “exactly once.”
Frequently Asked Questions
What if my CSV does not contain a unique ID?
Define a trustworthy business key before importing. You may need a source-system identifier or an agreed combination of fields.
Generating a fresh UUID for every row does not identify records that were imported previously. Likewise, hashing the whole row detects identical content, but changed content for the same customer produces a different hash.
Can I use an upsert to update existing customers?
Yes, if updating existing records is the intended behaviour. Specify which fields may change, which source is authoritative, and how older data is prevented from overwriting newer values.
Be especially careful with updates that increment counters or trigger other work. Repeating an operation must not accidentally apply its business effect again.
What if the process stops immediately after a successful commit?
Both the customer and checkpoint are already committed. Restarting the same job reads that checkpoint and skips the completed record.
The application may not have printed a success message, but the database state remains the source of truth.
Does this importer undo earlier rows when a later row fails?
No. Earlier transactions stay committed. Only the active record transaction rolls back.
If the entire file must succeed or fail as one unit, use an all-or-nothing design, potentially with a staging table and a final validation-and-apply step. That is a different requirement from progressively committing resumable work.
Does a completed checkpoint prove that every customer still exists?
No. A checkpoint records what the importer committed at the time. It does not repair later deletions or edits by other processes.
Keep job history and business data consistent, and use a reconciliation process when you need to verify their current state.
Build Recovery Into the Import Process
A reliable CSV import has an explicit answer to three questions: which file is being processed, which records are already committed, and what should happen when a business identifier appears again.
With those decisions in place, a failure becomes a recoverable job state rather than a manual cleanup exercise.
UGS Technology’s custom software development services can help build import workflows with validation, progress tracking and recovery suited to your application.
References
- Python documentation: CSV File Reading and Writing CSV parsing, quoted fields and newline handling. Python 3.15.2 documentation
- Python documentation: sqlite3 Database connections, parameter binding and transaction control. Python 3.15.2 documentation
- SQLite: Transactions Explicit transactions and SQLite’s single-writer behaviour. sqlite.org
- SQLite: Atomic Commit How transaction changes commit together and how interrupted transactions are recovered. sqlite.org
- SQLite: The ON CONFLICT Clause and UPSERT Conflict-handling behaviour and targeted uniqueness handling. sqlite.org