Type feedback: the fuel for the optimiser
An optimiser is useless without runtime type information. How the feedback vector records, per IC site, the maps, primitive-type lattice, call targets, and binary-op types the interpreter observes — and why garbage feedback produces generic code or no optimisation at all.
TurboFan compiles a function that does a + b and produces, for that one operation, a single integer-add machine instruction with no boxing, no type check beyond a cheap guard. How does a compiler for a dynamically-typed language know a and b are integers? It doesn’t — it asks the interpreter what it has seen. Strip that observation away and the same compiler can only emit the generic, branch-heavy “add anything to anything” routine. The fuel that turns a generic optimiser into a specialising one is type feedback.
Why an optimiser is blind without feedback
JavaScript has no static types the engine can trust. At the point function add(a, b) { return a + b; } is compiled, the engine cannot prove a is a number — it could be a string, an object with a valueOf, a BigInt. A naively-compiled + must therefore handle every case: check tags, branch on string-vs-number-vs-object, possibly call a user valueOf, box the result. That generic path is correct but slow.
The way out is speculation: assume the types you have actually observed, emit fast code for exactly those, and protect it with a cheap guard that bails if the assumption breaks (lesson 04). But speculation needs evidence — and the evidence comes from the only tier that runs every operation while watching its operands: Ignition, the interpreter. As Ignition runs, it writes down what it sees at each “interesting” location. That record is the feedback vector.
The feedback vector: structure and ownership
A feedback vector is a fixed-size array allocated in the GC heap. The crucial detail people get wrong is what owns it. The bytecode and the layout of the feedback slots are shared: they live on the function’s SharedFunctionInfo (SFI), the engine’s deduplicated record of “this function’s code”, one per source definition. But the feedback vector itself — the array holding the observed data — is allocated per closure. Two closures created from the same function source share bytecode and slot layout, but each has its own feedback vector, so their runtime observations don’t pollute each other.
Each slot corresponds to one inline cache (IC) site in the bytecode — a place where the type of the operands matters:
- Property access (
obj.x,obj.x = v) — records the map (hidden class) of the object seen, plus a handler describing how to load/store at that map. - Calls (
fn(),obj.method()) — records the call target(s) observed, enabling inlining. - Binary operations (
a + b,a < b) — records the type lattice of the operands: were they always Smi (small integer)? Smi-or-HeapNumber? String? Any? - Element access (
arr[i]) — records the elements kind (packed Smi, packed double, holey, dictionary).
The primitive-type lattice
For arithmetic, the feedback is not just “number”. V8 tracks operand types on a small lattice that it widens monotonically as it sees more cases. A useful mental model for a + slot:
None -> SignedSmall (Smi) -> Number (Smi or HeapNumber) -> NumberOrOddball -> Any
\-> String (if a string operand appears) -> AnyEach new observation can only move up the lattice (widen), never narrow. A slot that has only ever seen small integers stays at SignedSmall, and TurboFan can emit a 32-bit integer add guarded by a single “is Smi” check. The first time that slot sees a value that overflows Smi range, it widens to Number, and the next optimisation emits float64 arithmetic instead. If it ever sees a string, it widens toward Any, and arithmetic falls back to the fully generic routine. This monotonic widening is exactly why mixing types is so corrosive: one off-type value permanently pollutes the slot for the lifetime of that feedback vector.
Garbage in, generic out
Here is the practical question: if you call a hot function with five different object shapes in its first dozen invocations, what does the optimiser see when it finally compiles? The optimiser is only as good as the feedback. Three states matter for any IC slot:
- Monomorphic — one map / one stable type observed. The optimiser specialises hard: direct offset load, inlined call, integer add. Fastest.
- Polymorphic — a small handful (V8’s cap is 4) of maps/types. The optimiser can still inline with an upfront map check that branches between the known cases. Slower, still optimised.
- Megamorphic — more than the cap. The slot is marked with a megamorphic sentinel; the optimiser gives up on specialising it and emits a generic dispatch (a runtime lookup). It may decline to optimise the surrounding function at all.
Together these three states form the whole story: warming with one shape gives you the fast path, letting two or three shapes in still keeps you optimised, but blasting more than four through the same slot permanently degrades it to generic dispatch.
- Monomorphic
- 1 map / type -> specialise
- Polymorphic
- 2-4 maps -> inline w/ check
- Megamorphic threshold
- more than 4 maps
- Megamorphic
- generic dispatch / no opt
- Lattice widening
- monotonic, one-way
- Feedback vector ownership
- per closure
- Slot layout / bytecode owner
- SharedFunctionInfo
- d8 inspector
- %DebugPrintFeedback(fn)
The practical rule that falls out of this: warm a function with consistent types before it tiers up. If a hot function will mostly process integers, do not let the first dozen calls feed it strings; if a call site will mostly receive one object shape, do not route five shapes through it. The feedback vector is filled during the interpreted phase, and whatever lattice and map set it accumulates is exactly what the optimiser will (or won’t) be able to specialise on.
Two closures are created from the same function source. What do they share, and what is per-closure?
A `+` site processes 9,999 integer pairs, then one pair where one operand is a string, then a million more integer pairs. What feedback does TurboFan see, and what code does it emit?
Order the lifecycle of a single binary-op feedback slot from a cold function to specialised machine code.
- 1 The slot starts at None (the function is cold, never run)
- 2 Ignition executes the op and records the observed operand type (e.g. SignedSmall)
- 3 Repeated calls keep the slot monomorphic at SignedSmall
- 4 The budget trips; the optimiser reads the slot and emits a Smi-guarded integer add
▸Edge cases
A subtle consequence: feedback vectors are GC-heap objects and can be collected under memory pressure, then re-allocated empty. A long-lived process that suffers a feedback-vector flush effectively re-cools the affected functions — they must re-observe types before they can re-optimise. This is rare, but it explains the occasional “why did this hot function deopt to interpreter speed after an hour of uptime with no code change?” mystery: the vector was reclaimed and had to refill.
- 01What is the feedback vector, what does each slot record, and who owns it?
- 02Why is the operand-type lattice monotonic, and what is the practical cost?
- 03Explain monomorphic vs polymorphic vs megamorphic feedback and what the optimiser does in each case.
A JavaScript optimiser cannot read your types statically, so it specialises by speculation on what was actually observed at runtime. Those observations live in the feedback vector: a fixed-size GC-heap array with one slot per inline-cache site. Each slot records what matters at that site — the map for a property access, the call target for a call, the elements kind for an array access, and a monotonically-widening type lattice for a binary op. Ownership is split between the SharedFunctionInfo (which holds the deduplicated bytecode and the slot layout, one per source function) and the per-closure feedback vector (which holds that closure’s own observations). Only Ignition fills the vector; Maglev and TurboFan only read it. Feedback quality determines code quality: a monomorphic slot is specialised hard, a polymorphic slot (up to 4 maps) is inlined behind a check, and a megamorphic slot collapses to generic dispatch and can block optimisation entirely. Because the lattice only widens, one off-type value pollutes a slot for the life of the vector — so warming a function with consistent types before it tiers up is the whole game, and TypeScript annotations, being erased, contribute nothing. Now when you profile a function and wonder why it runs generic add instead of a single integer instruction, check the feedback first: one stray string five minutes ago may still own that slot.
Practice
Start at the top. Tasks go easiest → hardest: recall a fact, apply it to a case, then a senior-level stretch. Open one, attempt it, then reveal.
appears again in184
- Why GraphQL gets N+1junior
- DataLoader mechanics: tick-boundary batchingmiddle
- Batch function contracts: ordering, shapes, errorsmiddle
- Federation and lookahead: batching beyond DataLoadermiddle
- Query complexity defences: depth, cost, persisted queriesmiddle
- Senior GraphQL API: scheduling contract, tenant isolation, observabilitysenior
- Why idempotency: making retries safejunior
- Server-side state machine: four states of an idempotency keymiddle
- Outbox and inbox: effectively-once across the dual-write boundarymiddle
- Concurrency and cache architecture for idempotency at scalesenior
- Observability, production failures, and global-scale designsenior
- The event loop: one thread, three queuesjunior
- Tasks, microtasks, and scheduler.yield()middle
- Microtask starvation, Long Tasks, and LoAFsenior
- Node.js event loop: phases, nextTick, and loop lagsenior
- React, Vue, and INP observability in productionsenior
- The render pipeline: six stages from bytes to pixelsjunior
- Stage costs and the renderer process modelmiddle
- Invalidation, dirty bits, and containmiddle
- Compositor layers: promotion, overlap, and GPU memorymiddle
- DevTools flame strip and the frame lifecyclemiddle
- Layout thrash: forced synchronous layoutsenior
- BeginMainFrame, compositor-driven animations, and GPU memorysenior
- Production observability: LoAF, INP, and the full attack surfacesenior
- What V8 is and why performance varies 100×junior
- V8''''s four-tier JIT pipeline and profile-guided tieringmiddle
- Hidden classes, transition trees, and memory layoutmiddle
- Inline caches, IC states, and deoptimizationmiddle
- Orinoco GC: parallel scavenger, concurrent marking, and write barriersmiddle
- TurboFan''''s speculative engine and the deopt-loop trapsenior
- V8 in production: isolates, pointer compression, and real failuressenior
- Service worker lifecycle and cache strategiesmiddle
- Service worker edge cases: version skew, durability, and navigation trapssenior
- What the reconciler does: render vs commitjunior
- The fiber object and the double-buffer treemiddle
- Render phase purity and commit phase sub-stepsmiddle
- Reconciliation: diffing heuristics and the key trapmiddle
- Priority lanes, time-slicing, and useTransitionmiddle
- Bailout, memoisation, and tearingsenior
- React Profiler, the Compiler, and production observabilitysenior
- Rendering strategies: SSG, SSR, ISR, streaming, and hydrationjunior
- SSG, SSR, ISR, streaming, and RSC — how each worksmiddle
- Hydration cost: selective, progressive, islands, resumabilitymiddle
- Hydration mismatch: causes, detection, and the determinism rulesenior
- RSC, per-route strategy, and production observabilitysenior
- Core Web Vitals: what LCP, INP, and CLS measurejunior
- CLS: why layout shifts happen and how to stop themmiddle
- Metric tradeoffs, RUM attribution, and the CI+field loopsenior
- The full picture: URL to LCP to INP as a relay racejunior
- Eight layers traced: from the service worker to the second navigationmiddle
- Five canonical breaks: where production reliably diessenior
- The three-track method: reading traces and building a monitored systemsenior
- What is a cache stampede and why it makes things worsejunior
- Lock and single-flight: bounding concurrent rebuildsmiddle
- XFetch: coordination-free probabilistic early expirationmiddle
- Stale-while-revalidate and CDN request coalescingmiddle
- Detecting stampedes and designing TTL for productionmiddle
- Metastable failure, fencing tokens, and production postmortemssenior
- What a relation is: tables, rows, keys, and constraintsjunior
- Constraints, keys, and Postgres data typesmiddle
- Normal forms, denormalization, and why schemas stickmiddle
- JSONB, arrays, and when a side table winsmiddle
- Heap storage, TOAST, and column alignmentsenior
- Schema integrity: deferral, versioning, and production failure modessenior
- Relational vs document, wide-column, graph, and key-valuesenior
- Index-only scans, the Visibility Map, and INCLUDEsenior
- Production failure modes and the index audit playbooksenior
- pg_statistic, ANALYZE, and production observabilitymiddle
- Production failure modes and plan stabilitysenior
- MVCC: why readers and writers never wait for each otherjunior
- Row versions and snapshots: the on-disk mechanicsmiddle
- HOT updates and isolation levels: what you gain and what you paymiddle
- Vacuum and bloat: keeping the storage tax boundedmiddle
- CLOG, XID wraparound, and MultiXact: deep visibility internalssenior
- SSI internals and production autovacuum tuningsenior
- Real-world MVCC failures, deployment patterns, and distributed snapshotssenior
- Connection pools: amortising the cost of a Postgres backendjunior
- PgBouncer session, transaction, and statement modesmiddle
- Pool sizing: the (cores × 2) + spindles formula and the two-layer stackmiddle
- Pool exhaustion and idle-in-transaction: the 3 AM failure modemiddle
- Migrating to transaction mode: rollout playbook and PgBouncer 1.21 prepared statementsmiddle
- The Postgres process model and why raising max_connections degrades throughputsenior
- Pooler landscape 2026, serverless connection storms, and the full failure-mode taxonomysenior
- What a schema migration is and why it replaces ad-hoc DDLjunior
- ADD COLUMN: instant in PG 11+ vs rewrite in older Postgresjunior
- The lock-queue failure mode: why instant DDL can freeze the databasemiddle
- Safe DDL patterns: NOT VALID, CONCURRENTLY, and unsafe-op fixesmiddle
- Expand-contract: zero-downtime for breaking schema changesmiddle
- Advisory locks, migration tools, and deploy coordinationsenior
- Migration failure taxonomy and production disciplinesenior
- Why sharding exists: the single-Postgres ceilingjunior
- Shard-key selection: hash, range, list, and directory strategiesmiddle
- Partitioning vs sharding: same word, two different thingsmiddle
- Co-location and Citus: the invariant that makes sharding usablemiddle
- The hot-shard failure mode: detection, isolation, and durable policymiddle
- Schema-based sharding and multi-tenancy alternativessenior
- Online resharding, 2PC, and the operational cost of shardingsenior
- The seven acts: from CREATE TABLE to Citusjunior
- Acts 1–3 in depth: schema, indexes, and planner statisticsmiddle
- Acts 4–6 in depth: MVCC bloat, connection pooling, and safe migrationsmiddle
- Act 7 in depth: sharding, co-location, and the seven-tier tradeoff cascademiddle
- Observability, anti-patterns, and production triagesenior
- Raft roles, terms, and why majority quorums prevent split brainjunior
- How Raft replicates a log entry and decides it is safe to commitmiddle
- Raft leader election: timeouts, voting rules, and the four safety propertiesmiddle
- Raft in the real world: partitions, slow disks, and client routingmiddle
- Raft extensions: pre-vote, learners, snapshots, and linearizable readssenior
- Raft in production: membership changes, Multi-Raft, and observabilitysenior
- Where data fetching happens — and why it decides LCPjunior
- Fetch waterfalls — diagnosis and the Promise.all curemiddle
- React Server Components and Suspense streamingmiddle
- Client-side cache: TanStack Query, SWR, and stale-while-revalidatemiddle
- LCP, prefetch, and race conditions in interactive fetchingmiddle
- Senior internals: RSC payload, caching layers, and production failure modessenior
- The three-way handshakejunior
- Sequence numbers and connection statemiddle
- DNS: what it does and why it existsjunior
- The resolver walk: referrals, record types, and gluemiddle
- TTL, caching, and DNS propagationmiddle
- The 1-RTT handshake: key shares and ECDHEmiddle
- Session resumption and 0-RTTmiddle
- WebSocket: the HTTP upgrade handshakejunior
- WebSocket frame format: opcodes, masking, fragmentationmiddle
- WebSocket backpressure: when clients can''''t keep upmiddle
- Reconnection: jittered backoff, thundering herd, message resumptionsenior
- WebSocket at scale: HTTP/2 multiplexing, permessage-deflate, C10Msenior
- WebSocket in production: proxies, security, and distributed architecturesenior
- What reverse proxies dojunior
- Health checks, connection draining, and slow startmiddle
- Session affinity, consistent hashing, and the right fixmiddle
- Retry storms, circuit breakers, and load sheddingsenior
- Resilient LB architecture: anycast, zone-aware routing, and observabilitysenior
- Why QUIC and not TCP+TLSjunior
- Connection IDs and network migrationmiddle
- 0-RTT resumption and packet encryptionsenior
- DDoS: what it is and why it worksjunior
- Amplification attacks and state exhaustionmiddle
- Rate limiting: algorithms and architecturemiddle
- WAFs, firewalls, mTLS, and HSTSmiddle
- DNS cache poisoning and BGP hijackingsenior
- Defense-in-depth architecture and attack economicssenior
- DNS, TCP, TLS in sequence: where the milliseconds gomiddle
- Proxy intercepts and security gates: rate limiters, WAF, mTLSmiddle
- Alternate paths: QUIC 0-RTT, WebSocket upgrade, connection migrationmiddle
- Observability: distributed traces, USE/RED, and samplingsenior
- Resilience: cascading retries, circuit breakers, and error budgetssenior
- What the three signals are: logs, metrics, and tracesjunior
- Why structured logs exist: the diary vs the spreadsheetjunior
- The production log schema: fields every line must carrymiddle
- PII redaction and log injectionsenior
- OTel Logs Data Model and audit logs as a subsystemsenior
- SLI, SLO, and the error budget: reliability by the numbersjunior
- Error budget policy, latency SLOs, and composite journeysmiddle
- Production SLO failures, self-observability, security, and the big picturesenior
- The incident loop: from pager to postmortem to preventionmiddle
- Cache lines, struct layout, and false sharingmiddle
- SIMD, SoA vs AoS, and memory bandwidthmiddle
- Cache-oblivious algorithms, PGO, and production failuressenior
- GC in production: observability, security, edge cases, and fleet governancesenior
- Batching: amortize fixed cost per operationjunior
- The batching window: size and wait timemiddle
- Batching in Kafka and Postgresmiddle
- io_uring and observability of batchingmiddle
- From Nagle to io_uring: evolution of batchingmiddle
- Backpressure, failure isolation, and batch security in productionsenior
- CI enforcement and RUM: making budgets stickmiddle
- V8 JIT pipeline, HTTP priorities, and bundle securitysenior
- The performance loop: discipline, not a projectjunior
- Classify and fix: matching bottleneck families to remediesmiddle
- Observability stack and CI gates: catching regressions before they shipmiddle
- Incident to enforcement: SLO burn to verified fix in 35 minutesmiddle
- Culture, economics, and org-scale performancesenior
- At-most-once, at-least-once, exactly-once: the three delivery contractsjunior
- The three failure legs — where duplicates and losses actually happenmiddle
- Consumer-side dedup: the cheapest path to exactly-once processingmiddle
- Kafka exactly-once semantics: idempotent producer and transactionsmiddle
- SQS visibility timeout, DLQ, and the outbox patternmiddle
- Exactly-once in production: impossibility proof, hybrid patterns, and real incidentssenior
- What OAuth is and why passwords are not the answerjunior
- Authorization code flow with PKCEmiddle
- ID token validation and JWKS cache managementmiddle
- Refresh token rotation and scope-based least privilegemiddle
- Sender-constrained tokens: DPoP and mTLSsenior
- OAuth in production: audience attacks, observability, and real failuressenior
Something unclear?
Ask a question about this lesson. Questions are anonymous and go straight to the author to make the lesson better.