Cache V8 compiled scripts in a C++ embedder
Reduce repeated parse/compile cost in V8 embedders by producing and consuming script code caches, with fallback on cache misses.
04 Nov 2026, 12:17 UTC

Problem: repeated compilation in a V8 embedder
When a C++ application embeds V8 and executes the same JavaScript source repeatedly—once per isolate, once per serverless invocation, or on every startup—V8 parses and compiles that source from scratch each time. For large libraries or startup-critical scripts, this repeated work adds latency without changing program behavior.
Useful takeaway: V8's ScriptCompiler API can serialize compiled script output into a reusable blob called a code cache. Produce it once, store it, and pass it back on later compiles so V8 skips parsing and most compilation. If the blob is missing, stale, or incompatible, fall back to ordinary compilation and run the script normally.
Prerequisites
- A C++ toolchain linked against a V8 build and
libplatform. - A running
v8::Isolatewith an activev8::HandleScope. - The script source as a
v8::Localand a matchingv8::ScriptOrigin. - A place to persist the blob, such as a file or in-memory cache keyed by source hash.
Terms used in this guide
- Code cache: a binary blob produced by V8 that represents compiled script output. It is not machine code portable across processors.
- CachedData: the V8 type that owns a code-cache blob. The embedder manages its lifetime.
- Isolate: a V8 VM instance with its own heap and compiled-script state.
Produce a code cache on the first compile
Pass kProduceCodeCache to ScriptCompiler::Compile. On success, V8 populates the Source object with a CachedData* pointer. The embedder owns that pointer and must serialize it for later reuse. Adapt this snippet to your V8 version; API signatures can change between releases.
v8::ScriptCompiler::CachedData* ProduceCache(
v8::Isolate* isolate,
v8::Local source,
const v8::ScriptOrigin& origin) {
v8::ScriptCompiler::Source script_source(source, origin);
v8::ScriptCompiler::CacheOptions options =
v8::ScriptCompiler::CacheOptions::kProduceCodeCache;
v8::Local script =
v8::ScriptCompiler::Compile(isolate, &script_source, options);
if (script.IsEmpty()) {
return nullptr;
}
return script_source.GetCachedData();
}
After production, serialize the blob's data and length to disk or memory. Release the CachedData when your embedder no longer needs the in-memory copy.
Store and load the cached blob
Cache blobs are not portable across V8 versions, build configurations, pointer-compression modes, or target architectures. Key your stored blob by a combination of source content hash, V8 build identifier, and architecture so you never attempt to consume a blob built under different conditions.
Consume the cache on later compiles
Load the stored blob, wrap it in a CachedData, attach it to the Source, and pass kConsumeCodeCache. V8 validates the blob against the current source and isolate configuration. If validation passes, compilation skips parsing and most code generation.
v8::Local CompileWithCache(
v8::Isolate* isolate,
v8::Local source,
const v8::ScriptOrigin& origin,
v8::ScriptCompiler::CachedData* cached) {
v8::ScriptCompiler::Source script_source(source, origin, cached);
v8::ScriptCompiler::CacheOptions options =
v8::ScriptCompiler::CacheOptions::kConsumeCodeCache;
return v8::ScriptCompiler::Compile(isolate, &script_source, options);
}
Handle cache misses and invalid blobs
V8 treats cache consumption as optional. A missing file, changed source, or upgraded V8 produces a silent miss: Compile returns an empty script or ignores the blob. Your embedder must always retry without the cache.
v8::Local CompileScriptResilient(
v8::Isolate* isolate,
v8::Local source,
const v8::ScriptOrigin& origin,
v8::ScriptCompiler::CachedData* cached) {
v8::Local script = CompileWithCache(isolate, source, origin, cached);
if (!script.IsEmpty()) {
return script;
}
v8::ScriptCompiler::Source uncached(source, origin);
return v8::ScriptCompiler::Compile(
isolate, &uncached, v8::ScriptCompiler::CacheOptions::kNoCacheOptions);
}
Build the embedder
Run on your build host with read access to the V8 headers and libraries:
c++ -std=c++17 -I/path/to/v8/include \
-L/path/to/v8/lib -lv8 -lv8_libplatform \
embedder.cc -o embedder
Replace /path/to/v8/include and /path/to/v8/lib with your V8 checkout paths. A mismatch between the headers used to compile the embedder and the V8 shared library at runtime can cause crashes or silent cache rejection.
Expected checks
- After
kProduceCodeCache, confirmGetCachedData()returns non-null and the blob length is greater than zero. - After
kConsumeCodeCache, confirm the returned script runs and produces the same result as an uncached compile. - Change one character in the script source and confirm the embedder falls back to uncached compilation without crashing.
- Upgrade V8 and confirm previously stored blobs are rejected and rebuilt.
A practical way to verify without instrumentation: run the same script repeatedly with cache consumption enabled and disabled, then compare end-to-end startup or compile latency. A durable reduction on repeated loads indicates the cache path is working. A one-off script should show no meaningful throughput improvement.
Limitations
- Code caching amortizes compile cost over repeated loads. It does not speed up a single execution.
- The cached blob occupies resident memory until released. Do not cache every script indiscriminately.
- Blobs are bound to the exact source, V8 version, isolate configuration, and architecture. Any mismatch causes a silent miss and normal recompilation.
- Treat code-cache blobs as executable artifacts: protect stored blobs with the same integrity and isolation controls as generated code.
Recovery options
Producing a cache allocates memory and, if you persist it, writes a file. Neither operation requires a database rollback, but both can leave stale state.
- If
kConsumeCodeCachefails, discard the blob and retry withkNoCacheOptions. - If a V8 upgrade changes the cache format, delete stored blobs so the embedder regenerates them.
- If memory pressure is a concern, release
CachedDataafter serialization and do not keep blobs for scripts that run only once.
Minimal decision flow
1. Is the same source compiled more than once? If no, skip caching.
2. Produce a cache on the first compile.
3. Store the blob keyed by source hash and build identity.
4. On later compiles, consume the blob; on any failure, fall back to uncached compilation.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.