Article: Building an Offline-First AI Coding Tutor for Low-End Android Phones

MMS Founder
MMS • Chidi Nwaogu

Key Takeaways

  • On low-end devices in low-bandwidth markets, a full storage volume is a normal operating condition rather than an edge case, so any await on a cache or database write inside a critical render path is a latent blank screen and should be treated as a non-fatal degradation instead.
  • localStorage is the wrong persistence layer for any cache that scales with content or locale, because its roughly 5MB ceiling and synchronous API impose the heaviest cost on precisely the underpowered devices you are trying to serve, while IndexedDB with a dual-read migration window lets you move without stranding existing users.
  • WebAssembly runtimes such as Pyodide and sql.js make server-free code execution viable on smartphones, but only if you defer initialisation into a Web Worker and treat cold-start cost as a first-class UX problem rather than a benchmark footnote.
  • AI features that depend on a hosted endpoint should be designed with an explicit degradation contract, which includes a defined second tier, a defined timeout, persisted session state across the switch, and feedback formats that stay useful when the weaker model answers.
  • Discoverability and usability are different properties, and a feature placed outside a user’s working line of sight is functionally a feature that does not exist.

I spent a year watching students disappear. I was running an academy where they would join a live class, participate actively, and then vanish mid-session. When I followed up, almost none of them had chosen to leave. Their connections could not hold long enough to finish a lesson. Out of one cohort of 80 enrolled students, 6 graduated.

That experience exposed four assumptions underneath most coding education platforms, so normalised they barely register as assumptions: the learner has a laptop, the learner has broadband, the learner reads English comfortably, and the learner can pay for a subscription or belongs to an institution that already has.

The platform I built, Efiwe, inverts every one of those assumptions. It runs in a smartphone browser, works offline after a single setup, executes learner-submitted code locally, and does not require a data bundle after the initial load. It has been used by more than 22,000 learners across 160 countries, and it has been deployed in structured school pilots in Lagos and Ogun State in Nigeria, and in Uttarakhand, India.

This article is not about pedagogy. It is about engineering, and specifically about the parts that broke. The interesting problems in this space are not model quality. They are storage, quota, cold start, and failure-path design. Those problems generalise well beyond education, to any product whose users are on constrained devices and intermittent connections.

Why a PWA and not a native app

The first decision was distribution. A native Android app is the obvious route, yet we did not take it for three reasons.

First, install friction. An APK from a store is tens of megabytes before any content is available, consuming a data bundle that the learner may be rationing. A progressive web app lets a learner start on the first tap and pay the caching cost incrementally, in the background, while they are already learning.

Second, update cadence. We ship changes continuously. A service worker update propagates on the next visit. A store release does not, and in markets where users defer app updates to save data, a store release can leave a long tail of clients running code you fixed months ago.

Third, the web platform gave us a single runtime for code execution. We needed learners to write Python, SQL, JavaScript and HTML and see results immediately, without a server. WebAssembly in the browser gave us that on every platform at once.

A native shell wrapping a WebView would have given us the same execution model, and we considered it. Loading remote content, it would also have solved the update problem. What it would not have solved is install friction: the APK is still a download before any learning happens, on a data bundle the learner may be rationing. For a product whose entire premise is removing barriers to starting, that was enough to decide it.

The cost of this choice is that we inherit the browser’s storage model, including its quota behaviour, and that is where most of our production pain has come from.

Executing code without a server

Grading a coding challenge normally means shipping the submission to a server, running it in a sandbox, and returning a verdict. That model requires a round trip per attempt. In a classroom in Ijebu-Ode, Nigeria, with unreliable connectivity and learners who attempt a challenge ten or twelve times before solving it, that model is unusable.

So execution happens on the device. For SQL we use sql.js, which is SQLite compiled to WebAssembly. For Python we use Pyodide, which is CPython compiled to WebAssembly. Both are large, both are slow to initialise, and both will freeze the main thread if you let them.

The rule we settled on is that no runtime initialises on the main thread and no runtime initialises before it is needed. Course selection triggers a lazy worker spin-up, and the first paint of the challenge screen never waits on it. This is exemplified in the following snippet:

// runtime-host.js (main thread)

let workerPromise = null;

export function getRuntime(kind) {

  if (!workerPromise) {

    workerPromise = new Promise((resolve, reject) => {

      const worker = new Worker('/workers/runtime.js', { type: 'module' });

      const timer = setTimeout(
        () => reject(new Error('runtime-init-timeout')),
        45_000
      );

      worker.addEventListener('message', function onReady(e) {
        if (e.data?.type !== 'ready') return;
        clearTimeout(timer);
        worker.removeEventListener('message', onReady);
        resolve(worker);
      });

      worker.postMessage({ type: 'init', kind });
    });
  }
  return workerPromise;
}

Inside the worker, initialisation is guarded so a second init message is a no-op, and the module payload is fetched from the cache first so that a repeat session on a device that has been offline for a week still starts.

// workers/runtime.js

let runtime = null;

self.addEventListener('message', async (e) => {

  const { type, kind, code, fixture } = e.data;

  if (type === 'init') {
    if (!runtime) runtime = await boot(kind);
    self.postMessage({ type: 'ready' });
    return;
  }

  if (type === 'run') {
    try {
      const result = await runtime.exec(code, fixture);
      self.postMessage({ type: 'result', result });
    } catch (err) {
      // A learner error is data, not an exception. Never let it kill the worker.
      self.postMessage({ type: 'result', error: String(err?.message ?? err) });
    }
  }
});

The distinction in that last block is worth dwelling on. In a normal application, a thrown exception from executed code is a bug. Here it is the expected case most of the time, because the learner is a beginner and the entire point is that they will get it wrong. Every layer of the execution path has to treat failure as ordinary traffic.

For SQL grading we do not compare output strings. We compare result shape and content, which lets a learner write a correct query with different formatting, aliasing or column ordering and still pass where the challenge permits it.

export function gradeSql(actual, expected, opts = {}) {

  if (!actual || !actual.length) return { 
    pass: false, reason: 'empty' 
  };

  const [got] = actual;
  const cols = got.columns.map((c) => c.toLowerCase());
  const want = expected.columns.map((c) => c.toLowerCase());

  if (!opts.orderedColumns) {
    cols.sort();
    want.sort();
  }

  if (cols.join('|') !== want.join('|')) {
    return { pass: false, reason: 'columns', got: cols, want };
  }

  const norm = (rows) =>
    rows.map((r) =>
      r.map(String).join('u0001')).sort().join('u0002');

  const rowsMatch = opts.orderMatters
    ? JSON.stringify(got.values) === JSON.stringify(expected.values)
    : norm(got.values) === norm(expected.values);

  return rowsMatch ? { pass: true } : { pass: false, reason: 'rows' };

}

The reason field is not decoration. It is the input to the feedback system described later, and it lets us tell a learner that their columns are right but their filter is wrong, rather than telling them only that they failed.

The persistence layer, and why localStorage ran out

Efiwe presents content in 246 languages. Translated challenge text is cached on the device so that a learner who selected Yoruba or Hindi does not re-fetch the same strings on every session, and so that translation survives going offline.

We started that cache in localStorage. It was the wrong choice and it failed in two ways at once.

The first failure is capacity. localStorage is typically capped at around 5MB per origin, though the exact limit varies by browser and platform. Cached translated content for a multi-hundred-challenge course in even a handful of languages exceeds that. When it does, writes throw QuotaExceededError, and if you have not wrapped every write, that throw lands somewhere unhelpful.

The second failure is worse and quieter. localStorage is synchronous. Every read and every write blocks the main thread. On a mid-range laptop that is a few milliseconds nobody notices. On an entry-level Android device with a slow flash controller and a saturated CPU, a large synchronous read at startup is a visible stall on exactly the hardware that can least afford one. We had optimised our JavaScript payload carefully and then hidden a main-thread block inside the storage layer.

We moved to IndexedDB. IndexedDB is asynchronous, its quota is a percentage of available disk rather than a fixed few megabytes, and it stores structured values without a JSON round trip.

Choosing IndexedDB was the easy part. Moving existing users onto it without losing their data was the problem that actually took the work. We had live users holding data in the old store, many of them offline for days at a stretch and therefore reaching the new code at unpredictable times. A hard cutover would have silently discarded their cached translations and their in-progress state. Instead we ran a dual-read window: read the new store first, fall back to the legacy store once, promote whatever we find, and delete the legacy key.

import { get as idbGet, set as idbSet } from './idb.js';

const LEGACY_PREFIX = 'efiwe.tr.';

export async function readTranslation(key) {

  const fresh = await idbGet('translations', key);
  if (fresh !== undefined) return fresh;

  // One-time promotion from the legacy synchronous store.
  let legacy = null;
  try {
    const raw = localStorage.getItem(LEGACY_PREFIX + key);
    legacy = raw ? JSON.parse(raw) : null;
  } catch {
    legacy = null; // corrupt or unreadable, treat as absent
  }

  if (legacy === null) return undefined;

  try {
    await idbSet('translations', key, legacy);
    localStorage.removeItem(LEGACY_PREFIX + key);
  } catch {
    // Promotion is best-effort. Serving the value matters more than moving it.
  }
  return legacy;
}

Two details in that function are the whole lesson. The legacy read is wrapped, because a partially written localStorage value from an interrupted session will throw on JSON.parse and you do not want a parse error on a cache to take down a page. And the promotion write is wrapped separately, because the write can fail on a full device while the read succeeded, and in that case the correct behaviour is to hand the learner their content anyway and try again next time.

Storage quota as a first-class failure mode

This is the incident I would most want another engineer to learn from this article.

During the Nigerian pilot, an educator reported that on some students’ phones the learning page did not display after account creation. The account was created, the login succeeded, and then the course simply did not appear. Blank.

Our first hypothesis was hardware compatibility at the low end of the Android range. It was a reasonable guess but it was wrong, and we lost time on it because the reports clustered on cheaper devices. They clustered there for a correlated reason rather than a causal one: cheaper devices have smaller storage, and smaller storage fills up.

The root cause was a single await in the course startup sequence. On boot, we persisted an initial course manifest to the cache and then continued. On a device with no free space, that write could be rejected. The rejection was not caught, which made the promise chain halt before the render call. No error surfaced to the learner because nothing had crashed in a way the UI could detect. The course was simply never asked to draw itself.

Here is the shape of the original code:

// Before: a storage failure silently halts the render path.

async function startCourse(courseId) {
  const manifest = await fetchManifest(courseId);
  await cacheManifest(courseId, manifest); // rejects on a full device
  renderCourse(manifest);                  // never reached
}

And the fix:

// After: persistence is an optimisation, not a precondition.

async function startCourse(courseId) {
  const manifest = await fetchManifest(courseId);
  cacheManifest(courseId, manifest).catch((err) => {
    reportNonFatal('manifest-cache-failed', err);
    setOfflineAvailability(courseId, false);
  });
  renderCourse(manifest);
}

The course now starts normally even when it cannot save data to the device. Offline availability is degraded and the learner is told so, but learning is not blocked. We verified the fix across a matrix of storage conditions, including a device deliberately filled up to its capacity, before closing it. The whole cycle from report to verified fix ran within the same day.

The generalisable rule we adopted afterwards: persistence calls in a startup path are fire-and-forget with an explicit catch, never awaited. If your render depends on a successful write, your users’ full phones are a blank screen waiting to happen.

We also added a preflight so that we can degrade deliberately rather than discover the problem at write time.

export async function storageBudget() {

  if (!navigator.storage?.estimate) {
    return { known: false, freeBytes: Infinity };
  }

  const { quota = 0, usage = 0 } = await navigator.storage.estimate();
  return { known: true, freeBytes: Math.max(0, quota - usage), quota, usage };
}

export async function canCacheCourse(estimatedBytes) {

  const { known, freeBytes } = await storageBudget();
  if (!known) return true;            // unknown is not a reason to block
  return freeBytes > estimatedBytes * 1.25; // headroom for overhead
}

navigator.storage.estimate() returns padded and approximate values by design, for privacy reasons, so it is a planning signal and not a guarantee. It is enough to decide whether to attempt a full course precache or to fetch lazily, and it is enough to tell a learner in advance that they should free space if they want offline mode.

Two-tier AI feedback and an honest degradation contract

Efiwe gives every learner personalised feedback on wrong answers. That is the feature that our field data rated highest, at 4.3 out of 5 across the Nigerian pilot, with nine of ten educators scoring it 4 or 5.

It is also the feature most at odds with the offline premise, because the strongest feedback comes from a hosted model behind an API, and the whole point of the product is that the network is not there.

We resolved this with two tiers and an explicit contract between them. Tier one is the hosted model, used when connectivity is available and within a hard timeout. Tier two is a smaller on-device path that combines deterministic analysis of the submission with a local model. Tier two is always available and always correct about facts, because the deterministic part does the factual work.

const HOSTED_TIMEOUT_MS = 4000;

export async function getFeedback(submission, challenge) {

  const local = analyseLocally(submission, challenge); // always runs, always cheap

  if (!navigator.onLine) return { ...local, tier: 'device' };
  try {
    const hosted = await withTimeout(
      requestHostedFeedback(submission, challenge, local),
      HOSTED_TIMEOUT_MS
    );
    return { ...hosted, tier: 'hosted' };
  } catch {
    return { ...local, tier: 'device' };
  }
}

function withTimeout(promise, ms) {

  return Promise.race([
    promise,
    new Promise((_, rej) => setTimeout(() => rej(new Error('timeout')), ms)),
  ]);
}

Three design points here that took us longer to learn than they should have.

The local analysis runs first and unconditionally, not as a fallback. It is cheap, it is deterministic, and it is also passed as context into the hosted request. This means the hosted model is reasoning about a pre-diagnosed submission rather than starting from scratch, which produces more consistent output and a smaller prompt.

navigator.onLine is checked but never trusted. It reports whether a network interface exists, not whether anything is reachable, and on a phone attached to a captive portal or a stalled mobile connection it will happily report true. It is used as a fast negative signal only. The timeout is what actually protects the learner.

And the tier is recorded on the response. We do not hide which path gave an answer. That matters for our own telemetry, and it matters because feedback that arrives from the weaker tier is written differently.

Making feedback pedagogically useful

Our early feedback was binary and flat. A learner who submitted consolee.log("hi") and a learner who had fundamentally misunderstood what a function is both received a variant of “this is wrong, it should be this instead.”

An educator in the pilot flagged this precisely. Her students were receiving corrections they could not act on without her sitting beside them, which defeats the point of a tutor that scales.

The fix was to measure how close the submission is to correct before deciding what kind of feedback to give. A near-miss gets a character-level nudge. A structural miss gets a conceptual explanation.

export function proximityHint(submitted, expected) {

  const d = levenshtein(submitted, expected);
  if (d === 0) return null;
  if (d > 2 || Math.abs(submitted.length - expected.length) > 2) {
    return null; // not a near-miss; escalate to conceptual feedback
  }

  const diff = firstDivergence(submitted, expected);
  if (diff.kind === 'extra') {
    return `You're almost there. You have an extra "${diff.char}". Remove it and you'll have it.`;

  }

  if (diff.kind === 'missing') {
    return `You're almost there. You're missing the letter "${diff.char}". Add it and you'll have it.`;
  }
  return `You're almost there. Check the character at position ${diff.index + 1}.`;
}

The analogy I use internally is two teachers marking the same page. The less experienced one puts a red cross next to the wrong answer and writes the correct one beside it. The more experienced one circles exactly what is wrong and writes a note about the specific thing that needs to change. This change moved our feedback from the first kind of marking to the second, and it is entirely deterministic, which means it works identically offline.

Multi-user devices are an architectural requirement

In the Nigerian pilot, eight of ten educators cited students not owning a personal device as the dominant obstacle. Phones were shared between siblings, borrowed from teachers, or passed around a group during a session.

Our authentication model at the time assumed one device, one learner. Two students on one phone meant logging out and back in, which on a slow connection is a minute of lost session time each way and, worse, risks a learner losing local progress that had not synced.

Account switching therefore is not a convenience feature, it is a consequence of the deployment context. A device now holds up to twenty saved profiles, and switching is one tap with no full logout. Architecturally this meant namespacing every local store by profile, so that progress, translation cache and runtime state are partitioned rather than global.

const scoped = (profileId, store) => `${store}::${profileId}`;

export const progressStore = (profileId) => ({
  get: (k) => idbGet(scoped(profileId, 'progress'), k),
  set: (k, v) => idbSet(scoped(profileId, 'progress'), k, v),
});

If you are building for a market where devices are shared, retrofit this early. Unpicking a globally scoped local store after launch is considerably more expensive than namespacing it on day one.

What the field data changed

Two deployments gave us the evidence base for most of the above. In Uttarakhand, India, four institutions ran the platform with structured, managed device access. In Lagos and Ogun State, both in Nigeria, ten educators across ten schools ran it over eight weeks relying almost entirely on students’ personal phones.

The contrast isolated platform problems from context problems, which is the single most useful thing a pilot can do for an engineering roadmap. Offline reliability scored 4.0 out of 5 in Nigeria, and every low score traced to the same condition: connectivity dropped before the first caching cycle completed. That is not a reliability failure, it is a first-run sequencing failure, and it is fixable in code by prioritising the minimum viable offline payload ahead of everything optional. Device access, by contrast, is not fixable in code at all, and pretending otherwise wastes engineering time.

The finding that stung most was about language. Supporting 246 languages was one of the reasons the platform exists. In the pilot, four of ten educators never tried a local-language interface, and one tried and could not work out how. Every one of them had been shown the feature in onboarding.

The button was in the page footer. A learner moving through challenges has no reason ever to scroll to a footer. The feature was present, documented and demonstrated, and it was functionally invisible.

Discoverability and usability are not the same property. A feature that requires a user to already know where to look is, for most users, a feature that does not exist. We are moving the control into the active learning line of sight, but the more valuable outcome is the check we now run before shipping anything: not “can a user find this if told where it is” but “will a user encounter this in the path they actually walk.”

Open problems

Three things remain unsolved and I would rather say so than write a tidy ending.

Cold start on WebAssembly runtimes is still worse than I want on the weakest devices, and streaming compilation only partly helps when the module has to come from cache rather than the network.

On-device model quality is the real ceiling on offline feedback. Deterministic analysis carries more of the load than I would like, and it does well only because coding challenges have checkable answers. A softer domain would not have that fallback.

Storage remains adversarial. Quota is padded, eviction is opaque, and persist() is granted inconsistently across browsers. The defensive posture described here is a workaround for a platform gap, not a solution to it.

None of these are reasons not to build this way. The alternative, which is assuming a laptop and broadband, excludes the majority of the people who would benefit. The engineering is harder, but the addressable population is several billion larger.

About the Author

Subscribe for MMS Newsletter

By signing up, you will receive updates about our latest information.

  • This field is for validation purposes and should be left unchanged.

Cloudflare Opens Quicksilver to Customers as Workers KV Instant, Inside a 1 MB Envelope

MMS Founder
MMS • Steef-Jan Wiggers

Cloudflare recently made Quicksilver available to customers for the first time, as a new mode for Workers KV called KV Instant. Reads resolve in 1.62 ms at the 99th percentile, compared with 287 ms for classic KV. What determines whether a team can use it isn’t the latency, but the envelope around it.

Quicksilver is Cloudflare’s own configuration store, introduced in 2020. Nearly every request to Cloudflare looks up at least one key in it, Rob Sutter writes, and it has never been a customer-facing product. Brendan Irvine-Broque, who works on Cloudflare’s developer platform, announced the change on X:

we have this crazy key-value store at Cloudflare called Quicksilver

instantly updates keys across our whole network. microsecond reads from every location. stupid fast

our customers have asked us for years to make it available

we finally did – in a way we think is quite simple – as a new mode for Workers KV

The published figures, measured to over 300 edge locations:

Mode p99 reads (all) median write replication p99 write replication
Instant 1.62 ms 107 ms 256 ms
Classic 287 ms under 1 s 4.38 s

Cloudflare notes it has no sub-second fidelity for replication lag in classic mode, so the classic median and p95 figures are upper bounds rather than measurements. p95 reads in Instant mode are reported in microseconds.

The API is the Workers KV one, with three differences. Mode is set at namespace creation with a "mode": "instant" attribute, and cannot be changed afterward. Metadata is unsupported, so getWithMetadata always returns null. And list returns every matching key with no pagination.

Then the limits. A namespace holds at most 10,000 key-value pairs and one megabyte in total, with keys up to 300 bytes. Writes are capped at one per namespace per second, which Cloudflare contrasts with classic KV’s one write per key per second, on the grounds that a single system of record “makes it easier for you to reason about update order in your application.” That difference is the one most likely to catch a team migrating: a pattern classic KV permits across many keys concurrently becomes a single serialised queue.

Pricing points the same direction, and Cloudflare says so plainly: “storage and Class A operations are significantly more expensive than Workers KV.”

  Reads (Class B) Writes, deletes, lists (Class A) Storage
KV Instant $0.20 per million $0.10 per operation $100 per MB, per month
Classic KV $0.50 per million $5.00 per million $0.50 per GB, per month

Reads cost 60% less. A write costs ten cents, against five dollars per million in classic mode. Storage runs $100 per megabyte per month, and since a namespace tops out at one megabyte, that is also the ceiling. Multi-key reads bill per key, so requesting three keys in one get costs the same three Class B operations as three separate calls.

Irvine-Broque set out the reasoning in the same thread:

just like how we use Quicksilver ourselves, it’s for small data that is read often and updated infrequently

pricing reflects this – reads actually cost 60% less than even Workers KV

Writes cost what they cost, he added, because writing a key replicates it to hundreds of locations. This is a store priced so that you read from it constantly and write to it rarely.

Benjie Malinao, also on X, read the fit the same way:

This is the config store agents actually need. Sub-2ms p99 reads and global writes landing in about a quarter second at p99, on the same KV API. Feature flags and agent settings without waiting on a TTL. I’d move hot-path config over first.

Feature flags, routing tables and agent settings fit that shape. Session state, user records and anything with a write path do not.

The comparison practitioners reached for was Vercel. Developer Shawn Mclean asked Irvine-Broque directly:

I’m looking into using Vercel Global Config for a middleware read. They claim 15ms. If I move my workloads to CF, are you saying I can read from middleware for a platform tenant domain mapping in 2ms?

The answer did not quite confirm it:

even p50 of Workers KV (non-instant) from 2 years ago was ~5ms. KV Instant is even faster than that (see numbers in the post)

Cloudflare’s own worked example is a launch flag read on every request and flipped at a keynote, which is precisely the workload: one key, one write, read everywhere immediately.

Classic Workers KV, which launched during Birthday Week in 2018, remains the recommendation for large or frequently updated data. The two modes now sit under one API with opposite economics.

KV Instant is in private beta with a sign-up form, and Cloudflare says it plans to open it up more widely. No general availability date is given.

About the Author

Subscribe for MMS Newsletter

By signing up, you will receive updates about our latest information.

  • This field is for validation purposes and should be left unchanged.

Uber Moves beyond CPU Cores with Performance-Aware Scheduling for Stateful Workloads

MMS Founder
MMS • Craig Risi

Uber has introduced Normalized Compute Units (NCUs) to make CPU allocation more consistent across its highly heterogeneous server fleet. The approach, implemented in Uber’s Odin stateful orchestration platform, accounts for differences in processor performance rather than treating every CPU core as equivalent.

Odin manages around 5 million CPU cores across on-premises data centres and public clouds, including multiple generations of x86 hardware and ARM processors. Uber found that single-threaded performance can vary by almost a factor of two between the fastest and slowest cores. Consequently, the same workload can require significantly different numbers of physical CPU cores depending on where it runs.

The problem creates two competing risks. Allocating resources according to the slowest hardware can waste capacity on faster machines, while allocating according to average usage can leave workloads under-provisioned when they move to slower servers. For stateful workloads, where moving traffic to another machine is often not possible, the latter can become a reliability problem.

Uber’s solution is to separate the amount of compute performance a workload requires from the physical cores used to provide it.

Odin assigns each server type a performance factor, using an older server generation as a baseline of 100. Newer hardware can have considerably higher values; Uber reports factors approaching 190 for some servers. These factors are initially determined during hardware qualification and then refined using production workload data.

CPU usage is converted into normalized units using these factors. Odin can then determine that a workload requires a particular amount of compute capacity and translate that requirement into a different number of physical cores depending on the server hosting it.

A workload on faster hardware may therefore receive fewer cores, while the same workload on slower hardware receives more. The objective is not to make the number of cores identical, but to make the computational capacity more comparable.

Uber also found that performance factors differ between technologies. Its measurements for Kafka, for example, showed substantially different performance between ARM, older on-premises hardware, and newer x86 systems. The company therefore updates factors using production measurements rather than relying exclusively on synthetic benchmarks.

For stateless services, differences between servers can often be addressed through load balancing. Traffic can be directed towards less-loaded or faster machines.

Stateful systems do not have the same flexibility. A request may need to reach the server containing a particular shard or piece of data. Moving the request elsewhere does not solve the underlying resource problem.

In the post, Uber describes workloads where a leader consumes more than ten times the CPU of its followers. If that leader moves from a fast server to a slower one, its CPU consumption can increase substantially, potentially causing resource pressure even though the workload itself has not changed.

Uber has rolled the approach out across approximately 1.4 million CPU cores of automatically scaled Odin workloads. For Kafka, CPU utilisation initially varied by around eight percentage points between server types, with the hottest hardware running at approximately 50% higher utilisation than the coldest.

After introducing performance-aware allocation, the difference fell to around three percentage points, with the hottest hardware only about 10% higher than the slowest. Uber also reduced total Kafka CPU allocation by approximately 8%, with much of the reduction occurring on faster hardware where the savings are potentially more valuable.

The approach differs from the CPU abstraction used by Kubernetes, where CPU requests are expressed as cores or millicores. Kubernetes deliberately treats a CPU unit as an absolute quantity of CPU time, regardless of the size of the underlying machine. That abstraction works well for portable workload definitions, but it does not inherently express the relative performance of different processor generations.

Uber’s NCU model addresses a somewhat different problem: making the resource itself performance-aware. Rather than primarily deciding how many workloads should fit on a machine or how much CPU a workload should receive, it asks how much computational capacity a CPU allocation actually represents.

About the Author

Subscribe for MMS Newsletter

By signing up, you will receive updates about our latest information.

  • This field is for validation purposes and should be left unchanged.

Presentation: Serving LLMs at Scale: The Hidden KV Cache Advantage

MMS Founder
MMS • Khawaja Shams

Transcript

Khawaja Shams: How many of you find yourselves to be experts in inference? My name is Khawaja. I will try to keep this light-hearted, and there will be a little bit of repetition because one of the things I learned as a teacher was sometimes repetition really helps to internalize the concepts. These concepts are interesting, but once they click they make a lot of sense. I started my career building cameras for the Mars rovers. I was at NASA for eight years doing distributed systems. Then I ran DynamoDB at AWS, which is a large-scale NoSQL database. Today I run a startup. I’m a co-founder at a startup called Momento, where we work really hard to make access to data really fast. This works for AI inference stacks as well as the boring cache as well.

Perspective of a Distributed Systems Engineer

I was really happy to see that not everybody here or most people here don’t consider themselves an inference expert. I can share with you that as somebody who came from a distributed systems background, I personally found the inference stack to be extremely intimidating. There are these crazy new words like attention heads, KV projections, CUDA kernels, tensors, quantization that made me feel like I need to go back to my linear algebra class. Luckily, in the world of inference, there’s a lot of space for distributed systems people to make an impact. The same problems that start to appear when web scale came back in our histories where you had to take care of problems like routing, you had to take care of problems like your tail latency for your data access, how do you think about your caches and so forth. All those problems still exist inside the inference stack.

Currently, in today’s world, one of the most scarce resources is GPUs. You can’t produce them fast enough. Even if you could, there aren’t enough data centers to go around. While the world is busy producing more GPUs, building more data centers, this is going to be a renaissance for us distributed systems people because we can help improve a very critical metric, which is the utilization. Some of the concepts you’ll learn today, they all feed into how do you make the inference stack have higher utilization. If you have better utilization, if you can use the capacity better, then that leads to better availability, it leads to better performance, and it leads to better economics.

Two Stages of Inference

When we talk about inference, this is when I go to ChatGPT and I say, please say hello to me, and it takes like 2 seconds for that thing to happen. There are actually two stages of that prompt being inferred. The first stage is the prefill stage. This is where the prompt actually gets processed. I’ll give you a quick example, and I’ll try to make these as relevant to the way humans talk to each other as I possibly can to help you internalize all these concepts. Think back to when you were in high school or earlier, you may recall this riddle where people will show up and say, you are driving a bus, and that bus has no passengers. Then at the first stop, you get one person. At the next stop, you get two people. Then at the third stop, it doubles. Then at the fourth stop, a third of the people leave and so forth.

Now imagine if I sat here for the duration of this talk, and I just kept going on and on about that particular riddle, and in the end, all I’m going to ask you is who’s driving the bus? The answer is you, but you cannot answer that question until you are done processing all of the input. That is the prefill stage. This is where the input prompt that you have is getting converted into machine code that maps to how the model thinks. The decode side is the actual answer. This is when you’re saying the answer being like, I’m driving the bus. That’s the decode side. In the inference stack, these two are very separate stages. It’ll make more sense a little bit how these stages map to each other. The prefill side is very compute bound. You are just sitting there parsing the words that are coming out, and you’re converting them.

It runs all in parallel, takes up a lot of CPU. The decode side has to reference all of those things, so it has to be very memory bound. You might have heard this metric that the whole world obsesses over, it’s time to first token. This is the metric that users care about because it lets you improve the perceived interactivity, like how fast this thing is responding. The first token will not land on your screen until the prefill is completely done. Just like you can’t even begin to answer the question about the school bus until I finish the question.

Journey of a Prompt

Let’s go through this from the perspective of a prompt. Today, in the magic school bus, you are the prompt. You are going to get entered. The user is going to enter you, and you’re going to fly through the packets on the internet. You’re going to land on a routing box. That particular prompt has to get tokenized. The programming analog here is when you take your C program and you compile it into assembly, that’s what’s happening. That’s the tokenization phase. It’s not one-to-one. A single word may not become a single token. It’s roughly one-to-one, but it’s not quite that much. Then after the prompt is generated, what the tokens generated, the routing layer is going to actually go and check, have I seen this before? Like, have I heard this riddle before? Or, have I heard parts of this riddle before? You go and you check.

Sometimes as I was asking the question, some of you were already thinking the answer is me. Because you’ve seen this before. You’ve already compiled this analogy or this riddle. Then the prefill starts to happen. In the prefill stage, if you haven’t seen it before, you’re generating the machine code. You’re generating the 1s and 0s that map back to the way the model pays attention. Then you store that data inside what’s called the KV cache. Then once the prefill stage is completely done, you go in the decode loop, which produces one token at a time. Once the response is complete, as each token comes in, it gets streamed back to your screen. The costs here on the prefill side is just compute. On the KV cache side, it’s very storage heavy. It’s in the gigabytes. On the decode side, it’s very memory bandwidth heavy. All the user care about is how quickly they get their tokens.

Now, KV caching, it seems somewhat orthogonal as a user of inference services. If you understand how KV caching works, it’ll help you drive your inference stack better, even if you’re not running your own inference stack. It’ll help you drive your Claude Code sessions better too. KV caching is hard because it takes a lot of storage. GPU memory is extremely limited. KV caches, it’s not easy to share them between sessions. We’ll get into each of these three. For the purposes of this talk, I learned by doing, and I created a few experiments. These experiments were done on a very modest model. This model is 4 billion parameters. Some of the larger models, like when you’re using GPT-5.5, those are trillion parameters model. They go into trillions. Claude Opus 4.8, trillions of parameters. This is a 4 billion parameter model. The experiments were run on a G6 instance type, which is actually readily available inside of AWS, costs a couple of bucks an hour.

You can go reproduce these. For this very modest 4 billion parameter model, let’s compute how big a single token is for your KV cache. That single token, your LLM model has 36 layers. Each layer has 8 KV heads. Each token gets converted, multiplied to embeddings of 128 dimensions. Then you have 1 byte for the key and 1 byte for the vectors that follow. You multiply those numbers together and your hello just got converted to 72 kilobytes. That’s a lot of data. One of the experiments that we’ll get into in a bit was 20,000 tokens. Just to put things in perspective, your Claude Code sessions are constantly churning 100,000-plus tokens back and forth. 72 kilobytes per token, a 20,000 token prompt is 1.6 gigabyte. That might be ok if you owned that GPU for yourself. In a fleet that your ChatGPT provider or your Claude Code provider behind the scenes is running, that’s running on GPUs. The GPUs have RAM from the 2000s in a certain extent. The GPU that I was playing around with, the cheaper one, only has 24 gigs of RAM. The really expensive Blackwell models have 192 gigabytes of RAM. RAM inside of GPU is not very big, so storing gigabytes of data for each user becomes very expensive very quickly.

Then there’s a second part which is, it’s really hard to share KV caches across sessions. This is because each individual word that gets converted into tokens, KV is a little misleading because people think KV means for this token, here’s the value. It’s not a HashMap lookup. What you’re really asking is for this token, after it’s been preceded by these other tokens, what is the value? This applies to humans as well, the way we perceive language. If I say time flies like an arrow, or if I say fruit flies like a banana, if you were to go and encode flies independently, the word flies has two different meanings. It depends on the context that preceded it. You can’t just individually go cache individual tokens and expect them to be reusable across sessions and so forth. Your KV cache that’s running behind your ChatGPT queries and so forth is generally pretty personalized to you, because you and the other users might be asking very different things.

In fact, one of my team members just committed a patch to Llama.cpp, which is an inference engine that you can run. One of the things that Llama.cpp was doing was, it was injecting a timestamp before the prompt got sent. That would invalidate the entire KV cache, and the whole prefill had to be done again. You can imagine a simple mistake like, I’m going to insert the timestamp, seems so benign. It means your GPU has to do all of that work again. It doesn’t have the reasoning skills of a human where it can say, yes, that’s just a timestamp, let me ignore it. No, the prefix does not match, therefore I must compute it.

Prompt Anatomy

Let’s take a look at the anatomy of the prompt. There are some parts that are shareable. The first part is the system prompt. If you are running Codex, the system prompt is actually not all that complicated, but it’s very long. The system prompts by saying, you are Codex, a coding agent. Then it has all kinds of instructions about what you should and shouldn’t do. Like, don’t over-explain, don’t write comments unless somebody asks for it. I highly recommend, if you can go get access to it, you can see some of the Claude Code prompts on the open internet now after a leak as well. Just read through what the system prompt looks like. It is like you’re talking to a child. It’s like, important in urgent. Anybody watch The Office from back in the days where Michael Scott had Urgent A, Urgent B, Urgent C? It’s like that.

It’s like, there’s important, there’s super important, and there’s caps used. In fact, the Codex prompt, I kid you not, says, no matter what, do not talk about goblins. I can help explain my theory offline about why that token is in there. The system prompt, especially for coding agents and things like that where somebody is using the same thing over and over again, that is very common across your user base. Every Claude Code session is going to start with the same system prompt. That part you can share across users. If a user is online, their prior turns are also, you’ve seen it recently, you probably still have it. If I were to continue my riddle now and say, what is the maximum speed do you think that vehicle will go? You know the answer without having to think through and reprocess the whole bus story. If I ask, how fast will it fly?

You will also know the answer because you know it’s a bus. It’s still in your cache. If the person comes back reasonably quickly, within minutes or hours or whatever, the prefill for their session is likely still there from their prior turns. The new stuff is what they just added. Like, how fast can this vehicle go? Or, will it fly? That’s the part that needs to be regenerated if you got a KV hit. If you pay attention to your Claude Code session, you’ll notice that your cache hit rate is actually quite high. The reason for that is when Claude Code takes your turns, it’s not sending a brand-new prompt every time. It’s just appending to the last one. That’s why your token consumption goes up the longer your session goes. Then eventually you run into that compaction side because your context just grows and grows and grows, but they keep appending so that your prefixes keep matching.

Learn by Example

Let’s go to the experiment. Just to help you internalize some of this, again, modest model, 4 billion parameters. Cheap GPU. We use floating point, FP8 just means floating point 8. It’s a float. If you remember floats from your coding schools or your classes. Then we use vLLM. APC just means automatic prefix caching. We did a sweep where we said, run one concurrent session, run two, run three, run four, up to 48 concurrent sessions. The workflow was a mini-agentic coding workflow that we were trying to simulate. It starts with a 10,000-token system prompt that says you’re a coding agent. Don’t talk about goblins. Then you take 12 turns and each turn you add like 1,067 tokens. Then you just go back and back and back. At the peak, you get 22,800 tokens at turn 12. We wanted to see where does the GPU hit a cliff in performance between 1 to 48 concurrent sessions.

I’ll skip to the good part where when we got to 12 sessions, it looked pretty good. The time to first token at p50 was only one second. It was a complex prompt. It’s a long riddle. It has to be prefilled and everything. Just to give you, 22,000 tokens is roughly like 10 pages of written text. For a computer to just go parse through that and at p50 give you a second, it’s pretty good. At p99, the time to first token was 2.6 seconds. That’s with 12 concurrent sessions running and it’s doing a little bit of prefill every time, getting a cache hit for the prior turns before. The reason why it does so well is because the KV cache actually still fits, and we did the math and it turns out that it can sit around 13. There’s overhead and so forth. Then we added two more.

Same experiment, but we did 14 concurrent sessions. Now you are adding a little bit more load where the data just doesn’t fit in memory anymore. Between turns, it’s getting lost, so it has to be regenerated. If anybody was around in the 2000s and may remember your Windows PC, remember the word swap space? You can still see it in your MacBook too. Remember when your computer would go into using swap and everything will come to a halt? It’s like that. Where the GPU just can’t keep it in memory anymore so things start to evict and it has to recompute. The p99 jumps from 2.6 seconds before at 12 concurrent to 38.9 seconds. That’s a major noticeable jump. It just comes down to being not able to fit everything in memory. The cliff is actually quite bad because the sessions that get run out of memory, like that end up being evicted from the GPU, they end up doing really badly.

The lucky sessions, that’s why the p50, the 50th percentile ends up still being ok because at 50th percentile, you’re still getting some cache hit rates. You’re getting lucky and that’s why it’s raising so gradually. We’ve all heard of tiered storage and tiered caching. Memory is very expensive because GPUs are very expensive. What about DRAM? As much as the world is saying that DRAM is getting expensive, it’s still way cheaper than GPU RAM. VRAM is the GPU RAM. It’s like tens of gigs. We saw up to 192 gigs. On these massive boxes with GPUs, you can get terabytes of DRAM. This is just like the RAM on your laptop and so forth. The DRAM, we’re living in a world where I can actually say this, RAM is too slow. Like you have terabytes of it, but now you got to copy the data from the RAM to the GPU on every turn.

You have terabytes of it and it’s still going to be cheaper than recomputing it. Then there’s NVMe, this is your SSDs, which can have tens of terabytes on a regular EC2-style server that you might have. Not only is it even slower than DRAM, it actually has write endurance problems. One of the things that goes wrong is if you keep writing over and over and over again, you’ll just trash the SSD and it’ll just stop working. The KV cache, because the data is so large, you are constantly going to be writing and you can exhaust the lifetime of your SSD pretty quickly. The tier below that is you can always just recompute. This is a cache that never has a miss because if you don’t have the data, you can regenerate it as well. That’s simpler, but it causes you to use more GPUs, and GPUs are scarce. Each tier basically trades latency for capacity.

Storage

Now, let’s take a quick detour into, there is local caching that we talked about and then there is remote caching. We started going down this path of how do I make a good remote cache for this environment because GPUs are still expensive. A lot of times people who build cache, including me and my own team, we really like to talk about sub-millisecond latencies or 100 microsecond latencies, but here the latency to first byte is not that important. You’re trying to download gigabytes of context about a user. What really matters is your throughput. Within the throughput, what matters is can you saturate the network card that you have because you don’t want to leave any bandwidth unused. You want to get the data as quickly as possible because then you’re not sitting there having your GPU wait. The G6 instance type that I use for my experiments has a modest 25 gigabit NIC.

When I say 25 gigabit NIC is modest, I feel a little guilty saying that. Twenty-five gigabits is a pretty decent network card. Just to put it in context, the instances that have the really expensive GPUs that I hope to be able to afford one day, they cost like 50 bucks an hour. They have terabits per second of bandwidth. A lot of the challenges here become, how do I consume all of that bandwidth? Some of this comes down to, how do I divide my objects into lots of smaller objects of megabytes, which in the world of caching, they’re considered large objects, but it’s better than downloading a single 1.6 gigabyte object. You can download a bunch of them in parallel. Your goal when building something like this for a remote KV cache is to saturate the NIC. Techniques like smaller chunks does help. The open-source software I work on is called Valkey.

This is, again, being a distributed systems person, being able to help the inference world a little bit. Anybody heard of Redis? Valkey is a Redis fork backed by Amazon, Google, and so forth. There’s been a lot of performance optimizations in that space. One of the optimizations that got made is copy avoidance. Redis, from the very beginning, branded itself as having single-threaded. Because if you’re single-threaded, you can move really fast. There’s no locks. That works really well when you have tiny 5 kilobyte, 10 kilobyte objects. What happens when you have a 4-megabyte object is that your main thread is busy writing to the kernel buffers to write to the NIC so that the data can go on the network. While it’s doing that, it’s not actually answering any of their calls. For the KV caching workflow, you’re not only downloading, you’re also checking, do you have this prefix?

Do you have that prefix? All those calls will get locked behind it. In the latest version of Valkey, one of the interesting things that happened is that there are I/O threads. The I/O threads deal with the network, and the main thread just says, yes, you want that object? Please copy offset by this to this from this address onto the NIC. I/O thread goes and does its thing while the main thread moves on. The reason why I bring this up is that simple optimization makes a big difference on whether you can consume the entire NIC or not. Because until the 4 megabyte is copied from the main thread to the I/O thread or whatever, you can’t even start to write the first byte. Then the software layer that’s going and downloading each individual object can’t actually pass it on and start to stitch it together until it downloads each individual chunk.

This gets really expensive. Copy avoidance, funny enough, has actually been the most profound optimization that we have done not just on the server side but also on the client side. The inference engines, like if you might have heard of vLLM or SGLang and so forth, often written in Python. Everybody thinks Rust is going to be much faster. I can say that because I’m a big Rust fan too, if I can make fun of people who think Rust will make them go faster. This is a classic example of when Rust will slow you down. Somebody had the bright idea that, yes, this isn’t Python, I’m going to write my client in Rust and I’m going to do a native binding. What happens is that that Rust layer now has to download the 4-megabyte object and it can’t pass it to the Python layer until the 4-megabyte object is done downloading.

Then it has to copy it over to the Python space which then has to go copy it over to the CUDA space which then has to go copy it over to the GPU. All those copies, they add up. I harp on this example because that is a classic example of your CS skills coming in handy for this very complicated looking inference stack. Minimize copies wherever possible.

With that out of the way, let’s see if we can use DRAM. We’ll go back to local caching and see what happens when we add a little bit of DRAM. We notice that the first row is just 8-bit floating point. The p99 cliff happened at 14 connection, and our latency was 38.9 seconds for p99. Then we said, let’s just add 16 gigs of local RAM, the DRAM. That actually helped meaningfully. Our p99 at 14 connections actually went down from 38 seconds to a more bearable three and a half seconds. We ran a sweep to see, how much does it help. Actually, it turns out, for this particular workflow, if you add 32 gigabytes of local DRAM, you can push your concurrency cliff from 14 to 28. 8-gig didn’t really help much, it went to 14. Really having the 16 was a key tipping point. The impact becomes more and more profound the higher your concurrency gets. It’s still pretty bad. You really want the data to be in the GPU whenever possible if you want the fastest possible inference.

Synthesis

After harping on why you should really think about how much concurrency you need, I have some bad news. If you are running a multi-tenanted cluster of inference and you have users that will ask short questions, and you have users that will ask long questions, and sometimes you’ll have a very spiky mix of them. A new release of Claude Code might completely change the way your traffic looks if you’re running an inference service and that gets really tricky. You really can’t make any assumptions on being able to admit by concurrency count. In the early days that’s what everybody did. It’s like they just said, ok, I’m going to run this much concurrency. What happens is somebody shows up with a 100,000 or 200,000 token prompt and it just thrashes everybody away from the GPU VRAM, and that causes problems. What you really have to do is think hard about, for this model that I’m hosting, what is my per token cost?

How much budget do I have for my KV cache on the GPU? Then, what is my cliff estimate for a particular token size? When you make your admission control decision, when you want to decide, do I add another request to this GPU or not? You really have to be looking at how your KV cache consumption is going, and are you going to cause an eviction the moment that you add this particular request. It’s very workflow specific, and this is where the multi-tenancy makes it harder. If you have single-turn questions like, ChatGPT, what’s the meaning of life? That’s like 1,000 tokens, perhaps. Very hard question but the prefill for that is really fast, I can tell you that. Those are very short single-turn questions. The tiny agentic coding sessions are tens of thousands. Code reviews might be a few thousand and so forth. The key message I want you to take away is that the token consumption really depends on the workflow, and if your fleet is supporting a variety of them, you got to be very mindful of that too.

Routing and Processing

Thus far we have covered storage aspect of it, if you’re running the inference fleet. Now let’s talk about routing choices. There are still web servers involved, all this still happens on HTTP, so more good news for systems people. The request goes to a web server and the web server has to decide which GPU am I going to send this particular request to. If you do a naive thing, back 20, 30 years ago, there was the situation where people came up with sticky sessions. Sticky sessions are beautiful because the likelihood of the user landing on that node that still has their stuff on the cache is higher, so sticky sessions work really well in the web space. Here people still try to do sticky sessions to the GPU, so the web server will try to remember, this particular request for your coding agent session went to this GPU, so let me just go back to that GPU.

Because the odds of it having the KV cache locally on its SSDs or whatever is meaningfully higher. The problem is that these are extremely spiky workloads. I might take my next turn immediately. I might go for lunch and come back. I might never come back. This creates these like very spiky bursts. If you’re trying to just do naive sticky sessions, you can get into situations where a particular GPU becomes really hot. It’s like a bank run. Everybody shows up to that particular node and you get essentially a noisy neighbor hotspot issue. Your fleet-wide p99 is going to follow your hottest node. Load imbalance becomes a real problem in this space. The industry is doing a lot of interesting things there. The Mooncake folks are doing proactive KV migration so that if they can say, this node is more likely to get hotspotted, let me copy some stuff over.

NVIDIA’s Dynamo is like, how much preference do I want to give it so that I can avoid this hotspot and so forth. It does make a difference. If things do fit in the cache, the KV-aware routing and session affinity does help. I ran a quick experiment with the same thing where I just had one GPU. My output metric was just, I was outputting 110 tokens per second. As soon as I went to two GPUs, my output, it didn’t go to 220, it went to 128. Which means I was only 58% efficient. The same thing on two GPUs but saying, I’m going to put each session to the place that it went to before, it did 201 tokens per second. It’s not quite double but it became pretty efficient. I tried that with three GPUs, I got to 278 instead of 330, and then with four I was at 324.

The session awareness does help but with some caveats. One of the core distributed systems principle is, do constant work. If you’re trying to do constant work and you also want to try to scale your components independently of each other, with prefill and decode that becomes really hard, running on the same node. A new technique is emerging where people are saying we’re going to turn inference into a distributed systems problem where we’re going to do the prefill on one node and we’re going to do the decode aspect on another node. This is called disaggregation. If you get this right, you can scale these very dynamically. You can improve yourself or you can protect yourself from a situation where a single long prefill thing causes all the other decodes to slow down because the GPUs are busy doing the prefill side.

Let’s talk through from a component level how this works. NVIDIA has this framework called Dynamo, which unfortunately is very confusing because I worked on DynamoDB which has nothing to do with NVIDIA’s Dynamo. NVIDIA’s Dynamo, one of its centerpieces, it’s got a routing layer. The routing layer is actually the pinnacle of all of these lifecycles. This is the web server that I referred to earlier. The request lands on the routing layer. The routing layer will go ask a node to say, can you take this prompt and tokenize it? Then it’s going to go and see, does anybody have it? Who is the node that is most likely to have the longest part of this prefix available? Then it’s going to send that node a prefill request. This is to generate the machine code that a model can understand. When that node has finished generating the prefill tokens, it will store it in a KV cache, and then it transfers metadata back to the router, and says, ok, the prefixes, prefills, these are the chunks that you need and here are the hosts where they’re at.

That gets transferred over to the decode node which then goes and says, everybody, can I have this object? Can I have this object, and so forth? Then it loads it and then it can start the decode process. The nice thing here is that you can focus the nodes to be either completely prefill and be completely decode. When you bring up let’s say a vLLM, your node can switch positions. You can say, ok node, I’m going to schedule a bunch of prefill jobs on you, and the next second I can say I’m going to schedule a bunch of decode jobs on you, and it’s totally fine with that. This allows the router to actually become quite intelligent and dynamic in the way it’s scheduling.

To make this a little bit more memorable as to why disaggregation is so useful, we’re going to do a quick exercise that will hopefully help you remember it. I like to call it the ABCD exercise. I’m going to time you all. I want you to say the numbers 1 through 12 as fast as you can. I’m going to say 1, 2, 3, and then you are going to just say 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12. That’s your job. 1, 2, 3, go. Pretty fast. Now I want you to say A through L as fast as you can. L, I think, is the 12th letter. 1, 2, 3, go. Still pretty fast. A little slower than numbers but you remember your ABCs. I want to make it a little bit harder. Now I want you to say A1, B2, C3 and so forth.

1, 2, 3, go. Many of us just gave up halfway through. This is what happens when you’re asking the same node to do multiple things at the same time. If you time yourself saying 1 through 12 and A through L and you added that together, I bet you that was less than a quarter of the time it took you to say A1, L12. You can cache it. If you do this enough times, you’ll do it really fast. For the first time, you see this becomes a really hard problem. This ability to disaggregate is actually quite useful. You can have special purpose-built hardware for the prefill versus decode. They use different types of things. In fact, there are specific hardware that are now being built that are optimized primarily for the decode stage so that you can prefill elsewhere and then decode really fast. The distributed systems concepts that we talked about try to do bounded work, pinning the roles, balanced by the pressure, and then you can do constant work if you make your KV cache mobile.

Like if you don’t say it runs locally on the same host. Some of these things may look like they will slow you down because now you have to do a network call. In isolation, they will make you slower because you have to go fetch it. If you’re thinking about multi-tenancy, if you’re thinking from a fleet-wide perspective, it improves your throughput and actually improves the latency that your users get because they’re not sitting there waiting once in a while for that hotspot to conclude. These things about six months ago were still super controversial, but now it seems like everybody is converging on cache-aware placement remotely, disaggregation of prefill and decode, and then the mobile KV state.

Conclusion

I hope that what you took away from this is relevant to you even if you’re not running your own inference stack today. Some reminders for you. Every token that you are using becomes state that somebody has to carry. If you feel the temptation because you’re really nice and you like to say please, just know that’s like an extra 72k that Anthropic has to carry, and you’re hurting their margins. The fact that you’re saying please probably is why they couldn’t become a trillion-dollar company, were only 965. Just if only you didn’t say please enough. That’s state that everybody has to carry. When you’re doing this, if you’re familiar with The Office, be like Kevin. Why use more words when few words do trick. Use as few words as you possibly can. When you are inside your Claude Code session, like if you have side quests that you want to do, launch sub-agents or launch a different window and run it so that you’re not diluting the context because of the prefix caching.

If you do this often enough, you will actually start to appreciate that the quality of your output will get better and you’ll hit the compaction window a lot less frequently if you took your side quest and ran them as sub-agents so that you’re not diluting your prefix cache. As users, long context is powerful, but use it deliberately and carefully. Don’t fill it up with all these pleases. As builders, if you are running an inference stack and if you’re not today, I suspect you will in the next couple of years because databases in the ’90s, were really hard, and if you wanted a hardcore database, you had to go pay this company a lot of money to get a whole rack full of databases, and now people just turn on Postgres. This will get commoditized and you will run your own inference stacks soon enough. It’ll become more common.

When you’re doing that, think hard about what are the underlying scaling dimensions. Then as designers, just remember, when you’re designing your system prompt, when you’re doing prompt engineering, when you’re deciding where to put the user input, just think about locality and think about what can you trim from the prompt without losing the meaning, so that your users can have a better experience even if you’re providing the application and not just the inference stack. This is all called mechanical empathy. If you are aware of the system and how it operates underneath, you can drive it a lot better and a lot faster. Design for the state you create.

Questions and Answers

Participant 1: The question I have is, first off, I don’t actually know, but does the KV caching hit rate affect the price you pay as a customer? Second is, I believe that in the MCP protocol, when you change this list of tools for your server, for example, that causes the prefix of the thing to change. Was that just a giant mistake, would you say?

Khawaja Shams: It’s hard to say if that’s a giant mistake or not. To answer your first question, Anthropic and even OpenAI, I think they give you like a 90% discount if you have a cache hit rate. That doesn’t mean that it’s ten times cheaper for them. It’s just a convenient number. It’s not exactly 90% off, but it’s like 0.89 or something. They give you a pretty nice discount if you get a cache hit. In fact, if you use a proxy, you can actually see what your cache hit rate was. Designing for that is good.

To answer your second question, I’m not sure if messing up the prefix is a mistake or if it’s deliberate to make the model perform better because you don’t want the model to be distracted by the previous list of tools. Because you might also remove some tools as well. There are little techniques though that come into play, like, for instance, if you ask it for a file that’s changed and the original file was already in the prompt, it’ll send a git change rather than the entire new file. There’s techniques like that that the Claude Code agent is taking into play. It’s hard for me to speculate on whether resetting the prefix is a mistake or not. It might have been a deliberate choice.

Participant 2: I’m just trying to understand, like Redis key value, obviously, one then maps to a value over there. From what I understood from your talk, you are loading all of the context that was previously hit with the previously churns in every time a new query comes in. I’m just trying to understand the separation of the system prompt and then the original context and the new churn, how the actual similarity matching is happening there, and where it decides to include or not include things. Because your data goes to 35 seconds from 3 seconds. You figure if it was semantically matching, it would have a little bit more of a subtle gradient to it because some of it matches and some of it doesn’t. It’s just binary. It goes from 3 seconds to 38 seconds. Why is it going from 3 seconds to 38 seconds if it’s semantically trying to evaluate the key-value store to do the matching?

Khawaja Shams: The name KV cache is quite unfortunate, especially for somebody who works in the caching world, KV means key value. Except it’s not a HashMap lookup. It’s not a value. The V is like a vector of everything that preceded behind it and embedded into a single floating point. You really need the entire prefix. You need the KV for the first token, the second token, the third token. If you have lost and if you have evicted even like one link in the chain, you have to go recompute the whole thing. The 38-second jump is because it’s having to do precomputation. It’s like the GPU is actually having to do a lot more computation because it lost some of the data. Today in a cache you can get very clever about simple techniques like LRU, which tend to be pretty good for eviction. For instance, if you evict the first block of a particular prompt or whatever, you may as well just get rid of the rest, because they’re likely not going to match. It’s not doing a semantic search or anything like that. It’s looking for very precise values which end up being like these attention mechanisms that are referencing every token that preceded the particular token for which you’re looking up the value.

Participant 2: That makes sense, but why is it always so binary? Why wouldn’t it just be like, it’s halfway through, the token got rejected and so then it’s 20 seconds instead of 38 seconds. Why is it always 3 seconds to 38 seconds in every example?

Khawaja Shams: Ever have too many browser tabs and like your browser comes to a halt? That still happens today.

Participant 2: Every moment.

Khawaja Shams: Yes, so it’s like that. It’s just like it’s thrashing and it’s losing. It’s evicting the data that it now has to go recompute and that’s causing pipeline stalls and that’s causing delays, because now it’s causing you to use up more compute. There are other things that can happen too, like precompute could be very compute heavy. It could cause your GPU to start running hot and run into thermal throttling as well. Having specific hardware for prefill versus decode helps, like not having to run it simultaneously is also super useful.

See more presentations with transcripts

Subscribe for MMS Newsletter

By signing up, you will receive updates about our latest information.

  • This field is for validation purposes and should be left unchanged.

How Amazon Uses Guardrails In Software Development

MMS Founder
MMS • Ben Linders

Carlos Arguelles spoke about Amazon’s inflection points in engineering productivity at QCon San Francisco, where he explained that shift testing left can help catch issues early. He suggested using guardrails such as code reviews and coverage checks. Your repo strategy, monorepo or multirepo, will impact the guardrails that need to be in place.

When a company is new, it has to move fast, so there are very few guardrails in place. It’s also generally small enough where you know all the people touching a codebase, Arguelles said. As your customer base grows and more and more people depend on your product, it becomes increasingly important to adopt best practices and ensure everybody adheres to them, he added. Those guardrails don’t come for free: they add friction and reduce your ability to move fast in places, so there’s often a tradeoff here.

As a company grows, investing in custom developer tools may become necessary, as Arguelles explained in Inflection Points in Engineering Productivity:

Initially, standard tools suffice, but as the company scales in engineers, maturity, and complexity, industry tools may no longer meet needs. Inflection points, such as a crisis, hyper-growth, or reaching a new market, often trigger these investments, providing opportunities for improving productivity and operational excellence.

The software development life cycle at Amazon starts with an inner developer loop, where an engineer iterates on a piece of code in their own workspace. By default, engineers run unit tests, gather and gate on code coverage and execute various linters every time they create a build, Arguelles said. When they submit a code review, the code review tool runs a number of additional tests on that code.

When those validations pass and the engineer has thumbs up from their reviewer, the code gets pushed to a repo and CI/CD shepherds that code change through various testing stages and increasingly exhaustive tests, including load and performance tests, before finally pushing to production, Arguelles explained:

We expect most of our code changes to reach production within hours of checkin, as all the guardrails should be automated. Once they reach production, canaries further validate the changes.

Finding issues earlier is always better, Arguelles mentioned. And shifting testing left so that you can catch issues in the inner developer loop (pre-submit), and not in the outer developer loop (post-submit) becomes more and more important as your codebase grows:

This is because if a bad piece of code is submitted and merged, it now blocks N developers around you until it’s rolled back or fixed, and as your system grows, so does N.

Shifting testing left is non-trivial because in order for you to effectively and reliably run end-to-end integration tests against unreleased code you need to invest in ephemeral, hermetic test environments, Arguelles said.

One critical decision that Amazon made is that they operate in a multi-repo world, meaning every team has their own micro-repo. This is in contrast with other companies that have gone the route of a monorepo for the entire company (like Google).

Google uses a monorepo where ~100k engineers use a single repo with no branches. Everybody has to be committed to the health of the repo, because the blast radius of a bad code checkin is enormous; you could literally block thousands of people, Arguelles said. Pre-submit end-to-end testing is not just “nice-to-have,” but business-critical.

Amazon, on the other hand, chose to go the route of multirepos, with every team having essentially their own repo, Arguelles mentioned. This acts as a natural blast-radius reduction mechanism: a bad checkin can break an individual microrepo, but there are more guardrails in place to prevent it from cascading into other team’s microrepos.

Arguelles mentioned that there’s unavoidable complexity in large systems. How you choose to do your development determines where in the software development lifecycle you need to deal with that complexity. Neither company was able to avoid it, but they’re tackling it either pre- or post- submit, he concluded.

InfoQ interviewed Carlos Arguelles about guardrails and micro vs mono repo.

InfoQ: How do guardrails at Amazon look?

Carlos Arguelles: For example, when Amazon was a much smaller company in 2009, you could quickly ssh to a production host to investigate an issue, tail logs, etc. Any manual interaction is inherently a dangerous thing to do – imagine you type the wrong command or accidentally press an extra “0” and bring down that host or cause data loss. So we put guardrails such that if you want to run a command on a production host, it needs to be code reviewed and there’s an auditable record of your action.

Another example is you cannot submit code directly to a repo without going through code review and having a thumbs up from another person. Or we now gate on code coverage drops to ensure all code going to production meets a minimum test coverage bar. Tooling like this provides scalable ways to encode and enforce best practices.

InfoQ: What are the implications of working with micro repos compared to monorepo?

Arguelles: This is a place where the two places where I worked, Amazon and Google, differed significantly because of a foundational decision made by both companies decades ago: Google using a monorepo and Amazon micro repos.

This decision impacts guardrails that need to be in place. For Amazon, end-to-end pre-submit testing was “nice-to-have,” but it was not business-critical.

The decision to have micro repos at Amazon did not come for free, though. In a monorepo, every service is naturally integrated, whereas in a multirepo world, you need to coordinate how changes safely cascade from repo to repo.

About the Author

Subscribe for MMS Newsletter

By signing up, you will receive updates about our latest information.

  • This field is for validation purposes and should be left unchanged.

Presentation: Maximizing Deep Learning Performance on CPUs using Modern Architectures

MMS Founder
MMS • Bibek Bhattarai

Transcript

Bhattarai: My name is Bibek. I work at Intel as AI Technical Lead. Our group mostly deals with customers directly. We have firsthand knowledge of what customers are deploying, where they are deploying, and what platform they use, what matrix they really prefer when it comes to deploying the model. Today’s talk in particular, I’m going to focus on this little addition in CPU architectures called AMX, Advanced Matrix Extensions. It’s added from 4th Gen Intel Xeon processors, you can find on the data center.

Basically, I’m going to go into a little bit of a dirty detail into what exactly in AMX, and what makes it really good for matrix multiplication, and why you should be careful in learning how to enable it, and then how to take advantage of it. I break down the whole presentation into four parts. Why should I care? Then, what does it exactly solve? Then, how does it solve it? I will go into a little bit of detail in there. Then, last but not least, how do I leverage it? How do I make sure I am using it, and then I am taking full advantage of it?

What Deep Learning Workloads Usually Run in CPUs?

From our interaction with customers, our collaboration with customers, there is still a lot of the deep learning workloads that still runs on some CPU. This may be because of availability, which is obviously a big issue. GPUs are hard to come by. You might want to use your GPU for something more important, like training large language models. Or some of the models are inherently bound on the memory bandwidth. For whatever reason, there are a lot of the workloads that still makes sense to deploy on CPU rather than using on GPU. Not to be the downer, because everybody’s talking about LLMs, you can really squeeze a lot of performance out of a CPU. This is a number published by Intel when Llama 3.1 was released. It was on the day of release.

Then, this is what you can get. You can get pretty much one token every 20 milliseconds if you compress your model and then deploy it on a 5th-generation Intel CPU server. What I’m going to say here is, for whatever reason, you may be deploying your workloads on CPU, or you may be doing feasibility analysis to see if you can deploy your workload on CPU. If you’re one of those folks, I want to help you understand what is the maximum I can squeeze out of my CPU so that you can make an educated, informed decision on the selection.

GEMMs (General Matrix Multiplication) Dominate the Runtime

What’s the most time-consuming part in all these workloads? There’s a huge compute-bound part, and there’s also a huge memory-bound part in LLM. A lot of the traditional machine learning tasks, traditional deep learning models, they are heavily bound in computation. Whatever the model architecture is, in the heart of the model is what we call GEMM operation. It stands for General Matrix Multiplication. It’s a matrix multiplication. If you are using encoder-only or decoder-only transformer models, around 70% of the runtime is being spent on the GEMM. Same goes for CNN. You can convert your 1D, 2D, 3D CNN into a matrix multiplication operation, and that takes significant amount of time.

For RNN models, you can convert your LSTM gates, GRU gates, into a linear operation, which transmits to the GEMM operation. You get the idea. Basically, whatever model you are running on the surface, eventually what you are doing on the hardware is spending a lot of the cycle doing matrix multiplication. Obviously, it makes sense to go after this huge component if we want to accelerate our workload on CPU.

Let’s do a little exercise on matrix multiplication. I know it seems like a high school math class. I’m sure pretty much every one of you have written matrix multiplication code at some point in your life. If nowhere, probably during preparing for the interview. I did. This is what typical matrix multiplication looks like. You have matrix A, that size, let’s say M by K, M rows, K column. You have another matrix B, that is K by N, K rows, N column, and then you multiply them together. You get a matrix C, M rows, and then N column.

Typically, the first source code you probably wrote for matrix multiplication probably looked like this. You iterate through M, you iterate through N, that basically iterates over every cell on matrix C. For every cell in matrix C, you need to get one row from matrix A, one column from matrix B, and then do the element-wise multiplication, accumulate all of them together into a single value, and then you move to the next cell on matrix C. This is not an efficient algorithm, obviously, because it’s the most naive matmul.

One thing I really want to point out here is, this is really terrible when it comes to cache utilization. I want to reiterate that cache locality is very important. We saw the impact of caching here. I’m sure you are familiar with the hardware caching. When you fetch a data element from matrix, so this matrix is in memory, when you fetch this particular element, it will fetch a bunch of other elements, assuming that you’re going to use them in future. Then, same goes on matrix B. When you fetch this one, it will fetch a bunch of these elements and put it on the L1 cache. Eventually, when doing the matrix multiplication from matrix B, you are only going to use this element, and you got to move to next row. All these elements you just fetched went to waste. You bought it in the L1 cache, they didn’t get used, so they went to waste.

One really easy way to fix this is called loop reordering. It’s surprisingly really easy, and then it’s very efficient. All we did from the last code is we swapped K and N order in the loop. When we do this, we see this consecutive memory access on all matrix A, B, and C. To compute one row in matrix C, you will use this one, and then you do next row, next row, next row, all the way down, and then you are done with one row.

Then, you will switch on A, and then repeat the process on B. There are lots of other ways to make matrix multiplication cache-friendly. For example, tiled matrix multiplication is one of the popular approaches nowadays, especially because of the GPUs and parallelization potential of these tiled matrix multiplication. Basically, when you are doing the matrix multiplication on CPU, whatever tiles you are operating on, you want to bring them as close to your processor as possible, so preferably on L1 cache. You want to bring them in L1 cache. As you can see, this simple decomposition, I decomposed my 1K-by-1K matrix into tile of 128-by-128, and then I used this two-tiered loop, and then it actually reduced the runtime from 130 milliseconds to 89 milliseconds.

Obviously, we’re not going to spend the whole time optimizing the matrix multiplication, because there are literally teams of hundreds of engineers in almost every big company who are working full-time to optimize GEMM kernels. What I want you to take from this little exercise is the fact that data locality is really important. Obviously, with modern CPU architecture, the optimization is much more complicated. The tiling is not cache agnostic. There are multiple tiers of caches. You want to maintain locality in all of them. There are architectures like AVX, which can process huge chunks of data in a single go. You want to take that into consideration when optimizing your algorithm. If you just run this matrix multiplication on NumPy, it runs in around 13 milliseconds. We are still seven-fold away from that optimal solution. NumPy, when you run in CPU, it is just oneMKL from Intel, so you get the idea.

One point I really want to emphasize here is, for better performance, you want to have a large amount of useful data as close to the CPU as possible. You want to have as large amount of data close to CPU, but those large amounts of data have to be useful. It cannot be useless. If you really want to go into detail of what matrix multiplication optimization really looks like, there are a couple of blogs I’ve linked here. I really love them. They have code, illustration, everything, so feel free to go through them.

Low-Precision Computation (Intel AMX)

We got one motivation. We want our computer architecture to be able to handle large chunks of data, and then we want them to keep it really close to the processing unit. The second point I want to emphasize, especially with the rise of deep learning and then large language models, is you must be able to compute efficiently on low-precision data. Meryem from TitanML also emphasized that point as one of the five key takeaways for deploying LLMs. She said quantized models are your friend. You want to use the low-precision numbers. Due to the sheer amount of memory you need, and then the amount of compute you need, you want to be able to store your model parameters, weights, and biases using low-precision data format.

Then, you want to have a compute unit that is able to process this data really efficiently. We got our two objectives, and that’s exactly what Intel AMX fixes. For the data part, we want to have a large chunk of data close to CPU, so we used to have tiles on L1 cache. What’s better than having data on L1 cache? You can now have 2D chunk of data in register. You can load 1 kilobyte of data in single register at a time. You have really large chunks of data close to your processing unit. Then, the next part, you should be able to compute those low-precision computation efficiently. Then, that part is handled by what they call tiled matrix multiplication unit, or TMUL. It is basically a systolic area of Fused Multiply-Add ALUs. You can multiply two elements, and then add with the existing element, and then it gives the result. Systolic area of that FMA unit is what’s in the TMUL.

In order to operate these tiles, and TMUL, they have added the instruction sets in x86, so there are basically three groups of instructions you want to take a look at. One is managing the configuration. You need to be able to load your tile configs, and then store your tile configs efficiently. The second group on the bottom left is for data management. You should be able to clear your tile registers, and then you need one instruction to load the data from memory to tile, and then another instruction that can store the data from tile into main memory. As far as the computation goes on the TMUL, right now it supports int8 and bf16. You can see there are four combinations of int8, basically handling signed and unsigned combination. You can do unsigned to unsigned, unsigned to signed, signed and unsigned, and then signed, signed combination.

Then, last one is for bf16. Some more information on resources specification. You get in total eight of those tiles. You can use all of them to make sure you are processing as much as possible at a time. Each of these tiles have to be configured in a way that they cannot exceed 16 rows, and then they cannot have more than 64 bytes in one row. Basically, maximum size you get is 16-by-64 bytes, so that would amount to 1 kilobyte in total.

Then, depending on the precision of the data you are storing on these, if you are doing int8 matrix multiplication, you get to fit a 16-by-64 int8 chunk in one register. If you are doing bf16, you get a 16-by-32 chunk in your register. Basically, what AMX does now is it gets two 16-by-64 int8 matrix and then multiplies that, and then it stores it into a 16-by-16 int8 matrix. Accumulation happens on int32 so that it does not overflow. Then, same for bf16. It gets 16-by-32 matrix A, and then 16-by-32 matrix B, and then the result will be 16-by-16, this time float32 because you don’t want to overflow your bf16.

AMX Utilization

We understood why, and then what exactly is in the AMX. Now I want to move into how we can use this. We already saw a little bit of instruction set that is available for you to manipulate AMX, but obviously you’re not going to do programming using those commands, so you’re going to have to write in high-level languages. This next section covers that. First of all, you want to check if your CPU has AMX or not. For AMX, you will need at least 4th-generation Xeon processor from Intel. That would be Sapphire Rapids, codenamed, or if you are on AWS, that would be M7i, R7i, C7i instances. Then, you will need Linux kernel at least 5.16, because that’s when the intrinsics for programming AMX were introduced on Linux.

Once you have that, if you do lscpu on your Linux server, you’ll see a bunch of information on the CPU, like cores, cache size available, and a bunch of other information among this. This is the one I want you to check. On the flags field, there are a bunch of other flags. Just to check if you have AMX or not, you need to confirm you have these three flags. AMX-TILE is for tile manipulation, AMX_BF16 and AMX_INT8 are for computing on bf16 and int8. Then, for the power efficiency, AMX is disabled by default when running a bunch of softwares. If your software or if your core section needs AMX, you’ll have to make a system call to ask Linux to let you use the AMX resources. This is usually present on every bit of software that uses AMX.

Basically, you have to do this prctl system call and then ask for this X feature, XTILEDATA. Then, once you get that feature access, you will be able to use AMX in your code. There is a link to the Linux document that you can go and then check for more detail.

Once you ask for Linux kernel to use AMX, the next steps are really straightforward. First thing you want to do is, based on your application, you want to configure the tile. There are a bunch of different things you need to configure. You can see there is a structure on the left. First one is palette_id. It has to be 1 when you initialize the tiles, when you configure the tiles. There is start_row. start-row is basically for fault tolerance. If your matrix multiplication or any of these AMX instruction fail, it has to know where to go back to fetch the data. That’s basically what a start_row does.

Then, there are a bit of a result bit. Those are reserved for future architecture extensions. That’s not relevant right now. Two factors that you really need to configure are these. These are columns byte and then rows. These are basically your tile sizes. You want to make sure how big of a tile you want for each of the register. If you undersubscribe this, let’s say if you only use 8 rows and then 32 bytes, then rest of the 8 rows and then remaining 32 bytes will be filled with 0s when doing the computation so that you can still proceed with the operation. Here’s an example initialization I did for a toy code. Like I said, I set palette_id to 1, start_row to 0.

Then, now we want to compute two int8 matrix and then accumulate them into int32, so matrix A, matrix B, and matrix C. Matrix C will be in tmm0. Matrix A and B will be in tmm1 and tmm2. We want 16 rows on each of those tiles and then 64 bytes. What we have is 16-by-64 matrix A, 16-by-64 matrix B, those are int8. Then, when we multiply those together, we get 16-by-16 int8 matrix. B is basically B transpose. You can think 64 is the common dimension when multiplying the matrix. Actually, it’s happening with dot product, so this seems a little bit of a confusing part.

Once you configure your tiles, next step is you load the data from memory to tile. You can use tile load data intrinsics for that. We load C into register 0, A into 1, B into 2, we get these nice three tiles. Next step is basically doing the computation now. Now you can just use this instruction here, dot-product byte, and then we have signed int, signed int, and then we will do accumulation on the DWORD that is int32. I will go into a little bit of detail over this in a while, but basically you are multiplying two int8 chunks and then getting your result in 32 tile. Under the hood, it’s working like this. Like I said, there is a systolic area of FMA, this is a two-dimensional systolic area of FMA, and then it will propagate the data from tile A, and then tile B, and then tile C, and then basically add to what’s already on tile C while multiplying A and B.

Once you are done with your computation, you will store the result from the tile 0 to C, basically back to memory. We can do one tile to one tile and then get one tile. How does this translate to doing really large matrix multiplication? We basically divide them into a bunch of tiles. If we have matrix A and B, that means that if only one-fourth of A, B, and C fits in one tile, we will do this. We will divide A into four tiles, B into four tiles, and then we will follow a schematic where we load some tiles from matrix A, some tiles from matrix B, and then do the computation and then update the result in C. In reality, we are only using three tiles here. We still have five more tiles, so we can load two more from B and then two more from C and then do a huge computation at the same time.

This is basically the continuation of this one. In our example earlier, we loaded C into tmm0, A into tmm1, and then B into tmm2, and then this is basically showing all the data flow that’s happening in your processing element. Before I move forward with this, I want to emphasize that whatever hardware I just described, it’s present on every single core on the CPU. Every single core will have this added piece of silicon that has T, the tile register that can do the data management, and then the TMUL units that can do the computation. These are the supported combinations for now. As you can see, there is a bf16 on the very top. You can multiply two bf16, accumulate them into float32, and basically all combinations of signed and unsigned int, and you will accumulate on int32 to avoid the overflow. How does this map into our low-precision compute requirements?

Obviously, the default training and inference precision, most of the time, is float32. For float32, we don’t use AMX, we stick with AVX-512. For floating-point 16, there is AMX-FP16 and AMX-COMPLEX that’s coming on new 6th-generation of Xeon. It’s not supported right now. For all the other bf16 and then signed and unsigned integers, you use AMX-BF16 or AMX-INT8. The good thing about this AMX or the TMUL architecture is that it’s extensible. Whenever there is a demand for new precision, for example, FP8 is picking up pace really well, int4 has been really popular in the literature. If you have this low-precision format that becomes really popular, then Intel will add native hardware computation support for those in the next iteration of CPU, and then you get to enjoy them.

How Do I Take Advantage of AMX?

You can do matrix multiplication with this really tedious way. Why would I do this? That’s the question most people ask. Why would I want to do that? This is for how exactly you leverage AMX on your deep learning workload. For this, you don’t really need to do whatever matrix multiplication I just did. If you are someone who is developing a custom operator, custom primitives, like we talked earlier on the TPPs, so if you have new primitives that uses a different form of GEMM, then you might have to implement this on your own, or you can just put in request to Intel’s oneDNN team, and then they’ll do implementation for you. If you are someone who is working on frameworks that is not one of the popular ones, like TensorFlow, PyTorch, ONNX, these frameworks are widely supported by Intel engineers. They push their optimization regularly to those frameworks.

If you are working on one of those frameworks that does not have Intel support, then all you need to do to enable these features on Intel machine is port either oneDNN, oneMKL, and then whatever other libraries that are relevant to your framework. Even for this, if your framework is picking up popularity, then Intel will be more than happy to jump in and then do the integration for you. I don’t see anybody exactly doing this outside of Intel, or maybe AMD, or some other folks who want to enable and maximize the ability of their hardware. For the folks who are either data scientists and ML engineers who rely on framework, all you have to do is install the new enough framework. That’s all you need to do. You have TensorFlow 2.10. After TensorFlow 2.10, it uses oneDNN by default on CPU. If you have a workload running on CPU, make sure you are using newer than 2.10 TensorFlow. Same goes for PyTorch. If you have a workload that is running on PyTorch, you want to make sure it is new enough.

Once you have new enough PyTorch, this is all you need to do. If you want to use AMX_BF16, you just run your workload using Auto Mixed Precision. You run your model using Auto Mixed Precision, and then AMX_BF16 will automatically kick in. There are a bunch of operators that are supported on the oneDNN for bf16 precision. Same goes for int8. If you quantize your model using PyTorch or some other framework, and then you run it using PyTorch, then you are automatically utilizing the AMX_INT8 that’s implemented in oneDNN. Because PyTorch uses oneDNN by default on CPU. Whenever you use framework, AMX gets used whenever possible. If you have your model in bf16, int8, more than likely you are already utilizing AMX_BF16 or AMX_INT8.

The good thing is this works really well with both torch.compile and TorchScript because folks have exported their model into different formats. Intel makes sure that all the torch.compile and then TorchScript exported model supports the AMX kernels. The same goes for TensorFlow. You need to make sure that MAX ISA is AMX_BF16 so that it can use the AMX_BF16. Once you do that, all you need to do is set the AMX flag true. Then you get to enjoy the acceleration without doing anything at all. Obviously, you can quantize your model and run it. The same thing goes here.

For Optimization Freaks

For people who are going to go to the extra mile to get the best performance, so this is where I would say I reside. I want to make sure I can get the best performance I can on the model without losing accuracy. Obviously, I talked about TensorFlow and PyTorch. Intel contributes periodically to this framework. A lot of the optimization that are not yet upstreamed into PyTorch and TensorFlow, more aggressive ones, some that does not meet the Meta or Google’s requirement, they reside on these repositories. Intel Extension for PyTorch, Intel Extension for TensorFlow. As you heard earlier, IPEX was mentioned on AMD’s evaluation as well. It optimizes a lot of the PyTorch workload. Depending on the model, you can get a really huge boost. To compress your model really well, sometimes just converting using PyTorch’s default quantized dynamic does not meet your accuracy requirement because there is a huge accuracy loss when you quantize to low-precision format.

Intel has tools that give you a way to quantize your model, compress your model using sparsity pruning, do distillation, basically make it as small as possible so that you can run efficiently on CPU. Then, these frameworks have a safeguard that allows you to tune for accuracy. You can put in, “I am willing to lose no more than this much accuracy”. Then, they will iterate on your model and then find the config that meets that accuracy requirement and then give you the compressed version of your model.

Then, OpenVINO Toolkit is a little bit different. It has the compression capability, just like Intel Neural Compressor. It’s also an end-to-end system, so you can actually train your model and also deploy your model because it has Model Server as well. If you want really best performance on CPU, I would pay some attention to this toolkit. I know the transformer has been really the focus of a lot of the conversations on this conference, as well as the whole deep learning industry.

Intel Extension for Transformers is a tool that does more or less what Intel Neural Compressor does, but more aggressively for transformer model. You can get lots of improvement on your large language models, embedding models by using the compression techniques that are in this tool. They have a really large amount of examples on how to convert model to bf16, int8, int4, int2, whatever precision you need. I would check this out for some examples.

How Does This Translate to Different Models?

What does this mean? We saw the matrix multiplication. What does this do to actual deep learning model runtimes? These are some of the performance metrics I took over the year from our customer works. These are the models that have been deployed in CPU. Then they were deployed in 3rd-generation Xeon, then they moved to 4th-generation Xeon. We do this analysis all the time to give them the best config they can get to make sure they optimize the performance per dollar.

As you can see, the red vertical line, is the float32 baseline. Just by using AMX_BF16 or AMX_INT8 for accelerating GEMM operations, you can get a really good improvement. For DistilBERT or the BERT base, you get more than 5x improvement just going bf16 with no loss in accuracy. For all these numbers, there is less than 1% loss in accuracy for int8. For bf16, no loss in accuracy. For some of the CNN model or CRNN model, you get more than 10x improvement just by using the new enough framework and then doing the model quantization.

Summary

What is it? It’s an instruction set architecture extension that was introduced on 4th Gen Xeon. It will continue to evolve when we produce more iterations of Xeon. It’s basically a dedicated piece of silicon on each core that has data management unit and then compute unit. What data types are supported? For now, AMX-TILE is for your data management. Then, AMX_BF16 and AMX_INT8 are for doing computation on bf16 and int8 data. On the future iteration of Xeon, AMX-COMPLEX and AMX-FP16 are coming. Then, obviously, how do I use it? Most of the time, just use the framework that already uses oneDNN, OpenBLAS, oneMKL. If you want to go the extra mile and optimize your workload, look into OpenVINO, Neural Compressor, and other tools I just mentioned earlier.

Questions and Answers

Yue: I’m always curious about how the sausage is made. The packaging makes it really easy to use these features, if you’re on one of the libraries or frameworks. Most people probably won’t write a CUDA kernel, but it’s fascinating to learn how you can maximize the hardware performance by doing the right thing in software. What kind of effort went into enabling these hardware features in those libraries that people can easily pick up? What is the process like?

Bhattarai: When it comes to enabling these features in the framework, it’s mostly down to oneDNN and oneMKL to write the efficient kernels. They want to make sure all these operations are really optimal. There are a couple of different level of effort happening. One is obviously, like I said earlier, you want to optimize the uses of AMX resource you have. You want to peel all the tiles you have available and then keep your TMUL unit busy. By doing this, you can get up to 8x more operations per cycle compared to the last iteration of the processors. That’s one part. Then the second part oneDNN library really focused on, is breaking the operation into these tiles really efficiently. When you have a linear operation versus when you have 1D, 2D, or 3D convolution, GEMM looks really different.

Some of the time, some of the GEMM operation will not have all 16 rows because they have a really small dimension in one of the dimensions. Factoring for those things and then putting this safeguard for some of those low utilization use cases is one of the things that does. That actually also translates into how you optimally use AMX. If you have a small enough model, it’s suggested to use really large batch because that way you get to fill the 16 rows in AMX_TILE versus for some of the model, if you just use batch size one, then your GEMM operation becomes GEMM B operation. It will be matrix vector multiplication, and then you will not fill the tile and then that way you will waste a lot of the resources there.

Participant: If we use bare metal versus virtual machines, all those techniques to improve the efficiency of the computation, is there any different considerations we can have when we have bare metal versus Linux?

Bhattarai: On the bare metal, we do have control on all the physical threads as well as Hyper-Threads. Basically, enabling Hyper-Thread might not always help, but it will not do the harm. Same goes for these instances. When you are running on cloud with CPU, you don’t know what the rest of the node is being used for. If there is a way for you to utilize Hyper-Threading, then you can enable Hyper-Thread to get the performance improvement on cloud.

See more presentations with transcripts

Subscribe for MMS Newsletter

By signing up, you will receive updates about our latest information.

  • This field is for validation purposes and should be left unchanged.

Article: Building Reproducible ML Systems with Apache Iceberg and SparkSQL: Open Source Foundations

MMS Founder
MMS • Anant Kumar

Key Takeaways

  • Time travel in Apache Iceberg lets you pinpoint exactly which data snapshot produced your best results instead of playing detective with production logs.
  • Smart partitioning can slash query times from hours to minutes just by partitioning on the same columns you are already filtering on anyway.
  • With schema evolution, you can actually add new features without that sinking feeling of potentially breaking six months of perfectly good ML pipelines.
  • ACID transactions eliminate those mystifying training failures that happen when someone else is writing to your table.
  • The open source route gives you enterprise-grade reliability without the enterprise price tag or vendor lock-in, plus you get to customize things when your ML team inevitably has special requirements that nobody anticipated.

If you’ve spent any time building ML systems in production, you know the pain. Your model crushes it in development, passes all your offline tests, then mysteriously starts performing like garbage in production. Sound familiar?

Nine times out of ten, it’s a data problem. And not just any data problem: it’s the reproducibility nightmare that keeps data engineers up at night. We’re talking about recreating training datasets months later, tracking down why features suddenly look different, or figuring out which version of your data actually produced that miracle model that everyone’s asking you to “just rebuild really quickly”.

Traditional data lakes? They’re great for storing massive amounts of stuff, but they’re terrible at the transactional guarantees and versioning that ML workloads desperately need. It’s like trying to do precision surgery with a sledgehammer.

That’s where Apache Iceberg comes in. Combined with SparkSQL, it brings actual database-like reliability to your data lake. Time travel, schema evolution, and ACID transactions are the things that should have been obvious requirements from day one but somehow got lost in the shuffle toward “big data at scale”.

The ML Data Reproducibility Problem

The Usual Suspects

Let’s be honest about what’s really happening in most ML shops. Data drift creeps in silently: Your feature distributions shift over time, but nobody notices until your model starts making predictions that make no sense. Feature pipelines are supposed to be deterministic, but they’re not; run the same pipeline twice and you’ll get subtly different outputs thanks to timestamp logic or just plain old race conditions.

Then there’s the version control situation. We’ve gotten pretty good at versioning our code (though let’s not talk about that “temporary fix” from three months ago that’s still in prod). But data versioning? It’s still mostly manual processes, spreadsheets, and prayers.

Here’s a scenario that’ll sound depressingly familiar: Your teammate runs feature engineering on Monday, you run it on Tuesday, and suddenly you’re getting different results from what should be identical source data. Why? Because the underlying tables changed between Monday and Tuesday, and your “point-in-time” logic isn’t as point-in-time as you thought.

The really insidious problems show up during model training. Multiple people access the same datasets, schema changes break pipelines without warning, and concurrent writes create race conditions that corrupt your carefully engineered features. It’s like trying to build a house while someone keeps changing the foundation.

Why Traditional Data Lakes Fall Short

Data lakes were designed for a world where analytics required running batch reports and maybe some ETL jobs. The emphasis was on storage scalability, not transactional integrity. That worked fine when your biggest concern was generating quarterly reports.

But ML is different. It’s iterative, experimental, and demands consistency in ways that traditional analytics never did. When your model training job reads partially written data (because someone else is updating the same table), you don’t just get a wrong report, you get a model that learned from garbage data and will make garbage predictions.

Schema flexibility sounds great in theory, but in practice it often creates schema chaos. Without proper evolution controls, well-meaning data scientists accidentally break downstream systems when they add that “just one more feature” to an existing table. Good luck figuring out what broke and when.

The metadata situation is even worse. Traditional data lakes track files, not logical datasets. So when you need to understand feature lineage or implement data quality checks, you’re basically flying blind.

The Hidden Costs

Poor data foundations create costs that don’t show up in any budget line item. Your data scientists spend most of their time wrestling with data instead of improving models. I’ve seen studies suggesting sixty to eighty percent of their time goes to data wrangling. That’s… not optimal.

When something goes wrong in production – and it will – debugging becomes an archaeology expedition. Which data version was the model trained on? What changed between then and now? Was there a schema modification that nobody documented? These questions can take weeks to answer, assuming you can answer them at all.

Let’s talk about regulatory compliance for a minute. Try explaining to an auditor why you can’t reproduce the exact dataset used to train a model that’s making loan decisions. That’s a conversation nobody wants to have.

Iceberg Fundamentals for ML

Time Travel That Actually Works

Iceberg’s time travel is a snapshot-based architecture that maintains complete table metadata for every write operation. Each snapshot represents a consistent view of your table at a specific point in time, including schema, partitions, and everything.

For ML folks, this is game-changing. You can query historical table states with simple SQL:

-- This is how you actually solve the reproducibility problem
SELECT * FROM ml_features 
FOR SYSTEM_TIME AS OF '2024-01-15 10:30:00'

-- Or if you know the specific snapshot ID
SELECT * FROM ml_features 
FOR SYSTEM_VERSION AS OF 1234567890

No more guessing which version of your data produced good results. No more “well, it worked last week” conversations. You can compare feature distributions across time periods, analyze model performance degradation by examining historical data states, and build A/B testing frameworks that actually give you consistent results.

The metadata includes file-level statistics, so query optimizers can make smart decisions about scan efficiency. This isn’t just about correctness, it’s about performance too.

Schema Evolution Without the Drama

Here’s something that should be basic but somehow isn’t: Adding a new column to your feature table shouldn’t require a team meeting and a migration plan. Iceberg’s schema evolution lets you adapt tables to changing requirements without breaking existing readers or writers.

You can add columns, rename them, reorder them, and promote data types, all while maintaining backward and forward compatibility. For ML pipelines, data scientists can safely add new features without coordinating complex migration processes across multiple teams.

The system tracks column identity through unique field IDs, so renaming a column doesn’t break existing queries. Type promotion follows SQL standards (integer to long, float to double), so you don’t have to worry about data loss.

-- Adding a feature is actually this simple
ALTER TABLE customer_features 
ADD COLUMN lifetime_value DOUBLE

-- Renaming doesn't break anything downstream
ALTER TABLE customer_features 
RENAME COLUMN purchase_frequency TO avg_purchase_frequency

ACID Transactions (Finally!)

ACID support allows ML workloads to safely operate on shared datasets without corrupting data or creating inconsistent reads. Iceberg uses optimistic concurrency control: Multiple writers can work simultaneously, but conflicts get detected and resolved automatically.

Isolation levels prevent readers from seeing partial writes. So when your training job kicks off, it’s guaranteed to see a consistent snapshot of the data, even if someone else is updating features in real-time.

Transaction boundaries align with logical operations rather than individual file writes. You can implement complex feature engineering workflows that span multiple tables and partitions while maintaining consistency guarantees. No more “oops, only half my update succeeded” situations.

Building Reproducible Feature Pipelines

Partitioning That Actually Makes Sense

Let’s talk partitioning strategy, because this is where a lot of teams shoot themselves in the foot. The secret isn’t complex: Partition on dimensions that align with how you actually query the data.

Most ML workloads follow temporal patterns, training on historical data and predicting on recent data. So temporal partitioning using date or datetime columns is usually your best bet. The granularity depends on your data volume. For high-volume systems, use daily partitions. For smaller datasets, use weekly or monthly partitions.

CREATE TABLE customer_features (
    customer_id BIGINT,
    feature_timestamp TIMESTAMP,
    demographic_features MAP,
    behavioral_features MAP,
    target_label DOUBLE
) USING ICEBERG
PARTITIONED BY (days(feature_timestamp))

Multi-dimensional partitioning can work well if you have natural business groupings. Customer segments, product categories, geographic regions, etc., reflect how your models actually slice the data.

Iceberg’s hidden partitioning is particularly nice because it maintains partition structures automatically without requiring explicit partition columns in your queries. Write simpler SQL, get the same performance benefits.

But don’t go crazy with partitioning. I’ve seen teams create thousands of tiny partitions thinking it will improve performance, only to discover that metadata overhead kills query planning. Keep partitions reasonably sized (think hundreds of megabytes to gigabytes) and monitor your partition statistics.

Data Versioning for Experiments

Reproducible experiments require tight coupling between data versions and model artifacts. This is where Iceberg’s snapshots really shine. They provide the foundation for implementing robust experiment tracking that actually links model performance to specific data states.

Integration with MLflow or similar tracking systems creates auditable connections between model runs and data versions. Each training job records the snapshot ID of input datasets, precisely reproducing the experimental conditions.

import mlflow
from pyspark.sql import SparkSession

def train_model_with_versioning(spark, snapshot_id):
    # Load data from specific snapshot
    df = spark.read 
        .option("snapshot-id", snapshot_id) 
        .table("ml_features.customer_features")
    
    # Log data version in MLflow
    mlflow.log_param("data_snapshot_id", snapshot_id)
    mlflow.log_param("data_row_count", df.count())
    
    # Continue with model training...

Branching and tagging capabilities enable more sophisticated workflows. Create stable data branches for production model training while continuing development on experimental branches. Use tags to mark significant milestones, such as quarterly feature releases, regulatory checkpoints, etc.

Feature Store Integration

Modern ML platforms demand seamless integration between data infrastructure and experiment management. Iceberg tables play nicely with feature stores, leveraging time travel capabilities to serve both historical features for training and point-in-time features for inference.

This combination provides consistent feature definitions across training and serving while maintaining the performance characteristics needed for real-time inference. No more training-serving skew because your batch and streaming feature logic diverged.

from feast import FeatureStore
import pandas as pd

def get_training_features(entity_df, feature_refs, timestamp_col):
    try:
        fs = FeatureStore(repo_path=".")
        
        # Point-in-time join using Iceberg backing store
        training_df = fs.get_historical_features(
            entity_df=entity_df,
            features=feature_refs,
            full_feature_names=True
        ).to_df()
        
        return training_df
    except Exception as e:
        print(f"Error accessing feature store: {e}")
        raise

Production Implementation

Real-World Example: Customer Churn Prediction

Let me walk you through a customer churn prediction system that actually works in production. This system processes millions of customer interactions daily while maintaining full reproducibility.

The data architecture uses multiple Iceberg tables organized by freshness and access patterns. Raw events flow into staging tables, are validated and cleaned, and then aggregated into feature tables optimized for ML access patterns.

-- Staging table for raw events
CREATE TABLE customer_events_staging (
    event_id STRING,
    customer_id BIGINT,
    event_type STRING,
    event_timestamp TIMESTAMP,
    event_properties MAP,
    ingestion_timestamp TIMESTAMP
) USING ICEBERG
PARTITIONED BY (days(event_timestamp))
TBLPROPERTIES (
    'write.format.default' = 'parquet',
    'write.parquet.compression-codec' = 'snappy'
)

-- Feature table with optimized layout
CREATE TABLE customer_features (
    customer_id BIGINT,
    feature_date DATE,
    recency_days INT,
    frequency_30d INT,
    monetary_value_30d DOUBLE,
    support_tickets_30d INT,
    churn_probability DOUBLE,
    feature_version STRING
) USING ICEBERG
PARTITIONED BY (feature_date)
CLUSTERED BY (customer_id) INTO 16 BUCKETS

Feature engineering pipelines implement incremental processing using Iceberg’s merge capabilities. This incremental approach minimizes recomputation while maintaining data consistency across different processing schedules.

def incremental_feature_engineering(spark, processing_date):
    # Read new events since last processing
    new_events = spark.read.table("customer_events_staging") 
        .filter(f"event_timestamp >= '{processing_date}'")
    
    # Compute incremental features (implementation depends on business logic)
    new_features = compute_customer_features(new_events, processing_date)
    
    # Merge into feature table with upsert semantics
    new_features.writeTo("customer_features") 
        .option("merge-schema", "true") 
        .overwritePartitions()

def compute_customer_features(events_df, processing_date):
    """
    User-defined function to compute customer features from events.
    Implementation would include business-specific feature engineering logic.
    """
    # Example feature engineering logic would go here
    return events_df.groupBy("customer_id") 
        .agg(
            count("event_id").alias("event_count"),
            max("event_timestamp").alias("last_activity")
        ) 
        .withColumn("feature_date", lit(processing_date))

Performance Optimization

Query performance in Iceberg benefits from several complementary techniques. File sizing matters. Aim for 128MB to 1GB files depending on your access patterns with smaller files for highly selective queries and larger files for full-table scans.

Parquet provides natural benefits for ML workloads since you typically select column subsets. Compression choice depends on your priorities. Use Snappy for frequently accessed data (faster decompression) and Gzip for better compression ratios on archival data.

Data layout optimization using clustering or Z-ordering can dramatically improve performance for multi-dimensional access patterns. These techniques colocate related data within files, reducing scan overhead for typical ML queries.

-- Optimize table for typical access patterns
ALTER TABLE customer_features 
SET TBLPROPERTIES (
    'write.target-file-size-bytes' = '134217728',  -- 128MB
    'write.parquet.bloom-filter-enabled.customer_id' = 'true',
    'write.parquet.bloom-filter-enabled.feature_date' = 'true'
)

Metadata caching significantly improves query planning performance, especially for tables with many partitions. Iceberg’s metadata layer supports distributed caching (Redis) or in-memory caching within Spark executors.

Monitoring and Operations

Production ML systems need monitoring that goes beyond traditional infrastructure metrics. Iceberg’s rich metadata enables sophisticated monitoring approaches that actually help you understand what’s happening with your data.

Data quality monitoring leverages metadata to detect anomalies in volume, schema changes, and statistical distributions. Integration with frameworks like Great Expectations provides automated validation workflows that can halt processing when quality thresholds are violated.

import great_expectations as ge
from great_expectations.dataset import SparkDFDataset

def validate_feature_quality(spark, table_name):
    df = spark.read.table(table_name)
    ge_df = SparkDFDataset(df)
    
    # Define expectations
    ge_df.expect_table_row_count_to_be_between(min_value=1000)
    ge_df.expect_column_values_to_not_be_null("customer_id")
    ge_df.expect_column_values_to_be_between("recency_days", 0, 365)
    
    # Validate and return results
    validation_result = ge_df.validate()
    return validation_result.success

Performance monitoring tracks query execution metrics, file scan efficiency, and resource utilization patterns. Iceberg’s query planning metrics provide insights into partition pruning effectiveness and file-level scan statistics.

Don’t forget operational maintenance (e.g., file compaction, expired snapshot cleanup, and metadata optimization). These procedures maintain query performance and control storage costs over time. Set up automated jobs for this stuff – trust me, you don’t want to do it manually.

Best Practices and Lessons Learned

Choosing Your Table Format

When should you actually use Iceberg instead of other options? It’s not always obvious, and the marketing materials won’t give you straight answers.

Iceberg excels when you need strong consistency guarantees, complex schema evolution, and time travel capabilities. ML workloads particularly benefit from these features because of their experimental nature and reproducibility requirements.

Delta Lake provides similar capabilities with tighter integration into the Databricks ecosystem. If you’re primarily operating within Databricks or need advanced features like liquid clustering, Delta might be your better bet.

Apache Hudi optimizes for streaming use cases with sophisticated indexing. Consider it for ML systems with heavy streaming requirements or complex upsert patterns.

And you know what? Sometimes plain old Parquet tables are fine. If you have simple, append-only workloads with stable schemas, the operational overhead of table formats might not be worth it. Don’t over-engineer solutions to problems you don’t actually have.

Common Pitfalls

Over-partitioning is probably the most common mistake I see. Creating partitions with less than 100MB of data or more than ten thousand files per partition will hurt query planning performance. Monitor your partition statistics and adjust strategies based on actual usepatterns, rather than theoretical ideals.

Schema evolution mistakes can break downstream consumers even with Iceberg’s safety features. Implement schema validation in CI/CD pipelines to catch incompatible changes before deployment. Use column mapping features to decouple logical column names from physical storage. It will save you headaches later.

Query anti-patterns often emerge when teams don’t leverage Iceberg’s optimization capabilities. Include partition predicates in WHERE clauses to avoid unnecessary scans. Use column pruning by selecting only required columns instead of SELECT * (yes, I know it’s convenient, but your query performance will thank you).

Migration Strategies

Migrating from legacy data lakes requires careful planning. You can’t just flip a switch and expect everything to work. Implement parallel systems during transition periods so you can validate Iceberg-based pipelines against existing systems.

Prioritize critical ML datasets first, focusing on tables that benefit most from Iceberg’s capabilities. Use import functionality to migrate existing Parquet datasets without rewriting data files.

-- Migrate existing table to Iceberg format
CALL system.migrate('legacy_db.customer_features_parquet')

Query migration means updating SQL to leverage Iceberg features while maintaining backward compatibility. Feature flags or configuration driven table selection enable gradual rollout.

Pipeline migration should be phased. Start with batch processing before moving to streaming workflows. Iceberg’s compatibility with existing Spark APIs minimizes code changes during migration.

Wrapping Up

Apache Iceberg and SparkSQL provide a solid foundation for building ML systems that actually work reliably in production. The combination of time travel, schema evolution, and ACID transactions addresses fundamental data management challenges that have plagued ML infrastructure for years.

The investment pays off through improved development velocity, reduced debugging time, and increased confidence in system reliability. Teams consistently report better experiment reproducibility and faster time-to-production for new models.

But success requires thoughtful design decisions around partitioning, schema design, and operational procedures. The technology provides powerful capabilities, but you need to understand both the underlying architecture and the specific requirements of ML workloads to realize the benefits.

As ML systems grow in complexity and business criticality, reliable data foundations become increasingly important. Iceberg represents a mature, production-ready solution that helps organizations to build ML systems with the same reliability expectations as traditional enterprise applications.

Honestly? It’s about time we had tools that actually work the way we need them to work.

About the Author

Subscribe for MMS Newsletter

By signing up, you will receive updates about our latest information.

  • This field is for validation purposes and should be left unchanged.

MONGODB ALERT: Bragar Eagel & Squire, P.C. is Investigating MongoDB, Inc. on Behalf of

MMS Founder
MMS • RSS

Bragar Eagel & Squire, P.C. Litigation Partner  Brandon Walker  Encourages Investors Who Suffered Losses In MongoDB (MDB) To Contact Him Directly To Discuss Their Options

If you are a long-term stockholder in  MongoDB  between August 31, 2023 and May 30, 2024 and would like to discuss your legal rights, call Bragar Eagel & Squire partner Brandon Walker or Marion Passmore directly at (212) 355-4648.  MongoDB between August 31, 2023 and May 30, 2024 and would like to discuss your legal rights, call Bragar Eagel & Squire partner Brandon Walker or Marion Passmore directly at (212) 355-4648.

This page requires Javascript.

Javascript is required for you to be able to read premium content. Please enable it in your browser settings.

Subscribe for MMS Newsletter

By signing up, you will receive updates about our latest information.

  • This field is for validation purposes and should be left unchanged.

ScyllaDB vs. MongoDB: How Numberly Optimizes NoSQL for Performance and Flexibility

MMS Founder
MMS • RSS

Numberly has been using both ScyllaDB and MongoDB in production for 5+ years. Learn which NoSQL database they rely on for different use cases and why.

Within the NoSQL domain, ScyllaDB and MongoDB are two totally different animals. MongoDB needs no introduction. Its simple adoption and extensive community/ecosystem have made it the de facto standard for getting started with NoSQL and powering countless web applications. ScyllaDB’s close-to-the-metal architecture enables predictable low latency at high throughput. This is driving a surge of adoption across teams such as Discord, TRACTIAN and many others who are scaling data-intensive applications and hitting the wall with their existing databases.

But database migrations are not the focus here. Instead, let’s look at how these two distinctly different databases might coexist within the same tech stack – how they’re fundamentally different, and the best use cases for each. Just like different shoes work better for running a marathon vs. scaling Mount Everest vs. attending your wedding, different databases work better for different use cases with different workloads and latency/throughput expectations.

So when should you use ScyllaDB vs. MongoDB and why? Rather than provide the vendor perspective, we’re going to share the insights from an open source enthusiast who has extensive experience using both ScyllaDB and MongoDB in production: Alexys Jacob, the CTO of Numberly. Alexys shared his perspective at ScyllaDB Summit 2019, and the video has been trending ever since.

Here are three key takeaways from his detailed tech talk:

Scaling Writes is More Complex on MongoDB

The base unit of a MongoDB topology is called a replica set, which is composed of one primary node and usually multiple secondary nodes (think of hot replicas). Only the primary node is allowed to write data. After you max out vertical write scaling on MongoDB, your only option to scale writes becomes what is called a sharded cluster. This requires adding new replica sets because you can’t have multiple primaries in a single replica set.

Sharding data across MongoDB’s replica sets requires using a special key to specify what data each replica set is responsible for, as well as creating a metadata replica set that tracks what slice of data lives on each replica (the blue triangle in the diagram below). Also, clients connecting to a MongoDB cluster need help determining what node to address. That’s why you also need to deploy and maintain MongoDB’s Smart Router instances (represented by the rectangles at the top of the diagram) connected to the replica sets.

The complexity of scaling writes in MongoDB

Having all these nodes leads to higher operational and maintenance costs as well as wasted resources since you can’t tap the replica nodes’ IO for writes, which make sharded MongoDB clusters the worst enemy of your total cost of ownership as Alexys noted.

For ScyllaDB, scaling writes is much simpler. He explained, “On the ScyllaDB side, if you want to add more throughput, you just add nodes. End of story.”

The simplicity of scaling writes in ScyllaDB

The simplicity of scaling writes in ScyllaDB

Alexys tied up this scaling thread:

“Avoid creating MongoDB clusters, please! I could write a book with war stories on this very topic. The main reason why is the fact that MongoDB does not bind the workload to CPUs. And the sharding, the distribution of data between replica sets in a cluster is done by a background job (the balancer). This balancer is always running, always looking at how sharding should be done, and always ensuring that data is spread and balanced over the cluster. It’s not natural because it isn’t based on consistent hashing. It’s something that must be calculated over and over again. It splits the data into chunks and then moves it around. This has a direct impact on the performance of your MongoDB cluster because there is no isolation of this workload versus your actual production workload.”

MongoDB Favors Flexibility Over Performance, While ScyllaDB Favors Consistent Performance Over Versatility

ScyllaDB and MongoDB have distinctly different priorities when it comes to flexibility and performance.

On the data modeling front, MongoDB natively supports geospatial queries, text search, aggregation pipelines, graph queries and change streams. Although ScyllaDB – a wide- column store (a.k.a. key-key-value) – supports user-defined types, counters and lightweight transactions, the data modeling options are more restricted than on MongoDB. Alexys noted, “From a development perspective, interacting with an JSON object just feels more natural than interacting with a row.” Moreover, while MongoDB offers the option of enforcing schema validation before data insertion, ScyllaDB requires that data adhere to the defined schema.

Querying is also simpler with MongoDB since you’re just filtering and interacting with JSON. It’s also more flexible, for better or for worse. MongoDB lets you issue any type of query, including queries that cause suboptimal performance with your production workload. ScyllaDB won’t allow that. If you try, ScyllaDB will warn you. If you decide to proceed at your own risk, you can enter a qualifier indicating that you really do understand what you’re getting yourself into.

MongoDB data modeling

MongoDB data modeling

ScyllaDB data modeling

ScyllaDB data modeling

Alexys summed up the key differences from a development perspective:

“MongoDB favors flexibility over performance. It’s easy to interact with and it will not get in your way. But it will have impacts on performance – impacts that are fine for some workloads, but unacceptable for others. On the other hand, ScyllaDB favors consistent performance over versatility. It looks a bit more fixed and a bit more rigid on the outside. But once again, that’s for your own good so you can have consistent performance, operate well and interact well with the system. In my opinion, this makes a real difference when you have workloads that are latency- and performance-sensitive.”

It’s important to note that even queries that follow performance best practices will behave differently on MongoDB than on ScyllaDB. No matter how careful you are, you won’t overcome the performance penalty that stems from fundamental architectural differences.

Together, ScyllaDB and MongoDB are a Great NoSQL Combo

“It’s not a death match; we are happy users of both MongoDB and ScyllaDB,” Alexys continued.

Numberly selects the best database for each use case’s technical requirements.

At Numberly, MongoDB is used for two types of use cases:

  • Web backends with REST APIs and possibly flexible schemas.
  • Real-time queries over unpredictable behavioral data.

For example, some of Numberly’s applications get flooded with web tracking data that their clients collect and send (each client with their own internally-developed applications). Numberly doesn’t have a way to impose a strict schema on that data, but it needs to be able to query and process it. In Alexys’ words, “MongoDB is fine here; its flexibility is advantageous because it allows us to just store the data somewhere and query it easily.”

ScyllaDB is used for three types of use cases at Numberly:

  • Real-time latency-sensitive data pipelines. This involves a lot of data enrichment, where there are multiple sources of data that need to be correlated, in real time, on the data pipelines. According to Alexys, “That’s tricky to do…and you need strong latency guarantees to not break the SLAs [service-level agreements] of the applications and data processes which your clients rely on down the pipe.”
  • Mixed batch and real-time workloads. Numberly also mixes a lot of batch and real-time workloads in ScyllaDB because it provides the best of both worlds (as Numberly shared previously). “We had Hive on one path and MongoDB on the other. We put everything on ScyllaDB and its sustaining Hadoop-like batch workloads and real time pipeline workloads.”
  • Web backends using GraphQL, which imposes a strict schema. Some of Numberly’s web backends are implemented in GraphQL. When working with schema-based APIs, it makes perfect sense to have a schema-based database with low latency and high availability.

Alexys concluded: “A lot of our backend engineers, and frontend engineers as well, are adopting ScyllaDB. We see a trend of people adopting ScyllaDB, more and more tech people asking ‘I have this use case, would ScyllaDB be a good fit?’ Most of the time, the answer is ‘yes.’ So, ScyllaDB adoption is growing. MongoDB adoption is flat, but MongoDB is certainly here to stay because it has some really interesting features. Just don’t go as far as to create a MongoDB sharded cluster, please!”

Bonus: More Insights from Alexys Jacob

Alexys is an extremely generous contributor to open source communities, with respect to both code and conference talks. See more of his contributions at https://ultrabug.fr/

About Cynthia Dunlop

Cynthia is Senior Director of Content Strategy at ScyllaDB. She has been writing about software development and quality engineering for 20+ years.

Subscribe for MMS Newsletter

By signing up, you will receive updates about our latest information.

  • This field is for validation purposes and should be left unchanged.

Data Breach Costs Fall for First Time in Five Years – IT Security News

MMS Founder
MMS • RSS

IBM found that the global average cost of a data breach has fallen by 9% compared to 2024, driven by improved detection and containment

This article has been indexed from www.infosecurity-magazine.com

Read the original article:

Subscribe for MMS Newsletter

By signing up, you will receive updates about our latest information.

  • This field is for validation purposes and should be left unchanged.