Overview

11 Predictive techniques

When you can’t make a slow operation truly faster, you can often hide its delay by doing the work before it’s needed. This chapter frames predictive techniques around a simple pattern: find latency you cannot reduce, predict when results will be required, and initiate the work early so outputs are ready just in time. Approaches like prefetching, optimistic updates, speculative execution, and predictive resource allocation aim to deliver an experience that feels instantaneous. The hard part is prediction: getting it right can create the illusion of zero latency; getting it wrong can waste resources and even make latency worse.

Prefetching hides read latency by retrieving data in advance, using either pattern-based signals (sequential, spatial, or strided access) or semantic cues (dependencies between entities, current context, and per-user history). Done well, it avoids waiting on I/O; done poorly, it wastes bandwidth and pollutes caches. Optimistic updates target write latency by applying changes locally and syncing in the background via a shadow write queue and an optimistic view over local storage. Synchronization then reconciles concurrent edits using strategies such as last-writer-wins with logical or hybrid logical clocks, operational transformation, or CRDTs, with consistency ranging from eventual to causal or strong eventual. Robustness relies on idempotent retries, partial application of changes, rollbacks via snapshots or operation dependencies, and escalation to the UI for human resolution when needed.

Speculative execution generalizes the idea to computing results ahead of time: keep state current with incremental computation (for example, materialized views), explore multiple paths via parallel speculation and keep the fastest useful outcome, and even predict values to provide immediate feedback while confirming the final result. At the infrastructure layer, predictive resource allocation reduces provisioning delays: overprovisioning keeps excess capacity ready for spikes, while pre-warming starts resources just before anticipated demand based on cycles, events, or live trends. All of these methods trade resources, complexity, and potential side effects for speed—mispredictions can displace useful data, steal capacity from real work, or trigger unintended behavior. Used judiciously and measured carefully, predictive techniques are powerful tools to deliver low-latency experiences once simpler optimizations have been exhausted.

With sequential prefetching, we predict that successive data elements relative to the one we’re accessing to are needed in the future. In this example, we access the first data element and, therefore, predict that the next subsequent data elements are also needed.
In spatial prefetching, we make a prediction that nearby data elements are likely to be needed. In this example, access the fourth data element and make a prediction that third and fifth data elements are likely to be needed, and, therefore, prefetch them.
In stride-based prefetching, we make a prediction that data is accessed at fixed intervals. In this example, we access the first data element and make a prediction that every second data element is needed and prefetch them.
Optimistic views build on a base database and a shadow write queue. In this example, we have a database table of tasks with ID, task, and information about completion. The application writes locally to a shadow write queue, which is combined into an optimistic view, shown on left.
Lamport timestamps record the causal relationship between events. Each process maintains a counter, which increments every time the process sends out a message. The process includes the counter as part of the sent out message and when another process receives the message, the process updates its timestamp to the maximum of current and the received timestamp. In this example, you have three processes sending and receiving messages.
Incremental computation updates state incrementally as updates happen. In this example of a materialized view, an INSERT statement to a base table is reflected in a materialized view combining two tables. This ensure that when the view is queried, there is no perceived latency.
With parallel speculation, a backend system can initiate speculative generation of recommendations while the authentication flow is in progress. When login is done, the user can immediately view recommendations if needed. Of course, if the user does not view the recommendations, the speculative work done in parallel is wasted use of compute resources.

Summary

  • Predictive techniques hide latency by performing operations before they’re needed, effectively creating zero-latency experiences when implemented correctly
  • Prefetching retrieves data ahead of time using pattern-based approaches (sequential, spatial, stride-based), semantic methods, or machine learning to predict access patterns
  • Optimistic updates hide write latency by allowing immediate client-side changes with background synchronization, requiring conflict resolution mechanisms like timestamps or CRDTs
  • Speculative execution performs tasks before confirming they’re needed through techniques like incremental computation, parallel execution paths, and value prediction
  • Predictive resource allocation eliminates provisioning latency through overprovisioning (maintaining excess capacity) or pre-warming (just-in-time allocation)
  • Failed predictions can waste resources, add complexity, and potentially increase latency, making accurate prediction mechanisms crucial to success
  • Each technique trades consistency for latency, requiring careful consideration of application requirements and tolerance for temporary inconsistency

FAQ

What are predictive techniques for hiding latency?Predictive techniques perform long-running operations before they’re actually needed so results are ready just in time. The basic flow is: (1) identify operations whose latency you can’t reduce, (2) specify predictors to anticipate when results will be needed, and (3) initiate work ahead of time so the results are available exactly when required. Done well, they can create the illusion of zero latency; done poorly, they add overhead and waste resources.
How does prefetching reduce read latency, and what are the risks?Prefetching speculatively loads data before it’s needed so access appears instantaneous. For example, preloading user-specific data during login can make the app feel instantly ready after authentication. Risks include wasted bandwidth/compute if predictions are wrong, cache pollution that displaces useful data (causing misses), and unintended side effects (for example, triggering read receipts in an email system). Even OSes (readahead) and CPUs prefetch; mispredictions at those layers can also harm performance.
What pattern-based prefetching strategies can I use?Pattern-based approaches infer likely future accesses from past ones without understanding application semantics: - Sequential prefetching: assume data is accessed one element after another; maintain a prefetch window to keep upcoming elements resident. - Spatial prefetching: fetch nearby items (for example, adjacent map tiles, neighboring B-tree nodes). - Stride-based prefetching: detect fixed-interval access (for example, every Nth element in matrix operations). They’re simple and effective when patterns hold, but harmful if the pattern assumption doesn’t match reality.
How does semantic prefetching differ from pattern-based prefetching?Semantic prefetching uses application context and relationships, not just raw access patterns. Common strategies are: - Dependency-based: prefetch related entities (for example, permissions with a user profile, shopping cart with recommendations). - Context-based: prefetch based on current state (for example, location-aware points of interest, fetching payment/address on checkout navigation). - History-based: use past user behavior to predict future needs. Combining these improves accuracy but adds complexity and can be unpredictable if over-engineered.
What are optimistic updates and how do I implement an optimistic view?Optimistic updates hide write latency by applying changes locally and syncing to the backend asynchronously. Implement an optimistic view by: - Keeping local storage (for example, in-memory or SQLite). - Recording user modifications in a shadow write queue instead of writing directly to the base data. - Querying a merged view that overlays shadow writes on top of the base data. Users see instant feedback (for example, adding an item to a cart), while background sync reconciles with the server.
How do I synchronize optimistic updates and resolve conflicts?Synchronize asynchronously to avoid blocking the UI, and reconcile concurrent changes when multiple clients write: - LWW with logical ordering (Lamport timestamps, vector clocks) or hybrid logical clocks (HLC) to avoid relying solely on unsynchronized physical clocks. - Operational Transformation (OT) via a central server that transforms operations to keep all clients consistent. - CRDTs to merge updates without centralized coordination, ensuring convergence by using commutative, associative, idempotent operations.
What consistency guarantees should I expect with optimistic updates?They trade stronger consistency for lower latency. Typical guarantees include: - Eventual consistency: all replicas converge eventually, but reads can be stale. - Strong eventual consistency with CRDTs: automatic conflict resolution ensures convergence to the latest state. - Causal consistency with HLCs: causally related operations are observed in order. Locally you may achieve snapshot-like behavior, but global isolation is weaker (think read committed with a local snapshot).
How should I handle errors and rollbacks in optimistic update systems?Key practices: - Transparent retries for transient failures; design sync to be idempotent (unique operation IDs, CRDT ops, or conditional updates). - Partial application: apply non-conflicting changes even if some fail, accepting temporary inconsistency when acceptable (for example, shopping carts). - Rollbacks: use data snapshots or operation dependencies to revert safely. - Human-in-the-loop: surface irreconcilable conflicts or validation errors to users for resolution.
What is speculative execution, and which application-level patterns use it?Speculative execution performs work before it’s confirmed necessary, discarding results if unneeded. It hides latency but consumes extra resources. Application-level patterns include: - Incremental computation (for example, materialized views) to keep results up to date. - Parallel speculation: run multiple branches and keep the first useful result. - Value prediction: use estimated values (for example, delivery date, query autocomplete) and correct later if needed. Predictions that miss can degrade performance by stealing CPU, memory, bandwidth, or DB connections from real work, so accuracy matters.
How does predictive resource allocation work (overprovisioning vs pre-warming)?It hides provisioning latency by preparing capacity before it’s needed: - Overprovisioning: maintain extra capacity to absorb spikes instantly; simple and effective but can be costly if idle. - Pre-warming: provision just-in-time based on patterns (daily/weekly/seasonal), events (launches, campaigns), or real-time signals (rising traffic); reduces waste versus overprovisioning while still avoiding cold-start delays. Capacity planning and prediction quality determine effectiveness.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Latency ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Latency ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Latency ebook for free