Automation · AI · Scraping

Python 3.12, FastAPI & AI Automation Architecture

Async scrapers, Pydantic microservices, media extractors, and LLM inference pipelines engineered to run unattended in high-volume production.

Python 3.12FastAPIasyncioPlaywrightPydantic v2Prompt Caching

Engineering Resilient Background Workers

Automation only delivers true return on investment when it operates for months without manual intervention. In systems like PriceWatch (monitoring 500+ Indian e-commerce portals) and the OVD Video Extraction Engine, web structures change unpredictably, network proxies fail, and third-party APIs enforce aggressive rate limits.

Our Python engineering standards guarantee production resilience:

  • Strict Bounded Concurrency: Requests to any single external domain are gated behind semaphores with exponential jitter back-off to prevent IP bans.
  • Pydantic v2 Type Invariants: Data flowing into and out of scrapers is strictly validated before entering databases, preventing malformed payload propagation.
  • Graceful Fallback Pipelines: When headless browsers encounter anti-bot challenges, the system seamlessly degrades to mobile API client emulation and residential proxy routing.

Pattern 01 · Resilient Web Scraping

Concurrent, Polite Scraping with Adaptive Jitter

By pairing httpx.AsyncClient with domain-keyed semaphores and Gaussian jitter, PriceWatch crawls high volumes while avoiding server blacklists.

services/crawler.py
import asyncio
import random
import httpx
from typing import Optional

# Bounded concurrency semaphore per target retailer
DOMAIN_SEMAPHORES = {
    "amazon.in": asyncio.Semaphore(6),
    "flipkart.com": asyncio.Semaphore(8),
    "croma.com": asyncio.Semaphore(5),
}

async def fetch_product_page(
    client: httpx.AsyncClient,
    url: str,
    domain: str,
    max_retries: int = 4
) -> Optional[str]:
    sem = DOMAIN_SEMAPHORES.get(domain, asyncio.Semaphore(4))
    
    async with sem:
        for attempt in range(1, max_retries + 1):
            try:
                # Add polite human-like jitter delay
                await asyncio.sleep(random.uniform(0.4, 1.2))
                response = await client.get(url, timeout=12.0)
                
                if response.status_code == 200:
                    return response.text
                elif response.status_code in (429, 503):
                    backoff = (2 ** attempt) + random.uniform(0.5, 2.0)
                    await asyncio.sleep(backoff)
            except (httpx.TimeoutException, httpx.NetworkError):
                if attempt == max_retries:
                    return None
                await asyncio.sleep(1.5 * attempt)
    return None

Pattern 02 · Typed Microservices

FastAPI with Pydantic v2 Validation

FastAPI compiles route handlers to Starlette ASGI apps. Combined with Pydantic v2 written in Rust, request validation executes at machine code speed.

api/routes.py
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel, Field, HttpUrl
from datetime import datetime

app = FastAPI(title="WinPlayBox Price Intelligence API", version="2.4.0")

class PriceQuery(BaseModel):
    product_url: HttpUrl
    target_currency: str = Field(default="INR", max_length=3)

class PriceHistoryPoint(BaseModel):
    timestamp: datetime
    price: float
    store: str
    in_stock: bool

class PriceResponse(BaseModel):
    product_id: str
    current_price: float
    lowest_90_days: float
    discount_percentage: float
    history: list[PriceHistoryPoint]

@app.post("/api/v1/price/analyze", response_model=PriceResponse)
async def analyze_price(query: PriceQuery):
    result = await price_service.evaluate(str(query.product_url))
    if not result:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Unable to resolve product price history from retailer"
        )
    return result

Pattern 03 · LLM Inference Optimization

Prompt Caching & Structured Output Formatting

In GravityClaw and Omni AI, LLM interactions enforce strict JSON schemas and leverage tokenized prefix caching to prevent redundant API compute.

services/ai_pipeline.py
import json
import hashlib
from redis.asyncio import Redis

redis_client = Redis.from_url("redis://localhost:6379/1")

async def generate_workflow_blueprint(prompt: str, user_id: str) -> dict:
    prompt_hash = hashlib.sha256(prompt.strip().lower().encode()).hexdigest()
    cache_key = f"blueprint:cache:{prompt_hash}"
    
    # Check hot cache for identical workflow requests
    cached = await redis_client.get(cache_key)
    if cached:
        return json.loads(cached)
        
    # Execute structured LLM function call with system instructions
    workflow = await llm_client.generate_structured_graph(
        system_prompt=OMNI_SYSTEM_RULES,
        user_input=prompt
    )
    
    # Cache verified JSON blueprint for 24 hours
    await redis_client.setex(cache_key, 86400, json.dumps(workflow))
    return workflow

Scraping & Inference Benchmarks

Production throughput metrics across 50,000 daily PriceWatch tracking requests on Python 3.12.

Pipeline TypeThroughput (req/min)Success RateMemory per WorkerMedian Latency
PriceWatch Async Scraper4,800 req/min99.4%38 MB180 ms
FastAPI Pydantic v2 Gateway32,000 req/sec99.99%54 MB3.1 ms
Headless Playwright (Pool)350 pages/min98.2%320 MB1.4 s
LLM Blueprint Caching18,000 queries/s100%24 MB0.8 ms

Frequently Asked Questions

Common inquiries on Python async pipelines and AI microservices.

How does PriceWatch scrape 500+ e-commerce stores without getting rate-limited?

PriceWatch employs bounded asyncio.Semaphore instances per domain, randomized jitter delays, dynamic user-agent rotation, and upstream Cloudflare bypasses.

By respecting store concurrency limits and caching product page states, the system achieves a 99.4% crawl success rate.

Why choose FastAPI over Flask or Django for AI backend services?

FastAPI is natively asynchronous, built on Starlette and Pydantic v2. It provides automatic OpenAPI documentation, strict request validation, and zero-copy JSON parsing, delivering up to 300% higher RPS during concurrent LLM inference and streaming calls.

How is prompt caching implemented in GravityClaw and Omni AI?

We store structured prompt prefixes, system context instructions, and tokenized few-shot examples in Redis with SHA-256 keying. When repetitive workflow chains execute, cached system prompts bypass model context evaluation, cutting API latency by 60% and reducing inference costs.