JsonlBatch is a high-performance Python framework for concurrent processing of JSONL files, architected for I/O-intensive tasks.
It provides an elegant, out-of-the-box solution for processing large JSONL datasets where each line requires an I/O-bound operation, such as calling a web API, querying a database, or generating vector embeddings. The framework abstracts away the complexities of concurrency, state management, error handling, and logging, allowing you to focus purely on your business logic.
- Data Enrichment: Calling external APIs to enrich records in a large dataset.
- Batch API Calls: Sending a high volume of requests to a rate-limited API endpoint.
- ETL Processes: Performing transformations that involve heavy I/O with databases or file systems.
- Vector Embedding: Generating embeddings for a large corpus of text via model APIs.
- Web Scraping: Processing a list of URLs to fetch and parse data.
- 🚀 High-Performance Concurrency: Utilizes
asyncioto handle a high volume of concurrent I/O tasks efficiently, maximizing throughput. - 🛡️ Resilient & Resumable: Never lose work on interruptions. Automatically tracks and skips completed tasks on restart.
- ⏱️ Built-in Rate Limiting: Easily conform to API limits by setting a maximum number of requests per minute.
- ⚡ Fully Asynchronous: Employs an end-to-end non-blocking I/O pipeline with
aiofilesandaiologgerfor a truly stall-free performance. - 📦 Managed Resource Lifecycle: Provides
on_startupandon_shutdownhooks to gracefully initialize and release shared resources. - ✍️ Efficient Batch Writing: Buffers results and writes them to disk in batches to minimize I/O overhead.
- 💣 Granular Error Handling: Isolates failures to individual records. Failed items are logged with rich context to a separate error file without halting the process.
- 🔄 Automatic Retries: Automatically retries failed tasks with exponential backoff, configured globally in
config.py. - 📊 Real-time Progress & Reporting: Displays a dynamic
tqdmprogress bar with live success/failure counts and generates a detailed statistical summary upon completion.
The framework is organized into six well-defined modules for maximum clarity and maintainability.
your_project/
├── config.py # Your single source of truth for all settings.
├── logging_config.py # Centralized configuration for the async logger.
├── utils.py # Houses reusable, business-agnostic components.
├── processor.py # The framework's engine. You should not need to edit this.
├── task.py # Your workspace. Implement your task-specific logic here.
└── main.py # The application's generic entry point.
aiohttptqdmaiofilesaiologger
The framework requires Python 3.9+. Place the six framework files in your project directory and install the dependencies:
pip install aiohttp tqdm aiofiles aiologgerModify the Settings class in config.py to define your file paths, unique ID key, and performance parameters.
class Settings:
INPUT_FILE: str = "data/input.jsonl"
OUTPUT_FILE: str = "data/output.jsonl"
ID_KEY: str = "id"
MAX_CONCURRENCY: int = 50
REQUESTS_PER_MINUTE: int = 0
MAX_RETRIES: int = 3
RETRY_INITIAL_DELAY: float = 2.0
# ...This is where you define your task by implementing three key functions. See "Core Concepts Explained" below for details.
Run the framework from your terminal:
python main.pyThe framework interacts with your code through a clear contract defined in task.py. You must implement three functions that manage your task's lifecycle.
-
on_startup() -> dict: This coroutine runs once before any processing begins. Its purpose is to initialize and return acontextdictionary containing any shared resources (e.g., SDK clients, database connection pools). -
process_record(record: dict, context: dict) -> dict | None: This is your main worker coroutine. It runs concurrently for each line in your input file. It receives the datarecordfor one line and the sharedcontextobject. Its job is to perform the desired operation and return the resulting dictionary to be saved. ReturningNonewill skip saving a result for that record. -
on_shutdown(context: dict): This coroutine runs once after all processing is finished (even if errors occurred). Use it to gracefully clean up and release the resources created inon_startup.
The context object acts as the bridge, safely passing shared resources from startup to every worker and finally to shutdown. The framework also automatically adds a shared aiohttp.ClientSession to the context as context['session'].
Goal: Enrich a list of IP addresses from a JSONL file with geolocation data from an external API.
1. Input Data (data/ips.jsonl):
{"ip": "8.8.8.8", "source": "Google DNS"}
{"ip": "1.1.1.1", "source": "Cloudflare DNS"}2. Configuration (config.py):
class Settings:
INPUT_FILE: str = "data/ips.jsonl"
OUTPUT_FILE: str = "data/ips_enriched.jsonl"
ID_KEY: str = "ip"
MAX_CONCURRENCY: int = 10
REQUESTS_PER_MINUTE: int = 120
MAX_RETRIES: int = 2
RETRY_INITIAL_DELAY: float = 5.0
# ...3. Logic Implementation (task.py):
# task.py
from typing import Dict, Any
# No special resources are needed for this simple task.
async def on_startup() -> Dict[str, Any]:
return {}
async def on_shutdown(context: Dict[str, Any]):
pass
# Note: The retry decorator is no longer needed here.
# The framework handles retries automatically based on config.py settings.
async def process_record(record: Dict[str, Any], context: Dict[str, Any]) -> Dict[str, Any]:
session = context['session'] # Use the session provided by the framework
ip_address = record.get("ip")
api_url = f"http://ip-api.com/json/{ip_address}"
async with session.get(api_url) as response:
response.raise_for_status()
location_data = await response.json()
if location_data.get('status') == 'success':
record['country'] = location_data.get('country')
record['city'] = location_data.get('city')
record['isp'] = location_data.get('isp')
return record4. Run & Check Output (data/ips_enriched.jsonl):
After running python main.py, the output file will contain:
{"ip": "8.8.8.8", "source": "Google DNS", "country": "United States", "city": "Mountain View", "isp": "Google LLC"}
{"ip": "1.1.1.1", "source": "Cloudflare DNS", "country": "United States", "city": "Los Angeles", "isp": "Cloudflare, Inc."}The framework provides two parameters to control how you interact with external services: MAX_CONCURRENCY and REQUESTS_PER_MINUTE. It's important to understand their roles:
MAX_CONCURRENCY: This limits how many tasks can be running in parallel at any single moment. It's like setting the number of workers on an assembly line.REQUESTS_PER_MINUTE: This controls the overall rate at which new tasks are started. It's like setting the speed of the conveyor belt feeding the assembly line.
The framework has a built-in, robust retry mechanism to handle transient errors automatically. You no longer need to add any decorators to your process_record function.
You can configure the retry behavior globally in config.py:
MAX_RETRIES: The maximum number of times to retry a failed task.RETRY_INITIAL_DELAY: The initial wait time in seconds before the first retry. The delay increases exponentially for subsequent retries.
If you must use a blocking library (e.g., a synchronous database driver), wrap the blocking call in await asyncio.to_thread(...) inside your process_record function to keep the framework responsive.
For critical tasks that write to a database, ensure your process_record logic is idempotent (running an operation multiple times has the same effect as running it once). This prevents duplicate writes if a job is restarted after a partial failure.
To re-process specific, already completed items, set the RERUN_KEY in config.py (e.g., to "force_rerun"). In your output.jsonl file, add this key to any record you want to re-run (e.g., {"id": "...", "force_rerun": true}). The framework will pick it up on the next run.
This project is licensed under the MIT License.