🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Data Management / Database Administration › ETL Pipelines: Extract, Transform, and Load for Database Administration › Lesson 5
TEC-DATA86-06 · Lesson 5 · 11 clock hours · practice

Error Handling, Logging, and Pipeline Restart

Objective. Students will add structured error handling and a checkpoint restart mechanism to an existing ETL script so that a simulated mid-run failure can be diagnosed and the pipeline restarted without data duplication or loss.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

Why Error Handling Matters in ETL Pipelines

An ETL pipeline moves data through three stages: Extract (read from a source), Transform (clean and reshape), and Load (write to the target database). Any of these stages can fail—a network drop, a malformed row, a lost database connection. Without deliberate error handling, a failure mid-run can leave the target table in a partial state: some rows written, others missing, and no record of where things went wrong. Recovering from that situation manually is time-consuming and error-prone.

Structured error handling, combined with logging and a checkpoint restart mechanism, solves this problem. You know exactly what happened, where the pipeline stopped, and how to resume without writing duplicates or losing rows.

The Python logging Module

Python's built-in `logging` module lets you record pipeline events at named severity levels. The two levels you will use most in ETL work are:

Configure a `FileHandler` that writes to a dated log file (for example, `pipeline_2024-11-15.log`). Set the format to include the timestamp, level, and message. Log row counts after every stage so that when something fails you can see exactly how far the pipeline progressed before the error.

Key practice: always log the start time at the very beginning and the end time only when all stages complete successfully. That gap in the log tells you immediately whether a run finished or not.

try/except Around the Load Stage

The load stage is the most critical to protect because it writes to the database. Wrap the load logic in a `try/except` block that catches `psycopg2.DatabaseError`. This is the base exception class for database-level errors in the psycopg2 adapter, covering connection failures, constraint violations, and server errors.

When the except block fires:

1. Call `connection.rollback()` immediately to undo any partial writes in the current transaction. This is your first data-safety action—never skip it.

2. Log the full exception message at ERROR level.

3. Write a checkpoint file containing the ID of the last batch that was fully committed before the failure. A simple JSON file works well: `{"last_committed_batch": 4, "timestamp": "2024-11-15T14:32:07"}`.

4. Exit the script with a non-zero return code (for example, `sys.exit(1)`). A non-zero exit code signals to any scheduler or calling process that the run failed.

Using database transactions correctly is also a safety concern for data integrity. Think of a transaction as an all-or-nothing unit: either every row in the batch is committed, or none of them are. Rolling back on error keeps the database in the last known good state.

Checkpoint Restart Logic

A checkpoint file stores the progress marker so the pipeline can resume rather than restart from scratch. At pipeline startup, add logic that checks whether a checkpoint file exists:

After a successful run completes, delete or archive the checkpoint file so that the next scheduled run starts fresh.

This approach is called idempotent restart: running the pipeline again after a failure produces the same final result as a clean run, with no duplicates and no missing rows.

Preventing Duplicate Rows

Checkpoint restart alone does not guarantee no duplicates unless you also design the load stage correctly. Two common strategies:

During the hands-on activities you will confirm the final row count with a `SELECT COUNT(*)` query and check for duplicates with a `GROUP BY` on the primary key, looking for any count greater than one.

Physical and Environmental Safety

Although database work is office-based, standard lab safety applies:

Connecting to Industry Credentials

Error handling and logging are tested across all four credentials this program prepares you for. Oracle DBA CA and Microsoft DP-300 both address transaction management and recovery strategies. The DAMA CDMP Associate exam covers data quality and pipeline governance, which includes audit logging. EDB PostgreSQL CE tests transaction control and error handling in PostgreSQL specifically. Building these skills now prepares you for both the exams and real production work.

Key terms8

Structured loggingRecording pipeline events with a consistent format that includes timestamp, severity level, and message, enabling automated parsing and troubleshooting.
psycopg2.DatabaseErrorThe base exception class in the psycopg2 PostgreSQL adapter that represents errors returned by the database server or connection failures.
Transaction rollbackUndoing all database changes made within the current transaction so the database returns to its last committed state, used after a caught error.
Checkpoint fileA small file written by the pipeline when it fails, recording the last successfully committed batch ID so a restart can resume from that point.
Idempotent restartThe property of a pipeline whereby re-running it after a failure produces the same correct final result, with no duplicate or missing rows.
Non-zero exit codeA return code other than zero returned by a script to its calling process or scheduler, signaling that the script did not complete successfully.
UpsertA database operation that inserts a new row if no matching key exists, or updates the existing row if it does; in PostgreSQL written as INSERT … ON CONFLICT DO UPDATE.
Batch IDA numeric or string identifier assigned to each group of rows processed together in a single load operation, used by the checkpoint mechanism to track progress.
In class: Instrument an existing ETL script with Python's logging module at INFO and ERROR levels: log pipeline start time, row counts after each stage, any row-level rejection, and pipeline end time to a dated log file. · Add a try/except block around the load stage that catches psycopg2.DatabaseError, rolls back the transaction, writes the error message and last successfully processed batch ID to a checkpoint file, and exits with a non-zero return code. · Simulate a failure by having the instructor kill the database connection mid-load; then modify the pipeline startup logic to read the checkpoint file and resume from the last committed batch; run the full pipeline again and confirm final row count is correct with no duplicates.
Materials: Student laptops, Python 3 logging module, psycopg2, PostgreSQL 15, instructor-prepared base ETL script (intentionally missing error handling), checkpoint file template, pipeline run log template
Check: Demonstration to instructor: student triggers the simulated failure, shows the checkpoint file contents, restarts the pipeline, and queries the database to prove correct final row count and no duplicates; pass = correct final count with no duplicates confirmed by instructor query

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

ETL pipeline operations and database administration practices
1. In Python's logging module, which level should you use to record that the pipeline successfully processed 500 rows after the transform stage?
Transaction management and error recovery
2. A psycopg2.DatabaseError is caught during the load stage. What is the FIRST action the except block should take to protect data integrity?
ETL checkpoint and restart mechanisms
3. A pipeline processes data in batches numbered 1 through 10. It fails partway through batch 7. The checkpoint file records last_committed_batch = 6. When the pipeline restarts, which batch should it begin loading?
Data quality and SQL query techniques
4. After restarting a pipeline from a checkpoint, a developer wants to verify there are no duplicate rows in the target table on a column called customer_id. Which SQL approach best identifies duplicates?
PostgreSQL SQL syntax and data loading
5. Which PostgreSQL syntax prevents duplicate rows when loading data that may already exist in the target table?
Pipeline operations and automation
6. A pipeline script exits with return code 0 after completing. A scheduler is configured to retry failed jobs. What will happen?
ETL pipeline design and data integrity
7. Which statement BEST describes why a checkpoint file should be deleted or archived after a pipeline run completes successfully?
DAMA CDMP data governance and data quality
8. The DAMA CDMP Associate exam body of knowledge considers pipeline audit logging primarily relevant to which data management knowledge area?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.