Quick answer
Cache a SERP response only when the application can reuse the same search context for the task’s freshness window. Key the entry by account scope and the complete request, expire it deliberately, and keep API failures distinct from empty results. Serving your own stored response avoids that outbound call; it does not establish a free-cache policy at the API provider.
This guide implements an application-side cache for SearchCans organic SERP responses. It does not claim a provider cache-hit tariff, a latency benchmark, a data-retention policy or a compliance guarantee. For the response model, start with SERP output and inference boundaries.
Make request identity part of correctness
| Input | Why it affects reuse |
|---|---|
| Application-owned account or tenant scope | Two callers must not accidentally share cached output across the intended boundary. Do not use raw API keys as cache labels. |
| Engine, query and market fields | A different engine, country or language is a different requested observation. |
| Depth, pagination and selected result options | A shallow or differently configured response may not satisfy the same task. |
| Every other request field | The example serializes the complete JSON payload rather than guessing which fields can be ignored. |
Use controls actually supported by the endpoint. Country and language do not establish city or device targeting. See the current Google Search API contract. The key in this example includes exact query text. It does not assume that lowercasing, removing words or merging similar queries preserves the result.
Choose a TTL from the task
A cache entry’s age is not the source document’s age. The example measures TTL from insertion after the response arrives. Reuse must satisfy both the entry’s original expiry and the caller’s current TTL. A shorter TTL rejects older entries; a longer TTL does not extend an existing expiry. The code makes no claim about upstream collection time. Retain the observation time beside the output.
| Event | Example policy |
|---|---|
| Unexpired exact key | Return a defensive copy; do not send a new request. |
| Expired key | Fetch again and validate before storing. |
| TTL zero | Remove that key and force a fresh application fetch. |
| Valid empty organic array | Return it without storing it under this policy. |
| Business failure or malformed result | Raise an error and do not cache it. |
| Capacity reached | Evict the least recently used retained entry. |
The nonempty-response validation below is deliberately limited to the organic envelope and URL fields. Your application must still check relevance, required optional fields and the permitted use of returned sources. A cached snippet is not evidence that the linked article was fully read.
Run the cache without making a network request
Save this standard-library Python code as serp_ttl_cache.py and run it. The supplied fetch function is synthetic. It produces one illustrative result; it does not call SearchCans or measure provider performance. Replace that callback with a separately validated HTTP client when integrating the cache.
import copy
import json
import math
import time
from collections import OrderedDict
from urllib.parse import urlsplit
class SerpTTLCache:
"""Single-process, single-worker example; not a distributed cache."""
def __init__(self, max_entries=128, clock=time.monotonic):
if type(max_entries) is not int or max_entries <= 0:
raise ValueError("max_entries must be a positive integer")
self.max_entries = max_entries
self.clock = clock
self.entries = OrderedDict()
def get_or_fetch(self, scope, payload, fetch, ttl_seconds):
if not isinstance(scope, str) or not scope.strip():
raise ValueError("Use a nonempty application-owned scope")
if not isinstance(payload, dict):
raise ValueError("Use a JSON request object")
if isinstance(ttl_seconds, bool):
raise ValueError("Use a finite nonnegative TTL")
try:
ttl = float(ttl_seconds)
except (TypeError, ValueError) as exc:
raise ValueError("Use a finite nonnegative TTL") from exc
if not math.isfinite(ttl) or ttl < 0:
raise ValueError("Use a finite nonnegative TTL")
key = (scope, json.dumps(payload, sort_keys=True,
separators=(",", ":"), allow_nan=False))
current = self.clock()
if ttl == 0:
self.entries.pop(key, None)
elif key in self.entries:
stored_at, expires, result = self.entries.pop(key)
if current < expires and current - stored_at < ttl:
self.entries[key] = (stored_at, expires, result)
return copy.deepcopy(result), True
result = fetch(copy.deepcopy(payload))
if (not isinstance(result, dict) or type(result.get("code")) is not int
or result["code"] != 0):
raise ValueError("SERP business response failed")
data = result.get("data")
if not isinstance(data, dict) or not isinstance(data.get("organic"), list):
raise ValueError("Expected data.organic")
organic = data["organic"]
def usable_link(row):
if not isinstance(row, dict) or not isinstance(row.get("link"), str):
return False
try:
url = urlsplit(row["link"])
return url.scheme in ("http", "https") and bool(url.hostname)
except ValueError:
return False
if any(not usable_link(row) for row in organic):
raise ValueError("Malformed organic row")
# Empty organic is a valid return, but this policy does not cache it.
if ttl > 0 and organic:
now = self.clock()
for old_key, (_, expires, _) in list(self.entries.items()):
if expires <= now:
del self.entries[old_key]
self.entries[key] = (now, now + ttl, copy.deepcopy(result))
while len(self.entries) > self.max_entries:
self.entries.popitem(last=False)
return copy.deepcopy(result), False
if __name__ == "__main__":
calls = []
def synthetic_fetch(payload):
calls.append(copy.deepcopy(payload))
return {"code": 0, "data": {"organic": [
{"link": "https://example.com/", "position": 1}
]}}
cache = SerpTTLCache()
request = {"t": "google", "s": "example query",
"country": "us", "language": "en"}
_, first_hit = cache.get_or_fetch("tenant-A", request, synthetic_fetch, 60)
_, second_hit = cache.get_or_fetch("tenant-A", request, synthetic_fetch, 60)
print(first_hit, second_hit, len(calls)) # False True 1
The demonstration prints False True 1: the first response is fetched, the second comes from this process’s cache, and the synthetic upstream callback is invoked once. The 60-second TTL is an example input, not a recommended freshness setting for all workloads.
Test the failure and isolation boundaries
- Use an injected clock to test a hit before expiry and a miss exactly at expiry.
- Change country, engine, query, pagination or tenant scope. The old entry must not serve the changed key.
- Modify a returned object and confirm the cached object remains intact.
- Return a business error, malformed organic row or empty organic array. Confirm the stated no-cache behavior.
- Fill a small capacity and request an evicted key again; it must invoke the upstream callback.
- Set TTL to zero even when a valid entry exists; this must bypass and remove that entry.
Python’s monotonic clock, deep copy and OrderedDict support the mechanisms used here. The test outcomes validate this local example, not a production service-level agreement.
Count avoided calls rather than assume free repeated requests
A hit in your own application does not call the upstream API. Sending the same request again to a provider is a separate event with its own billing outcome. Use the current credit rules and observed account usage; request similarity alone does not prove that a repeated call is free. For the full search-and-reading request mix, use the workflow cost worksheet.
Keep attempted API calls, responses accepted by the application and cache-served responses in separate counters. A high hit count does not prove the data is current or that the application has the right evidence. Reusing an incomplete response can make a system consistently wrong.
Keep application storage and provider policy separate
This cache stores copies in the application process until expiry, eviction or process exit. The code establishes nothing about a provider’s storage, retention, deletion or legal commitments. Check those terms separately and define who can access your own cached query and result data. Do not infer a no-storage guarantee from JSON or Markdown output.
The example is intended for a single worker in one process. Concurrent threads, multiple processes and distributed caches require additional synchronization and deployment design. It does not implement background refresh, persistence, authenticated browser sessions or a complete production cache service.