Cache the compiled schema validators

Node · Node · intermediate · modification

Adds an in-memory memo cache to getValidator so each (schemaName, draft) pair is compiled once and reused. Repeated lookups now hit the Map instead of re-running the expensive compileSchema. Behavior is unchanged; the validators returned are identical to before, just cached.

getValidator sits on the hot path of a JSON API gateway: every inbound request looks up a validator by (schemaName, draft), and compileSchema builds it by walking the full schema graph. The same handful of pairs is requested millions of times a day.

Requirements

Files touched

--- src/validation/validatorCache.js
 const { compileSchema } = require('./compileSchema');
+
+const cache = new Map();
 
 // Returns a validator function for the named schema at the given draft version.
 // compileSchema walks the whole schema graph to build the validator (hundreds of
 // microseconds), and the same (schemaName, draft) pair is requested on nearly
-// every incoming request.
+// every incoming request, so we memoize the compiled result.
 function getValidator(schemaName, draft) {
-  return compileSchema(schemaName, draft);
+  const key = { schemaName, draft };
+  if (cache.has(key)) {
+    return cache.get(key);
+  }
+
+  const validator = compileSchema(schemaName, draft);
+  cache.set(key, validator);
+  return validator;
 }
 

Review this PR

Node practice