Skip to content
m1r4g3-codePublic

About

Distill — Turn any URL into clean, structured data for AI pipelines, RAG systems, and intelligent agents.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

52 Commits

Folders and files

Repository files navigation

Distill

A production-grade web extraction and AI data infrastructure platform. Turn any URL into clean Markdown, crawl entire sites, search the web, and pull structured JSON out of unstructured pages — all behind one API.

FastAPI Next.js PostgreSQL Redis Playwright Gemini


What is Distill

Distill is a Firecrawl-style extraction engine built for teams feeding LLMs and agents with real web data. Under the hood it's two cooperating services — a synchronous FastAPI gateway and a Redis/ARQ background worker fleet — sitting in front of a dual-fetch pipeline (HTTPX first, headless Playwright on fallback) that survives the parts of the web that break naive scrapers: SPA shells, meta-refresh redirects, bot walls, and slow JS hydration.

It ships as a complete product, not just an API: a Next.js dashboard with a live request playground, per-key usage analytics, job tracking, billing tiers, and generated API docs — the kind of surface area a paying developer actually expects.

Screenshots

Dashboard — live account overview Distill dashboard showing total jobs, success rate, pages extracted, cache hit rate, and recent job history

Playground — build and run requests against every endpoint Distill playground with scrape configuration form and generated curl snippet

Jobs — async job tracking with progress and duration Distill jobs table showing map, agent extract, and search scrape jobs with status and page counts

Usage & Metrics — request volume, cache hits, top scraped URLs Distill usage dashboard with requests-over-time chart and top URLs scraped

Docs — in-app API reference Distill in-app documentation listing core capabilities and endpoints

Billing — usage-based tiers Distill billing page with Free, Pro, and Enterprise plans

Architecture

Distill separates request intake from execution. Fast, boundable work (/scrape, /search) runs synchronously on the API process; anything that can blow past a gateway timeout — full-site crawls, LLM-backed extraction — is handed to an ARQ worker pool over Redis and polled through the jobs API.

flowchart LR
    Client["Client / Dashboard"] -->|"X-API-Key"| API["FastAPI Gateway"]

    API -->|"sync"| Scrape["/scrape /search"]
    API -->|"enqueue"| Queue[("Redis + ARQ Queue")]

    Queue --> Worker["ARQ Worker Pool"]
    Worker --> PWPool["Playwright Browser Pool"]

    Scrape --> Fetch["Fetch Pipeline"]
    Worker --> Fetch

    Fetch -->|"1. try"| HTTPX["HTTPX Client"]
    HTTPX -.->|"SPA shell / thin HTML"| PW["Playwright Fallback"]

    Fetch --> Clean["Trafilatura + Readability\nHTML to Markdown"]
    Clean --> DB[("PostgreSQL\npages / jobs / api_keys / events")]

    Worker -->|"structured extraction"| Gemini["Google Gemini"]

    API --> Auth["API Key Auth + Rate Limiter"]
    API --> SSRF["SSRF Guard\nprivate ranges, schemes, DNS resolve"]

    subgraph Frontend["Next.js 16 Dashboard"]
        UI["App Router + Supabase Auth"]
    end
    UI -->|"REST"| API
Loading

Design decisions worth calling out:

  • Sync vs. async split by SLA, not by endpoint type. /scrape and /search return inline because they're bounded; /map and /agent/extract are queued because a full crawl or an LLM round-trip can legitimately take minutes — forcing them synchronous would just trade a clean 202 for gateway timeouts.
  • Fetch escalation, not dual-fetch by default. Every request tries HTTPX first. Playwright — with a pooled, reused browser context via PlaywrightBrowserPool — only spins up when heuristics detect a JS-rendered shell, keeping the common case cheap.
  • Idempotency and dedup are first-class, not bolted on: X-Idempotency-Key prevents duplicate job creation, and every fetched page is keyed by a normalized-URL hash so re-scraping a known page hits the cache instead of the network.
  • SSRF isn't a checkbox. The guard blocks private/link-local/loopback CIDR ranges, resolves hostnames before connecting (not just string-matching them), and restricts schemes — closing the classic "fetch http://169.254.169.254" cloud-metadata attack.

Feature Set

Capability Endpoint Behavior
Scrape POST /api/v1/scrape Synchronous single-URL extraction to clean Markdown, metadata, and internal/external link maps. Auto-detects when JS rendering is required.
Map POST /api/v1/map Asynchronous breadth-first crawl that discovers and indexes every internal URL on a site up to configurable depth/page limits.
Search POST /api/v1/search Web search (Serper) with optional top-N result scraping in a single round-trip.
Agent Extract POST /api/v1/agent/extract Give it a URL, a prompt, and a JSON schema — Gemini returns structured data extracted from the page.
Jobs GET /api/v1/jobs/{id} · /results Poll status/progress or fetch the final payload for any async job.

Platform-level reliability:

  • SSRF protection with private-range blocking, scheme allowlisting, and DNS-resolved validation
  • Robots.txt compliance (togglable per request)
  • Sliding-window per-API-key rate limiting
  • Exponential-backoff retries (tenacity) on transient network failures
  • URL-hash based response caching with configurable TTL
  • Structured JSON logging (structlog) with request-ID correlation across the API and worker
  • Health endpoint that independently checks Postgres, Redis, and Playwright/Chromium liveness

Tech Stack

Backend

  • FastAPI + Pydantic v2 — async API layer with typed request/response contracts
  • SQLAlchemy 2.0 (async) + asyncpg — PostgreSQL ORM
  • ARQ + Redis — background job queue and worker orchestration
  • Playwright (pooled contexts) + HTTPX — dual-mode fetching
  • Trafilatura, readability-lxml, markdownify, BeautifulSoup — content extraction and HTML→Markdown pipeline
  • Google Gemini (google-genai) — structured extraction agent
  • structlog, Sentry — observability
  • pytest / pytest-asyncio / pytest-httpx — 40+ tests across scrape, map, search, agent, auth, and admin surfaces

Frontend

  • Next.js 16 (App Router) + React 19 + TypeScript
  • Supabase — auth (OAuth + email) and session management
  • TanStack Query + Zustand — server-state and client-state management
  • Tailwind CSS 4, Framer Motion, Recharts — dashboard UI, motion, and analytics charts

Infrastructure

  • Backend deployed on Railway (Nixpacks build, /health-gated rollout with auto-restart)
  • Frontend deployed on Vercel
  • PostgreSQL for durable state, Redis for the job queue

Project Structure

distill/
├── backend/
│   ├── app/
│   │   ├── routers/        # scrape, map, search, agent, jobs, admin, auth, metrics
│   │   ├── services/       # fetcher, extractor, crawler, llm, robots, url_utils (SSRF)
│   │   ├── worker/         # ARQ worker entrypoint + pooled Playwright browser manager
│   │   ├── tasks/          # scheduled cleanup jobs
│   │   ├── db/             # SQLAlchemy models + async session
│   │   └── middleware/     # request logging / correlation IDs
│   └── tests/              # pytest suite (unit + integration)
├── frontend/
│   ├── app/
│   │   ├── (marketing)/    # public landing page
│   │   ├── (auth)/         # login, signup, password reset
│   │   └── (dashboard)/    # playground, jobs, api-keys, usage, billing, docs, settings
│   ├── components/         # layout, shared UI primitives
│   └── lib/                # api client, Supabase clients, state store
└── docker-compose.yml       # API + Postgres + Redis for local dev

Data Model

Table Purpose
api_keys Hashed keys, per-key scopes, rate limits, and user_id linkage to Supabase accounts
jobs Async job lifecycle — type, status, input params, idempotency key, progress, timing
pages Cache layer keyed on normalized-URL hash — markdown, metadata, links, fetch diagnostics
job_pages Many-to-many join recording crawl depth per discovered page
extractions Structured JSON output from agent/extract, linked back to its source page
events Structured event log for observability, keyed by API key and job

Getting Started

Prerequisites

  • Python 3.10+
  • Node.js 18+
  • PostgreSQL and Redis (or just run docker-compose up postgres redis)
  • Gemini API key (AI Studio)
  • Serper API key (optional — enables /search)

Backend

cd backend
pip install -r requirements.txt
playwright install chromium

# .env
DATABASE_URL=postgresql+asyncpg://user:password@localhost:5432/webextract
REDIS_URL=redis://localhost:6379
GEMINI_API_KEY=your_gemini_key
SERPER_API_KEY=your_serper_key
SECRET_KEY=your_secret_key
ADMIN_KEY=your_admin_key

python seed_api_key.py            # bootstrap an API key
uvicorn app.main:app --reload --port 8000    # API
python -m app.worker.arq_worker   # background worker (separate process)

Frontend

cd frontend
npm install

# .env.local
NEXT_PUBLIC_API_URL=http://localhost:8000
NEXT_PUBLIC_SUPABASE_URL=your_supabase_url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key

npm run dev

Everything, containerized

docker-compose up

Tests

cd backend
pytest

API Reference

Base URL: https://api.distill.dev/api/v1 (or http://localhost:8000/api/v1 locally) Auth: X-API-Key: sk_your_key on every request.

curl -X POST https://api.distill.dev/api/v1/scrape \
  -H "X-API-Key: sk_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com",
    "use_playwright": "auto",
    "include_links": true,
    "respect_robots": true
  }'
{
  "url": "https://example.com",
  "title": "Example Domain",
  "markdown": "# Example Domain\n\nThis domain is for use in illustrative examples...",
  "metadata": { "word_count": 123, "language": "en" },
  "links": { "internal": [], "external": ["https://www.iana.org/domains/example"] },
  "cached": false
}
Method Path Description
POST /scrape Synchronous single-URL extraction
POST /map Start an async site-mapping job
POST /search Web search with optional top-N scraping
POST /agent/extract Async schema-guided extraction via Gemini
GET /jobs/{id} Job status and progress
GET /jobs/{id}/results Job output
GET /health Liveness — checks DB, Redis, and Playwright independently

Full interactive reference (OpenAPI/Swagger) is served at /docs on the running API.

Security

  • SSRF protection — DNS-resolved hostname validation against private/loopback/link-local CIDR ranges, not string matching; blocks file://, ftp://, data:, and javascript: schemes outright
  • Robots.txt compliance — enforced by default, togglable per request
  • API-key authentication — SHA-256 hashed at rest, never stored or logged in plaintext
  • Rate limiting — sliding window, enforced per key
  • CORS allowlisting — explicit origin list, no wildcard in production

Contributors


Built for developers who need the web in a format a machine can actually reason about.

About

Distill — Turn any URL into clean, structured data for AI pipelines, RAG systems, and intelligent agents.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages