Claude API Batch Summarization for Large Datasets
If you need to summarize thousands of support tickets, legal documents, transcripts, or research papers, calling the Claude API one document at a time will work — but it will be slow, expensive to debug, and easy to break on rate limits. Batch summarization at scale requires a different design than a single chat completion: you need chunking, controlled concurrency, retry handling, and a way to track token usage across the whole run.
This article walks through a practical pattern for summarizing large datasets with Claude: splitting input correctly, writing a prompt that produces consistent output across thousands of calls, running requests concurrently without tripping rate limits, and handling documents that are too long for a single context window using map-reduce summarization.
Why batch jobs behave differently than chat requests
A single chatbot-style call to Claude tolerates latency and occasional errors — a user just waits a second longer. A batch job summarizing 10,000 rows does not tolerate that gracefully: a 2% failure rate means 200 failed summaries you have to detect, log, and retry. The main engineering problems in batch summarization are:
- Throughput: how many requests you can run in parallel before hitting rate limits.
- Consistency: making sure every summary follows the same structure, length, and tone.
- Cost visibility: knowing token usage per batch, not just per request.
- Long inputs: documents that exceed context limits need to be chunked and summarized hierarchically.
Step 1: Chunk the dataset, not just the text
Before writing any prompt, decide the unit of work. For most datasets this is one row = one API call (one ticket, one transcript, one article). Keep each unit small enough to summarize in a single request — if a document is under roughly 15–20k tokens, you usually don't need to split it further.
For documents that are longer than that, split them into sections first (by heading, by page, or by a fixed token count with slight overlap), summarize each section, then summarize the summaries. This is the map-reduce pattern covered in Step 4.
Step 2: Write one prompt template, reuse it everywhere
Consistency across thousands of summaries matters more than cleverness in any single one. Use a fixed template with explicit output constraints:
Summarize the following document in 3-5 bullet points.
Rules:
- Each bullet under 20 words.
- No preamble, no "Here is a summary".
- Preserve names, dates, and numbers exactly as written.
Document:
"""
{{document_text}}
"""
Keeping the instructions identical across every call makes outputs easier to validate programmatically (e.g., checking bullet count) and easier to debug when something goes wrong.
Step 3: Run requests with controlled concurrency
Sequential requests are slow — a 5,000-document batch at 2 seconds per call takes nearly 3 hours. Running everything at once risks rate limit errors. The practical middle ground is a concurrency pool: a fixed number of requests in flight, with new ones starting as others finish.
import pLimit from "p-limit";
const limit = pLimit(8); // tune based on your plan's rate limits
async function summarize(doc) {
const res = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "claude-3-5-sonnet",
max_tokens: 300,
messages: [
{ role: "user", content: buildPrompt(doc.text) },
],
}),
});
if (!res.ok) throw new Error(`HTTP ${res.status} for doc ${doc.id}`);
const data = await res.json();
return { id: doc.id, summary: data.content[0].text };
}
const results = await Promise.allSettled(
documents.map((doc) => limit(() => summarize(doc)))
);
Promise.allSettled is important here — a single failed document should not abort the whole batch. Collect the rejected promises separately and retry them with backoff instead of re-running the entire dataset.
If you're routing these calls through SubToAPI, each sub_live_... key gives you a single HTTPS endpoint (/docs/messages) with usage metadata attached to every response, so you can log token counts per request without extra instrumentation. Details on request/response shape are in the docs.
Step 4: Map-reduce summarization for long documents
When a single document exceeds a comfortable context size, don't try to force it through one call. Instead:
- Map: split the document into chunks (by section or ~8k-token windows with small overlap) and summarize each chunk independently.
- Reduce: concatenate the chunk summaries and run one more summarization pass over that combined text to produce the final summary.
const chunkSummaries = await Promise.all(
chunks.map((chunk) => limit(() => summarize({ text: chunk })))
);
const finalSummary = await summarize({
text: chunkSummaries.map((c) => c.summary).join("\n"),
});
This pattern scales to documents of almost any length and keeps each individual call fast and cheap. It also makes partial failures recoverable — if one chunk fails, you only retry that chunk, not the whole document.
Step 5: Track cost and usage across the batch
Large batches are where unexpected token costs show up. Log input_tokens and output_tokens from every response (available via SubToAPI's usage metadata) and aggregate them per run, not just per call. A quick running total lets you catch a misconfigured prompt — like accidentally including full documents twice — before it burns through your plan's quota.
If you're running this on a team, SubToAPI's seat-based plans (Solo, Team, Scale — see pricing) let you separate API keys per project or environment, so a runaway batch job in staging doesn't affect production usage. Streaming isn't usually needed for batch summarization since you want the full text before storing it, but it's available via /docs/streaming if you want to show live progress on a dashboard.
Avoiding rate limit errors in large runs
Keep concurrency conservative on your first run (4–8 parallel requests) and increase it gradually while watching for 429 responses. Add exponential backoff to your retry logic for any failed request, and consider adding a small random jitter so retries don't all land in the same second. For very large datasets (100k+ rows), process in batches of a few thousand with a short pause between batches rather than one giant concurrent run — it makes failures easier to isolate and restart.
Getting started takes a few minutes: create a free trial account, generate a sub_live_... key, and follow the quickstart to send your first summarization request before scaling up concurrency.
questions
How many documents can I summarize per request? Send one document per request for best quality and easiest error handling. Batching multiple documents into a single prompt is possible but makes it hard to isolate failures and keep summaries consistent in length and structure.
What model should I use for large-scale summarization? A faster, lower-cost model is usually sufficient for straightforward summarization tasks, reserving larger models for documents requiring nuanced judgment or domain-specific accuracy. Test both on a sample before committing to one for the full dataset.
How do I handle documents longer than the context window? Use map-reduce summarization: split the document into chunks, summarize each chunk independently, then run a final summarization pass over the combined chunk summaries to produce one coherent result.