Write a program that implements batch processing with incremental updates.
- User
Write a program that implements batch processing with incremental updates.
Assistant
Write a program that implements batch processing with incremental updates.
1. Understand the Goal: The user wants a program that demonstrates "batch processing with incremental updates." This means processing a large dataset (or a stream of data) in chunks (batches) and updating the state or results as new data arrives or as processing progresses.
Determine the Core Concepts:
Select a Scenario: What's a relatable and clear example?
Decision: Let's go with a Sales Data Aggregator. It's intuitive: we have a large stream of sales transactions, and we want to calculate total revenue, items sold, and maybe category breakdowns, processing them in batches and printing intermediate (incremental) results.
Design the Program Structure (Python):
Drafting the Code Steps:
random for data generation, time to simulate work.generate_sales_data(num_records) yielding dictionaries like {'product': 'A', 'price': 10.0, 'quantity': 2}.SalesAggregator.
total_revenue, sales_by_product.update(batch). This is the key "incremental" part. It takes a list of transactions and adds them to the current totals.update.Refining the "Incremental" Aspect: To make it truly "incremental" and robust (like a real-world ETL pipeline), I should add:
Writing the Code (Mental Draft & Iteration):
Batching logic: Python's itertools is great, specifically islice, but a simple custom generator is more readable for a tutorial. Let's write a chunker generator.
The "Incremental Update" Logic:
Adding Robustness (The "Professional" touch):
dataclasses for cleaner data structures.json for saving state (checkpointing).Finalizing the Example: Let's build a system that processes a "large" CSV file (simulated) and updates a running summary, saving a checkpoint file after every batch.
Constructing the explanation:
Review against constraints:
Self-Correction during coding:
Final Code Structure:
Transaction dataclass.AnalyticsState dataclass (handles the + operator for easy updates).stream_data(): Generates infinite/streaming data.get_batches(): Chunks the stream.process_batch(): Logic.checkpoint(): Save to disk.Let's write the Python solution based on this structure. It is readable, demonstrates the concepts clearly, and uses modern Python features (type hinting, dataclasses).
(Self-Correction on complexity): Keep the math simple. Summing floats and counting integers is enough to demonstrate the logic without getting bogged down in complex statistics.
This program simulates a real-world data pipeline (like processing server logs or financial transactions). It focuses on three key requirements for this pattern:
Instead of iterating one by one, the program adds items to batch_buffer. Only when the buffer hits BATCH_SIZE does the actual processing logic run. This reduces I/O overhead (if writing to a DB) or makes better use of CPU cache.
Notice the process_batch function. It does not return a new total; it modifies the existing state object:
state.total_revenue += batch_revenue
This allows the program to hold aggregate data (like a Grand Total) in memory without keeping the raw data (individual transactions) in memory.
The save_state function writes the current progress to progress_checkpoint.json.
Ctrl+C to force stop it.The data_generator acts as a "Stream." In a real scenario, this might be open('large_file.csv') or a database cursor. Crucially, we initialize it using state.last_processed_id + 1, ensuring we don't reprocess data we've already handled.
import time
import json
import os
import random
from dataclasses import dataclass, asdict
from typing import List, Dict
# ==========================================
# 1. Configuration & Data Structures
# ==========================================
BATCH_SIZE = 1000 # Process 1000 items at a time
CHECKPOINT_FILE = 'progress_checkpoint.json'
INPUT_SIZE = 5000 # Total items to simulate
@dataclass
class Transaction:
id: int
amount: float
category: str
@dataclass
class ProcessingState:
"""Maintains the cumulative state of the processing."""
last_processed_id: int = 0
total_revenue: float = 0.0
sales_by_category: Dict[str, int] = None
def __post_init__(self):
if self.sales_by_category is None:
self.sales_by_category = {}
# ==========================================
# 2. Core Logic
# ==========================================
def load_state() -> ProcessingState:
"""Load state from disk to enable resumption."""
if os.path.exists(CHECKPOINT_FILE):
with open(CHECKPOINT_FILE, 'r') as f:
data = json.load(f)
print(f"✅ Resuming from checkpoint. Last ID: {data['last_processed_id']}")
return ProcessingState(**data)
print("🚀 Starting fresh processing.")
return ProcessingState()
def save_state(state: ProcessingState):
"""Save current state to disk (Checkpointing)."""
with open(CHECKPOINT_FILE, 'w') as f:
json.dump(asdict(state), f, indent=4)
def data_generator(start_id: int, limit: int):
"""
Simulates fetching data from a database or large file.
Yields individual records.
"""
current_id = start_id
while current_id < limit:
# Simulate data variation
category = random.choice(['Electronics', 'Books', 'Clothing', 'Home'])
amount = round(random.uniform(10.0, 500.0), 2)
yield Transaction(id=current_id, amount=amount, category=category)
current_id += 1
def process_batch(batch: List[Transaction], state: ProcessingState):
"""
The core business logic.
Updates the state incrementally based on the current batch.
"""
batch_revenue = 0.0
for tx in batch:
batch_revenue += tx.amount
# Update category counts
if tx.category not in state.sales_by_category:
state.sales_by_category[tx.category] = 0
state.sales_by_category[tx.category] += 1
# Incremental Update Logic
state.total_revenue += batch_revenue
state.last_processed_id = batch[-1].id
# Simulate heavy computation time
time.sleep(0.5)
# ==========================================
# 3. Main Execution Loop
# ==========================================
def main():
print("--- Starting Batch Processing Pipeline ---")
# 1. Load previous state (if any)
state = load_state()
# 2. Initialize the data stream starting from where we left off
# Note: In a real DB, you would use OFFSET/LIMIT or seek()
stream = data_generator(state.last_processed_id + 1, INPUT_SIZE)
batch_buffer = []
batches_processed = 0
try:
for record in stream:
# A. Fill the buffer
batch_buffer.append(record)
# B. Buffer full? Process it.
if len(batch_buffer) >= BATCH_SIZE:
process_batch(batch_buffer, state)
batches_processed += 1
# C. Report Progress
print(f"Batch {batches_processed} processed. "
f"Current Total Revenue: ${state.total_revenue:,.2f}")
# D. Save Checkpoint (Incremental Commit)
save_state(state)
# E. Clear buffer for next batch
batch_buffer.clear()
# F. Process any remaining items in the buffer (Partial Batch)
if batch_buffer:
process_batch(batch_buffer, state)
save_state(state)
print("Processed final partial batch.")
print("\n--- Processing Complete ---")
print(f"Final Revenue: ${state.total_revenue:,.2f}")
print(f"Sales Breakdown: {state.sales_by_category}")
# Clean up checkpoint file on success
if os.path.exists(CHECKPOINT_FILE):
os.remove(CHECKPOINT_FILE)
except KeyboardInterrupt:
print("\n⚠️ Process interrupted by user.")
print("State has been saved. Run again to resume.")
except Exception as e:
print(f"\n❌ Critical Error: {e}")
print("State has been saved to checkpoint.")
if __name__ == "__main__":
main()