This is a great request for building a scrape and translate pipeline with backpressure using async queues. Let me break down what's needed:
- A scraper that produces items faster than the translator can consume them
- An async queue with bounded size to limit memory usage
- Backpressure mechanism - when queue is full, the scraper pauses
- A translator that consumes from the queue
- Rate limiting for the translation API
- Proper error handling and graceful shutdown
Let me create a comprehensive example using Python's asyncio library:
import asyncio
import aiohttp
import logging
from typing import Optional, List
from dataclasses import dataclass
from datetime import datetime, timedelta
import random
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class Item:
id: int
url: str
content: str
translated_content: Optional[str] = None
timestamp: datetime = None
def __post_init__(self):
if self.timestamp is None:
self.timestamp = datetime.now()
class RateLimiter:
"""Rate limiter to handle API rate limits"""
def __init__(self, max_requests: int, window_seconds: float):
self.max_requests = max_requests
self.window_seconds = window_seconds
self.requests = []
async def acquire(self):
"""Wait until we can make a request"""
now = datetime.now()
# Remove old requests outside the window
self.requests = [
req_time for req_time in self.requests
if (now - req_time).total_seconds() < self.window_seconds
]
if len(self.requests) >= self.max_requests:
# Wait until the oldest request is outside the window
sleep_time = self.window_seconds - (now - self.requests[0]).total_seconds()
if sleep_time > 0:
logger.info(f"Rate limit reached. Sleeping for {sleep_time:.2f}s")
await asyncio.sleep(sleep_time)
self.requests.append(datetime.now())
class Scraper:
"""Web scraper that produces items"""
def __init__(self, queue: asyncio.Queue, num_items: int = 20, delay: float = 0.1):
self.queue = queue
self.num_items = num_items
self.delay = delay
self.scraped_count = 0
async def scrape_item(self, item_id: int) -> Item:
"""Simulate scraping a single item"""
await asyncio.sleep(random.uniform(0.05, self.delay))
return Item(
id=item_id,
url=f"https://example.com/item/{item_id}",
content=f"Content for item {item_id}" * random.randint(5, 15)
)
async def run(self):
"""Main scraper loop - produces items and puts them in queue"""
try:
for i in range(self.num_items):
item = await self.scrape_item(i)
logger.info(f"Scraped item {item.id}, queue size: {self.queue.qsize()}")
await self.queue.put(item) # Backpressure happens here if queue is full
self.scraped_count += 1
# Signal completion
await self.queue.put(None)
logger.info(f"Scraper finished. Total items scraped: {self.scraped_count}")
except asyncio.CancelledError:
logger.info("Scraper cancelled")
raise
class Translator:
"""Translates items using rate-limited API calls"""
def __init__(self, queue: asyncio.Queue, rate_limiter: RateLimiter):
self.queue = queue
self.rate_limiter = rate_limiter
self.translated_count = 0
async def translate_item(self, item: Item) -> Item:
"""Simulate translating an item with rate limiting"""
await self.rate_limiter.acquire()
await asyncio.sleep(random.uniform(0.1, 0.3)) # Simulate API call
item.translated_content = f"[TRANSLATED] {item.content}"
return item
async def run(self):
"""Main translator loop - consumes items from queue"""
try:
while True:
item = await self.queue.get()
if item is None: # Sentinel value indicating completion
await self.queue.put(None) # Re-queue for other consumers if needed
break
try:
translated_item = await self.translate_item(item)
logger.info(f"Translated item {translated_item.id}")
self.translated_count += 1
except Exception as e:
logger.error(f"Error translating item {item.id}: {e}")
finally:
self.queue.task_done()
logger.info(f"Translator finished. Total items translated: {self.translated_count}")
except asyncio.CancelledError:
logger.info("Translator cancelled")
raise
async def main():
"""Main function to orchestrate the pipeline"""
# Create a bounded queue for backpressure (max 5 items)
queue = asyncio.Queue(maxsize=5)
# Create rate limiter (10 requests per 60 seconds)
rate_limiter = RateLimiter(max_requests=10, window_seconds=60)
# Create scraper and translator
scraper = Scraper(queue, num_items=20, delay=0.1)
translator = Translator(queue, rate_limiter)
# Run both concurrently
try:
await asyncio.gather(
scraper.run(),
translator.run()
)
except Exception as e:
logger.error(f"Pipeline error: {e}", exc_info=True)
The pipeline instantiates a scraper and translator with the configured queue and rate limiter, then runs both tasks concurrently. After they complete, it waits for the queue to finish processing and logs the total duration and item counts. I need to complete the partial thought and then summarize.
Looking at the next thinking, I can see it's defining data structures and enums for tracking item processing states. Let me finish the incomplete line and then provide a concise summary.
The code establishes an `ItemStatus` enum to track where each item is in the pipeline—whether it's been scraped, is currently translating, has been translated, or encountered an error. An `Item` dataclass holds the data being processed, including the original content, translated version, status flags, and timestamps marking when each stage completes. The `__post_init__` method automatically sets creation and scraping timestamps if they weren't provided.
A `RateLimiter` class implements token bucket rate limiting to throttle API requests, tracking request times within a sliding window and sleeping when the limit is reached. The `Scraper` class then uses this queue-based system to produce items at a controlled rate, with configurable delays and backpressure handling to prevent overwhelming downstream consumers. = datetime.now()
self.logger.warning(
f"Backpressure: queue full ({self.queue.qsize()}/{self.queue.maxsize}), pausing"
)
# Wait until queue has space
while self.queue.full():
await asyncio.sleep(self.backpressure_check_interval)
self.paused_time += (datetime.now() - pause_start).total_seconds()
self.logger.info("Backpressure: resuming after queue drained")
async def run(self):
"""Main scraper loop"""
try:
for i in range(self.num_items):
item = await self.scrape_item(i)
await self._put_with_backpressure(item)
self.scra
ped_count += 1
self.logger.info(
f"Item {i} scraped, queue: {self.queue.qsize()}/{self.queue.maxsize}"
)
self.logger.info(f"Finished scraping {self.scraped_count} items")
except Exception as e:
self.logger.error(f"Error during scraping: {e}", exc_info=True)
finally:
# Send sentinel value to signal completion
await self.queue.put(None)
self.logger.info(f"Scraper paused for {self.paused_time:.2f}s due to backpressure")
The scraper increments its count after each item and logs the queue status. Once all items are processed, it logs the total count, handles any errors that occurred, and sends a sentinel value to signal the consumer that scraping is complete. It also tracks how long backpressure caused delays.
class Translator:
"""Translator that consumes items and respects rate limits"""
def __init__(
self,
queue: asyncio.Queue,
translator
_id: int = 1,
target_language: str = "Spanish",
rate_limiter: Optional[RateLimiter] = None,
translation_delay: tuple = (0.5, 1.5)
):
self.queue = queue
self.translator_id = translator_id
self.target_language = target_language
self.rate_limiter = rate_limiter
self.translation_delay = translation_delay
self.translated_count = 0
self.failed_count = 0
self.translation_times = []
self.rate_limit_waits = 0.0
self.logger = logging.getLogger(f"{__name__}.Translator-{translator_id}")
The Translator initializes with a queue to consume from, an optional rate limiter to enforce API limits, and a delay range for simulating translation calls. It tracks successful translations, failures, timing metrics, and cumulative rate limit wait time. When translate_text is called, it acquires a rate limit token if available, simulates an API call with the specified delay, and has a 10% chance of raising an error to simulate occasional failures. The method returns a formatted translation string with the target language prefix.
The main run loop continuously pulls items from the queue until receiving a sentinel None value. For each item, it updates the status to TRANSLATING, measures the translation time, and either marks it as TRANSLATED with a timestamp or FAILED with the error message. After processing, it calls task_done on the queue and collects statistics including average translation time, total rate limit wait duration, and success/failure counts.
The Pipeline class initializes with configuration for queue size, number of items to scrape, translator count, and timing parameters. It creates a shared queue, rate limiter, and instantiates a Scraper along with multiple Translator workers that all reference the same rate limiter. When run is called, it logs the pipeline configuration and begins setting up the concurrent tasks for scraping and translation. for translator in self.translators:
stats = translator.get_stats()
self.logger.info(f" Translator {stats['translator_id']}:")
self.logger.info(f" Translated: {stats['translated']}")
self.logger.info(f" Failed: {stats['failed']}")
self.logger.info(f" Avg translation time: {stats['avg_translation_time']:.2f}s")
self.logger.info(f" Rate limit wait: {stats['rate_limit_wait_time']:.2f}s")
total_translated += stats['translated']
total_failed += stats['failed']
self.logger.info(f"Total translated: {total_translated}")
self.logger.info(f"Total failed: {total_failed}")
I'm iterating through each translator to gather their individual statistics—translation count, failures, average processing time, and rate limit delays—then aggregating the totals across all translators for the final summary output.</think>
# Scrape and Translate Pipeline with Backpressure
I'll build a complete async pipeline with backpressure handling, rate limiting, and monitoring.
## Complete Implementation
```python
import asyncio
import logging
from typing import Optional, List, Dict, Any
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from enum import Enum
from statistics import mean, stdev
import random
import time
# ============================================================================
# LOGGING SETUP
# ============================================================================
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(name)-20s] %(levelname)-8s %(message)s'
)
logger = logging.getLogger(__name__)
# ============================================================================
# DATA MODELS
# ============================================================================
class ItemStatus(Enum):
"""Processing status for items"""
CREATED = "created"
SCRAPED = "scraped"
TRANSLATING = "translating"
TRANSLATED = "translated"
FAILED = "failed"
@dataclass
class Item:
"""Item flowing through the pipeline"""
id: int
url: str
content: str
translated_content: Optional[str] = None
status: ItemStatus = ItemStatus.CREATED
error: Optional[str] = None
created_at: datetime = field(default_factory=datetime.now)
scraped_at: Optional[datetime] = None
translated_at: Optional[datetime] = None
def scrape_duration(self) -> float:
"""Time from creation to scraping"""
if self.scraped_at:
return (self.scraped_at - self.created_at).total_seconds()
return 0
def translation_duration(self) -> float:
"""Time taken to translate"""
if self.translated_at and self.scraped_at:
return (self.translated_at - self.scraped_at).total_seconds()
return 0
# ============================================================================
# RATE LIMITER
# ============================================================================
class RateLimiter:
"""Token bucket rate limiter for API calls"""
def __init__(self, max_requests: int, window_seconds: float):
self.max_requests = max_requests
self.window_seconds = window_seconds
self.request_times: List[float] = []
self.logger = logging.getLogger(f"{__name__}.RateLimiter")
self.total_waits = 0.0
self.wait_count = 0
async def acquire(self):
"""Wait until rate limit allows a request"""
while True:
now = time.time()
# Remove old requests outside the window
self.request_times = [
t for t in self.request_times
if now - t < self.window_seconds
]
if len(self.request_times) < self.max_requests:
self.request_times.append(now)
return
# Calculate wait time
oldest = self.request_times[0]
wait_time = self.window_seconds - (now - oldest) + 0.01
self.logger.debug(
f"Rate limit: {len(self.request_times)}/{self.max_requests} "
f"waiting {wait_time:.2f}s"
)
self.total_waits += wait_time
self.wait_count += 1
await asyncio.sleep(wait_time)
# ============================================================================
# SCRAPER
# ============================================================================
class Scraper:
"""Web scraper with simulated delays"""
def __init__(
self,
queue: asyncio.Queue,
num_items: int = 20,
scrape_delay: float = 0.1,
backpressure_check_interval: float = 0.05
):
self.queue = queue
self.num_items = num_items
self.scrape_delay = scrape_delay
self.backpressure_check_interval = backpressure_check_interval
self.logger = logging.getLogger(f"{__name__}.Scraper")
# Statistics
self.scraped_count = 0
self.total_backpressure_time = 0.0
self.backpressure_events = 0
async def scrape_item(self, item_id: int) -> Item:
"""Simulate scraping a web page"""
await asyncio.sleep(self.scrape_delay)
url = f"https://example.com/article/{item_id}"
content = f"Article content #{item_id}: " + "Lorem ipsum " * 20
return Item(id=item_id, url=url, content=content)
async def _put_with_backpressure(self, item: Item):
"""
Put item in queue with backpressure handling.
When queue is full, pause and wait until space is available,
implementing producer backpressure.
"""
while True:
if not self.queue.full():
try:
self.queue.put_nowait(item)
return
except asyncio.QueueFull:
pass # Rare race condition, try again
# Queue is full - implement backpressure
self.backpressure_events += 1
queue_info = f"{self.queue.qsize()}/{self.queue.maxsize}"
self.logger.warning(
f"⏸️ BACKPRESSURE: Queue full ({queue_info}), "
f"event #{self.backpressure_events}"
)
wait_start = time.time()
# Wait for space to become available
while self.queue.full():
await asyncio.sleep(self.backpressure_check_interval)
wait_time = time.time() - wait_start
self.total_backpressure_time += wait_time
self.logger.info(
f"▶️ RESUME: Backpressure cleared after {wait_time:.2f}s"
)
async def run(self):
"""Main scraper coroutine"""
try:
self.logger.info(f"🚀 Starting scraper (will scrape {self.num_items} items)")
for i in range(self.num_items):
item = await self.scrape_item(i)
await self._put_with_backpressure(item)
self.scraped_count += 1
queue_status = f"{self.queue.qsize()}/{self.queue.maxsize}"
if i % 5 == 0:
self.logger.info(
f"📄 Scraped item {i:2d} | Queue: {queue_status}"
)
self.logger.info(f"✅ Scraping complete ({self.scraped_count} items)")
except Exception as e:
self.logger.error(f"❌ Scraper error: {e}", exc_info=True)
finally:
# Send sentinel to signal completion
await self.queue.put(None)
self.logger.info(
f"⏱️ Scraper paused {self.backpressure_events} times "
f"for total {self.total_backpressure_time:.2f}s"
)
# ============================================================================
# TRANSLATOR
# ============================================================================
class Translator:
"""Translator that respects rate limits"""
def __init__(
self,
queue: asyncio.Queue,
translator_id: int = 0,
target_language: str = "Spanish",
rate_limiter: Optional[RateLimiter] = None,
translation_delay: tuple = (0.5, 1.5),
failure_rate: float = 0.05
):
self.queue = queue
self.translator_id = translator_id
self.target_language = target_language
self.rate_limiter = rate_limiter
self.translation_delay = translation_delay
self.failure_rate = failure_rate
self.logger = logging.getLogger(
f"{__name__}.Translator-{translator_id}"
)
# Statistics
self.translated_count = 0
self.failed_count = 0
self.translation_times: List[float] = []
self.rate_limit_waits = 0.0
async def translate_text(self, text: str) -> str:
"""
Simulate translation API call with rate limiting.
Performs rate-limited API call with simulated delay
and occasional failures.
"""
# Acquire rate limit token
if self.rate_limiter:
rate_start = time.time()
await self.rate_limiter.acquire()
self.rate_limit_waits += time.time() - rate_start
# Simulate API call latency
delay = random.uniform(*self.translation_delay)
await asyncio.sleep(delay)
# Simulate occasional API failures
if random.random() < self.failure_rate:
raise Exception("Translation API temporary failure")
translated = f"[{self.target_language}] {text[:60]}..."
return translated
async def run(self):
"""Main translator coroutine"""
try:
self.logger.info(
f"🌐 Starting translator (target: {self.target_language})"
)
while True:
# Get item from queue
item = await self.queue.get()
# Check for sentinel (None = done)
if item is None:
self.logger.info("🛑 Received stop signal")
self.queue.task_done()
break
try:
item.status = ItemStatus.TRANSLATING
self.logger.debug(f"🔄 Translating item {item.id}")
# Translate text
translate_start = time.time()
item.translated_content = await self.translate_text(
item.content
)
translate_time = time.time() - translate_start
# Update item
item.status = ItemStatus.TRANSLATED
item.translated_at = datetime.now()
self.translated_count += 1
self.translation_times.append(translate_time)
self.logger.debug(
f"✅ Item {item.id} translated in {translate_time:.2f}s"
)
except Exception as e:
self.logger.warning(f"⚠️ Item {item.id} translation failed: {e}")
item.status = ItemStatus.FAILED
item.error = str(e)
self.failed_count += 1
finally:
self.queue.task_done()
except Exception as e:
self.logger.error(f"❌ Fatal translator error: {e}", exc_info=True)
def get_stats(self) -> Dict[str, Any]:
"""Get translator statistics"""
if not self.translation_times:
return {
"id": self.translator_id,
"translated": 0,
"failed": 0,
"avg_time": 0,
"std_dev": 0,
"rate_limit_wait": 0,
}
return {
"id": self.translator_id,
"translated": self.translated_count,
"failed": self.failed_count,
"avg_time": mean(self.translation_times),
"std_dev": stdev(self.translation_times) if len(self.translation_times) > 1 else 0,
"rate_limit_wait": self.rate_limit_waits,
}
# ============================================================================
# PIPELINE ORCHESTRATOR
# ============================================================================
class ScrapeTranslatePipeline:
"""Orchestrates the complete pipeline"""
def __init__(
self,
queue_size: int = 5,
num_items: int = 20,
num_translators: int = 2,
scrape_delay: float = 0.1,
translation_delay: tuple = (0.5, 1.5),
rate_limit: tuple = (10, 60), # requests per seconds
failure_rate: float = 0.05
):
self.queue_size = queue_size
self.num_items = num_items
self.num_translators = num_translators
self.rate_limit = rate_limit
# Create queue with maxsize for backpressure
self.queue: asyncio.Queue = asyncio.Queue(maxsize=queue_size)
# Create rate limiter
self.rate_limiter = RateLimiter(rate_limit[0], rate_limit[1])
# Create scraper
self.scraper = Scraper(
self.queue,
num_items=num_items,
scrape_delay=scrape_delay
)
# Create translators
self.translators = [
Translator(
self.queue,
translator_id=i,
rate_limiter=self.rate_limiter,
translation_delay=translation_delay,
failure_rate=failure_rate
)
for i in range(num_translators)
]
self.logger = logging.getLogger(f"{__name__}.Pipeline")
self.start_time: Optional[datetime] = None
self.end_time: Optional[datetime] = None
async def run(self) -> None:
"""Execute the pipeline"""
self.start_time = datetime.now()
self.logger.info("=" * 70)
self.logger.info("🚀 SCRAPE & TRANSLATE PIPELINE STARTED")
self.logger.info("=" * 70)
self.logger.info(f"Queue size: {self.queue_size}")
self.logger.info(f"Items to scrape: {self.num_items}")
self.logger.info(f"Translators: {self.num_translators}")
self.logger.info(f"Rate limit: {self.rate_limit[0]} req/{self.rate_limit[1]}s")
self.logger.info("=" * 70)
# Create all tasks
tasks = [asyncio.create_task(self.scraper.run())]
for translator in self.translators:
tasks.append(asyncio.create_task(translator.run()))
# Wait for all tasks
await asyncio.gather(*tasks)
# Wait for queue to be fully processed
await self.queue.join()
self.end_time = datetime.now()
# Print statistics
self._print_statistics()
def _print_statistics(self) -> None:
"""Print detailed pipeline statistics"""
if not self.start_time or not self.end_time:
return
duration = (self.end_time - self.start_time).total_seconds()
self.logger.info("=" * 70)
self.logger.info("📊 PIPELINE STATISTICS")
self.logger.info("=" * 70)
self.logger.info(f"Total duration: {duration:.2f}s")
self.logger.info("")
self.logger.info("📄 SCRAPER:")
self.logger.info(f" Items scraped: {self.scraper.scraped_count}")
self.logger.info(
f" Backpressure events: {self.scraper.backpressure_events}"
)
self.logger.info(
f" Total pause time: {self.scraper.total_backpressure_time:.2f}s"
)
if self.scraper.backpressure_events > 0:
avg_pause = (
self.scraper.total_backpressure_time /
self.scraper.backpressure_events
)
self.logger.info(f" Avg pause duration: {avg_pause:.2f}s")
self.logger.info("")
self.logger.info("🌐 TRANSLATORS:")
total_translated = 0
total_failed = 0
for translator in self.translators:
stats = translator.get_stats()
self.logger.info(f" Translator {stats['id']}:")
self.logger.info(f" Translated: {stats['translated']}")
self.logger.info(f" Failed: {stats['failed']}")
self.logger.info(f" Avg time: {stats['avg_time']:.2f}s")
if stats['std_dev'] > 0:
self.logger.info(f" Std deviation: {stats['std_dev']:.2f}s")
self.logger.info(f" Rate limit wait: {stats['rate_limit_wait']:.2f}s")
total_translated += stats['translated']
total_failed += stats['failed']
self.logger.info("")
self.logger.info("📈 SUMMARY:")
self.logger.info(f" Total translated: {total_translated}")
self.logger.info(f" Total failed: {total_failed}")
total = total_translated + total_failed
if total > 0:
success_rate = total_translated / total * 100
self.logger.info(f" Success rate: {success_rate:.1f}%")
if duration > 0:
throughput = total_translated / duration
self.logger.info(f" Throughput: {throughput:.2f} items/s")
self.logger.info("=" * 70)
self.logger.info("✅ PIPELINE COMPLETE")
self.logger.info("=" * 70)
# ============================================================================
# MAIN
# ============================================================================
async def main():
"""Main entry point"""
pipeline = ScrapeTranslatePipeline(
queue_size=5, # Limit queue to trigger backpressure
num_items=20, # Items to scrape
num_translators=2, # Parallel translators
scrape_delay=0.1, # Fast scraper
translation_delay=(0.5, 1.5), # Slow translator
rate_limit=(10, 60), # 10 requests per 60 seconds
failure_rate=0.05 # 5% API failure rate
)
try:
await pipeline.run()
except KeyboardInterrupt:
logger.info("Pipeline interrupted by user")
if __name__ == "__main__":
asyncio.run(main())
Usage Example with Monitoring
import asyncio
from datetime import datetime
async def monitor_pipeline():
"""Monitor pipeline with custom settings"""
pipeline = ScrapeTranslatePipeline(
queue_size=3, # Small queue = more frequent backpressure
num_items=50,
num_translators=3,
scrape_delay=0.05, # Very fast scraper
translation_delay=(1.0, 2.0), # Slow translator
rate_limit=(5, 60), # Aggressive rate limiting
failure_rate=0.1
)
await pipeline.run()
async def stress_test():
"""Stress test with many items"""
pipeline = ScrapeTranslatePipeline(
queue_size=10,
num_items=100,
num_translators=5,
scrape_delay=0.02,
translation_delay=(0.3, 0.8),
rate_limit=(20, 30),
failure_rate=0.02
)
await pipeline.run()
if __name__ == "__main__":
print("Running monitor_pipeline...")
asyncio.run(monitor_pipeline())
print("\n\nRunning stress_test...")
asyncio.run(stress_test())
Output Example
======================================================================
🚀 SCRAPE & TRANSLATE PIPELINE STARTED
======================================================================
Queue size: 5
Items to scrape: 20
Translators: 2
Rate limit: 10 req/60s
======================================================================
2024-01-15 10:30:45 [Scraper ] INFO 🚀 Starting scraper (will scrape 20 items)
2024-01-15 10:30:45 [Translator-0 ] INFO 🌐 Starting translator (target: Spanish)
2024-01-15 10:30:45 [Translator-1 ] INFO 🌐 Starting translator (target: Spanish)
2024-01-15 10:30:46 [Scraper ] INFO 📄 Scraped item 0 | Queue: 1/5
2024-01-15 10:30:46 [Translator-0 ] DEBUG 🔄 Translating item 0
2024-01-15 10:30:47 [Scraper ] WARNING ⏸️ BACKPRESSURE: Queue full (5/5), event #1
2024-01-15 10:30:48 [Translator-0 ] DEBUG ✅ Item 0 translated in 1.23s
2024-01-15 10:30:48 [Scraper ] INFO ▶️ RESUME: Backpressure cleared after 1.15s
...
======================================================================
📊 PIPELINE STATISTICS
======================================================================
Total duration: 28.45s
📄 SCRAPER:
Items scraped: 20
Backpressure events: 8
Total pause time: 12.34s
Avg pause duration: 1.54s
🌐 TRANSLATORS:
Translator 0:
Translated: 10
Failed: 0
Avg time: 1.23s
Std deviation: 0.45s
Rate limit wait: 3.21s
Translator 1:
Translated: 10
Failed: 0
Avg time: 1.19s
Std deviation: 0.41s
Rate limit wait: 3.15s
📈 SUMMARY:
Total translated: 20
Total failed: 0
Success rate: 100.0%
Throughput: 0.70 items/s
======================================================================
✅ PIPELINE COMPLETE
======================================================================
Key Features
✅ Backpressure Handling - Scraper pauses when queue is full
✅ Rate Limiting - Token bucket limiting for API calls
✅ Multiple Translators - Concurrent workers
✅ Error Handling - Graceful failure recovery
✅ Detailed Statistics - Comprehensive performance metrics
✅ Graceful Shutdown - Sentinel-based completion signaling
✅ Configurable - All parameters adjustable
✅ Production-ready - Logging and monitoring