Concurrent Rust requests do not automatically produce the right regional dataset. I make the region part of the task: which proxy configuration, which language, and which returned region are expected. Otherwise, concurrency only collects incorrect samples faster.

This example uses reqwest0.12.24 and Tokio for separate US and DE groups. Each group advances at most two requests at once; the first region finishes before the next starts. That makes regional differences easier to inspect without claiming the highest-throughput production design.

Separate proxy routing from business language

Each region has its own endpoint and account configuration, with US_ and DE_ prefixes. Obtain these values through the provider's actual configuration mechanism. The code does not invent country suffixes for arbitrary usernames.

The owned endpoint accepts region and language query parameters and returns matching fields. This example uses en-US and de-DE. Real destinations may use a different interface, so implement their documented contract rather than append these parameters to an arbitrary URL.

Complete regional asynchronous program

Use a native Rust2021-edition project. reqwest is pinned to0.12.24 and futures-util to0.3.31; Tokio uses1.x. Keep Cargo.lock after resolving dependencies and revalidate upgrades. The toolchain must satisfy all resolved dependency requirements.

Inject PROXY_URL, PROXY_USER, and PROXY_PASS for a single configuration. The regional version uses US_URL, US_USER, US_PASS, DE_URL, DE_USER, and DE_PASS. Proxy URLs are HTTP endpoints without embedded credentials. URLS_FILE points to the UTF-8 URL list.

The TOML block is Cargo.toml; the Rust block is src/main.rs. Run cargo run in the project directory after preparing configuration. Output contains completion counts or redacted error stages, not complete target URLs or proxy passwords.

[package]
name = "proxy_demo_06"
version = "0.1.0"
edition = "2021"

[dependencies]
reqwest = { version = "=0.12.24", default-features = false, features = ["rustls-tls", "json"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
futures-util = "=0.3.31"
serde_json = "1"
use futures_util::{stream, StreamExt};
use reqwest::{Client, Proxy};
use serde_json::{json, Value};
use std::{env, fs, time::{Duration, SystemTime, UNIX_EPOCH}};

type AnyError = Box<dyn std::error::Error + Send + Sync>;

fn client(prefix: &str) -> Result<Client, AnyError> {
    let endpoint = env::var(format!("{prefix}_URL"))?;
    let parsed = reqwest::Url::parse(&endpoint)?;
    if parsed.scheme() != "http" || !parsed.username().is_empty() || parsed.password().is_some() {
        return Err("Expected an HTTP proxy endpoint without embedded credentials".into());
    }
    let user = env::var(format!("{prefix}_USER"))?;
    let password = env::var(format!("{prefix}_PASS"))?;
    let proxy = Proxy::all(endpoint)?.basic_auth(&user, &password);
    Ok(Client::builder().proxy(proxy)
        .redirect(reqwest::redirect::Policy::none())
        .retry(reqwest::retry::never())
        .connect_timeout(Duration::from_secs(5))
        .timeout(Duration::from_secs(20)).build()?)
}

async fn fetch(c: &Client, url: &str) -> Result<Value, String> {
    let mut response = c.get(url).send().await.map_err(|e| {
        if e.is_timeout() { "timeout".to_string() } else { "transport".to_string() }
    })?;
    if !response.status().is_success() {
        return Err(format!("http_{}", response.status().as_u16()));
    }
    let media = response.headers().get("content-type")
        .and_then(|x| x.to_str().ok()).unwrap_or("").split(';').next().unwrap_or("");
    if media.trim() != "application/json" { return Err("content_type".into()); }
    let mut body = Vec::new();
    while let Some(chunk) = response.chunk().await.map_err(|_| "body_read")? {
        if body.len() + chunk.len() > 1_048_576 { return Err("body_too_large".into()); }
        body.extend_from_slice(&chunk);
    }
    serde_json::from_slice(&body).map_err(|_| "json_parse".into())
}

fn urls() -> Result<Vec<String>, AnyError> {
    let text = fs::read_to_string(env::var("URLS_FILE")?)?;
    let urls: Vec<_> = text.lines().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).collect();
    if urls.is_empty() || urls.len() > 100 { return Err("Expected 1 to 100 example URLs".into()); }
    Ok(urls)
}

async fn run() -> Result<(), AnyError> {
    for region in ["US", "DE"] {
        let c = client(region)?;
        let language = if region == "US" { "en-US" } else { "de-DE" };
        // Do not share cookies between regions; this example has no cookie store.
        let mut jobs = stream::iter(urls()?).map(|url| {
            let c = c.clone();
            async move {
                let mut parsed = reqwest::Url::parse(&url).map_err(|_| "target_url")?;
                parsed.query_pairs_mut().append_pair("region", region).append_pair("language", language);
                fetch(&c, parsed.as_str()).await
            }
        }).buffer_unordered(2);
        let mut accepted = 0;
        while let Some(result) = jobs.next().await {
            let data = result.map_err(|e| { eprintln!("stage={e}"); e })?;
            if data.get("region").and_then(Value::as_str) != Some(region)
                || data.get("language").and_then(Value::as_str) != Some(language) {
                return Err("Region or language validation failed".into());
            }
            accepted += 1;
        }
        println!("region={region}, accepted_tasks={accepted}");
    }
    Ok(())
}

#[tokio::main]
async fn main() {
    if run().await.is_err() {
        eprintln!("Stopped: check configuration, response status and output directory; credentials were not printed.");
        std::process::exit(1);
    }
}

An IP check is not enough

An IP database labels a network address. A business response may continue using an account, delivery address or cookie preference. Even if an external IP check matches, the page may be the wrong regional version. That is why the program also verifies region and language in the response.

Those fields must describe the returned business data, not labels inserted by the client afterward. If the destination has no such fields, extract equivalent evidence from verified page elements or its actual response structure. Sending region=DE is not itself proof that German data was returned.

Language can change parsing rules

Decimal separators, date formats and category labels can change with language. This example checks region and language only. A product parser should preserve amount and currency separately, use explicit timezone information, and handle each supported language format.

Do not translate every name before deduplication. Retain product identifiers and original text; a translated name is not a stable ID. Add a translated display column when needed instead of replacing the original value.

Concurrency belongs in the task policy

Clients are reused within each region and results arrive in completion order. Two concurrent requests do not mean two per second. Add a shared rate limiter before dispatch if the destination imposes a rate; independent sleeps in each task do not necessarily constrain aggregate bursts.

An error stops the program, drops unfinished Futures in the current group, and prevents the next region from starting. Determine unfinished tasks before resuming. This program has no durable checkpoint, so repeating a whole list must not be interpreted as a new independent sample.

Next, inspect two regional versions of one product and align region, language, currency and observation time. Establish what counts as the same product before drawing a price comparison.

Frequently asked questions

Must two countries use different gateway hostnames?

No. A provider may select regions through different generated settings on one gateway. Configuration and validation must remain distinct even when the hostname is shared.

Does this reqwest client retain cookies?

No cookie-store feature is enabled here. A stateful application should configure and isolate cookie storage by the required task or region.

Why stop a batch on one error?

During small-scale validation, an explicit incomplete batch is easier to diagnose than an apparently complete mixed result. Production recovery needs separate durable task-state design.

Related reading

Sources

About the author

小张 — Cross-border data collection and overseas proxy author

Expertise: Cross-border product data; overseas proxy selection; region and session management; dynamic pages and browser collection; collection troubleshooting; provider trials and cost comparison