After this page, you can decide whether a set of requests should use standard, Batch, Flex, or Priority, and safely submit, verify, and retrieve a batch job. It is for developers with evaluation, preprocessing, or bulk-classification needs.
Exact discount and premium percentages and limit numbers change, so this page covers structure only; for numbers see the pricing page and the rate-limits page.
A path reminder first
Section titled “A path reminder first”The Batch page opens with a notice that the feature is currently available only with the generateContent API. The other API pages on this site (such as First API call) use the Interactions API. The request structures differ:
- Batch uses
client.batches.create(...), and the body uses theGenerateContentRequeststructure; - Flex and Priority add a
service_tierfield to an Interactions API request.
Do not put an Interactions request body into a batch, and do not expect Batch to support the style used on this site’s other pages. This page was checked against the official pages on 2026-11-24; if that notice has disappeared, Google changed it, and the official page governs.
How to choose among the four modes
Section titled “How to choose among the four modes”| Mode | Latency | Cost | Reliability and limits | Status (as checked) |
|---|---|---|---|---|
| Standard | Seconds to minutes | Standard price | Normal limits | Generally available |
| Batch | Asynchronous, target within 24 hours, often faster | Listed by Google at a discount tier of the standard price | Its own limits, counted separately from live requests | Documented as stable; generateContent only |
| Flex | Synchronous, target of minutes, variable latency | Discounted | Best effort, may be preempted; no server-side fallback | Preview |
| Priority | Synchronous, low latency | Premium | Ahead of Standard and Flex; downgraded to standard when over capacity | Preview |
Order of decision:
- Is a user waiting for the result? If yes, use standard or Priority.
- Does the result feed the next step immediately? If yes, choose synchronous Flex rather than asynchronous Batch.
- Is the volume large and can it wait a day? Choose Batch and plan against its separate limits.
- Is it business-critical and must not be preempted? Evaluate Priority and accept its preview status and premium.
Preview features can change, so do not bet the only path of an important business on a preview service tier.
Batch: submit, poll, retrieve
Section titled “Batch: submit, poll, retrieve”Batch has two ways to submit:
- Inline requests: put a list of
GenerateContentRequestobjects straight into the create request; the total size must be under 20 MB, which suits small batches; - Input file: a JSON Lines (JSONL) file with one complete request per line, which suits large batches; the input file limit is 2 GB.
Job states are JOB_STATE_PENDING, RUNNING, SUCCEEDED, FAILED, CANCELLED, and EXPIRED. When polling, stop only at the last four terminal states. Cancelling, deleting, and fetching results after creation all use the matching client.batches.* methods; names and returned fields follow the official examples and your installed SDK.
Creation is not idempotent
Section titled “Creation is not idempotent”Submitting the same batch twice creates two jobs, and both are billed. “Just click again” after a network timeout is the riskiest move:
- Before submitting, generate and record your own job label and write it with
display_name, for exampleeval-2026-11-24-run1; - After a timeout, list existing jobs and look for the label to see whether it was created before deciding to resend;
- Do not unconditionally retry the create call in an unattended script.
Check the failure count and per-row errors
Section titled “Check the failure count and per-row errors”A job state of SUCCEEDED only means the job as a whole finished, not that every request succeeded. After retrieving results, check:
- The failed-request count fields returned by the job, and the per-row error objects in the inline responses or the output file;
- How failed rows map to input rows (use your own request keys; do not assume order);
- Whether the failure ratio is within your tolerance; if not, do not treat the results as a complete evaluation.
Field names vary with SDK and API version, so check the official examples and make “check failures” a separate step in your code.
Flex and Priority (preview)
Section titled “Flex and Priority (preview)”Both add a field to an Interactions API request:
import osfrom google import genai
client = genai.Client() # reads the GEMINI_API_KEY environment variable
result = client.interactions.create( model=os.environ["GEMINI_MODEL"], input="Classify the following three synthetic log lines as info, warn, or error.", service_tier="flex", # or "priority"; omit for standard)print(result.output_text)Key points, all from the official pages:
- Flex: discounted from the standard price, with variable latency and a default target of minutes; when capacity is tight it may return
503or429; there is no server-side fallback, so the system will not automatically move a request to the standard tier, and you must write retries and backoff yourself; because requests may wait in a queue, Google recommends raising the client timeout to 10 minutes or more; Flex traffic shares limits with ordinary requests rather than having separate limits like Batch. - Priority: premium, ahead of Standard and Flex; when you exceed the Priority limit, requests degrade gracefully to standard processing instead of failing and are billed at the standard price. Priority has its own default limit, set as a fixed fraction of the standard limit; see the rate-limits page for the value.
The example was not run with a real key, and both features are in preview, so fields and behavior may change.
Minimal example: an inline batch of two synthetic requests
Section titled “Minimal example: an inline batch of two synthetic requests”The example uses only fictional prompts and shows the skeleton of create, poll, and retrieve. The model ID comes from an environment variable.
import osimport timefrom google import genai
client = genai.Client() # reads the GEMINI_API_KEY environment variablemodel = os.environ["GEMINI_MODEL"]
inline_requests = [ {"contents": [{"parts": [{"text": "Explain what a cache is in one sentence."}], "role": "user"}]}, {"contents": [{"parts": [{"text": "Explain what idempotent means in one sentence."}], "role": "user"}]},]
job = client.batches.create( model=model, src=inline_requests, config={"display_name": "demo-two-requests-001"},)print("created:", job.name)
done = {"JOB_STATE_SUCCEEDED", "JOB_STATE_FAILED", "JOB_STATE_CANCELLED", "JOB_STATE_EXPIRED"}while job.state.name not in done: time.sleep(30) job = client.batches.get(name=job.name)
print("final state:", job.state.name)if job.state.name == "JOB_STATE_SUCCEEDED": for i, item in enumerate(job.dest.inlined_responses, start=1): print(i, "error" if getattr(item, "error", None) else "ok")Expected: the job name and final state are printed; on success, each item is marked ok or error. Google states a 24-hour target turnaround; a small job may finish quickly or may wait a long time, so the script must not assume it finishes within minutes. If it fails, follow “Failure recovery” below.
Relationship to spend caps
Section titled “Relationship to spend caps”The billing page states that long-running work such as completed batch jobs and agent sessions can exceed a project spend cap. A Prepay account can also keep consuming during the billing-pipeline delay. So:
- Estimate before submitting a large job; see Pricing and billing;
- Give batch work its own project to isolate its spend;
- Caching also works for batch; see Long context and caching.
Counterexamples and rewrites
Section titled “Counterexamples and rewrites”Counterexample:
After the evaluation script timed out, it called
batches.createagain, and both jobs ran to completion.
Rewrite: use display_name as an idempotency marker before creating, list jobs first after a timeout; check the failure count when the job completes; keep an explicit job record table for each batch of requests.
Counterexample:
Because Flex is cheaper, switch all live requests to it.
Rewrite: Flex has no server-side fallback and fails when capacity is tight; use it only for flows where no user is waiting, and implement backoff retries and long timeouts.
Verification checklist
Section titled “Verification checklist”- You confirmed the official page’s current statement about Batch’s scope;
- Batch code and Interactions code are not mixed;
- There is an idempotency marker and a job record before submitting;
- After completion you checked failed items, not only the final state;
- Flex requests have backoff retries and a timeout of at least 10 minutes;
- You assessed how batch and long tasks affect spend caps.
Failure recovery
Section titled “Failure recovery”| Symptom | Order of handling |
|---|---|
| The create call times out | List jobs by label first and confirm whether it was created; do not resend directly |
The job is FAILED |
Read the job’s error information; shrink the batch or check the input format first |
The job is EXPIRED |
The job expired after not finishing for a long time; split into smaller batches and resubmit |
| Succeeded but some rows have errors | Pull the failed rows and rerun them separately, keeping your own request keys |
Flex returns 503 or 429 |
Retry with exponential backoff; if it still fails, return to the standard tier or postpone to off-peak |
| A Priority response’s actual tier differs from expected | Check the tier field in the response and remember that a downgrade is billed at the standard price |
| Balance or cap looks wrong | See Pricing and billing |
- Weigh cost levers: Pricing and billing.
- Bulk parsing with structured output: Structured output.
- How to read limits and status: Models and quotas.
- For large file inputs see Multimodal API; this page does not repeat it.