Currently, our app/api/gemini/chat and app/api/gemini/insights endpoints make a live call to the Google Gemini API for every request. This leads to:
- Increased API costs (duplicate token usage)
- Higher latency for repeated queries
- Poor scalability under load
If multiple users send identical or similar requests (e.g., generating report cards), we unnecessarily recompute the same response.
Objective
Introduce a caching layer to:
- Reduce redundant API calls
- Improve response time
- Optimize cost efficiency
Cache Strategy
- Cache full Gemini API response
- Use deterministic cache key based on request payload
- Store responses with TTL (Time-To-Live)
Key Generation
Example:
hash(JSON.stringify(sortedRequestBody))
Tasks
Edge Cases
Invalidation Policy
Acceptance Criteria
Tech Notes
Currently, our
app/api/gemini/chatandapp/api/gemini/insightsendpoints make a live call to the Google Gemini API for every request. This leads to:If multiple users send identical or similar requests (e.g., generating report cards), we unnecessarily recompute the same response.
Objective
Introduce a caching layer to:
Cache Strategy
Key Generation
Generate cache key using SHA-256 hash
Hash should include:
promptEnsure stable JSON serialization before hashing
Example:
Tasks
Integrate caching layer (Vercel KV / Redis /
unstable_cache)Implement SHA-256 hashing for request payload
Create cache lookup before Gemini API call
Store successful API responses in cache
Set TTL to 24 hours
Skip caching for:
Edge Cases
Avoid caching:
Ensure cache consistency across deployments
Handle JSON ordering issues in request body
Invalidation Policy
Automatic expiration via TTL (24 hours)
Future scope:
Acceptance Criteria
Identical requests within 24 hours:
Cached response latency:
API call reduction:
No caching of failed or partial responses
Tech Notes
Recommended tools:
@vercel/kvor Rediscryptomodule for hashingUse middleware pattern or wrapper function for reuse
Ensure compatibility with serverless environment