Hitting the same API or expensive sheet scan every trigger run burns quota. CacheService gives you a short-lived store (max ~6 hours) — perfect for rates, lookups, and memoized config.
What you'll need
- A stable cache key string
- A TTL in seconds (Apps Script caps at
21600)
How to use this snippet
function cacheGetJson(key) {
var raw = CacheService.getScriptCache().get(key);
if (raw == null) return null;
return JSON.parse(raw);
}
function cachePutJson(key, value, ttlSeconds) {
ttlSeconds = ttlSeconds || 600;
CacheService.getScriptCache().put(key, JSON.stringify(value), ttlSeconds);
}
function getRatesCached() {
var cached = cacheGetJson('fxRates');
if (cached) return cached;
var rates = JSON.parse(UrlFetchApp.fetch('https://example.com/rates').getContentText());
cachePutJson('fxRates', rates, 300);
return rates;
}
Tips:
- Cache is best-effort — it can be evicted early under memory pressure. Always treat a miss as normal.
- Values must fit in ~100KB; for bigger blobs, store an ID and fetch from Drive/Sheet.
Happy Coding!
