Why Non-Realtime Work Should Cost Less
A request that nobody is waiting on is an easier thing to serve than one that is. Providers can pack deferrable jobs into whatever capacity they have spare, they can run them in off-peak windows, and they can retry them without a human noticing. That is why non-realtime work is generally billed below interactive work — and why the same prompt can cost meaningfully less when it is part of a 50,000-row backfill rather than a chat box.
The exact rates change, so check aicreditsapi.com/pricing for what applies today instead of trusting a number written in any blog post, including this one. The engineering discipline below is what actually moves your bill, and it stays true regardless of the rate card.
Two Kinds of Batching — Pick Deliberately
"Batch processing" gets used for two very different setups, and confusing them is how teams end up with a pipeline that neither saves money nor finishes on time.
| Dimension | Provider batch endpoint | Your own queue |
|---|---|---|
| What it is | Upload a JSONL job file, collect results later | Fan out normal requests with a thread pool or queue |
| Pricing | Billed at the provider's non-realtime rate | Standard request rates; savings come from cache hits, off-peak windows, and cheaper models |
| Latency | Turnaround measured in hours, no per-item guarantee | You control it; results land as they complete |
| Control | Limited — you mostly wait | Full: retries, splitting, partial results, escalation |
| Best for | Huge one-shot backfills where nothing is urgent | Recurring pipelines that need results the same day |
Most teams want the second column. It works with any OpenAI-compatible endpoint — including AiCredits' access to deepseek-v4-flash and deepseek-v4-pro — and it gives you the levers that matter: cache-friendly prompts, off-peak scheduling, and the ability to send only the hard 2% to a stronger model.
A Resumable Batch Runner in Python
The expensive failure in batch work is not a slow request. It is a job that dies at 80% and reruns from zero. An append-only JSONL file keyed by your own stable ID gives you free resumability: kill the process, restart it, and it picks up where it stopped.
import json, os, random, time
from concurrent.futures import ThreadPoolExecutor, as_completed
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
MODEL = "deepseek-v4-flash"
ALLOWED = {"billing", "bug", "feature", "other"}
RETRYABLE = ("429", "500", "502", "503", "504")
SYSTEM = (
"You triage support tickets. Reply with JSON only, no markdown, no prose: "
'{"category": "billing|bug|feature|other", "urgency": "low|high"}'
)
def classify(item, attempts=5):
for n in range(attempts):
try:
r = client.chat.completions.create(
model=MODEL,
messages=[
{"role": "system", "content": SYSTEM},
{"role": "user", "content": item["text"]},
],
response_format={"type": "json_object"},
temperature=0,
max_tokens=64,
)
data = json.loads(r.choices[0].message.content)
if data.get("category") not in ALLOWED:
raise ValueError(f"schema mismatch: {data}")
return {"id": item["id"], "category": data["category"], "urgency": data["urgency"]}
except Exception as e:
if any(code in str(e) for code in RETRYABLE) and n < attempts - 1:
time.sleep(2 ** n + random.random())
continue
raise
def run(items_path, out_path, workers=8):
items = [json.loads(l) for l in open(items_path) if l.strip()]
done = set()
if os.path.exists(out_path):
with open(out_path) as f:
done = {r["id"] for r in (json.loads(l) for l in f if l.strip()) if "id" in r}
todo = [i for i in items if i["id"] not in done]
print(f"{len(done)} done, {len(todo)} queued")
with open(out_path, "a") as out, ThreadPoolExecutor(max_workers=workers) as pool:
for fut in as_completed([pool.submit(classify, i) for i in todo]):
try:
out.write(json.dumps(fut.result()) + "\n")
except Exception as e:
out.write(json.dumps({"error": str(e)}) + "\n")
out.flush()
if __name__ == "__main__":
run("tickets.jsonl", "tickets_out.jsonl")
Three details make this hold up in production. First, the writer runs in the main thread while workers only compute — no interleaved writes, no corrupted lines. Second, a failed row is written without an id, which means the resume logic will retry it on the next pass instead of silently skipping it. Third, the ID is yours, not the provider's: it is the idempotency key that makes re-runs safe.
Chunk Long Inputs Before You Fan Out
Documents, transcripts, and logs blow past context limits in ways that fail halfway through a run. Chunk first with a small overlap so sentences and table rows survive the boundary; deduplicate at the merge step rather than trying to make the chunks perfectly clean.
def chunk(text, size=6000, overlap=400):
if size <= overlap:
raise ValueError("size must exceed overlap")
chunks, start = [], 0
while start < len(text):
end = min(start + size, len(text))
chunks.append(text[start:end])
if end == len(text):
break
start = end - overlap
return chunks
doc = open("contract.txt").read()
parts = chunk(doc)
print(len(parts), "chunks, sizes:", [len(c) for c in parts])
Design Prompts So the Cache Can Hit
Cached input is billed less than fresh input, and the cheapest cache hit is the one you designed for on day one. Cache matching works on the prompt prefix, so ordering is everything.
Static first, variable last: instructions, output schema, and few-shot examples at the top; the ticket text or document chunk at the bottom.
Keep the prefix byte-identical: a timestamp, a run ID, or a "today is…" line in the system prompt invalidates every cached token after it.
Version your prompts instead of editing them in place — old batches should keep matching their old prefix.
Do not shuffle few-shot examples between runs. Reordering them is a new prefix, and a new prefix is a full-price call.
A batch job you can resume is worth more than a faster one you can't.
Sort Failures Before You Retry Them
Blanket retries on a batch of 50,000 turn one bad prompt into a rate-limit storm. Classify the error first.
Rate limits and 5xx: retry with exponential backoff plus jitter, and lower the worker count. Sustained 429s mean your concurrency is the problem, not the provider.
Context-length errors: never retry. Split the input, requeue the halves.
Schema mismatches or empty output: retry once at temperature 0, then escalate that item to deepseek-v4-pro rather than looping.
Timeouts: treat as unknown, not failed. Re-submit only after checking your ID store if the downstream action has side effects.
A Two-Tier Quality Check Beats a Uniform Model Choice
The default that works for most backfills: run everything on deepseek-v4-flash, then send a random sample and every escalated failure through deepseek-v4-pro. Compare labels on the overlap. If agreement is high, ship the flash output and keep the audit as a regression check. If it is not, tighten the schema or move that specific category up to pro permanently. Pro costs more per call than flash, so spend it where disagreement actually lives instead of paying for it across the whole corpus.
Scheduling and Concurrency Discipline
Run recurring batches in off-peak windows — off-peak usually costs less and queues are shorter. Start at four to eight workers, not fifty; the wall-clock difference between eight and fifty is often small, while the failure rate difference is not. Submit work in pages of a few thousand items rather than loading the whole corpus into memory, and keep the output file append-only so a crash costs you one page, not the run.
FAQ
No. A provider batch endpoint is billed at a non-realtime rate and is usually the cheapest option for large backfills. Client-side batching does not get a discount by itself — the savings come from prompt caching, off-peak windows, and routing bulk work to a cheaper model like deepseek-v4-flash. If your job is a few hundred short prompts due in ten minutes, plain synchronous calls are fine.
Not for anything a user is waiting on. Batch output arrives out of order and with no per-item latency guarantee. Use it for backfills, nightly re-scoring, enrichment, moderation sweeps, and evaluation runs.
No. You are calling the same deepseek-v4-flash or deepseek-v4-pro either way. What changes is scheduling and rate, not the weights — so a batch classification should match an interactive one, given the same prompt.
That is what the append-only JSONL file is for. Rerun the script; rows whose ID already appears in the output file are skipped, and rows that failed (written without an ID) are retried. No state server required.
AiCredits sells DeepSeek API credits to international developers and accepts card or PayPal — no Chinese phone number or bank account needed. The endpoint is OpenAI-compatible, so the code above runs unchanged with your key from aicreditsapi.com.