Build a Thread-Safe Proxy Pool Class in Python (Production Ready)
Introduction
Building a robust and thread-safe proxy pool class is essential for developers running web scraping or automation tasks at scale. A well-designed proxy pool can distribute load efficiently, handle failures gracefully, and maintain a list of active proxies that are verified to be functional. This guide will walk you through creating a production-ready ProxyPool class in Python, focusing on thread safety, efficient rotation, and automatic handling of failed proxies.
Key Features of the Proxy Pool Class
- Thread Safety: Using
threading.Lockto ensure safe access to shared resources. - Deque Rotation: Efficiently managing proxy rotation with a double-ended queue (
deque) for fast appends and pops. - Failure Counter: Each proxy has a failure counter. After reaching a certain threshold, the proxy is automatically blacklisted.
- Async Health Check: Periodically checks proxies to remove dead or inactive ones.
- Re-integration after Cooldown: Failed proxies are re-added to the pool after a specified cooldown period if they become active again.
Setting Up the Environment
Before diving into the code, ensure you have Python installed. This guide assumes you're using Python 3.6 or later due to the use of asyncio and other modern features. You'll also need the requests library for making HTTP requests. Install it using pip if you haven't already:
pip install requests
Proxy Pool Class Implementation
Step 1: Initialize the ProxyPool Class
Let's start by creating the basic structure of our ProxyPool class.
import threading
from collections import deque
import asyncio
import time
class ProxyPool:
def __init__(self, proxies=None, max_failures=3, cooldown=60):
self.lock = threading.Lock()
self.proxies = deque(proxies or [])
self.max_failures = max_failures
self.cooldown = cooldown
self.blacklist = set()
def add_proxy(self, proxy):
with self.lock:
if proxy not in self.blacklist and proxy not in self.proxies:
self.proxies.append(proxy)
def remove_proxy(self, proxy):
with self.lock:
if proxy in self.proxies:
self.proxies.remove(proxy)
Step 2: Implement Thread-Safe Proxy Rotation
To ensure thread safety during proxy rotation, use a lock to synchronize access.
def get_next_proxy(self):
with self.lock:
if not self.proxies:
return None
proxy = self.proxies.popleft()
self.proxies.append(proxy)
return proxy
Step 3: Handle Proxy Failures
Implement a mechanism to track failures and blacklist proxies.
def mark_failure(self, proxy):
with self.lock:
if proxy in self.proxies:
index = list(self.proxies).index(proxy)
self.proxies[index] = (proxy, 1) # Start failure count
elif isinstance(proxy, tuple) and proxy[0] in self.proxies:
index = list(self.proxies).index(proxy[0])
current_failures = proxy[1]
if current_failures < self.max_failures - 1:
self.proxies[index] = (proxy[0], current_failures + 1)
else:
self.blacklist.add(proxy[0])
del self.proxies[index]
def is_blacklisted(self, proxy):
with self.lock:
return proxy in self.blacklist
Step 4: Async Health Check to Prune Dead Proxies
Use asyncio to periodically check the health of proxies.
async def health_check(self):
while True:
await asyncio.sleep(60) # Check every minute
with self.lock:
to_remove = []
for proxy in self.proxies:
if isinstance(proxy, tuple):
proxy, _ = proxy
try:
response = requests.get("http://example.com", proxies={"http": proxy, "https": proxy}, timeout=5)
if response.status_code != 200:
to_remove.append(proxy)
except Exception as e:
to_remove.append(proxy)
for proxy in to_remove:
self.remove_proxy(proxy)
def start_health_check(self):
asyncio.run(self.health_check())
Step 5: Re-integration after Cooldown
After a proxy is blacklisted, attempt to re-add it to the pool after a cooldown period.
async def cooldown_monitor(self):
while True:
await asyncio.sleep(10) # Check every 10 seconds
with self.lock:
current_time = time.time()
for proxy in list(self.blacklist):
try:
response = requests.get("http://example.com", proxies={"http": proxy, "https": proxy}, timeout=5)
if response.status_code == 200:
self.add_proxy(proxy)
self.blacklist.remove(proxy)
except Exception as e:
pass
def start_cooldown_monitor(self):
asyncio.run(self.cooldown_monitor())
Conclusion
This guide has provided a comprehensive approach to building a thread-safe proxy pool class in Python. The ProxyPool class includes features for efficient proxy rotation, handling failures, pruning dead proxies, and re-integrating blacklisted proxies after a cooldown period.
If you'd rather not manage proxy lists manually, ProxyForge auto-tests and rotates proxies locally on your machine — one-off $29 unlock, no subscription: https://proxyforge.dev/#download.
For professional or managed proxy services that offer residential proxies and reliable rotating proxies for production use, consider providers like Bright Data and SmartProxy. These services can provide a more robust solution if you need to scale your proxy usage significantly.
By following this guide, you should be able to implement a ProxyPool class that meets the needs of most web scraping or automation tasks at scale.
Free proxies break. ProxyForge doesn't.
The free lists above are public and often unreliable. ProxyForge auto-tests and rotates proxies on your machine, your IP — no stale lists, no shared pools, no surprises. One-off purchase, no subscription.
Download ProxyForge free →