Short-Lived Proxies in Python: Separate Lease Expiry from Request Timeouts

By GlobalProxyIP Editorial Team

A short-lived proxy needs two controls in Python: a valid resource lease when work is admitted, and sensible request waiting limits after it starts. Increasing a request timeout cannot extend an expired proxy lease.

There is no universal duration implied by “short-lived.” Providers may start the clock at allocation, extraction, activation, or another documented event. This article uses an explicit local lease format rather than inventing a provider API schema.

Define the adapter boundary

Assume your adapter has produced a JSON file with host, port, and an offset-aware expires_at. For example, proxy.example.invalid, a sample port, and an example timestamp are placeholders, not a usable proxy. Translate actual provider fields only after reading their meanings.

If a provider returns a remaining lifetime, establish when that value was measured and account for elapsed transfer time. If it gives no reliable deadline, do not fabricate one by attaching a marketing duration to the local receipt time.

Check expiry when work leaves the queue

Use Python 3 and requests==2.34.2. Set LEASE_FILE to your normalized local JSON file and TARGET_URL to a controlled, authorized target. The example assumes an HTTP endpoint with username/password authentication.

import os, json, time
from datetime import datetime, timezone
from pathlib import Path
from getpass import getpass
from urllib.parse import quote
import requests

# Local adapter format, NOT a provider API response schema. lease = json.loads(Path(os.environ["LEASE_FILE"]).read_text(encoding="utf-8")) expires = datetime.fromisoformat(lease["expires_at"]) if expires.utcoffset() is None: raise ValueError("expires_at must include a UTC offset") remaining = (expires - datetime.now(timezone.utc)).total_seconds() deadline = time.monotonic() + remaining # Example admission margin; NOT a guaranteed total request timeout. admission_margin = 30 user, password = input("Proxy username: "), getpass("Proxy password: ") proxy = (f"http://{quote(user, safe='')}:{quote(password, safe='')}" f"@{lease['host']}:{int(lease['port'])}") with requests.Session() as session: session.trust_env = False if time.monotonic() + admission_margin >= deadline: raise RuntimeError("Refresh the lease before admitting new work") with session.get(os.environ["TARGET_URL"], proxies={"http": proxy, "https": proxy}, timeout=(5, 20), allow_redirects=False) as response: response.raise_for_status() if not 200 <= response.status_code < 300: raise ValueError("Unexpected redirect") print("decoded_body_bytes", len(response.content))

The script converts a wall-clock expiry to a process-local monotonic deadline. This reduces the impact of later local clock adjustments on admission checks; it does not correct an inaccurate provider clock or incorrect adapter semantics.

The 30-second margin is an illustrative dispatch policy. It is not a service guarantee or a complete request deadline. Requests read timeouts limit waits between received bytes, so an active response may take longer than the chosen margin.

Keep renewal out of generic error handling

An expired lease may call for acquiring another resource. An authentication error calls for checking permissions or credentials. An origin refusal calls for reviewing authorization or rate limits. Catching all three and renewing forever hides the actual cause and creates uncontrolled consumption.

For permitted idempotent reads, define a limited retry budget, backoff, and a task recovery point. Do not assume replay is safe for state-changing requests.

Test the local policy separately

Prepare expired, nearly expired, and adequately valid local leases. Confirm that stale work is rejected before any request is sent. Repeat with deliberate queue delays, because checking only when the lease is acquired misses waiting time.

This is a single-process admission example, not a concurrent pool implementation. It does not reserve capacity, cancel requests at expiry, or implement provider renewal. Environment trust is disabled for predictable configuration; set an approved CA path explicitly if required.

Frequently asked questions

Can I calculate expiry from the product name?

No. Use documented timing semantics and actual response data; a product label is insufficient.

Does a monotonic deadline guarantee the proxy remains online?

No. It improves local elapsed-time accounting, not resource availability.

Is the admission margin a hard request deadline?

No. It only decides whether to start work. Strict cancellation and total deadlines require separate controls.

Sources

Sources reviewed on November 20, 2026.