Running half a million support tickets through an interactive LLM endpoint is an expensive mistake. You hit rate limits (HTTP 429), write complex retry exponential backoffs, watch your connection pools time out, and pay full sticker price for tokens you did not need returned in 400 milliseconds.
At 365Finds, we evaluate AI infrastructure through a pragmatic lens: if an end user is not waiting on the other side of a spinning spinner, you should never pay interactive rates. The Gemini Batch API cuts token costs by an immediate 50% across both input prompts and output candidates, bypasses standard interactive rate quotas, and processes workloads asynchronously within a target 24-hour turnaround window.
While Gemini Context Caching solves the problem of querying a single, massive static prefix (like a 200,000-token repository) repeatedly, batch processing solves the opposite challenge: millions of independent, heterogeneous classification prompts and offline evaluation rubrics. Here is how 365Finds configures the Gemini Batch API using the official google-genai SDK for production pipelines.
The Cost and Quota Economics: Why Batch Wins
Before writing code, understand the trade-offs. The Gemini Batch API operates on an asynchronous queue with distinct pricing and throughput characteristics:
- 50% Token Discount: You pay exactly half the standard pay-as-you-go rate for both prompt tokens and candidate response tokens.
- Dedicated Batch Quotas: Your batch requests do not deplete your real-time requests-per-minute (RPM) or tokens-per-minute (TPM) limits, preventing offline backfills from starving production web traffic.
- Turnaround SLA: Google targets job completion within 24 hours. In our workflows at 365Finds, batches containing 10,000 to 50,000 text classification requests routinely complete in 15 to 45 minutes, though you must design your architecture around asynchronous completion rather than immediate execution.
- Retention Lifespan: Output files generated in the Google Files API persist for 48 hours before automated cleanup. You must build an ingestion step to persist results to your internal database or object storage (such as AWS S3 or Google Cloud Storage).
Step 1: Formatting the JSON Lines (.jsonl) Input
Batch inference requires a JSON Lines (.jsonl) file where every line represents an independent API call. For high-volume classification and automated offline scoring (LLM-as-a-judge), you should enforce structured JSON output and attach a unique tracking identifier.
Each entry must include:
key: A unique string identifier. Because batch execution can return completed items out of order, this key is your sole mechanism for reconciling model outputs back to your internal database records.request: A validGenerateContentRequestobject containingcontentsand optionalgeneration_config.
Here is an example classification_requests.jsonl file configured for multi-class ticket triage with structured outputs:
{"key": "ticket_10821", "request": {"contents": [{"role": "user", "parts": [{"text": "Customer ticket: I cannot log in after resetting my password yesterday.\nAssign priority (high, medium, low) and category (billing, auth, bug)."}]}], "generation_config": {"response_mime_type": "application/json", "temperature": 0.0}}}
{"key": "ticket_10822", "request": {"contents": [{"role": "user", "parts": [{"text": "Customer ticket: Can you send me the invoice for June 2026?\nAssign priority (high, medium, low) and category (billing, auth, bug)."}]}], "generation_config": {"response_mime_type": "application/json", "temperature": 0.0}}}
365Finds Tip: Always set
temperature: 0.0for offline evaluation and categorization. You want deterministic classification rubrics, not imaginative token sampling.
Step 2: Uploading the Batch File and Creating the Job
Using the official Google GenAI Python SDK (google-genai), upload your .jsonl payload using the Files API and submit the batch job.
Install the current SDK if you haven't already:
pip install google-genai
The submission script:
import os
from google import genai
from google.genai import types
# 1. Initialize client using GEMINI_API_KEY from environment
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
input_file_path = "classification_requests.jsonl"
# 2. Upload the JSONL dataset to Google Files API
print("Uploading input dataset to Gemini Files API...")
uploaded_file = client.files.upload(
file=input_file_path,
config=types.UploadFileConfig(
display_name="support_ticket_classification_run",
mime_type="application/jsonl"
)
)
print(f"Uploaded File Reference: {uploaded_file.name}")
# 3. Create the Batch Job
# 365Finds preference: gemini-2.5-flash offers unbeatable cost/accuracy for classification
batch_job = client.batches.create(
model="gemini-2.5-flash",
src=uploaded_file.name,
config=types.CreateBatchJobConfig(
display_name="support_ticket_batch_2026_q4"
)
)
print(f"Batch Job Created Successfully.")
print(f"Job Name: {batch_job.name}")
print(f"Initial State: {batch_job.state.name}")
Step 3: Lifecycle Polling and State Monitoring
Because batch jobs execute asynchronously, your orchestrator (Airflow, Celery, or a lightweight worker script) must poll the job resource until it reaches a terminal status.
The primary states are:
JOB_STATE_PENDING: In queue, awaiting scheduling.JOB_STATE_RUNNING: Active processing across Gemini compute clusters.JOB_STATE_SUCCEEDED: Complete and ready for download.JOB_STATE_FAILED: The batch job encountered a terminal systemic error.JOB_STATE_CANCELLED: Job aborted by caller request.JOB_STATE_EXPIRED: Job failed to finish within the execution boundary.
Here is an automated polling loop with backoff:
import time
from google import genai
client = genai.Client()
job_name = batch_job.name # e.g., "batches/xyz123abc456"
print(f"Tracking status for {job_name}...")
terminal_failure_states = {
"JOB_STATE_FAILED",
"JOB_STATE_CANCELLED",
"JOB_STATE_EXPIRED"
}
poll_interval_seconds = 30
while True:
job_status = client.batches.get(name=job_name)
current_state = job_status.state.name
print(f"Current Status: {current_state}")
if current_state == "JOB_STATE_SUCCEEDED":
print("Batch processing completed successfully!")
break
if current_state in terminal_failure_states:
raise RuntimeError(f"Batch processing terminated with failure state: {current_state}")
time.sleep(poll_interval_seconds)
Step 4: Downloading and Parsing Results Safely
When job_status.state.name == "JOB_STATE_SUCCEEDED", the result is accessible via job_status.dest.file_name. Download the raw byte stream, decode the lines, and map the outputs back using the original key.
Crucially, a successful batch job does not guarantee that every individual row succeeded. If a prompt triggered a safety block or malformed input schema, that specific line will output an error dictionary instead of a response block. Your ingestion parser must handle row-level exceptions gracefully.
import json
from google import genai
client = genai.Client()
# Retrieve destination file name from completed job
result_file_ref = job_status.dest.file_name
print(f"Downloading batch results from: {result_file_ref}")
file_bytes = client.files.download(file=result_file_ref)
result_lines = file_bytes.decode("utf-8").splitlines()
success_count = 0
error_count = 0
for line in result_lines:
if not line.strip():
continue
record = json.loads(line)
item_key = record.get("key")
if "response" in record:
success_count += 1
# Extract candidate text
candidate = record["response"]["candidates"][0]
output_text = candidate["content"]["parts"][0]["text"]
token_usage = record["response"].get("usageMetadata", {})
# Parse structured classification payload
parsed_payload = json.loads(output_text)
print(f"[{item_key}] -> {parsed_payload} (Tokens: {token_usage.get('totalTokenCount')})")
elif "error" in record:
error_count += 1
error_info = record["error"]
print(f"[{item_key}] FAILED -> Code: {error_info.get('code')}, Message: {error_info.get('message')}")
print(f"\nProcessing Summary: {success_count} succeeded, {error_count} failed.")
365Finds Technical Assessment and Decision Matrix
At 365Finds, we see engineering teams frequently confuse Batch API with Context Caching. They serve radically different architecture patterns:
| Criterion | Gemini Batch API | Gemini Context Caching |
|---|---|---|
| Primary Use Case | Offline classification, benchmark suites, data labeling | Interactive agents over fixed codebases, large PDF repos |
| Pricing Benefit | Flat 50% discount on both prompt and candidate tokens | Up to 75%-90% discount on cached input prefix tokens only |
| Latency Expectation | Asynchronous (minutes to 24 hours) | Real-time synchronous (sub-second responses) |
| Prefix Dependency | None required; handles completely disparate prompts | Requires large shared static prefix (typically >32,768 tokens) |
| Concurrency Impact | Bypasses interactive RPM/TPM limits | Subject to standard interactive request quotas |
Our Practical Recommendations
- Default to Gemini 2.5 Flash for Batch Classification: There is rarely a financial or accuracy justification to run routine text labeling or sentiment tagging on Gemini 2.5 Pro. Flash gives near-instant classification accuracy at pennies per hundred thousand rows, and halving that already low price with Batch API yields extraordinary ROI.
- Never Ignore the 48-Hour TTL: The Google Files API is a transport buffer, not an archive. Write your worker to immediately offload completed
.jsonloutputs into Postgres, ClickHouse, or Parquet lakes. - Use Explicit Schema Keys: Keep your
keyvalues semantic (e.g.,ticket_{id}_{created_date}). When a run of 80,000 tickets contains 12 failures due to input validation or safety thresholds, you can isolate and re-queue only those specific failures without re-running the entire dataset.