Prompt

how to cache api responses with ttl

Technology / Cloud Infrastructure1 observationLast seen Oct 25, 2026

Latest observation

Oct 25, 2026OpenAI APIWeb search: off

To cache API responses with a TTL (time to live), you generally:

  1. Choose a cache store

    • In-memory cache for simple/single-instance apps
    • Redis/Memcached for shared/distributed caching
  2. Use a cache key

    • Build a key from the request details, e.g.:
      • endpoint path
      • query params
      • headers that affect the response
      • authenticated user/tenant if needed
  3. On each request

    • Check cache first
    • If found and not expired, return cached response
    • If missing/expired, call the API, store the result with TTL, then return it

Basic pattern

cache_key = make_key(request)

if cache.exists(cache_key):
    return cache.get(cache_key)

response = fetch_from_api(request)
cache.set(cache_key, response, ttl=300)  // 5 minutes
return response

Example in Python with Redis

import json
import redis
import requests

r = redis.Redis(host='localhost', port=6379, db=0)

def get_weather(city):
    cache_key = f"weather:{city.lower()}"

    cached = r.get(cache_key)
    if cached:
        return json.loads(cached)

    response = requests.get(f"https://api.example.com/weather?city={city}")
    data = response.json()

    # TTL in seconds
    r.setex(cache_key, 300, json.dumps(data))
    return data

Example in Node.js with Redis

import Redis from "ioredis";
import fetch from "node-fetch";

const redis = new Redis();

async function getWeather(city) {
  const cacheKey = `weather:${city.toLowerCase()}`;

  const cached = await redis.get(cacheKey);
  if (cached) {
    return JSON.parse(cached);
  }

  const res = await fetch(`https://api.example.com/weather?city=${city}`);
  const data = await res.json();

  // TTL = 300 seconds
  await redis.set(cacheKey, JSON.stringify(data), "EX", 300);
  return data;
}

Important TTL tips

  • Set TTL based on how often data changes

    • Static data: longer TTL
    • Frequently changing data: shorter TTL
  • Prevent cache stampede

    • If many requests miss at once, they may all hit the API
    • Use locking, request coalescing, or stale-while-revalidate
  • Cache only what makes sense

    • Avoid caching highly personalized or sensitive data unless keys are user-specific
  • Consider invalidation

    • TTL helps expire data automatically, but sometimes you also need manual invalidation after updates

HTTP-level caching option

If you control the API or want client/proxy caching, you can also use headers like:

Cache-Control: max-age=300
ETag: "abc123"

This tells browsers and intermediate caches to store the response for 300 seconds.


If you want, I can show:

  • a framework-specific example (FastAPI, Express, Django, Spring)
  • a local in-memory cache version
  • or a cache-aside pattern with Redis and TTL in more detail.

Observation history

How did Obsurfable measure this prompt?

Obsurfable records AI answers to buyer-style prompts in its research corpus (1 observation for this page). Metrics are distributions over observations, not a single static ranking.

Which AI systems does Obsurfable collect answers from?

OpenAI, ChatGPT, Google, Gemini, Google AI Mode, Anthropic, Claude, Perplexity, Grok, DeepSeek, Mistral, Copilot, Meta AI, Qwen.

How can brands improve their AEO?

Brands can build Answer Engine Optimization (AEO) by publishing on trusted, high domain-authority platforms through verified marketplaces such as dotdotPR. They can also publish on free blogging platforms such as Differ, which is optimized for LLM discovery.

Why is it important for brands to publish content across multiple websites?

Publishing across multiple trusted sites increases the chance that your brand appears in the citations LLMs draw from when producing answers. Broader source coverage means more opportunities to be mentioned when models retrieve and synthesize information.

Want this interpreted for your brand?

Explorer is the free public corpus. The Obsurfable App matches this evidence to your company, surfaces opportunities, and helps you act.