Skip to main content
ParityEdge
Rust (Axum / Actix)
Backend Runtimes

Rust (Axum & Actix-web) Backend Integration

Resolve localized purchasing power parity pricing with sub-millisecond overhead in high-throughput Rust web services, API gateways, and edge microservices.

Axum 0.7+ Handler with Moka In-Memory Cache

Wrap reqwest::Client and moka::future::Cache inside an Arc<AppState> for lock-free concurrency:

// src/main.rs (Axum 0.7+)
use axum::{
    extract::{ConnectInfo, State},
    http::HeaderMap,
    routing::get,
    Json, Router,
};
use moka::future::Cache;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ParityResponse {
    pub eligible: bool,
    #[serde(rename = "discountPercentage")]
    pub discount_percentage: u32,
    #[serde(rename = "countryCode")]
    pub country_code: String,
    #[serde(rename = "countryName")]
    pub country_name: String,
    pub currency: String,
    #[serde(rename = "couponCode")]
    pub coupon_code: String,
    pub tier: u8,
}

#[derive(Clone)]
pub struct AppState {
    pub http_client: reqwest::Client,
    pub cache: Cache<String, ParityResponse>,
    pub project_id: String,
}

pub async fn get_pricing(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    ConnectInfo(addr): ConnectInfo<SocketAddr>,
) -> Json<serde_json::Value> {
    let client_ip = headers
        .get("x-forwarded-for")
        .and_then(|h| h.to_str().ok())
        .map(|s| s.split(',').next().unwrap_or("").trim())
        .unwrap_or_else(|| addr.ip().to_string().as_str())
        .to_string();

    let parity = match state.cache.get(&client_ip).await {
        Some(cached) => Some(cached),
        None => {
            let url = format!(
                "https://api.parityedge.app/v1/lookup?pid={}",
                state.project_id
            );

            let res = state
                .http_client
                .get(&url)
                .header("x-forwarded-for", &client_ip)
                .send()
                .await;

            if let Ok(response) = res {
                if response.status().is_success() {
                    if let Ok(data) = response.json::<ParityResponse>().await {
                        state.cache.insert(client_ip.clone(), data.clone()).await;
                        Some(data)
                    } else {
                        None
                    }
                } else {
                    None
                }
            } else {
                None
            }
        }
    };

    let base_price = 49.00f64;
    let final_price = match &parity {
        Some(p) if p.eligible && p.discount_percentage > 0 => {
            let discount_multiplier = (100 - p.discount_percentage) as f64 / 100.0;
            (base_price * discount_multiplier * 100.0).round() / 100.0
        }
        _ => base_price,
    };

    Json(json!({
        "basePrice": base_price,
        "finalPrice": final_price,
        "parity": parity
    }))
}

#[tokio::main]
async fn main() {
    let state = Arc::new(AppState {
        http_client: reqwest::Client::builder()
            .timeout(Duration::from_millis(800))
            .pool_max_idle_per_host(50)
            .build()
            .unwrap(),
        cache: Cache::builder()
            .time_to_live(Duration::from_secs(600))
            .max_capacity(50_000)
            .build(),
        project_id: "prj_live_YOUR_KEY".to_string(),
    });

    let app = Router::new()
        .route("/api/pricing", get(get_pricing))
        .with_state(state);

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>())
        .await
        .unwrap();
}

High-Throughput Best Practices

Shared Reqwest Pool

Always wrap reqwest::Client in an Arc to reuse HTTP/2 multiplexed connections across Tokio worker threads.

Edge Threat Filtering

The ParityEdge Anycast network inspects ASN tags at the border to neutralize proxy arbitrage before requests hit your origin.