DiscoveryVIP / Apps Script AcademyHelp

88. Caching

Module 18 · 25 minutes · Lessons 1–87 as needed; read the related service introduction first

Open Interactive Lesson

Discover

How can caching solve a real automation problem without hiding an incorrect result?

Predict

Which values or resources will change, and which should stay unchanged? Write your prediction before execution.

Understand

Cache entries are optional temporary accelerators; correctness cannot depend on them existing. Check the cache first and compute the fallback on a miss. Store a serialized result with a declared lifetime and validate it on retrieval. The local cache is an in-run deterministic adapter and does not model eviction or distributed access. Real CacheService may return null before the requested expiration, so a complete fallback is always necessary.

Real-world application

Use this technique in a reviewed web application workflow. A cache miss computes and stores total 400; reading the same key returns it during this run. Apply it first to a copy containing fictional records; only a separately authorized Google deployment changes real Workspace data.

Definitions

Caching
Cache entries are optional temporary accelerators; correctness cannot depend on them existing. Check the cache first and compute the fallback on a miss.
Virtual service adapter
A supported local implementation of selected service methods operating on fictional JSON state; it is not a live Google account connection.
Verification contract
An independently inspected expected console/resource result under declared fixture inputs.
Fictional inputmain / selected functionJavaScript contractActual local outputReview / Google deployment

Local execution boundary: the browser changes fictional state only. Google authorization and deployment happen separately.

Exact controls and expected results

Run in Virtual Workspace
Execute the visible source against the current fictional records. Expected: A cache miss computes and stores total 400; reading the same key returns it during this run.
Run on fresh sample
Restore the sample input, then execute the visible source. Expected: {"logs":["400"],"error":null,"resource":"logs","value":null}
Execution Trace
Inspect ordered supported method calls, arguments and actual recorded results. Expected: The trace reflects this run; replay is not a paused Google debugger.
Reset Example
Confirm replacement to restore source and sample state. Expected: Your current modifications are replaced with the prepared case.

Example 1: Working caching

A cache miss computes and stores total 400; reading the same key returns it during this run.

function main() {
  const cache = CacheService.getScriptCache();
  let value = cache.get("total:v1");
  if (value === null) { value = JSON.stringify({total: 400}); cache.put("total:v1", value, 60); }
  console.log(JSON.parse(cache.get("total:v1")).total);
}
Important line explanations
Line 1: function main() {
Define a named callable block; defining it does not invoke it.
Line 2: const cache = CacheService.getScriptCache();
Bind the named value for the operations below; referenced arrays and objects may still be mutable.
Line 3: let value = cache.get("total:v1");
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 4: if (value === null) { value = JSON.stringify({total: 400}); cache.put("total:v1", value, 60); }
Evaluate this condition and test both accepted and rejected branches.
Line 5: console.log(JSON.parse(cache.get("total:v1")).total);
Parse syntax before validating business fields; malformed JSON throws.
Line 6: }
Close the current block; indentation shows the scope.
Exact expected output and resource
{
  "logs": [
    "400"
  ],
  "error": null,
  "resource": "logs",
  "value": null
}

Example 2: Find the first incorrect operation

This deliberately changed operation uses get("missing")).total. Predict the mismatch and compare its actual output with the reference.

function main() {
  const cache = CacheService.getScriptCache();
  let value = cache.get("total:v1");
  if (value === null) { value = JSON.stringify({total: 400}); cache.put("total:v1", value, 60); }
  console.log(JSON.parse(cache.get("missing")).total);
}
Important line explanations
Line 1: function main() {
Define a named callable block; defining it does not invoke it.
Line 2: const cache = CacheService.getScriptCache();
Bind the named value for the operations below; referenced arrays and objects may still be mutable.
Line 3: let value = cache.get("total:v1");
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 4: if (value === null) { value = JSON.stringify({total: 400}); cache.put("total:v1", value, 60); }
Evaluate this condition and test both accepted and rejected branches.
Line 5: console.log(JSON.parse(cache.get("missing")).total);
Parse syntax before validating business fields; malformed JSON throws.
Line 6: }
Close the current block; indentation shows the scope.
Exact expected output and resource
{
  "logs": [],
  "error": "Cannot read properties of null (reading 'total')",
  "resource": "logs",
  "value": null
}

Example 3: Repeat the operation and inspect idempotency

Execute the same operation twice against retained fictional state. Explain whether it repeats reads, duplicates a created object or safely skips completed work. The trace records actual supported service calls.

function lessonAction() {
  const cache = CacheService.getScriptCache();
  let value = cache.get("total:v1");
  if (value === null) { value = JSON.stringify({total: 400}); cache.put("total:v1", value, 60); }
  console.log(JSON.parse(cache.get("total:v1")).total);
}
function main() {
  lessonAction();
  lessonAction();
}
Important line explanations
Line 1: function lessonAction() {
Define a named callable block; defining it does not invoke it.
Line 2: const cache = CacheService.getScriptCache();
Bind the named value for the operations below; referenced arrays and objects may still be mutable.
Line 3: let value = cache.get("total:v1");
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 4: if (value === null) { value = JSON.stringify({total: 400}); cache.put("total:v1", value, 60); }
Evaluate this condition and test both accepted and rejected branches.
Line 5: console.log(JSON.parse(cache.get("total:v1")).total);
Parse syntax before validating business fields; malformed JSON throws.
Line 6: }
Close the current block; indentation shows the scope.
Line 7: function main() {
Define a named callable block; defining it does not invoke it.
Line 8: lessonAction();
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 9: lessonAction();
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 10: }
Close the current block; indentation shows the scope.
Exact expected output and resource
{
  "logs": [
    "400",
    "400"
  ],
  "error": null,
  "resource": "logs",
  "value": null
}

Example 4: Add a diagnostic failure boundary

Separate entry, success and a rethrown failure. A failure marker must not masquerade as success and must not swallow the original error.

function lessonAction() {
  const cache = CacheService.getScriptCache();
  let value = cache.get("total:v1");
  if (value === null) { value = JSON.stringify({total: 400}); cache.put("total:v1", value, 60); }
  console.log(JSON.parse(cache.get("total:v1")).total);
}
function main() {
  console.log("Start: Caching");
  try { lessonAction(); console.log("Completed operation"); }
  catch(error) { console.error("Failed operation: " + error.message); throw error; }
}
Important line explanations
Line 1: function lessonAction() {
Define a named callable block; defining it does not invoke it.
Line 2: const cache = CacheService.getScriptCache();
Bind the named value for the operations below; referenced arrays and objects may still be mutable.
Line 3: let value = cache.get("total:v1");
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 4: if (value === null) { value = JSON.stringify({total: 400}); cache.put("total:v1", value, 60); }
Evaluate this condition and test both accepted and rejected branches.
Line 5: console.log(JSON.parse(cache.get("total:v1")).total);
Parse syntax before validating business fields; malformed JSON throws.
Line 6: }
Close the current block; indentation shows the scope.
Line 7: function main() {
Define a named callable block; defining it does not invoke it.
Line 8: console.log("Start: Caching");
Record this actual result; inspect side effects too rather than treating a log as success.
Line 9: try { lessonAction(); console.log("Completed operation"); }
Record this actual result; inspect side effects too rather than treating a log as success.
Line 10: catch(error) { console.error("Failed operation: " + error.message); throw error; }
Record this actual result; inspect side effects too rather than treating a log as success.
Line 11: }
Close the current block; indentation shows the scope.
Exact expected output and resource
{
  "logs": [
    "Start: Caching",
    "400",
    "Completed operation"
  ],
  "error": null,
  "resource": "logs",
  "value": null
}

Example 5: Executable service-call and result assertions

Inject recording service adapters that delegate to the same supported virtual operations. Compare actual arguments and logs with fixed authored expectations. Change the operation and verify that the assertion fails; this local contract does not certify Google integration.

function invokeLesson(e, SpreadsheetApp, DocumentApp, DriveApp, GmailApp, MailApp, FormApp, CalendarApp, SlidesApp, ScriptApp, PropertiesService, CacheService, LockService, HtmlService, UrlFetchApp, Utilities, console, Logger) {
function lessonAction() {
  const cache = CacheService.getScriptCache();
  let value = cache.get("total:v1");
  if (value === null) { value = JSON.stringify({total: 400}); cache.put("total:v1", value, 60); }
  console.log(JSON.parse(cache.get("total:v1")).total);
}
  return lessonAction(e);
}

// A local dependency-injection contract test: calls still delegate to supported adapters.
function main() {
  const records = [];
  function serializable(value) {
    try { return JSON.parse(JSON.stringify(value)); } catch (error) { return "[non-serializable]"; }
  }
  function recordService(target, path) {
    return new Proxy(target, {get(object, key) {
      const value = object[key];
      if (typeof value !== "function") return value;
      return (...args) => {
        const method = path + "." + String(key);
        records.push({method, args: args.map(serializable)});
        const result = value.apply(object, args);
        if (Array.isArray(result)) return result.map((item, index) => item && typeof item === "object" && !Array.isArray(item) ? recordService(item, method + "()[" + index + "]") : item);
        return result && typeof result === "object" && !Array.isArray(result) && !(result instanceof Date) ? recordService(result, method + "()") : result;
      };
    }});
  }
  function recordLog(...args) {
    records.push({log: args.map(value => typeof value === "string" ? value : JSON.stringify(value)).join(" ")});
  }
  const capturedConsole = {log: recordLog, error: recordLog, warn: recordLog, info: recordLog};
  invokeLesson(e, recordService(SpreadsheetApp, "SpreadsheetApp"), recordService(DocumentApp, "DocumentApp"), recordService(DriveApp, "DriveApp"), recordService(GmailApp, "GmailApp"), recordService(MailApp, "MailApp"), recordService(FormApp, "FormApp"), recordService(CalendarApp, "CalendarApp"), recordService(SlidesApp, "SlidesApp"), recordService(ScriptApp, "ScriptApp"), recordService(PropertiesService, "PropertiesService"), recordService(CacheService, "CacheService"), recordService(LockService, "LockService"), recordService(HtmlService, "HtmlService"), recordService(UrlFetchApp, "UrlFetchApp"), recordService(Utilities, "Utilities"), capturedConsole, capturedConsole);
  const expected = [
    {
      "method": "CacheService.getScriptCache",
      "args": []
    },
    {
      "method": "CacheService.getScriptCache().get",
      "args": [
        "total:v1"
      ]
    },
    {
      "method": "CacheService.getScriptCache().put",
      "args": [
        "total:v1",
        "{\"total\":400}",
        60
      ]
    },
    {
      "method": "CacheService.getScriptCache().get",
      "args": [
        "total:v1"
      ]
    },
    {
      "log": "400"
    }
  ];
  if (JSON.stringify(records) !== JSON.stringify(expected)) throw new Error("Contract mismatch: inspect actual calls and logs");
  console.log("Contract assertions passed: lesson 88");
}
Important line explanations
Line 1: function invokeLesson(e, SpreadsheetApp, DocumentApp, DriveApp, GmailApp, MailApp, FormApp, CalendarApp, SlidesApp, ScriptApp, PropertiesService, CacheService, LockService, HtmlService, UrlFetchApp, Utilities, console, Logger) {
Inject the recording adapters and console into the lesson function, including its helpers; preserve the main entry point.
Line 2: function lessonAction() {
Define a named callable block; defining it does not invoke it.
Line 3: const cache = CacheService.getScriptCache();
Bind the named value for the operations below; referenced arrays and objects may still be mutable.
Line 4: let value = cache.get("total:v1");
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 5: if (value === null) { value = JSON.stringify({total: 400}); cache.put("total:v1", value, 60); }
Evaluate this condition and test both accepted and rejected branches.
Line 6: console.log(JSON.parse(cache.get("total:v1")).total);
Parse syntax before validating business fields; malformed JSON throws.
Line 7: }
Close the current block; indentation shows the scope.
Line 8: return lessonAction(e);
Return a result or stop this branch; returning differs from logging.
Line 9: }
Close the current block; indentation shows the scope.
Line 10:
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 11: // A local dependency-injection contract test: calls still delegate to supported adapters.
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 12: function main() {
Define a named callable block; defining it does not invoke it.
Line 13: const records = [];
Bind the named value for the operations below; referenced arrays and objects may still be mutable.
Line 14: function serializable(value) {
Define a named callable block; defining it does not invoke it.
Line 15: try { return JSON.parse(JSON.stringify(value)); } catch (error) { return "[non-serializable]"; }
Parse syntax before validating business fields; malformed JSON throws.
Line 16: }
Close the current block; indentation shows the scope.
Line 17: function recordService(target, path) {
Define a named callable block; defining it does not invoke it.
Line 18: return new Proxy(target, {get(object, key) {
Intercept supported service method access for this local contract test; calls still delegate to the original fictional adapter.
Line 19: const value = object[key];
Bind the named value for the operations below; referenced arrays and objects may still be mutable.
Line 20: if (typeof value !== "function") return value;
Evaluate this condition and test both accepted and rejected branches.
Line 21: return (...args) => {
Return a result or stop this branch; returning differs from logging.
Line 22: const method = path + "." + String(key);
Bind the named value for the operations below; referenced arrays and objects may still be mutable.
Line 23: records.push({method, args: args.map(serializable)});
Capture an actual method argument or console value for comparison with the frozen authored contract.
Line 24: const result = value.apply(object, args);
Execute the actual supported adapter method with its original receiver and arguments; the recorder does not fabricate a successful result.
Line 25: if (Array.isArray(result)) return result.map((item, index) => item && typeof item === "object" && !Array.isArray(item) ? recordService(item, method + "()[" + index + "]") : item);
Build a new output item for every input item, preserving the intended row shape.
Line 26: return result && typeof result === "object" && !Array.isArray(result) && !(result instanceof Date) ? recordService(result, method + "()") : result;
Return a result or stop this branch; returning differs from logging.
Line 27: };
Close the current block; indentation shows the scope.
Line 28: }});
Close the current block; indentation shows the scope.
Line 29: }
Close the current block; indentation shows the scope.
Line 30: function recordLog(...args) {
Define a named callable block; defining it does not invoke it.
Line 31: records.push({log: args.map(value => typeof value === "string" ? value : JSON.stringify(value)).join(" ")});
Capture an actual method argument or console value for comparison with the frozen authored contract.
Line 32: }
Close the current block; indentation shows the scope.
Line 33: const capturedConsole = {log: recordLog, error: recordLog, warn: recordLog, info: recordLog};
Bind the named value for the operations below; referenced arrays and objects may still be mutable.
Line 34: invokeLesson(e, recordService(SpreadsheetApp, "SpreadsheetApp"), recordService(DocumentApp, "DocumentApp"), recordService(DriveApp, "DriveApp"), recordService(GmailApp, "GmailApp"), recordService(MailApp, "MailApp"), recordService(FormApp, "FormApp"), recordService(CalendarApp, "CalendarApp"), recordService(SlidesApp, "SlidesApp"), recordService(ScriptApp, "ScriptApp"), recordService(PropertiesService, "PropertiesService"), recordService(CacheService, "CacheService"), recordService(LockService, "LockService"), recordService(HtmlService, "HtmlService"), recordService(UrlFetchApp, "UrlFetchApp"), recordService(Utilities, "Utilities"), capturedConsole, capturedConsole);
Inject the recording adapters and console into the lesson function, including its helpers; preserve the main entry point.
Line 35: const expected = [
These are fixed authored expectations. They are not recalculated from the learner’s changed source.
Line 36: {
Close the current block; indentation shows the scope.
Line 37: "method": "CacheService.getScriptCache",
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 38: "args": []
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 39: },
Close the current block; indentation shows the scope.
Line 40: {
Close the current block; indentation shows the scope.
Line 41: "method": "CacheService.getScriptCache().get",
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 42: "args": [
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 43: "total:v1"
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 44: ]
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 45: },
Close the current block; indentation shows the scope.
Line 46: {
Close the current block; indentation shows the scope.
Line 47: "method": "CacheService.getScriptCache().put",
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 48: "args": [
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 49: "total:v1",
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 50: "{\"total\":400}",
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 51: 60
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 52: ]
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 53: },
Close the current block; indentation shows the scope.
Line 54: {
Close the current block; indentation shows the scope.
Line 55: "method": "CacheService.getScriptCache().get",
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 56: "args": [
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 57: "total:v1"
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 58: ]
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 59: },
Close the current block; indentation shows the scope.
Line 60: {
Close the current block; indentation shows the scope.
Line 61: "log": "400"
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 62: }
Close the current block; indentation shows the scope.
Line 63: ];
Follow this operation in the source and compare its exact arguments and effect with the authored explanation.
Line 64: if (JSON.stringify(records) !== JSON.stringify(expected)) throw new Error("Contract mismatch: inspect actual calls and logs");
Reject any changed call or result. This deterministic fixture comparison is not a general semantic-equivalence or Google integration test.
Line 65: console.log("Contract assertions passed: lesson 88");
Record this actual result; inspect side effects too rather than treating a log as success.
Line 66: }
Close the current block; indentation shows the scope.
Exact expected output and resource
{
  "logs": [
    "Contract assertions passed: lesson 88"
  ],
  "error": null,
  "resource": "logs",
  "value": null
}

Build and test

Repair the supplied source so that A cache miss computes and stores total 400; reading the same key returns it during this run. Inspect the output and preserve unrelated data. A completion message alone does not satisfy the resource contract.

function main() {
  const cache = CacheService.getScriptCache();
  let value = cache.get("total:v1");
  if (value === null) { value = JSON.stringify({total: 400}); cache.put("total:v1", value, 60); }
  console.log(JSON.parse(cache.get("missing")).total);
}

Graduated hints

Hint 1

Locate get("missing")).total in the failing source and predict its effect before changing it.

Hint 2

Compare the intended operation get("total:v1")).total with the failing operation get("missing")).total. Use the earliest different log or state value.

Hint 3

Replace the relevant get("missing")).total operation with get("total:v1")).total; rerun on fresh sample and explain why the result now satisfies the contract.

Reference solution

function main() {
  const cache = CacheService.getScriptCache();
  let value = cache.get("total:v1");
  if (value === null) { value = JSON.stringify({total: 400}); cache.put("total:v1", value, 60); }
  console.log(JSON.parse(cache.get("total:v1")).total);
}

Explain and reflect

Explain why A cache miss computes and stores total 400; reading the same key returns it during this run. Which operation provides the strongest evidence? Propose one independent input with an exact expected outcome, and state what must still be checked on Google.

Extend this operation for a second realistic dataset. Preserve the source records, define a normal and invalid case before execution, and write a rerun policy for side effects. Review the resulting source with a peer before authorizing real services.

Troubleshooting

Choose main as the entry function, or use the exact entry required by the example. Use the Manual event for this example. If there is no console output inspect the logs preview and Execution Trace. Reset before comparing to the fixed sample contract. Unsupported Google methods fail visibly; inspect the supported-service reference rather than assuming a successful fixture is a Google integration test.

Knowledge check

Explain the key method or operator. Give an exact output for a second input, plus one invalid case. Verify the result in the interactive lesson; written explanations need self or educator review.

Optional AI practice

Explain this concept using the source above. Help implement one small extension and define its tests. Review/debug the source using its actual expected output; cite real method references and never claim execution.

Transfer to Google and authorization guide

Next lesson: Locking and concurrency

Common mistakes

Official references

Three lesson-specific AI prompts

Explain
Explain this Apps Script lesson: Caching. Objective: Explain the input, important operations and evidence boundary in caching. Current reference source:
function main() {
  const cache = CacheService.getScriptCache();
  let value = cache.get("total:v1");
  if (value === null) { value = JSON.stringify({total: 400}); cache.put("total:v1", value, 60); }
  console.log(JSON.parse(cache.get("total:v1")).total);
}
Expected: A cache miss computes and stores total 400; reading the same key returns it during this run.
My changed source: [paste the current visible source]. Actual output/error: [paste the run result]. Explain supported methods, types, authorization, duplicate behavior and verification boundaries. Give normal, boundary and invalid tests. Do not claim you executed Google services; do not request credentials. I will verify every proposed change.
Implement
Implement this Apps Script lesson: Caching. Objective: Explain the input, important operations and evidence boundary in caching. Current reference source:
function main() {
  const cache = CacheService.getScriptCache();
  let value = cache.get("total:v1");
  if (value === null) { value = JSON.stringify({total: 400}); cache.put("total:v1", value, 60); }
  console.log(JSON.parse(cache.get("total:v1")).total);
}
Expected: A cache miss computes and stores total 400; reading the same key returns it during this run.
My changed source: [paste the current visible source]. Actual output/error: [paste the run result]. Explain supported methods, types, authorization, duplicate behavior and verification boundaries. Give normal, boundary and invalid tests. Do not claim you executed Google services; do not request credentials. I will verify every proposed change.
Review/debug
Review/debug this Apps Script lesson: Caching. Objective: Explain the input, important operations and evidence boundary in caching. Current reference source:
function main() {
  const cache = CacheService.getScriptCache();
  let value = cache.get("total:v1");
  if (value === null) { value = JSON.stringify({total: 400}); cache.put("total:v1", value, 60); }
  console.log(JSON.parse(cache.get("total:v1")).total);
}
Expected: A cache miss computes and stores total 400; reading the same key returns it during this run.
My changed source: [paste the current visible source]. Actual output/error: [paste the run result]. Explain supported methods, types, authorization, duplicate behavior and verification boundaries. Give normal, boundary and invalid tests. Do not claim you executed Google services; do not request credentials. I will verify every proposed change.