🎬No video for this question yet. The written answer is below.
How do you handle large datasets efficiently in Python (generators, chunking)?- Difference between multithreading and multiprocessing in Python?
- How do you implement error handling and logging in data pipelines?
- Explain decorators with a real-time use case.
- How do you optimize Python code performance in ETL jobs?
📝 Answer
Python ETL Interview Answers
Simple English · Clear explanation · 3-minute speaking format
1
Handling Large Datasets — Generators & Chunking
Core Idea
- Never load the entire dataset into memory at once — it can crash the system
- Process data in small pieces — generators or chunks
- Memory usage stays low, system stays stable
Technique 1 — Generators (One Record at a Time)
1# Generator — reads one line at a time, no full load into memory2def read_large_file(file_path):3 with open(file_path) as f:4 for line in f:5 yield line # yield → does NOT load full file67# Usage8for record in read_large_file("data.csv"):9 process(record)
Reading a 10GB log file from S3 line-by-line before inserting into Redshift
Technique 2 — Chunking (Batch at a Time)
1import pandas as pd23# Read 10,000 rows at a time — not the full file4for chunk in pd.read_csv("large_file.csv", chunksize=10000):5 process(chunk) # transform this batch6 load_to_db(chunk) # load batch into DB
ETL job: S3 CSV → transform in batches → load into RDS or Redshift
How to Say It in Interview
🎤 Speak This
When I work with large datasets in Python, my main focus is to avoid loading everything into memory at once. If I load a very large file directly, it can crash the system or slow down performance.So instead, I use two techniques. First, generators — they allow me to process data one record at a time instead of loading the full dataset. Memory usage stays very low.
Second, chunking — instead of processing the full dataset, I split it into smaller batches. For example, I read 10,000 records at a time, process them, then move to the next batch.
In real projects like ETL pipelines, I use these techniques when reading data from S3 or large files. This keeps the system stable and efficient.
So overall, the idea is simple — process data in small pieces instead of all at once.
2
Multithreading vs Multiprocessing in Python
Side-by-Side
🧵 Multithreading
- Best for I/O bound tasks
- API calls, file reading, DB queries
- Thread shares same memory
- Limited by Python GIL
- Not true parallel for CPU work
⚙️ Multiprocessing
- Best for CPU bound tasks
- Heavy transformations, JSON parsing
- Each process has own memory
- Not affected by GIL
- True parallel — uses multiple cores
Multithreading — Code Example
1from threading import Thread23def call_api(endpoint):4 # makes API call — waits for response (I/O)5 pass67# Run multiple API calls in parallel8t = Thread(target=call_api, args=("https://api.example.com",))9t.start()
Calling Melissa API, Elasticsearch, or multiple REST endpoints in parallel
Multiprocessing — Code Example
1from multiprocessing import Pool23def transform_record(record):4 # heavy CPU transformation logic5 return record["value"] * 267# Use 4 CPU cores in parallel8with Pool(processes=4) as pool:9 results = pool.map(transform_record, records)
Heavy data transformation, large JSON parsing in ETL pipelines
How to Say It in Interview
🎤 Speak This
Both multithreading and multiprocessing are used to improve performance, but in different situations.Multithreading is mainly used for I/O tasks like API calls, file reading, or database calls. The program spends time waiting, so threads can run in parallel and improve performance. But in Python, because of the GIL, multithreading cannot fully use the CPU for heavy computations.
For CPU-heavy tasks, we use multiprocessing. Each process runs independently and uses multiple CPU cores. This gives true parallel execution.
In real ETL projects — I use multithreading when calling APIs or reading files. I use multiprocessing when doing heavy transformations. So choosing the right approach depends on the type of work.
🔥 GIL Explained Simply
GIL (Global Interpreter Lock) is a Python mechanism that allows only one thread to execute Python code at a time. So for CPU tasks, threads don't help — use multiprocessing or concurrent.futures.ProcessPoolExecutor instead.
3
Error Handling & Logging in Data Pipelines
Error Handling — try / except
1try:2 process_data(record)34except Exception as e:5 logger.error(f"Failed to process record: {str(e)}")6 send_to_dlq(record) # push failed record to Dead Letter Queue7 raise # re-raise if needed
Logging Setup — Best Practice
1import logging23# Always use logging — not print()4logging.basicConfig(level=logging.INFO)5logger = logging.getLogger(__name__)67logger.info("Pipeline started")8logger.info(f"Records loaded: {count}")9logger.error("Transformation failed for batch 3")10logger.info("Pipeline completed successfully")
Pipeline Error Handling Best Practices
| Practice | How | AWS Service |
|---|---|---|
| Structured Logging | Use logging module, not print() | CloudWatch Logs |
| Retry Logic | Exponential backoff on temporary failures | Lambda / Step Functions |
| Dead Letter Queue | Push failed records for later reprocessing | SQS DLQ |
| Alerting | Notify on critical failures | SNS + CloudWatch Alarms |
| Log Key Steps | Start, records loaded, errors, completion | CloudWatch / Glue logs |
How to Say It in Interview
🎤 Speak This
Error handling and logging are very important in data pipelines because failures can happen anytime.First, error handling. I always use try-except blocks to catch errors. Instead of stopping the entire pipeline, I log the error and handle it properly — like pushing the failed record to a DLQ.
Second, logging. I use the logging module instead of print statements. Logging helps track what is happening — start time, end time, errors, and processed records.
In real projects, I also add retry mechanism for temporary failures, store logs in CloudWatch, and send alerts using SNS.
For example, if an API fails, I log the error and retry instead of failing the whole job.
So proper logging and error handling help in debugging, monitoring, and maintaining pipelines.
4
Decorators — Real-Time ETL Use Case
What is a Decorator?
- A way to add extra functionality to a function without changing its original code
- Like wrapping a function with additional logic
- Makes code cleaner, reusable, and maintainable
Example 1 — Logging Decorator
1def log_execution(func):2 def wrapper(*args, **kwargs):3 logger.info(f"Starting: {func.__name__}")4 result = func(*args, **kwargs)5 logger.info(f"Completed: {func.__name__}")6 return result7 return wrapper89@log_execution # apply to any ETL function10def extract_data():11 pass1213@log_execution # reuse same decorator14def transform_data():15 pass
One decorator, applied to extract / transform / load steps — no duplicate code
Example 2 — Retry Decorator
1def retry(max_attempts=3):2 def decorator(func):3 def wrapper(*args, **kwargs):4 for attempt in range(max_attempts):5 try:6 return func(*args, **kwargs)7 except Exception as e:8 logger.warning(f"Attempt {attempt+1} failed: {e}")9 return wrapper10 return decorator1112@retry(max_attempts=3)13def call_api(url):14 pass # auto retries 3 times on failure
API calls in ETL — auto-retry on failure without changing business logic
How to Say It in Interview
🎤 Speak This
Decorators are a way to add extra functionality to a function without changing its original code. In simple terms, it is like wrapping a function with additional logic.In real projects, I use decorators for common tasks like logging, retry logic, and performance tracking.
For example, instead of writing logging code inside every ETL function, I create one decorator and apply it to multiple functions. This makes the code cleaner and reusable.
Another real use case is retry logic. If a function fails, the decorator can automatically retry it without changing the main function.
In ETL pipelines, decorators are very useful because many steps need similar handling like logging or error checking.
5
Optimizing Python Code in ETL Jobs
Optimization Levels
| Level | Technique | Why It Helps |
|---|---|---|
| Code | Use generators instead of lists | Keeps memory usage low |
| Code | Use map(), filter(), built-ins | Faster than manual loops in Python |
| Data | Process only required columns | Reduces data size and memory use |
| Data | Use Parquet instead of CSV | Columnar — faster reads, less storage |
| Processing | Use multiprocessing for CPU tasks | True parallel execution |
| Query | Push filter/aggregate logic to SQL/DB | Database engines are faster than Python loops |
| AWS | Use Glue / Spark for large datasets | Distributed processing — not limited to one machine |
Push Logic to Database — Example
1# ❌ BAD — Python loop on full data (slow)2result = [r for r in records if r["status"] == "active"]34# ✅ GOOD — Push filter to SQL, load only what you need5query = "SELECT * FROM employees WHERE status = 'active'"6df = pd.read_sql(query, connection)
How to Say It in Interview
🎤 Speak This
When optimizing Python code in ETL jobs, I focus on reducing time, memory usage, and unnecessary processing.First, I avoid loading large data into memory. I use generators or chunking to process data in batches.
Second, I use efficient libraries like pandas or built-in functions instead of writing complex loops.
Third, I reduce unnecessary operations — I process only required columns instead of full data.
Fourth, I use parallel processing when needed, like multiprocessing for CPU-heavy tasks.
Fifth, I try to push logic to databases whenever possible. Instead of processing everything in Python, I use SQL queries to filter or aggregate data first.
In AWS projects, I also use services like Glue or Spark for large-scale processing instead of pure Python. So overall, optimization is about using the right tool, reducing data size, and processing efficiently.
📌 Senior-Level Closing Statement
"In real-world ETL systems, I don't rely only on Python optimization. I combine Python techniques like generators and multiprocessing with AWS-native tools like Glue, S3 partitioning, and Redshift. This ensures scalability, fault tolerance, and cost efficiency."
🎯 How to Speak in the Interview
- Speak slow and clear — don't rush
- Use simple words — avoid heavy jargon
- Always connect to AWS or real project
- Explain why, not just how