tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Generative AI > Google Gemini API > Gemini API Webhooks and Async Patterns

Gemini API Webhooks and Async Patterns

Author: Venkata Sudhakar

Synchronous Gemini API calls block your application until the response arrives. For long-running tasks - generating a detailed 2,000-word report, processing a large document, or running a multi-step analysis - an async pattern is better. You submit the job, get a job ID, and receive a webhook callback when it completes. ShopMax India uses this pattern for their nightly product analysis jobs.

The pattern uses two components: a job submission endpoint that starts the Gemini call in a background thread and returns a job ID immediately, and a webhook endpoint that the job POSTs results to on completion. Cloud Firestore tracks job status so clients can poll if needed.

The below example shows how ShopMax India implements async Gemini jobs with webhook callbacks using Flask and Cloud Firestore.


The job submission and status endpoints,


It gives the following output,

# POST /jobs/submit
{
  "prompt": "Generate a full sales analysis for ShopMax India November 2024",
  "webhook_url": "https://shopmax.in/webhooks/ai-job-complete"
}
Response (immediate - 202 Accepted):
{"job_id": "a3f1c8d2-...", "status": "queued"}

# GET /jobs/a3f1c8d2-... (poll for status)
{"job_id": "a3f1c8d2-...", "status": "completed", "result": "November 2024 Sales Analysis..."}

# Webhook fires when done:
POST https://shopmax.in/webhooks/ai-job-complete
{"job_id": "a3f1c8d2-...", "status": "completed", "result": "..."}

For production at ShopMax India, replace the threading approach with Cloud Tasks or Pub/Sub for reliable job delivery and automatic retries. Use Firestore real-time listeners on the client side instead of polling - the client gets notified the instant the job document status changes to completed.


 
  


  
bl  br