Pacing, Retries and Checkpoints for Long Text Pipelines

Many useful AI projects are not chats at all but long pipelines. Hobbyists build tools that turn DRM-free e-books into chaptered audiobooks, processing a whole book in one go; others summarise a folder of reports, translate product descriptions or tag thousands of support tickets. On their own GPU they can push as fast as the hardware allows. Through an API, they run into rate limits, timeouts and the occasional busy server.
This guide shows how to design a batch job that respects an API's limits, survives errors and can be stopped and resumed without losing work. The examples use the keyless endpoint on this site, whose limits are documented, but the same pattern applies to any OpenAI-compatible provider, including paid ones and your own vLLM or llama.cpp server.
It is written for developers comfortable with basic Python. By the end you will have a small, reusable script structure: split input into chunks, pace requests, retry politely, write results incrementally and resume where you left off.
Frequently asked questions
What is a rate limit?
It is a cap on how many requests or tokens a client may send in a period. Providers use it to share capacity fairly. Exceeding it usually returns HTTP 429, often with a header saying how long to wait.
How does a 429 differ from a 503?
A 429 means you, specifically, are sending too much and should slow down. A 503 means the server is busy or temporarily unavailable for everyone; waiting a few seconds and retrying is usually enough.
What is a checkpoint in a batch job?
It is a saved record of which items are already done. If the job stops, it reads the checkpoint on restart and skips completed items instead of starting over.
Why not just send everything in parallel?
Because the provider will reject most of it. Parallel requests beyond the allowed concurrency produce errors, waste time on retries and may lead to longer blocks. Steady pacing at the allowed rate finishes sooner.
How large should each chunk be?
Large enough to give the model context, small enough to fit comfortably within the context window with room for the answer. Splitting at natural boundaries such as chapters, sections or paragraphs keeps chunks coherent.
Which is better for batch work: a local GPU or an API?
A local GPU has no rate limits and keeps data private, so it suits large or sensitive jobs. An API needs no hardware and suits moderate jobs with non-sensitive data. Many people prototype on an API and move big runs to local hardware.
Can I use streaming in batch jobs?
You can, but it rarely helps. Streaming improves perceived latency for a human reader. In a batch job, a normal request is simpler to handle and retry.
How do I keep a long job from running up costs on a paid API?
Set a token budget, log usage from each response, stop when the budget is reached, and test on a small sample first. A free endpoint avoids cost but has fixed daily limits instead.
Step by step
- Write down the limits — Record rate, concurrency, daily allowance, context and output caps for your provider and estimate the job size.
- Chunk the input — Split at natural boundaries, keep chunks well under the context limit and give each a stable identifier.
- Add pacing and retries — Use a shared limiter at slightly under the allowed rate, honour Retry-After on 429 and back off on 503.
- Checkpoint every result — Append each result to a JSON Lines file and skip completed identifiers on restart.
- Test, then run — Process ten items, fix the prompt and format, then start the full job and review failed items in a second pass.
Know the limits before you start
Every provider documents limits differently: requests per second or minute, concurrent requests, tokens per day, context size and maximum answer length. Write them down for the provider you use, because your job design follows from them.
For the keyless API here, the limits per IP are one request per second with bursts of three, two requests in parallel, and 10,000 requests or 10,000,000 tokens per day, resetting at 00:00 UTC. Context is 32,000 tokens, answers up to 16,000. The model is free-ai, an independent open-weight model of about 35B parameters, served at https://api.apifreenvidia.com/v1.
Estimate the job size
Count items and approximate tokens per item, input plus output. Multiply to see whether the job fits in a day's allowance and how long it will take at one request per second. A thousand chunks take at least about seventeen minutes at that pace.
Who runs the service matters
This endpoint is an independent service; APIFreeNVIDIA is not affiliated with NVIDIA, and it does not provide access to NVIDIA-hosted models. If you use a different provider, look up its current limits page rather than assuming any numbers.
Split input into sensible chunks
Good chunking makes everything else easier. Split at natural boundaries: chapters for books, sections for reports, rows for tables. Keep each chunk well below the context limit, leaving room for your instructions and the answer.
Give each chunk a stable identifier, such as file name plus chunk number. The checkpoint uses it to know what is done, so it must not change between runs.
Binary formats such as e-books or office files should be converted to plain text first, with headings preserved, so the chunker sees clean structure instead of markup.
Overlap for continuity
For tasks like summarising a narrative, include the last paragraph of the previous chunk at the start of the next. The model then keeps names and context straight across boundaries.
Measure, do not guess
A quick rule of thumb is about four characters per token for English, but languages and formats vary. Check the token counts the API returns for your first few chunks and adjust.

Pace requests with a simple limiter
The simplest pacing is a shared clock: before each request, wait until at least one second has passed since the previous one. With two worker threads, that keeps you at the allowed rate and the allowed concurrency at the same time.
The code below implements a small thread-safe limiter. It uses requests and sets an explicit User-Agent, which this API expects; requests with Python urllib's default agent are rejected.
Leave a small margin
Pacing at slightly more than one second per request absorbs clock jitter and network delays, so you rarely hit 429 at all. The small margin costs little in total time.
import threading
import time
class Pacer:
"""Allow at most one call per `interval` seconds across all threads."""
def __init__(self, interval=1.05):
self.interval = interval
self.lock = threading.Lock()
self.next_at = 0.0
def wait(self):
with self.lock:
now = time.monotonic()
start = max(now, self.next_at)
self.next_at = start + self.interval
time.sleep(max(0.0, start - now))Retry politely on 429 and 503
Errors will happen in any long job. Handle them by type. On 429, read the Retry-After header and wait that long. On 503 or other temporary server errors, wait a few seconds, increasing the wait with each attempt. On client errors such as 400, stop and log the item, because retrying will not fix a bad request.
Cap the retries
A fixed number of attempts prevents an item from blocking the job forever. Log failed items and process them in a second pass after the main run.
Watch the daily allowance
If you hit 429 repeatedly with long waits, you may have used up the daily quota. Stop the job and resume after the reset rather than retrying through the night.
import requests
URL = "https://api.apifreenvidia.com/v1/chat/completions"
HEADERS = {"User-Agent": "batch-pipeline/1.0"}
pacer = Pacer()
def ask(prompt, max_tokens=800, attempts=6):
for attempt in range(attempts):
pacer.wait()
try:
r = requests.post(URL, headers=HEADERS, timeout=180, json={
"model": "free-ai",
"messages": [{"role": "user", "content": prompt}],
"max_tokens": max_tokens,
"temperature": 0.3,
})
except requests.RequestException:
time.sleep(3 * (attempt + 1))
continue
if r.status_code == 200:
data = r.json()
return data["choices"][0]["message"]["content"], data.get("usage", {})
if r.status_code == 429:
time.sleep(float(r.headers.get("Retry-After", 2)))
continue
if r.status_code in (502, 503, 504):
time.sleep(2 + 2 * attempt)
continue
raise RuntimeError(f"HTTP {r.status_code}: {r.text[:200]}")
raise RuntimeError("gave up after retries")
Write results incrementally and resume
Never hold all results in memory until the end. Append each result to a JSON Lines file as soon as it arrives. On startup, read that file, collect the identifiers already done and skip them. A crash, a reboot or a manual stop then costs only the items in flight.
With two worker threads, use a lock around file writes so lines do not interleave.
Keep inputs and outputs separate
Store original chunks in one place and model outputs in another. You can then rerun with a different prompt or model without re-chunking, and compare versions side by side.
import json
import os
from concurrent.futures import ThreadPoolExecutor
OUT = "results.jsonl"
write_lock = threading.Lock()
def done_ids():
if not os.path.exists(OUT):
return set()
with open(OUT, encoding="utf-8") as f:
return {json.loads(line)["id"] for line in f if line.strip()}
def process(item):
text, usage = ask("Summarise this section in five sentences:\n\n" + item["text"])
with write_lock, open(OUT, "a", encoding="utf-8") as f:
f.write(json.dumps({"id": item["id"], "summary": text, "usage": usage}) + "\n")
def run(items):
skip = done_ids()
todo = [it for it in items if it["id"] not in skip]
with ThreadPoolExecutor(max_workers=2) as pool: # matches the 2-parallel limit
for _ in pool.map(process, todo):
passTest on a sample first
Run the pipeline on ten items before the full job. Check that answers have the format you need, that token usage matches your estimate and that the prompt handles edge cases, such as very short chunks, tables or dialogue.
Adjust the prompt now, while changes are cheap. Rerunning a thousand items because of a formatting problem wastes a day's allowance.
Keep a short run report for each batch: start and end time, number of items, failures, total tokens and the prompt version used. When you rerun the job months later with a new model or a revised prompt, that report lets you compare speed, cost and quality honestly. It also helps you notice slow drifts, such as a growing share of retries on certain hours of the day, that point to a busy provider window you could avoid by scheduling the job differently.
Ask for structured output
If later steps parse the output, ask for JSON with fixed keys and validate each response. Put invalid ones in the retry list instead of letting them break downstream processing.
Fix sampling settings
A low temperature makes outputs more consistent across a large batch, which matters when results are compared or merged.

Privacy and the request log
Every request to a hosted API leaves a technical log on the provider's side. For this endpoint, that log holds time, IP, User-Agent, country, endpoint, status, latency, sizes and token counts; no conversation history is kept between calls. Even so, do not send material you are not allowed to share, such as client documents or personal data.
For sensitive collections, run the same pipeline against your own server. Because the script uses the OpenAI request format, switching is mostly a change of URL and model name. The guide to falling back between local and hosted backends shows how to keep private items local automatically.
Mind the content you process
The model behind this endpoint refuses less than many commercial assistants, but it keeps two hard rules: no sexual content involving minors and no operational instructions for mass-casualty weapons. Batch jobs that hit those rules will receive refusals, not results.
When to move the job to your own GPU
Rate limits become the bottleneck as jobs grow. If you regularly process tens of thousands of chunks, a local engine with batching will finish far faster, because it can serve many requests at once. Engines such as vLLM excel at exactly this pattern, as described in the comparison of inference engines.
Running long jobs locally brings its own concerns, such as heat and power. Scheduling them overnight and keeping hardware cool, as covered in the cooling guide, keeps both the machine and the room comfortable.
Quality versus scale
For complex tasks where quality matters more than volume, a large commercial model may still be the right choice despite cost. Run your sample on both and decide based on results, not on habit.

Send a prompt from the chat box on the home page: no key, no account and no card, just a quick look at how free-ai answers.
Read also
- Why Does the Same Model Have Different Context Limits on APIs?
- How to Keep Compact AI Boxes Cool During Long Inference Jobs
- Can a Huge Language Model Really Run on a CPU With Little RAM?
- Is Modding Your GPU or Edge Board Yourself Worth the Risk?
- vLLM vs llama.cpp vs Ollama: Which Inference Engine Fits You?