Gemini Files API: Upload State, Readiness Polling, and Token Budgets
Manage Gemini Files API lifecycles in production with content-hash upload deduplication, explicit ACTIVE state polling, tenant isolation, and token budgets.

Uploading large PDFs, audio recordings, images, or videos through the Google Gemini Files API decouples media transfer from prompt generation, but it also introduces stateful lifecycle requirements that ordinary chat calls do not have. If workers call generation before a file finishes processing, re-upload identical assets on every retry, or ignore multimodal token counts, a document pipeline quickly triggers validation errors and 429 RESOURCE_EXHAUSTED cascades.
Check the API429 documentation, API reference, and model catalog to verify which endpoints and input formats your connection supports before choosing between native files.upload calls and OpenAI-compatible multimodal payloads.
Compare inline payloads, Gemini Files API, and context caching
Google documents three distinct ways to supply media and large documents to Gemini models, while OpenAI-compatible gateways expose standard chat/multimodal message payloads:
| Input delivery mechanism | Lifecycle & retention | When to use | Key operational boundary |
|---|---|---|---|
Inline request payload (inline_data or OpenAI-compatible content parts) |
Stateless; sent on every request | Small one-off images or short documents within request byte limits | Resending large payloads on every turn wastes bandwidth and latency |
Native Google Gemini Files API (media.upload / files) |
Stateful URI; stored up to 48 hours on direct Google API | Large PDFs, audio, or video files reused across multiple turns in a direct Google project | File must reach STATE_ACTIVE before generation; URI is scoped to the uploading Google project |
| Gemini Context Caching on top of uploaded files | Explicit or implicit cached prefix with TTL | Repeated queries against the same large document or video | Requires method and model compatibility check per the context caching guide |
Never assume a file_uri created in one Google Cloud project can be read by another project or passed blindly through an unrelated gateway credential. Verify endpoint support in the API429 public OpenAPI specification and Google provider guide.
Separate upload deduplication, readiness polling, and generation retries
File-based pipelines fail when workers treat upload, media processing, and LLM generation as a single retryable block:
- Deduplicate uploads by tenant and SHA-256 content hash: If a generation call fails with HTTP 429 or times out, do not re-upload the 80 MB video or PDF. Store a local file ledger keyed by
(tenant_id, sha256_hex)that tracks the remotefile_name,state, andexpires_attimestamp (48 hours from upload on direct Google APIs), paired with your application idempotency ledger. - Poll file readiness until
ACTIVE: Newly uploaded videos and large documents often enterPROCESSINGstate first. Calling generation while a file is stillPROCESSINGfails immediately; calling generation when a file isFAILEDwill never succeed. Poll file metadata with bounded backoff untilstate == "ACTIVE"before enqueuing the generation request. - Budget multimodal tokens before dispatch: Referencing a file URI keeps the HTTP JSON body small, but the model still processes every page, frame, or audio second as input tokens. Estimate multimodal token size using the Gemini token counting guide, reserve cost via AI API cost guardrails, and schedule heavy jobs through the Gemini rate limits and queue admission design.
Runnable offline Python file lifecycle and token budget controller
The standalone Python module below manages tenant-scoped file registry reuse, prevents generation calls until the file reaches ACTIVE state before expiration, and verifies that the multimodal token estimate fits within both task cost guardrails and input TPM headroom:
from dataclasses import dataclass
@dataclass(frozen=True)
class StoredFileRecord:
tenant_id: str
sha256_hex: str
remote_uri: str
state: str # "PROCESSING" | "ACTIVE" | "FAILED"
uploaded_at_epoch: float
expires_at_epoch: float
estimated_tokens: int
@dataclass(frozen=True)
class FileJobDecision:
action: str
reason: str
remote_uri: str | None
def evaluate_file_generation_job(
record: StoredFileRecord | None,
*,
request_tenant_id: str,
now_epoch: float,
expiry_safety_margin_sec: float = 900.0,
available_input_tpm: int,
max_job_tokens: int,
) -> FileJobDecision:
if record is None:
return FileJobDecision("upload_required", "no_existing_file_record", None)
if record.tenant_id != request_tenant_id:
return FileJobDecision("reject_job", "cross_tenant_file_reference_blocked", None)
if record.state == "FAILED":
return FileJobDecision("upload_required", "remote_file_processing_failed", None)
if record.state == "PROCESSING":
return FileJobDecision("defer_poll_readiness", "file_still_processing", record.remote_uri)
if record.state != "ACTIVE":
return FileJobDecision("reject_job", f"unexpected_file_state:{record.state}", None)
if now_epoch + expiry_safety_margin_sec >= record.expires_at_epoch:
return FileJobDecision("upload_required", "file_expired_or_near_48h_ttl", None)
if record.estimated_tokens > max_job_tokens:
return FileJobDecision("reject_job", "exceeds_job_token_budget", record.remote_uri)
if record.estimated_tokens > available_input_tpm:
return FileJobDecision("defer_queue_tpm", "insufficient_input_tpm_headroom", record.remote_uri)
return FileJobDecision("dispatch_generation", "file_active_and_within_budget", record.remote_uri)
if __name__ == "__main__":
active_file = StoredFileRecord(
tenant_id="tenant_alpha",
sha256_hex="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
remote_uri="files/doc-alpha-001",
state="ACTIVE",
uploaded_at_epoch=1_700_000_000.0,
expires_at_epoch=1_700_172_800.0,
estimated_tokens=42_000,
)
processing_file = StoredFileRecord(
tenant_id="tenant_alpha",
sha256_hex="abc123",
remote_uri="files/vid-alpha-002",
state="PROCESSING",
uploaded_at_epoch=1_700_000_000.0,
expires_at_epoch=1_700_172_800.0,
estimated_tokens=180_000,
)
print(
"Active file decision:",
evaluate_file_generation_job(
active_file,
request_tenant_id="tenant_alpha",
now_epoch=1_700_010_000.0,
available_input_tpm=250_000,
max_job_tokens=100_000,
),
)
print(
"Processing file decision:",
evaluate_file_generation_job(
processing_file,
request_tenant_id="tenant_alpha",
now_epoch=1_700_010_000.0,
available_input_tpm=250_000,
max_job_tokens=200_000,
),
)
Enforce tenant isolation and retry boundaries
Never share uploaded file URIs across tenants unless the asset is an explicitly public catalog document. When a generation call referencing an ACTIVE file returns 429 Too Many Requests (RFC 6585 Section 4), apply the application retry budget policy to the generation call alone—reuse the existing remote_uri as long as its 48-hour expiration window still has a safety margin.
Check the pricing overview, Gemini API pricing comparison, and FAQ when estimating multimodal token costs across PDF pages, images, audio, and video inputs.
FAQ
Does using the Gemini Files API reduce input token usage?
No. Uploading a file avoids resending raw media bytes over the network on repeated calls, but every generation request that references the file still counts and bills the file's token equivalent against your model context window and input TPM limits.
Why did a generation request fail immediately after files.upload returned HTTP 200?
Large files—especially video and audio—often return from the upload call in the PROCESSING state. Your worker must poll files.get until state == "ACTIVE" before submitting the generation prompt.
How long do files remain available in the direct Google Gemini Files API?
Google's Files API retains uploaded files for 48 hours by default unless deleted earlier by your application. Store expires_at in your file ledger and refresh the upload before the TTL expires on long-running queues.
Should a worker re-upload a file when generation fails with HTTP 429?
No. If the file is already ACTIVE and not near expiration, re-uploading wastes bandwidth and processing time. Reuse the existing tenant-verified file_uri when scheduling a bounded generation retry.
When should teams combine the Gemini Files API with context caching?
When your application asks multiple separate questions against the same uploaded PDF, video, or audio asset within a short window. Uploading the file once and creating a verified cache resource (on supported models and methods) avoids paying the full input token rate on every question, provided you reconcile both cache storage and per-call usage across your tenant ledger.
Sources & further reading
Put the next step into practice.
Check model IDs, current pricing and request formats before integrating. Availability can depend on the model and provider route.

