---
title: "Where Is the Proxy in an LLM Data Pipeline? Fetch and Log"
description: "In an LLM data pipeline the proxy sits only in the fetch stage. Which fields to log on every fetch, retry rules and how the country changes the content."
url: https://proxynet.io/blog/llm-data-pipeline-proxy-stage
date: 2026-12-03
author: "Acar Diveroli"
category: "AI"
lang: en
---

# Where Is the Proxy in an LLM Data Pipeline? Fetch and Log

An LLM data pipeline is the chain of stages that turns web pages into pieces a model or a RAG index can read. It runs through five stages: source list, fetch, cleaning, chunking and storage. The proxy sits only in the fetch stage. The later stages never go out to the network; they read the files the fetch left behind. The trap is a failed fetch that quietly flows into cleaning and chunking. This post covers where the proxy sits in the pipeline, the fields of the fetch record, retry rules and how the country changes the content.

> **Note: Short answer**
>
> In an LLM data pipeline the proxy sits only in the fetch stage. On every fetch, log the source URL, the time, the requested country, the HTTP status code and the SHA-256 hash of the body. Never pass a failed fetch on to cleaning.

## The five stages of the pipeline

Only one stage of the pipeline connects to outside sites: the fetch. The source list says which URL to fetch from which country. Cleaning, chunking and storage work on the raw body on disk.

| Stage | Input | Output | Proxy |
|---|---|---|---|
| Source list | Domains, URLs | URL + country jobs | ✗ |
| Fetch | URL + country | Raw body + fetch record | ✓ |
| Cleaning | Raw body | Main text | ✗ |
| Chunking | Main text | Chunks | ✗ |
| Storage | Chunks + record | Index | ✗ |

This split has three practical results. The proxy address and password live in a single module. The country is decided in one place. When you change a cleaning rule, you do not revisit the sites; you reprocess the raw bodies on disk.

The source list stage checks robots.txt and the site's terms before the fetch. A disallowed path never enters the list. We covered the cleaning and chunking steps in our post on the [RAG data pipeline](/blog/web-scraping-for-rag). This post looks only at the fetch stage.

## Fields of the fetch record

A fetch record is a one-line JSON object that describes the result of each attempt. Lines are appended to a file in JSON Lines format: every line is a standalone JSON value. The raw body lives in a separate folder, in a file named after its own SHA-256 hash.

| Field | Example | What it is for |
|---|---|---|
| `url`, `final_url` | `/docs`, `/tr/docs` | Shows redirects |
| `fetched_at` | `2026-12-02T23:52:55+00:00` | Freshness and refresh order |
| `country` | `TR` | Which country version was fetched |
| `status` | `200`, `403`, `null` | Success and error type |
| `content_type`, `content_language` | `text/html`, `tr` | Is this the expected content |
| `sha256`, `bytes` | `f024ce…`, `39` | Identity of the raw body |
| `attempt`, `error` | `2`, `ProxyError` | Which attempt, and what happened |

Always write the time in UTC and in ISO 8601 format. Only then can fetches that run on different machines be put in order.

The `sha256` field is the hash of the raw bytes. The same hash means the same bytes arrived, and it saves you from storing a second copy. Even when the page content is identical, a session token or a date line in the HTML changes the hash. So measure text-level duplication separately, after cleaning. One more trap: a hash starting with `e3b0c442…` is the SHA-256 of an empty body. If you see it next to status `200`, the page came back empty.

The `country` field holds the country you asked for, not a verified exit country. Verification takes a separate request. You do not need it on every page: one check with an IP echo service at the start of each job batch is enough.

## The fetch function

The function takes a URL and a country and returns a record plus the body, if there is one. The country is selected in the proxy address, in the format your provider documents. The function receives that address through the `proxy` parameter and writes the country into the record.

```python
import hashlib
import time
from datetime import datetime, timezone

import requests

PROXY = "http://user:pass@pr.proxynet.io:8000"
RETRY = {429, 502, 503, 504}

def fetch(url, country, proxy=PROXY, tries=3):
    proxies = {"http": proxy, "https": proxy}
    for n in range(1, tries + 1):
        rec = {
            "url": url,
            "country": country,  # requested exit country
            "attempt": n,
            "fetched_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        }
        try:
            r = requests.get(url, proxies=proxies, timeout=(5, 30))
        except requests.RequestException as e:
            rec.update(status=None, ok=False, error=type(e).__name__)
            if n < tries:
                time.sleep(2 ** n)
            continue
        rec.update(
            status=r.status_code,
            final_url=r.url,
            content_type=r.headers.get("Content-Type", ""),
            content_language=r.headers.get("Content-Language", ""),
            bytes=len(r.content),
            sha256=hashlib.sha256(r.content).hexdigest(),
            error=None,
        )
        if r.status_code in RETRY and n < tries:
            wait = r.headers.get("Retry-After", "")
            time.sleep(min(int(wait), 60) if wait.isdigit() else 2 ** n)
            continue
        rec["ok"] = r.status_code == 200 and "text/html" in rec["content_type"]
        return rec, (r.content if rec["ok"] else None)
    return rec, None
```

The record is always appended to the file. The body is written to disk only when `ok` is true.

```python
import json
from pathlib import Path

rec, body = fetch("https://example.com/docs", country="TR")
with open("fetch_log.jsonl", "a", encoding="utf-8") as f:
    f.write(json.dumps(rec, ensure_ascii=False) + "\n")
if body:
    Path("raw", rec["sha256"] + ".html").write_bytes(body)
```

Every attempt starts with a fresh record object. The hash or status code of the previous attempt cannot leak into the next one. The timeout has two parts: 5 seconds to connect, 30 seconds to read. Without a timeout, a request in Requests can wait forever.

## Retry rules

Retry only on transient errors. A transient error is one where the same request may succeed a little later: `429`, `502`, `503`, `504` and dropped connections. `403` and `404` are not transient. Repeating them does not change the result; it only adds load on the site.

| Case | Retry | What the record shows |
|---|---|---|
| `429`, `503` | ✓, wait for `Retry-After` | Code of the last attempt |
| `502`, `504` | ✓, growing wait | Code of the last attempt |
| Connection error | ✓, growing wait | `status: null`, `error` set |
| `403`, `404` | ✗ | One attempt, `ok: false` |
| `407` | ✗ | Fix the proxy credentials |

The `Retry-After` header can carry seconds or an HTTP date. The function reads only seconds and falls back to exponential waiting for a date. The wait is capped at 60 seconds. A longer value tells you to leave that source for this round. We showed growing waits in detail in our post on [429 and exponential backoff](/blog/proxy-429-exponential-backoff-python).

Keep the number of attempts low. Three attempts cover a brief outage. If you still get `429` after the third, your rate is too high for the site. The fix is not more attempts but fewer requests.

## Country choice and content

The same URL can return different content from different countries. The server picks the language, the currency or the help text based on the visitor's location. Sometimes it redirects to a country version. That is why the country is part of the fetch record's key. If you fetched `/docs` from a TR and a DE exit, you have two separate records and two separate bodies.

Three fields in the record show the difference. `final_url` shows the redirect, `content_language` the language, and `sha256` whether the body changed. A server can state with the `Vary` header which request details the response depends on. A page that changes by location does not always say so in a header.

Choose the country based on your users. An assistant that answers users in Türkiye should be fed the page as seen from Türkiye. An index built from the wrong country version produces answers from prices or instructions the user has never seen. We explained the mechanics in our post on [country and city targeting](/blog/geo-targeting-proxy-explained). To pick a country with home-connection IPs, use [Residential Proxy](https://proxynet.io/residential-proxy).

## Keeping errors in their stage

A fetch error should stay in the fetch stage. Cleaning reads only records with `ok: true` and their bodies. Failed records stay in the same file but never reach the next stage. In the next round, only these are retried.

The sneakiest error is a wrong page with status `200`. A cookie consent screen, a maintenance page or an empty template can arrive with `200`. Chunking splits that text, and the index stores "Down for maintenance…" as knowledge. The `ok` condition in the function is the most basic check: status `200` and HTML content.

Add one more validation rule per source. Three rules catch most cases:

- **Minimum size.** A documentation page shorter than a few hundred bytes is suspicious.
- **Expected language.** If `content_language` differs from the expected language, the country or the redirect is wrong.
- **Expected marker.** If a heading or text that every page of the source carries is missing, the page is a different template.

When a record fails a rule, set `ok` to `false` and write the reason into `error`. With the reason in the record, one query tells you whether the problem is the source, the proxy or the rule.

## Debugging

The fetch record is the diagnosis itself. Where to look first, by symptom:

- **`ProxyError` in every record.** The proxy address is unreachable, or the password is wrong on an HTTPS target. For an HTTPS target, Requests reports `407` not as a status code but as a `ProxyError` exception. Retrying is pointless until you fix the credentials.
- **`status: 407` on an HTTP target.** The same password problem, this time as a status code.
- **`200` with an `e3b0c442…` hash.** The body is empty. The page may build its content with JavaScript.
- **Unexpected `content_language`.** The requested and the actual exit country differ, or the site redirected you to another language version. Check the `final_url` field.
- **Repeated `429` on the same URL.** Your request rate to the site is too high. Widen the interval for this source.

## How we tested

We ran the function on 3 December 2026 with Python 3.13 and Requests 2.34.2. The setup was local: an HTTP proxy that required `user:pass` and logged every request, plus a test site with five paths. The page that returned `503` on the first request came back with `200` on the second, and the record showed `attempt: 2`. The page that always returned `429` was tried three times and logged with `ok: false`. The page that returned `403` was requested once. The page that returned `200` with `application/pdf` got `ok: false`. A wrong password produced `status: 407` on an HTTP target, and a proxy on a closed port produced `ProxyError`. In a separate run, a proxy that returned `407` to an HTTPS target also produced `ProxyError`.

## The bottom line

Keep the proxy in the fetch stage, write every attempt as a one-line record and store the body under its hash. Make the country part of the record's key and retry only transient errors. Above all, stop wrong pages with status `200` from entering the index. We gathered the infrastructure side of this kind of collection work on our [data scraping](/data-scraping) page.

## Sources

- [RFC 9110, §10.2.3 Retry-After, §12.5.5 Vary, §15.6.4 503: rfc-editor.org](https://www.rfc-editor.org/rfc/rfc9110)
- [RFC 6585, §4 429 Too Many Requests: rfc-editor.org](https://www.rfc-editor.org/rfc/rfc6585)
- [Requests documentation, Advanced Usage, Proxies and Timeouts: requests.readthedocs.io](https://requests.readthedocs.io/en/latest/user/advanced/#timeouts)
- [JSON Lines format specification: jsonlines.org](https://jsonlines.org/)

## Frequently asked questions

### At which stage of an LLM data pipeline is a proxy used?

Only at the fetch stage. The source list decides which URL to fetch from which country. The fetch runs those jobs through the proxy and writes the raw body to disk. Cleaning, chunking and storage work with the files on disk and never connect to outside sites. Thanks to this split, the proxy settings live in one module. When a cleaning rule changes, you reprocess the bodies without revisiting the sites.

### Which fields should a fetch record contain?

At least seven: the source URL, the final URL, the UTC fetch time, the requested country, the HTTP status code, the content type and the SHA-256 hash of the body. The attempt number and the error name make diagnosis easier. The `Content-Language` header shows the language version. Append records line by line to a JSON Lines file and store the body in a separate file named after its hash.

### Which HTTP errors should be retried?

Only transient ones: `429`, `502`, `503`, `504` and dropped connections. If a `429` or `503` response carries a `Retry-After` header, wait that long. If not, double the wait on every attempt. `403` and `404` are not retried, because the result does not change. `407` means the proxy credentials are wrong. After three attempts, leave the source for the next round.

### How does the country choice change the fetched content?

The server can pick the language, the currency and the text based on the visitor's location. Sometimes it also redirects to a country version. The same URL can return two different bodies from two countries. So make the country part of the record's key and compare the `final_url`, `content_language` and `sha256` fields. Choose the country based on where the people who will use your assistant are.

### Why is the content hash taken from the raw body?

The raw body is the only fixed output of the fetch. The hash prevents storing the same bytes twice and ties the file to its record. Even if a cleaning rule changes, the raw file's name stays the same. Measure text-level duplication separately, after cleaning. A date line or a session token in the HTML changes the raw hash even when the content is identical.

### How do you filter out a page that returns 200 but is wrong?

With source-specific validation rules. Status code and content type are the first check. Then look at minimum size, expected language and a marker that is always present on the page. A cookie screen or a maintenance page trips one of these rules. Set the failing record to `ok: false`, write the reason into `error` and do not send it on to cleaning.
