Production Proxy Pool Management: Health Scoring, Rotation, and Auto-Purge
Introduction
Managing a proxy pool for large-scale web scraping and automation tasks is crucial for maintaining performance, reliability, and avoiding detection. This guide will walk you through setting up an efficient proxy pool management system using Python, focusing on health scoring, rotation, and auto-purge mechanisms. We'll cover the architecture, data structures, and specific implementation details to help you build a robust proxy management solution.
Proxy Pool Data Structure
The core of our proxy management system is the proxy pool data structure. We'll use a dictionary (dict) where the keys are proxy URLs and the values contain additional metadata such as health scores, usage statistics, and status flags.
# Example proxy pool data structure
proxy_pool = {
"http://proxy1.example.com:8080": {
"health_score": 0.9,
"success_rate": 0.95,
"speed_score": 0.8,
"last_checked": datetime.now(),
"status": "active",
# other metadata like usage count, cool-down timer, etc.
},
# more proxies...
}
Health Score Formula
The health score is a composite metric that considers both the success rate and the speed of the proxy. It helps in determining which proxy to use for a given request.
def calculate_health_score(success_rate, speed_score):
return success_rate * speed_score
- Success Rate: The ratio of successful requests over total attempts.
- Speed Score: A measure of how fast the proxy responds, typically calculated as the inverse of response time in milliseconds.
Proxy Rotation and Sticky Session Support
Effective rotation ensures that no single proxy is overwhelmed, reducing the risk of being blocked. We'll implement a simple round-robin rotation mechanism with support for sticky sessions using a hash of the target domain.
def get_next_proxy(proxy_pool):
active_proxies = [proxy for proxy in proxy_pool if proxy_pool[proxy]['status'] == 'active']
# Round-robin selection
next_proxy = active_proxies[hash("target_domain") % len(active_proxies)]
return next_proxy
# Sticky session support
def get_sticky_proxy(proxy_pool, target_domain):
hash_value = hash(target_domain)
index = hash_value % len(proxy_pool)
for _ in range(len(proxy_pool)):
proxy = list(proxy_pool.keys())[index]
if proxy_pool[proxy]['status'] == 'active':
return proxy
index = (index + 1) % len(proxy_pool)
return None # No active proxies available
Cool-Down Queue for Temporarily Banned Proxies
To handle proxies that are temporarily banned due to excessive use or detection, we'll implement a cool-down queue. Proxies in the cool-down queue will be checked periodically before being re-added to the pool.
cool_down_queue = {}
def add_to_cool_down(proxy_url, duration=300): # 5 minutes cool down by default
cool_down_queue[proxy_url] = datetime.now() + timedelta(seconds=duration)
def check_cool_down_queue(cool_down_queue):
current_time = datetime.now()
for proxy in list(cool_down_queue.keys()):
if cool_down_queue[proxy] < current_time:
# Re-add to active proxies
proxy_pool[proxy]['status'] = 'active'
del cool_down_queue[proxy]
Async Health Check Worker
To keep the proxy pool up-to-date, we'll use an asynchronous worker that periodically checks the health of each proxy. This ensures that any issues are detected and addressed promptly.
import asyncio
async def health_check_worker(proxy_pool):
while True:
for proxy in proxy_pool:
try:
# Perform a simple GET request to check health
response = requests.get("http://example.com", proxies={"http": proxy, "https": proxy})
success_rate = 1.0 if response.status_code == 200 else 0.0
speed_score = 1 / (response.elapsed.total_seconds() + 0.001) # Avoid division by zero
health_score = calculate_health_score(success_rate, speed_score)
proxy_pool[proxy]['success_rate'] = success_rate
proxy_pool[proxy]['speed_score'] = speed_score
proxy_pool[proxy]['health_score'] = health_score
except Exception as e:
print(f"Health check failed for {proxy}: {e}")
proxy_pool[proxy]['status'] = 'inactive'
await asyncio.sleep(60) # Check every minute
# Run the worker
asyncio.run(health_check_worker(proxy_pool))
Automatic Replenishment from Paid Provider API
To maintain a healthy pool size, we'll integrate with a paid proxy provider API (e.g., Bright Data's /proxy-manager/cp/cpm-new-ips endpoint) to automatically replenish the pool.
def fetch_new_proxies(api_url, api_key):
headers = {"Authorization": f"Bearer {api_key}"}
response = requests.get(api_url, headers=headers)
if response.status_code == 200:
new_proxies = response.json()
for proxy in new_proxies:
proxy_pool[proxy['url']] = {
"health_score": 0.0,
"success_rate": 0.0,
"speed_score": 0.0,
"last_checked": datetime.now(),
"status": 'active',
}
else:
print(f"Failed to fetch new proxies: {response.status_code}")
# Example usage
fetch_new_proxies("https://api.brightdata.com/proxy-manager/cp/cpm-new-ips", "YOUR_API_KEY")
Backing Store Options: Redis vs SQLite
For persistent storage, you can choose between Redis and SQLite. Redis is generally faster and more suitable for high-performance applications due to its in-memory nature and support for complex data structures. However, SQLite is simpler to set up and sufficient for smaller-scale operations.
Redis Example
import redis
redis_client = redis.StrictRedis(host='localhost', port=6379, db=0)
def save_to_redis(proxy_pool):
for proxy, metadata in proxy_pool.items():
redis_client.hset(f"proxy:{proxy}", mapping=metadata)
def load_from_redis(redis_client):
proxy_pool = {}
keys = redis_client.keys("proxy:*")
for key in keys:
proxy_url = key.decode('utf-8').split(":")[1]
metadata = redis_client.hgetall(key)
proxy_pool[proxy_url] = {k.decode('utf-8'): v.decode('utf-8') for k, v in metadata.items()}
return proxy_pool
# Save and load example
save_to_redis(proxy_pool)
proxy_pool = load_from_redis(redis_client)
SQLite Example
import sqlite3
def save_to_sqlite(proxy_pool):
conn = sqlite3.connect('proxies.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS proxies (url TEXT PRIMARY KEY, health_score REAL, success_rate REAL, speed_score REAL, last_checked TEXT, status TEXT)''')
for proxy, metadata in proxy_pool.items():
c.execute("INSERT OR REPLACE INTO proxies VALUES (?, ?, ?, ?, ?, ?)", (
proxy,
metadata['health_score'],
metadata['success_rate'],
metadata['speed_score'],
metadata['last_checked'].isoformat(),
metadata['status']
))
conn.commit()
conn.close()
def load_from_sqlite():
conn = sqlite3.connect('proxies.db')
c = conn.cursor()
c.execute("SELECT * FROM proxies")
rows = c.fetchall()
proxy_pool = {row[0]: {
'health_score': row[1],
'success_rate': row[2],
'speed_score': row[3],
'last_checked': datetime.fromisoformat(row[4]),
'status': row[5]
} for row in rows}
conn.close()
return proxy_pool
# Save and load example
save_to_sqlite(proxy_pool)
proxy_pool = load_from_sqlite()
Conclusion
Implementing a robust proxy pool management system is essential for any large-scale web scraping or automation project. By following this guide, you've set up the core components of your proxy management solution: health scoring, rotation, auto-purge mechanisms, and automatic replenishment from a paid provider API.
While building your own system offers flexibility and control, it also requires significant effort to maintain and scale. 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.
This tool simplifies the process of managing proxies by handling the complexities of health checks, rotation, and testing directly on your local machine. It's a practical alternative if you prefer to focus on your application logic rather than proxy management infrastructure.
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 →