<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Daniel Sam Pete Thiyagu</title>
    <description>The latest articles on DEV Community by Daniel Sam Pete Thiyagu (@danielsamfdo).</description>
    <link>https://dev.to/danielsamfdo</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4162586%2F8f9d46aa-5e57-4120-b82e-7452afb36635.png</url>
      <title>DEV Community: Daniel Sam Pete Thiyagu</title>
      <link>https://dev.to/danielsamfdo</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/danielsamfdo"/>
    <language>en</language>
    <item>
      <title>System Design, Plainly — Season 3, Part 6: Data Lakes vs Warehouses vs Lakehouses</title>
      <dc:creator>Daniel Sam Pete Thiyagu</dc:creator>
      <pubDate>Sat, 05 Dec 2026 17:09:53 +0000</pubDate>
      <link>https://dev.to/danielsamfdo/system-design-plainly-season-3-part-6-data-lakes-vs-warehouses-vs-lakehouses-76i</link>
      <guid>https://dev.to/danielsamfdo/system-design-plainly-season-3-part-6-data-lakes-vs-warehouses-vs-lakehouses-76i</guid>
      <description>&lt;p&gt;The most repeated claim in data architecture is wrong, and it's wrong by a factor of ten. "Object storage is 10–50x cheaper than warehouse storage" — check the list prices, December 2026, US East: S3 Standard is &lt;strong&gt;$23.55 per TB per month&lt;/strong&gt;. Snowflake storage is &lt;strong&gt;$23.00 per TB per month&lt;/strong&gt;. Per stored terabyte, they tie. The lakehouse does not win on storage prices. It wins because it deletes the second copy of your data — and because the copy was never just a storage bill. It was staleness, disagreement, and torn reads, all billed separately.&lt;/p&gt;

&lt;p&gt;Season 3 is "Data in Motion &amp;amp; at Rest". Part 1 covered message-queue delivery semantics, Part 2 stream windows and watermarks, Part 3 event sourcing and CQRS, Part 4 inverted indexes, Part 5 Bloom filters. This part is the storage layer those systems sit on: where the truth lives, what it costs, and how it breaks. The benchmark hook is cost arithmetic with verified list prices — every number below is recomputed in the companion notebook.&lt;/p&gt;

&lt;h2&gt;
  
  
  The ELI5 version
&lt;/h2&gt;

&lt;p&gt;A &lt;strong&gt;data warehouse&lt;/strong&gt; is a library with a card catalog. Every book is shelved, labeled, and indexed; you can find anything in seconds. The catch: the library only accepts books (structured tables), and shelf space is priced like prime real estate.&lt;/p&gt;

&lt;p&gt;A &lt;strong&gt;data lake&lt;/strong&gt; is a warehouse full of unsorted boxes. Anything fits — books, photos, loose papers, video tapes — and the rent is cheap. The catch: finding anything means opening boxes, and if someone is mid-way through relabeling a box, you might read half the old label and half the new one.&lt;/p&gt;

&lt;p&gt;A &lt;strong&gt;data lakehouse&lt;/strong&gt; is the boxes &lt;em&gt;plus&lt;/em&gt; a catalog taped to each box. The boxes stay cheap and open; the catalog gives you transactions, schema enforcement, and time travel. The trick that makes it possible is the &lt;strong&gt;open table format&lt;/strong&gt; — Iceberg, Delta Lake, or Hudi — a metadata layer that turns a pile of files into a table without moving the files.&lt;/p&gt;

&lt;h2&gt;
  
  
  The three, side by side
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;Warehouse&lt;/th&gt;
&lt;th&gt;Lake&lt;/th&gt;
&lt;th&gt;Lakehouse&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Storage&lt;/td&gt;
&lt;td&gt;Proprietary format, coupled to compute&lt;/td&gt;
&lt;td&gt;Open files on object storage&lt;/td&gt;
&lt;td&gt;Open files (Parquet) on object storage&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Cost per stored TB/month&lt;/td&gt;
&lt;td&gt;$23 (Snowflake, after compression)&lt;/td&gt;
&lt;td&gt;$23.55 (S3 Standard)&lt;/td&gt;
&lt;td&gt;$23.55 — same object storage&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ACID transactions&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes, via the table format&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Schema&lt;/td&gt;
&lt;td&gt;Enforced on write&lt;/td&gt;
&lt;td&gt;On read, or not at all&lt;/td&gt;
&lt;td&gt;Enforced on write, with evolution&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Query speed&lt;/td&gt;
&lt;td&gt;Fastest for SQL&lt;/td&gt;
&lt;td&gt;Slow — full scans&lt;/td&gt;
&lt;td&gt;Near-warehouse with pruning + compaction&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ML workloads&lt;/td&gt;
&lt;td&gt;Poor — export the data first&lt;/td&gt;
&lt;td&gt;Native — raw files&lt;/td&gt;
&lt;td&gt;Native — same files, two engines&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Data types&lt;/td&gt;
&lt;td&gt;Structured only&lt;/td&gt;
&lt;td&gt;Any&lt;/td&gt;
&lt;td&gt;Any&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Lock-in&lt;/td&gt;
&lt;td&gt;High (vendor format)&lt;/td&gt;
&lt;td&gt;Low (open files)&lt;/td&gt;
&lt;td&gt;Low (open formats)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Frb1np8jepbeoxwwchifn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Frb1np8jepbeoxwwchifn.png" alt="Three architectures: the warehouse (structured tables, fast SQL, expensive), the lake (any file, cheap, no guarantees), and the lakehouse (open Parquet files plus a transaction log — warehouse reliability on lake storage)." width="800" height="393"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The cost arithmetic, honestly
&lt;/h2&gt;

&lt;p&gt;The naive pitch says object storage is 10x cheaper. The real math says the two-tier architecture's storage bill is exactly 2x the lakehouse's, at every scale — because it stores everything twice:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Raw data&lt;/th&gt;
&lt;th&gt;Two-tier storage/month&lt;/th&gt;
&lt;th&gt;Lakehouse storage/month&lt;/th&gt;
&lt;th&gt;Saving&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;10 TB&lt;/td&gt;
&lt;td&gt;$93&lt;/td&gt;
&lt;td&gt;$47&lt;/td&gt;
&lt;td&gt;49%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;100 TB&lt;/td&gt;
&lt;td&gt;$931&lt;/td&gt;
&lt;td&gt;$471&lt;/td&gt;
&lt;td&gt;49%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;1,000 TB&lt;/td&gt;
&lt;td&gt;$9,310&lt;/td&gt;
&lt;td&gt;$4,710&lt;/td&gt;
&lt;td&gt;49%&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Assumptions, stated plainly: 5x Parquet compression (conservative; columnar data typically lands 5–10x vs raw JSON/CSV), one lake copy plus one warehouse copy in the two-tier case, one copy in the lakehouse case. The 49% is not "object storage is cheaper" — it's "you stopped paying for the copy." Tiering is the second lever, and it's real: cold data on Standard-IA is $12.80/TB-month, and Deep Archive is ~$1.01/TB-month — 100 TB of raw data's cold copy costs $20 a month, not $471.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvchxuq947wmjgqd6lr83.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvchxuq947wmjgqd6lr83.png" alt="Monthly storage cost vs raw data volume: the two-tier architecture pays for two copies at every scale, the lakehouse for one — a 49% saving that is structural, not a price difference." width="800" height="448"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Compute is where the meters actually diverge. BigQuery on-demand charges &lt;strong&gt;$6.25 per TiB scanned&lt;/strong&gt;, first TiB free each month. Snowflake charges &lt;strong&gt;$2 per credit&lt;/strong&gt; on Standard, with an XS warehouse burning 1 credit an hour. So:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;One unpartitioned &lt;code&gt;SELECT *&lt;/code&gt; over a 4 TiB fact table costs &lt;strong&gt;$25 every time an analyst runs it&lt;/strong&gt;. The table size doesn't matter; the scan does. Adding a &lt;code&gt;LIMIT&lt;/code&gt; doesn't help — BigQuery bills the columns selected, not the rows returned.&lt;/li&gt;
&lt;li&gt;Thirty full scans of a 10 TiB table in a month cost &lt;strong&gt;$1,868.75&lt;/strong&gt;. The same thirty queries with 90% partition pruning scan 30 TiB and cost &lt;strong&gt;$181.25 — 10.3x less, same answers&lt;/strong&gt;. Partitioning is not a performance tweak; it is the billing model.&lt;/li&gt;
&lt;li&gt;A Snowflake XS warehouse running 200 active hours a month costs a flat &lt;strong&gt;$400&lt;/strong&gt;. BigQuery breaks even against it at &lt;strong&gt;65 TiB scanned per month&lt;/strong&gt;. Below that, on-demand wins; above it, reserved capacity wins. That crossover — not a vendor slogan — is how you pick.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F607padh3qi3sv2fuah5k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F607padh3qi3sv2fuah5k.png" alt="Monthly compute cost vs TiB scanned: BigQuery on-demand climbs at $6.25/TiB while a Snowflake XS warehouse is flat at $400 for 200 hours; 90% partition pruning cuts the on-demand bill 10.3x." width="800" height="448"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  How it breaks: staleness, torn reads, and the small-file tax
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Staleness.&lt;/strong&gt; A two-tier pipeline copies lake → warehouse on an ETL schedule, and the schedule is a staleness guarantee. With hourly ETL, a dashboard read at a random time sees data that is Uniform(0, 60) minutes old: &lt;strong&gt;mean 30 minutes, and half of all reads are more than 30 minutes stale&lt;/strong&gt;. Worse, the ML feature store reads the lake while the dashboard reads the warehouse — same question, two answers, and both are "correct" against their own copy. Micro-batching to 15 minutes halves the mean to 7.5 minutes and quadruples the ETL runs; it never reaches zero, because the copy is the problem, not the schedule. The lakehouse removes the copy, so a commit is visible to every reader in seconds.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Torn reads.&lt;/strong&gt; A lake stores a table as many Parquet files, and rewriting a table means replacing those files one by one. A reader arriving mid-rewrite sees a mix of old and new files — a torn table, with no error and no warning. Toy model, recomputed in the notebook: reads arrive at rate λ, a rewrite takes w seconds, so P(a read overlaps a rewrite) = 1 − e^(−λw). A 2-second rewrite with one read every 5 seconds gives a &lt;strong&gt;33% chance&lt;/strong&gt; that any given read sees a torn table. The table format fixes this with an atomic metadata commit: readers see the old snapshot or the new one, never a mix. This is the single most important thing Iceberg, Delta Lake, and Hudi buy you — not performance, correctness.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The small-file tax.&lt;/strong&gt; The lakehouse's maintenance bill replaces the ETL bill. Ingest thousands of tiny files and every query pays to list and open every file; planning time grows with file count, not data size. Compaction — rewriting many small files into few large ones — is the recurring chore, and skipping it is how a lakehouse quietly becomes the slow lake it replaced. Budget for compaction the way you used to budget for ETL.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fv1ee9rf01e9cjp3sv25r.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fv1ee9rf01e9cjp3sv25r.png" alt="Left: staleness under hourly ETL is uniform from 0 to 60 minutes (mean 30) while a lakehouse commit is visible in seconds. Right: the probability a reader sees a torn table grows with rewrite duration — 33% for a 2-second rewrite at one read per 5 seconds." width="800" height="378"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Iceberg vs Delta Lake vs Hudi: the format war is over
&lt;/h2&gt;

&lt;p&gt;Three formats, one job — the transaction log on top of Parquet:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;Apache Iceberg&lt;/th&gt;
&lt;th&gt;Delta Lake&lt;/th&gt;
&lt;th&gt;Apache Hudi&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Origin&lt;/td&gt;
&lt;td&gt;Netflix → Apache&lt;/td&gt;
&lt;td&gt;Databricks, open-sourced 2019&lt;/td&gt;
&lt;td&gt;Uber → Apache&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Engine support&lt;/td&gt;
&lt;td&gt;Widest — designed engine-agnostic&lt;/td&gt;
&lt;td&gt;Best on Databricks/Spark; UniForm bridges the rest&lt;/td&gt;
&lt;td&gt;Spark + Flink, streaming-first&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Best for&lt;/td&gt;
&lt;td&gt;Multi-engine shops&lt;/td&gt;
&lt;td&gt;Databricks shops&lt;/td&gt;
&lt;td&gt;Heavy upserts / streaming ingest&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2026 position&lt;/td&gt;
&lt;td&gt;The default standard&lt;/td&gt;
&lt;td&gt;The Databricks choice&lt;/td&gt;
&lt;td&gt;The streaming specialist&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Iceberg won the standard war: every major vendor reads it now, Databricks acquired Tabular (Iceberg's founders) in 2024, and Snowflake and BigQuery both support Iceberg tables natively. The decision rule is simple: Databricks shop, Delta Lake; multiple engines, Iceberg; streaming upserts, Hudi; unsure, Iceberg — it has the broadest engine support and the most active community. The formats are converging anyway (Delta's UniForm reads as Iceberg), so the format choice matters less than it did two years ago. The architecture choice matters more.&lt;/p&gt;

&lt;h2&gt;
  
  
  The interview angle
&lt;/h2&gt;

&lt;p&gt;"Design a data platform for a company with 100 TB of event data" is the classic prompt, and the strong answer starts with the arithmetic, not the vendor. One copy vs two (49% of the storage bill), scan-based vs capacity-based compute (the 65 TiB/month crossover), staleness as a function of the ETL interval (mean = interval/2), and torn reads as a function of rewrite time. The separators: correcting the "10x cheaper object storage" claim with the actual list prices, naming the small-file tax unprompted, and reaching for the warehouse anyway when the data is small and the team is analysts — the lakehouse is the right &lt;em&gt;default&lt;/em&gt; for new platforms in 2026, not the right answer for every team.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Object storage is not 10x cheaper than warehouse storage — $23.55 vs $23.00 per TB-month, they tie.&lt;/strong&gt; The lakehouse saves 49% of the storage bill by deleting the second copy, not by finding cheaper bytes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;On-demand compute punishes wide scans, not big tables&lt;/strong&gt;: 30 full scans of a 10 TiB table cost $1,868.75 on BigQuery; 90% partition pruning cuts it to $181.25. The Snowflake XS break-even is 65 TiB scanned per month.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Two copies disagree by construction&lt;/strong&gt;: hourly ETL means mean 30-minute staleness and a 50% chance any read is more than 30 minutes old; the lakehouse's single commit is visible to every reader in seconds.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A bare lake has no transactions, so a 2-second rewrite gives a 33% chance of a torn read&lt;/strong&gt; — Iceberg, Delta Lake, and Hudi fix this with one atomic metadata commit.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Iceberg is the default format in 2026&lt;/strong&gt; (widest engine support, Tabular acquired by Databricks in 2024); Delta Lake for Databricks shops, Hudi for streaming upserts — and a warehouse is still the right call when the data is small and the team is analysts.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Honesty note: all prices are published list prices checked December 2026 (AWS S3, Snowflake Service Consumption Table, Google BigQuery pricing; us-east-1/us-central1) and will change — the vendor page is the final word. The TCO and scan-cost figures are arithmetic on those list prices in the companion notebook, not a measured deployment; Parquet compression is modelled at a conservative 5x. The query-time figures cited for point lookups and filtered scans are vendor/analyst-reported, not independently measured. The torn-read probabilities are a toy Poisson model, labelled as such. No excluded-vendor content, per the standing exclusion.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Follow for the next part — Season 3, Part 7 follows a request across 50 services with distributed tracing. More on dev.to: &lt;a href="https://dev.to/danielsamfdo"&gt;@danielsamfdo&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Companion notebook:&lt;/strong&gt; the runnable tutorial for this post — &lt;a href="https://danielsamfdo.github.io/blog/assets/lakehouse_tco.ipynb" rel="noopener noreferrer"&gt;download it here&lt;/a&gt; (open in Colab/Jupyter).&lt;/p&gt;

</description>
      <category>systemdesign</category>
      <category>architecture</category>
      <category>programming</category>
      <category>softwareengineering</category>
    </item>
    <item>
      <title>Serving Gemma 3 4B: vLLM vs Keras, Benchmarked</title>
      <dc:creator>Daniel Sam Pete Thiyagu</dc:creator>
      <pubDate>Sat, 05 Dec 2026 17:09:47 +0000</pubDate>
      <link>https://dev.to/danielsamfdo/serving-gemma-3-4b-vllm-vs-keras-benchmarked-15mm</link>
      <guid>https://dev.to/danielsamfdo/serving-gemma-3-4b-vllm-vs-keras-benchmarked-15mm</guid>
      <description>&lt;p&gt;Same weights, two stacks, one scoreboard. Take &lt;code&gt;google/gemma-3-4b-it&lt;/code&gt;, serve it with Keras Hub's &lt;code&gt;generate()&lt;/code&gt;, then serve it with &lt;code&gt;vllm serve&lt;/code&gt; — and the result is almost a trick question. At one request at a time the two stacks tie. At 64 concurrent requests, vLLM serves &lt;strong&gt;26.5x more tokens&lt;/strong&gt;. The gap is not the model, the GPU, or the weights. It is batching — and it starts paying at just &lt;strong&gt;3 concurrent requests&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This is GDE post #17, the head-to-head the Keras/JAX lane has been building toward. GDE #12 ran Gemma 3 locally with Keras, #14 showed one model on three backends, #15 priced TPU inference, #16 fine-tuned it with LoRA. This one answers the question those posts left open: once the model works, which stack do you serve it on? Every number below is recomputed in the companion notebook.&lt;/p&gt;

&lt;h2&gt;
  
  
  The ELI5 version
&lt;/h2&gt;

&lt;p&gt;Think of a restaurant. Keras is a talented home cook: one order at a time, cooked start to finish, excellent food, no waiting list. vLLM is a restaurant kitchen: same chef, same recipe, but orders are batched — the oven runs once for ten dishes, prep is shared, and the table layout (paged KV cache) means a big party doesn't block the room.&lt;/p&gt;

&lt;p&gt;The model is the recipe. The GPU is the kitchen. The serving stack is everything about &lt;em&gt;how orders flow through the kitchen&lt;/em&gt; — and for an LLM, the flow matters more than the recipe once more than one person is hungry.&lt;/p&gt;

&lt;h2&gt;
  
  
  The model: Gemma 3 4B, by the numbers
&lt;/h2&gt;

&lt;p&gt;Gemma 3 comes in 1B, 4B, 12B, and 27B sizes, all open weights, with 128K context on everything except the 1B (32K). The 4B is the sweet spot for this comparison: multimodal, 128K context, and small enough to fit on one 24 GB consumer card in bf16 — 4,301M parameters total (417M vision encoder + 675M embeddings + 3,209M transformer), about &lt;strong&gt;8.0 GiB of weights&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The architectural detail that decides this whole post is the attention pattern. Gemma 3 interleaves &lt;strong&gt;5 local layers per 1 global layer&lt;/strong&gt;, with the local layers' sliding window capped at 1,024 tokens. A full-attention model stores KV for every token at every layer. Gemma 3 stores every token at only 5 of its 34 layers; the other 29 store at most the last 1,024 tokens, forever.&lt;/p&gt;

&lt;p&gt;The arithmetic is exact, from the published config (34 layers, 8 query heads, 4 KV heads, head dim 256, bf16):&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Context&lt;/th&gt;
&lt;th&gt;Full-attention KV&lt;/th&gt;
&lt;th&gt;Gemma 3 KV&lt;/th&gt;
&lt;th&gt;Saving&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1K&lt;/td&gt;
&lt;td&gt;0.13 GiB&lt;/td&gt;
&lt;td&gt;0.13 GiB&lt;/td&gt;
&lt;td&gt;1.0x&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;8K&lt;/td&gt;
&lt;td&gt;1.06 GiB&lt;/td&gt;
&lt;td&gt;0.27 GiB&lt;/td&gt;
&lt;td&gt;3.9x&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;32K&lt;/td&gt;
&lt;td&gt;4.25 GiB&lt;/td&gt;
&lt;td&gt;0.74 GiB&lt;/td&gt;
&lt;td&gt;5.8x&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;128K&lt;/td&gt;
&lt;td&gt;17.00 GiB&lt;/td&gt;
&lt;td&gt;2.61 GiB&lt;/td&gt;
&lt;td&gt;6.5x&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;At 128K context, a full-attention 4B model needs 17.0 GiB of KV cache — more than a 24 GB card has left after the 8.0 GiB of weights. Gemma 3 needs 2.61 GiB. That is not a marginal optimisation. It is the difference between serving 128K context on one card and not serving it at all.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fm8ubvwfbl56kuld7p0ce.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fm8ubvwfbl56kuld7p0ce.png" alt="KV cache per sequence vs context length: a full-attention 4B model needs 17.0 GiB at 128K context, Gemma 3's 5:1 local/global pattern needs 2.61 GiB — 6.5x less. The dashed line is the 16.0 GiB left on a 24 GB card after weights." width="800" height="448"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;What fits on one 24 GB card, after weights:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Context per sequence&lt;/th&gt;
&lt;th&gt;Max concurrent sequences (Gemma 3)&lt;/th&gt;
&lt;th&gt;Full-attention equivalent&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;2K&lt;/td&gt;
&lt;td&gt;104&lt;/td&gt;
&lt;td&gt;60&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;8K&lt;/td&gt;
&lt;td&gt;59&lt;/td&gt;
&lt;td&gt;15&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;32K&lt;/td&gt;
&lt;td&gt;21&lt;/td&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;128K&lt;/td&gt;
&lt;td&gt;6&lt;/td&gt;
&lt;td&gt;0 — doesn't fit&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  The two stacks
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Keras&lt;/strong&gt; serves Gemma through &lt;code&gt;keras_hub&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;
&lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;environ&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"KERAS_BACKEND"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"jax"&lt;/span&gt;   &lt;span class="c1"&gt;# or "torch" / "tensorflow"&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;keras_hub&lt;/span&gt;

&lt;span class="n"&gt;gemma&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;keras_hub&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Gemma3CausalLM&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;from_preset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"gemma3_4b_en"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;gemma&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;generate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Explain attention in one sentence."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;max_length&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;64&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That is the whole serving path: load the preset, call &lt;code&gt;generate()&lt;/code&gt;. It runs anywhere Keras 3 runs — GPU, TPU via JAX, even CPU for the 1B — and the same code that fine-tuned the model (GDE #16) now serves it. What it does &lt;em&gt;not&lt;/em&gt; give you: an HTTP server (you write the FastAPI wrapper), continuous batching (one prompt at a time, or a static list), paged KV management, prefix caching, or structured output. Every request reads the full 8 GiB of weights, generates its tokens, and exits.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;vLLM&lt;/strong&gt; serves the same weights as a production server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;vllm serve google/gemma-3-4b-it --max-model-len 131072
curl http://localhost:8000/v1/chat/completions -d &lt;span class="s1"&gt;'{
  "model": "google/gemma-3-4b-it",
  "messages": [{"role": "user", "content": "Explain attention in one sentence."}]}'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One command buys an OpenAI-compatible API, continuous batching, PagedAttention, prefix caching, chunked prefill, and speculative decoding (EAGLE/MTP — GDE #5). The cost is operational: a server process to run, monitor, and scale, and GPU-first kernels (TPU support exists but trails — GDE #8).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvw88lqbw7v91i7ysjknv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvw88lqbw7v91i7ysjknv.png" alt="Two architectures: Keras generates one prompt at a time through a single generate() call, with requests waiting in line; vLLM runs an OpenAI-compatible server with continuous batching and PagedAttention, serving the whole batch in one forward pass." width="800" height="378"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The benchmark: where the gap actually lives
&lt;/h2&gt;

&lt;p&gt;Here is the measurement that decides the post, from an independent head-to-head published in November 2026 (xbill, Gemma 4 E2B on one NVIDIA L4, same prompts, same weights, greedy decoding):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;One request:&lt;/strong&gt; five engines — vLLM, SGLang, llama.cpp, mistral.rs, and a plain PyTorch loop — land within &lt;strong&gt;8% of each other&lt;/strong&gt;, 135–145 tok/s. At batch size 1, decode is memory-bandwidth bound: every token reads all the weights once, and no engine can dodge that. Keras' &lt;code&gt;generate()&lt;/code&gt; lives in this regime too.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;64 concurrent requests:&lt;/strong&gt; vLLM reaches &lt;strong&gt;3,716 tok/s&lt;/strong&gt;. The single-request engines don't move — they serve one request at a time, so their ceiling is the single-request rate. vLLM's continuous batching amortises one weight read across 64 sequences.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The same author measured the same shape on a Cloud TPU v5e: vLLM at 143.9 tok/s for one request, &lt;strong&gt;1,689 tok/s at 64&lt;/strong&gt; — an 11.7x rise on a much smaller chip. The pattern is hardware-independent; only the ceiling moves.&lt;/p&gt;

&lt;p&gt;Fitting a saturating curve &lt;code&gt;T(N) = Tmax · N / (N + K)&lt;/code&gt; to the two L4 anchors (140 at N=1, 3,716 at N=64) gives the full picture — recomputed in the notebook:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Concurrent requests&lt;/th&gt;
&lt;th&gt;vLLM (tok/s)&lt;/th&gt;
&lt;th&gt;Keras (tok/s)&lt;/th&gt;
&lt;th&gt;Ratio&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;140&lt;/td&gt;
&lt;td&gt;140&lt;/td&gt;
&lt;td&gt;1.0x&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;274&lt;/td&gt;
&lt;td&gt;140&lt;/td&gt;
&lt;td&gt;2.0x (1.96x — just under the 2x line)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;402&lt;/td&gt;
&lt;td&gt;140&lt;/td&gt;
&lt;td&gt;2.9x&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;8&lt;/td&gt;
&lt;td&gt;968&lt;/td&gt;
&lt;td&gt;140&lt;/td&gt;
&lt;td&gt;6.9x&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;16&lt;/td&gt;
&lt;td&gt;1,677&lt;/td&gt;
&lt;td&gt;140&lt;/td&gt;
&lt;td&gt;12.0x&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;32&lt;/td&gt;
&lt;td&gt;2,644&lt;/td&gt;
&lt;td&gt;140&lt;/td&gt;
&lt;td&gt;18.9x&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;64&lt;/td&gt;
&lt;td&gt;3,716&lt;/td&gt;
&lt;td&gt;140&lt;/td&gt;
&lt;td&gt;26.5x&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The crossover is the headline: &lt;strong&gt;vLLM is 2x Keras at just 3 concurrent requests.&lt;/strong&gt; You do not need a viral launch to justify a serving engine. Three users at once is enough. Sustained over a day, that's 12.1M tokens for the single-request stack vs 321M for the batched one — same GPU, same weights, same electricity.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fg37ztu7om60s8cxfcd3z.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fg37ztu7om60s8cxfcd3z.png" alt="Total throughput vs concurrent requests: Keras stays flat at 140 tok/s; vLLM rises from the same 140 to 3,716 tok/s at 64 requests. Red dots are the published measurement anchors; the crossover to 2x is at 3 concurrent requests." width="800" height="448"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The scoreboard
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;Keras &lt;code&gt;generate()&lt;/code&gt;
&lt;/th&gt;
&lt;th&gt;vLLM 0.33&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Single-request decode&lt;/td&gt;
&lt;td&gt;~140 tok/s&lt;/td&gt;
&lt;td&gt;~140 tok/s — a tie&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Max concurrent 8K sequences, one 24 GB card&lt;/td&gt;
&lt;td&gt;1 (serialized)&lt;/td&gt;
&lt;td&gt;59 (KV-bound)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Output tokens/day, sustained&lt;/td&gt;
&lt;td&gt;12.1M&lt;/td&gt;
&lt;td&gt;321M&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;HTTP API&lt;/td&gt;
&lt;td&gt;Write your own&lt;/td&gt;
&lt;td&gt;OpenAI-compatible, built in&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Continuous batching&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Prefix caching&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Structured output&lt;/td&gt;
&lt;td&gt;Manual&lt;/td&gt;
&lt;td&gt;Guided decoding, built in&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;TPU serving&lt;/td&gt;
&lt;td&gt;Yes, via JAX backend&lt;/td&gt;
&lt;td&gt;Yes, but kernels trail GPU&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Ops burden&lt;/td&gt;
&lt;td&gt;A script&lt;/td&gt;
&lt;td&gt;A server to run and monitor&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Best for&lt;/td&gt;
&lt;td&gt;Local/dev, single-user, fine-tune-then-serve&lt;/td&gt;
&lt;td&gt;Multi-user APIs, 3+ concurrent&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnztmkyeofchmi00k47gk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnztmkyeofchmi00k47gk.png" alt="Scoreboard: max concurrent 8K sequences on one 24 GB card (1 vs 59), sustained tokens per day (12.1M vs 321M), single-request decode rate (a tie at ~140 tok/s)." width="800" height="335"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Why it breaks: three ways to pick wrong
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Serving a multi-user API with a library.&lt;/strong&gt; The failure mode is silent: everything works in testing (one user, one request), then latency explodes at launch because requests serialise. If your p99 budget assumes parallelism, you need a stack that actually parallelises. The tell is the queue: if requests ever wait for each other, you are running a library, not a server.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Running a server for one user.&lt;/strong&gt; The opposite mistake. A vLLM server for a single-user local app buys you an ops burden — process supervision, health checks, GPU memory pre-allocation — for a 1.0x speedup. If concurrency never exceeds 2, Keras is simpler, cheaper to operate, and exactly as fast.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Forgetting the KV budget.&lt;/strong&gt; Both stacks share the same KV arithmetic, and 128K context is where it bites. Six concurrent 128K sequences fit on a 24 GB card with Gemma 3; a full-attention model fits zero. The fix is architectural (sliding windows, GQA, quantization — GDE #6 covered FP8 KV) before it is operational.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;At 1 request, vLLM and Keras tie at ~140 tok/s&lt;/strong&gt; — decode is memory-bandwidth bound and no engine dodges the weight read. Pick on workflow, not speed, at this scale.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;At 3 concurrent requests vLLM is already 2x; at 64 it is 26.5x&lt;/strong&gt; (3,716 vs 140 tok/s, measured on one L4). Batching is the whole gap.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Gemma 3's 5:1 local/global attention cuts 128K KV cache 6.5x&lt;/strong&gt; (17.0 → 2.61 GiB) — the reason 128K context and 59 concurrent 8K sequences fit on one 24 GB card.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Keras wins when the user count is 1, the stack is already Keras, or the hardware is a TPU&lt;/strong&gt; — and when you would rather write ten lines than operate a server.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;vLLM wins the moment a second and third user arrive&lt;/strong&gt; — the crossover is that low, and the OpenAI-compatible API is free with it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Honesty note: the KV arithmetic is exact, from Gemma 3's published config (tech report arXiv:2503.19786). The throughput anchors are published measurements by xbill (Nov 2026) on Gemma 4 E2B — one NVIDIA L4 and one Cloud TPU v5e — not Gemma 3 4B; the notebook fits a saturating model to those anchors and labels the curves as a calibrated model, not a live run on this machine (no GPU was available here). Gemma 4 E2B shipped in November 2026 (2B active of 26B, MoE); the serving story is unchanged and vLLM 0.33 serves it. Single-request rates of 135–145 tok/s across engines are the same author's measurements. No excluded-vendor content, per the standing exclusion.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Companion notebook:&lt;/strong&gt; the runnable tutorial for this post — &lt;a href="https://danielsamfdo.github.io/blog/assets/gemma_vllm_vs_keras.ipynb" rel="noopener noreferrer"&gt;download it here&lt;/a&gt; (open in Colab/Jupyter).&lt;/p&gt;

</description>
      <category>vllm</category>
      <category>llm</category>
      <category>googlecloud</category>
      <category>agents</category>
    </item>
    <item>
      <title>System Design, Plainly — Season 3, Part 5: Bloom Filters &amp; Probabilistic Structures</title>
      <dc:creator>Daniel Sam Pete Thiyagu</dc:creator>
      <pubDate>Fri, 04 Dec 2026 17:05:32 +0000</pubDate>
      <link>https://dev.to/danielsamfdo/system-design-plainly-season-3-part-5-bloom-filters-probabilistic-structures-40a8</link>
      <guid>https://dev.to/danielsamfdo/system-design-plainly-season-3-part-5-bloom-filters-probabilistic-structures-40a8</guid>
      <description>&lt;p&gt;Your database has a billion URLs. A user asks: "have we seen this URL before?" A hash set answers exactly — and costs &lt;strong&gt;50 GB&lt;/strong&gt; of RAM. A Bloom filter answers almost exactly, is wrong 1 time in 100, and costs &lt;strong&gt;1.2 GB&lt;/strong&gt;. That 42x saving is the entire idea of probabilistic data structures: trade a small, &lt;em&gt;quantified&lt;/em&gt; chance of being wrong for an order of magnitude less memory — and arrange the error so it can only ever fail in the safe direction.&lt;/p&gt;

&lt;p&gt;This is Season 3, Part 5. Part 4 built the inverted index for search; this part builds the structure that sits in front of almost every database, cache, and crawler in production — the one that says "definitely not" with certainty and "probably" the rest of the time.&lt;/p&gt;

&lt;h2&gt;
  
  
  The ELI5 version
&lt;/h2&gt;

&lt;p&gt;Imagine a bouncer with a cheat sheet: a row of light switches, all off. When a guest arrives for the first time, the bouncer runs their name through three different hash recipes, and each recipe points at one switch. He flips those three switches on.&lt;/p&gt;

&lt;p&gt;Now a stranger shows up. The bouncer runs the same three recipes on the stranger's name and checks the three switches. If any switch is off, the stranger was &lt;em&gt;definitely&lt;/em&gt; never here — no guest could have left that switch off. If all three are on, the stranger &lt;em&gt;might&lt;/em&gt; have been here — or three other guests might have coincidentally flipped exactly those switches. The bouncer can never wrongly turn away a real guest, but he sometimes waves in a stranger. That is a Bloom filter: &lt;strong&gt;false positives possible, false negatives impossible&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The cheat sheet is the whole data structure: m bits and k hash functions. Burton Bloom published it in 1970, and it has been in production ever since because the trade is so good.&lt;/p&gt;

&lt;h2&gt;
  
  
  How it works: three formulas
&lt;/h2&gt;

&lt;p&gt;Insert x: set bits h1(x), h2(x), …, hk(x) to 1. Query x: if all k bits are 1, answer "maybe"; if any is 0, answer "definitely not". That's it — there is no delete, no iteration, no stored keys. The filter never holds a single element; it holds a &lt;em&gt;shadow&lt;/em&gt; of the set.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fx4ez8his5lhe9wzd54ft.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fx4ez8his5lhe9wzd54ft.png" alt="A Bloom filter is a bit array plus k hash functions. Inserting 'cassandra' sets 3 bits; querying 'postgres' hits 3 set bits by coincidence (false positive); querying 'sqlite' finds an unset bit (definitely not)." width="799" height="417"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The false-positive rate follows from one probability. After inserting n elements with k hashes into m bits, the chance a given bit is still 0 is (1 − 1/m)^(kn) ≈ e^(−kn/m). A false positive needs all k of a stranger's bits to be 1, so:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;p ≈ (1 − e^(−kn/m))^k&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Two derived formulas do all practical sizing. The optimal number of hashes for a fixed bits-per-element is &lt;strong&gt;k = (m/n) · ln 2 ≈ 0.693 · (m/n)&lt;/strong&gt; — and at that optimum exactly half the bits are set, which is the filter's sweet spot. Substituting back gives the cleanest form in the field:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;p ≈ 0.6185^(m/n)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Read it as: every extra bit per element multiplies the false-positive rate by 0.6185. Or in the form you size with: &lt;strong&gt;each +4.8 bits per element divides false positives by 10&lt;/strong&gt;. The notebook measures all of this on a real filter: 100,000 keys at a 1% design point (m = 958,505 bits, k = 7) came back with &lt;strong&gt;measured FPR 1.00% against a formula prediction of 1.00%, zero false negatives, and the array 51.8% full&lt;/strong&gt; — the theory is not approximate here, it's exact to measurement.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F31v269kx7nlicl2ond4t.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F31v269kx7nlicl2ond4t.png" alt="False-positive rate vs bits per element: the formula curve p = 0.6185^(m/n) with measured points at 10% (4.8 bits), 1% (9.6 bits), 0.1% (14.4 bits). Every +4.8 bits divides false positives by 10." width="800" height="409"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The sizing table you actually use
&lt;/h2&gt;

&lt;p&gt;Design runs backwards from the target rate. Pick p, compute bits per element m/n = −ln(p) / (ln 2)², round k = (m/n) ln 2 to the nearest integer (the curve is flat near the optimum, so being one off costs almost nothing):&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Target FPR&lt;/th&gt;
&lt;th&gt;Bits per element&lt;/th&gt;
&lt;th&gt;Optimal k&lt;/th&gt;
&lt;th&gt;1M keys&lt;/th&gt;
&lt;th&gt;1B keys&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;10%&lt;/td&gt;
&lt;td&gt;4.79&lt;/td&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;0.60 MB&lt;/td&gt;
&lt;td&gt;0.60 GB&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;1%&lt;/td&gt;
&lt;td&gt;9.59&lt;/td&gt;
&lt;td&gt;7&lt;/td&gt;
&lt;td&gt;1.20 MB&lt;/td&gt;
&lt;td&gt;1.20 GB&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;0.1%&lt;/td&gt;
&lt;td&gt;14.38&lt;/td&gt;
&lt;td&gt;10&lt;/td&gt;
&lt;td&gt;1.80 MB&lt;/td&gt;
&lt;td&gt;1.80 GB&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;0.01%&lt;/td&gt;
&lt;td&gt;19.17&lt;/td&gt;
&lt;td&gt;13&lt;/td&gt;
&lt;td&gt;2.40 MB&lt;/td&gt;
&lt;td&gt;2.40 GB&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;0.001%&lt;/td&gt;
&lt;td&gt;23.96&lt;/td&gt;
&lt;td&gt;17&lt;/td&gt;
&lt;td&gt;3.00 MB&lt;/td&gt;
&lt;td&gt;3.00 GB&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Two things to internalize. First, the cost of certainty is logarithmic: going from 1% to 0.001% false positives costs 14 extra bits per key, not 1,000x the memory. Second, the filter's size depends only on &lt;em&gt;how many&lt;/em&gt; elements you insert, never on &lt;em&gt;how big&lt;/em&gt; they are — a billion 50-byte URLs and a billion 5 KB documents cost the same 1.2 GB at 1%. That is why the structure shows up wherever keys are big and counts are huge.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5njb08icl6coj6rvul37.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5njb08icl6coj6rvul37.png" alt="Memory for 1 billion keys averaging 50 bytes each: hash set 50.0 GB, Bloom filter at 1% FPR 1.2 GB, at 0.1% 1.8 GB, at 0.01% 2.4 GB. The 1% filter is 42x smaller." width="800" height="409"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Where it lives in production
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Databases — the SSTable skip.&lt;/strong&gt; This is the canonical deployment, and the numbers are the reason. Cassandra, Bigtable, and ScyllaDB keep one Bloom filter per SSTable on disk. A read for a key that lives in exactly one of 100 SSTables would otherwise touch all 100; with a 1% filter it touches 1 + 99 × 0.01 ≈ &lt;strong&gt;2 SSTables — 50x fewer disk reads&lt;/strong&gt;. The 1% of reads that check a wrong SSTable cost one wasted seek; the 99% that skip 99 SSTables are the whole point. LSM-tree engines (RocksDB, LevelDB) do the same per SSTable, and Parquet row-group filters do the same per row group.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Browsers — Safe Browsing.&lt;/strong&gt; Chrome keeps a local Bloom filter of known-malicious URLs (tens of megabytes, updated regularly). Every navigation checks the filter locally: a miss means safe with certainty and no network call; a hit means "maybe" and only then does Chrome ask Google's servers. The filter turns a privacy-sensitive lookup on every page load into a local bit test.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Crawlers and caches.&lt;/strong&gt; A web crawler with a billion-URL frontier keeps the seen-set as a Bloom filter instead of a hash set — 50 GB vs 1.2 GB, same decision. CDNs and caches use them to avoid asking a backend for keys that were never stored. Apache Spark uses Bloom filters in broadcast joins to skip shuffling rows that can't match.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The pattern to recognize:&lt;/strong&gt; a Bloom filter belongs anywhere the question is "have we seen this before?" and the cost of a &lt;em&gt;wrong yes&lt;/em&gt; is one wasted lookup, while the cost of a &lt;em&gt;wrong no&lt;/em&gt; would be catastrophic. If a wrong no is acceptable too, you don't need the asymmetry — and if a wrong yes is expensive (say, it triggers a $10 API call), you size the filter tighter or don't use one.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why it breaks: four failure modes
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Overfill.&lt;/strong&gt; A Bloom filter is sized for a specific n, and the false-positive rate explodes past it. The notebook measures it on the same 1%-designed filter: at design capacity the rate is 1%; at 1.5x capacity it's 5.7%; at 2x it's 16%; at 3x it's &lt;strong&gt;43%&lt;/strong&gt; — nearly half of all absent-key lookups returning "maybe". The filter doesn't degrade gracefully; it degrades exponentially, because every extra key sets k more bits and the fill ratio climbs toward 1. The fix is sizing for the &lt;em&gt;maximum&lt;/em&gt; n, not the average — or rebuilding the filter when the count grows.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F60qxxp98w6bn6yossf9h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F60qxxp98w6bn6yossf9h.png" alt="False-positive rate vs load factor: 1.0% at design capacity, 5.7% at 1.5x, 16% at 2x, 43% at 3x. Overshoot capacity and the rate explodes." width="800" height="409"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;No deletes.&lt;/strong&gt; Setting a bit to 0 might un-insert other elements that share it, so plain Bloom filters can't delete at all. The fixes are well known: a &lt;strong&gt;counting Bloom filter&lt;/strong&gt; replaces each bit with a small counter (typically 4 bits) so deletes decrement instead of clearing — at 4x the memory; or a &lt;strong&gt;Cuckoo filter&lt;/strong&gt; (Fan et al., 2014), which stores short fingerprints in cuckoo-hash buckets, supports deletion, and beats Bloom on space for false-positive rates below ~3%. If your set churns, pick one of those from the start — retrofitting deletion onto a plain filter is how you get silent corruption.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hash quality.&lt;/strong&gt; The formulas assume uniform, independent hashes. A weak hash (or an attacker who knows your hash function and crafts colliding inputs) breaks the independence assumption and the measured rate drifts far above the formula. Production filters use a strong hash or double-hashing from one good hash; if the input is adversarial — user-controlled keys — treat the hash choice as a security decision, not a performance one.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The wrong n, or the wrong question.&lt;/strong&gt; Size for the n you'll actually reach, including growth, and remember what the filter &lt;em&gt;can't&lt;/em&gt; answer: it can't list members, count them, or return the element — it's a membership test only. Teams that reach for a Bloom filter when they need a set usually discover this the week they need to iterate. HyperLogLog counts distinct elements; Count-Min Sketch counts frequencies; a Bloom filter answers one question, and answers it well.&lt;/p&gt;

&lt;h2&gt;
  
  
  The family: three structures, three questions
&lt;/h2&gt;

&lt;p&gt;Bloom filters are the middle child of the probabilistic family, and the interview answer is knowing which sibling answers which question:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Structure&lt;/th&gt;
&lt;th&gt;Question&lt;/th&gt;
&lt;th&gt;Memory for 1B items&lt;/th&gt;
&lt;th&gt;Error&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Bloom filter&lt;/td&gt;
&lt;td&gt;Is x in the set?&lt;/td&gt;
&lt;td&gt;~1.2 GB at 1% FPR&lt;/td&gt;
&lt;td&gt;False positives only&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;HyperLogLog&lt;/td&gt;
&lt;td&gt;How many distinct items?&lt;/td&gt;
&lt;td&gt;~12 KB&lt;/td&gt;
&lt;td&gt;±0.8% standard error&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Count-Min Sketch&lt;/td&gt;
&lt;td&gt;How many times did x appear?&lt;/td&gt;
&lt;td&gt;~MBs, tunable&lt;/td&gt;
&lt;td&gt;Overestimates only&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;All three share the same deal — fixed tiny memory, quantified error, never a false negative in the direction that matters — and all three show up in the same systems: HyperLogLog behind Redis's &lt;code&gt;PFCOUNT&lt;/code&gt; and BigQuery's &lt;code&gt;APPROX_COUNT_DISTINCT&lt;/code&gt;, Count-Min Sketch behind heavy-hitter detection in stream processors, Bloom filters in front of the disk.&lt;/p&gt;

&lt;h2&gt;
  
  
  The interview angle
&lt;/h2&gt;

&lt;p&gt;"Design a URL shortener" or "design a web crawler" are the classic Bloom filter prompts, and the strong answer starts with the arithmetic, not the structure. A billion URLs at 50 bytes is 50 GB as a hash set — too big to hold, and the interviewer knows it. The Bloom filter at 1% is 1.2 GB, and the follow-up writes itself: what does the 1% cost you? One wasted disk read in a hundred, or one redundant crawl fetch in a hundred — and what do you do when the crawler's seen-set grows past the design capacity? (Rebuild with a bigger m, or size for the max from the start.) The separators: deriving k = (m/n) ln 2 instead of reciting it, naming the no-delete limitation unprompted, and reaching for a Cuckoo filter when the interviewer adds deletion to the requirements.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;A Bloom filter trades a quantified false-positive rate for 42x less memory&lt;/strong&gt;: 1 billion keys at 1% FPR cost 1.2 GB, not 50 GB — and the size depends only on count, never on key size.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The whole design is three formulas&lt;/strong&gt;: p ≈ (1 − e^(−kn/m))^k, k_opt = (m/n) ln 2, and p ≈ 0.6185^(m/n) — every +4.8 bits per element buys a 10x lower rate.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The asymmetry is the point&lt;/strong&gt;: false positives possible, false negatives impossible. It belongs wherever a wrong "yes" costs one wasted lookup and a wrong "no" would be catastrophic.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;In production it sits in front of disk&lt;/strong&gt;: Cassandra/Bigtable SSTable filters turn 100 disk reads into ~2; Chrome Safe Browsing turns a network call into a local bit test.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;It breaks by overfill, not by age&lt;/strong&gt;: 1% FPR at design capacity becomes 43% at 3x capacity — size for the maximum n, and pick a counting Bloom or Cuckoo filter if the set needs deletes.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Follow for the next part — Season 3, Part 6 is data lakes vs warehouses vs lakehouses, and Part 7 follows a request across 50 services with distributed tracing. More on dev.to: &lt;a href="https://dev.to/danielsamfdo"&gt;@danielsamfdo&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Companion notebook:&lt;/strong&gt; the runnable tutorial for this post — &lt;a href="https://danielsamfdo.github.io/blog/assets/bloom_filters.ipynb" rel="noopener noreferrer"&gt;download it here&lt;/a&gt; (open in Colab/Jupyter).&lt;/p&gt;

</description>
      <category>systemdesign</category>
      <category>architecture</category>
      <category>programming</category>
      <category>softwareengineering</category>
    </item>
    <item>
      <title>2.6 Million Trainable, 1 Billion Frozen: LoRA Fine-Tuning with Keras and JAX</title>
      <dc:creator>Daniel Sam Pete Thiyagu</dc:creator>
      <pubDate>Fri, 04 Dec 2026 17:05:21 +0000</pubDate>
      <link>https://dev.to/danielsamfdo/26-million-trainable-1-billion-frozen-lora-fine-tuning-with-keras-and-jax-579j</link>
      <guid>https://dev.to/danielsamfdo/26-million-trainable-1-billion-frozen-lora-fine-tuning-with-keras-and-jax-579j</guid>
      <description>&lt;p&gt;Full fine-tuning of Gemma 3 1B with AdamW needs about &lt;strong&gt;12 GB&lt;/strong&gt; of training memory — weights, gradients, and optimizer states. Turn on LoRA at rank 16 and the same run needs about &lt;strong&gt;2 GB&lt;/strong&gt;. The trainable count drops from 999,885,952 parameters to &lt;strong&gt;2,609,152 — 0.26% of the model&lt;/strong&gt; — and a real medical Q&amp;amp;A fine-tune finished on a Kaggle TPU v5e-8 in under a minute. That is the whole pitch of parameter-efficient fine-tuning: you don't retrain the model, you steer it.&lt;/p&gt;

&lt;p&gt;This is GDE post #16, the fine-tuning post in the Keras/JAX lane. GDE #12 ran Gemma 3 locally with Keras, #14 showed one model on three backends, #15 priced TPU inference. This one closes the loop: how to &lt;em&gt;change&lt;/em&gt; what a Gemma model does, on hardware you already have, with one line of API. Every number below is recomputed in the companion notebook.&lt;/p&gt;

&lt;h2&gt;
  
  
  The ELI5 version
&lt;/h2&gt;

&lt;p&gt;A pretrained model is a library that already knows almost everything — grammar, facts, reasoning patterns. Fine-tuning it for your task is not rewriting the library. It's slipping a few annotated sticky notes into the right books.&lt;/p&gt;

&lt;p&gt;LoRA (Low-Rank Adaptation, Hu et al., 2021) is the sticky-note mechanism. For every weight matrix W you want to adapt, you freeze W and train two small matrices instead: A, which compresses the input down to r dimensions, and B, which expands it back out. The model's behavior changes by W + BA, but you only ever train A and B. With r = 16 and a 2048×2048 matrix, that's 16 × (2048 + 2048) = 65,536 trainable weights instead of 4,194,304 — a 64x reduction per matrix. When training ends, you fold BA back into W and the adapter disappears: zero inference overhead, same serving path as the base model.&lt;/p&gt;

&lt;p&gt;Why does this work at all? Because the &lt;em&gt;change&lt;/em&gt; a task needs is usually low-rank. The base model already contains the knowledge; adaptation is a small nudge in a few directions, not a rewrite. Aghajanyan et al. (2020) measured this directly: fine-tuning has a low intrinsic dimension, often in the hundreds, even for billion-parameter models.&lt;/p&gt;

&lt;h2&gt;
  
  
  The one line
&lt;/h2&gt;

&lt;p&gt;KerasHub ships LoRA as a single method call on the backbone. The setup is the standard Keras 3 + JAX pattern from GDE #12 — set the backend before the first import, load the preset, enable LoRA, compile, fit:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;
&lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;environ&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"KERAS_BACKEND"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"jax"&lt;/span&gt;   &lt;span class="c1"&gt;# must come before the first keras import&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;keras&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;keras_hub&lt;/span&gt;

&lt;span class="n"&gt;gemma_lm&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;keras_hub&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Gemma3CausalLM&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;from_preset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="s2"&gt;"hf://google/gemma-3-1b-it"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;preprocessor&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;gemma_lm&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;preprocessor&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;keras_hub&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Gemma3CausalLMPreprocessor&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;from_preset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="s2"&gt;"hf://google/gemma-3-1b-it"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;sequence_length&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;256&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# The one line that matters:&lt;/span&gt;
&lt;span class="n"&gt;gemma_lm&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;backbone&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;enable_lora&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;rank&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;   &lt;span class="c1"&gt;# 999.9M params -&amp;gt; 2.6M trainable&lt;/span&gt;

&lt;span class="n"&gt;gemma_lm&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;compile&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;loss&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;keras&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;losses&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;SparseCategoricalCrossentropy&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;from_logits&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;optimizer&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;keras&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;optimizers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;SGD&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;learning_rate&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;1e-4&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;weighted_metrics&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;keras&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;metrics&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;SparseCategoricalCrossentropy&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;from_logits&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;gemma_lm&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;train_ds&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;validation_data&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;val_ds&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;epochs&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Two details matter. First, the backend line must run before &lt;code&gt;import keras&lt;/code&gt; — Keras 3 reads &lt;code&gt;KERAS_BACKEND&lt;/code&gt; once at import time, and on a TPU machine you want &lt;code&gt;jax&lt;/code&gt;, not the default. Second, the preset comes from Kaggle (&lt;code&gt;hf://google/gemma-3-1b-it&lt;/code&gt;), so accept the Gemma terms of use first; the weights download is the only gated step in the whole pipeline. Current versions at time of writing: Keras 3.13.2, JAX 0.9.2.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fctaa6sgbf00c6gs2m2tm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fctaa6sgbf00c6gs2m2tm.png" alt="The LoRA mechanism: a frozen 2048x2048 weight matrix W plus two trainable low-rank matrices B (2048xr) and A (rx2048). At rank 16, 65,536 trainable weights per matrix. The adapter merges back into W after training." width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  How many weights does LoRA actually train?
&lt;/h2&gt;

&lt;p&gt;It depends on which matrices you adapt — and the answer is always a fraction of a percent. Gemma 3 1B has hidden size 2048 and 26 layers; targeting all four attention projections (q, k, v, o) at each rank:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Rank r&lt;/th&gt;
&lt;th&gt;Trainable (q/k/v/o)&lt;/th&gt;
&lt;th&gt;Share of 1B&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;372,736&lt;/td&gt;
&lt;td&gt;0.04%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;1,490,944&lt;/td&gt;
&lt;td&gt;0.15%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;8&lt;/td&gt;
&lt;td&gt;2,981,888&lt;/td&gt;
&lt;td&gt;0.30%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;16&lt;/td&gt;
&lt;td&gt;5,963,776&lt;/td&gt;
&lt;td&gt;0.60%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;32&lt;/td&gt;
&lt;td&gt;11,927,552&lt;/td&gt;
&lt;td&gt;1.19%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;64&lt;/td&gt;
&lt;td&gt;23,855,104&lt;/td&gt;
&lt;td&gt;2.39%&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The community TPU run cited below reported &lt;strong&gt;2,609,152 trainable at rank 16 (0.26%)&lt;/strong&gt; — a narrower targeting choice than all-four-projections, same order of magnitude. The Keras docs' own example is the same story at a different scale: Gemma 2B at rank 4 goes from 2.5 billion parameters to &lt;strong&gt;1,363,968 trainable (0.054%)&lt;/strong&gt;. Whichever matrices you pick, LoRA trains well under 1% of the model.&lt;/p&gt;

&lt;h2&gt;
  
  
  The rank sweep: where more rank stops paying
&lt;/h2&gt;

&lt;p&gt;Rank is the one knob that matters most, and the notebook measures it directly. Take a synthetic weight update of true rank 8 and recover it with rank-r approximations (SVD gives the optimal rank-r fit, so this is the best any rank-r adapter could do):&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fplhjimuwhnastejiuaz1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fplhjimuwhnastejiuaz1.png" alt="Relative error recovering a rank-8 ground-truth update with rank-r approximations: r=1 0.90, r=2 0.82, r=4 0.64, r=8 0.00. Error collapses at the true rank and flatlines after it." width="799" height="409"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Error falls from 0.90 at rank 1 to 0.64 at rank 4, then collapses to exactly zero at rank 8 — and stays zero at 16, 32, 64. Past the true rank, extra rank buys nothing but memory. Real tasks don't have a single true rank, but the shape holds: published LoRA results cluster at rank 8–16 for single-task adaptation, and the original LoRA paper found rank 4–8 sufficient on most GLUE-style tasks. Start at 16; drop to 8 if you're memory-bound; go to 32 only if your eval says rank 16 is underfitting — and check the eval, because rank 32 doubles your trainable count for a gain that usually isn't there.&lt;/p&gt;

&lt;p&gt;Two more knobs ride alongside rank. &lt;strong&gt;Alpha&lt;/strong&gt; scales the adapter's contribution: the effective update is (alpha / r) × BA, so alpha = 16 with r = 16 is a scale of 1.0, and the common convention alpha = 2r doubles the update's weight. &lt;strong&gt;Target modules&lt;/strong&gt; decide which matrices get adapters — attention-only (q, v) is the cheap default; adding the MLP projections (up, gate, down) roughly triples trainable count and helps when the task needs new behavior rather than new style.&lt;/p&gt;

&lt;h2&gt;
  
  
  The memory math: why LoRA fits where full fine-tuning can't
&lt;/h2&gt;

&lt;p&gt;Full fine-tuning with AdamW pays 12 bytes per parameter: 2 for bf16 weights, 2 for bf16 gradients, 4 + 4 for the fp32 Adam m and v states. LoRA pays the 12 bytes only on the trainable fraction; the frozen base costs just its 2-byte weights.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fa8jn6rw21ia4hb42ljd2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fa8jn6rw21ia4hb42ljd2.png" alt="Training memory for Gemma 3 1B with AdamW: full fine-tuning 12.00 GB vs LoRA rank 4 2.02 GB, rank 8 2.04 GB, rank 16 2.03 GB, rank 32 2.14 GB. LoRA is ~6x smaller." width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Gemma 3 1B: &lt;strong&gt;12.00 GB full vs 2.03 GB LoRA — 5.9x smaller&lt;/strong&gt;. The gap widens with size: a 12B model needs ~144 GB for full fine-tuning (multi-GPU territory, or aggressive sharding) versus ~24 GB with LoRA rank 16 — one consumer GPU. And if even that is too much, QLoRA (quantized base + LoRA, in the same KerasHub example) drops the frozen weights to 4-bit, cutting the base cost roughly in half again. The optimizer state is the hidden tax in full fine-tuning — AdamW's m and v alone are 8 of the 12 bytes — and LoRA is the only mainstream method that dodges it without changing optimizers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why LoRA tolerates a much higher learning rate
&lt;/h2&gt;

&lt;p&gt;LoRA runs typically use lr 1e-4 to 2e-4, while full fine-tuning of the same model wants 1e-5 to 5e-5 — a 10x gap that looks reckless until you see the geometry. The toy model in the notebook makes it concrete: loss = 0.5(x² + 20y²), a bowl with one flat direction and one steep one. A full update steps in both directions and diverges once lr passes 2/20 = 0.10. A rank-1 update confined to the flat direction never diverges — at any learning rate.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5hcj2ya0ce9abjyuhv75.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5hcj2ya0ce9abjyuhv75.png" alt="Final loss after 60 gradient steps vs learning rate: the full update converges up to lr 0.09 then explodes past 0.10; the rank-1 update stays flat at loss 10 for every learning rate. Stability bought with expressiveness." width="799" height="409"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The catch is visible in the same chart: the rank-1 update floors at loss 10 because it can never touch the steep direction at all. That is the rank trade-off in one picture — stability and cheapness, bought with expressiveness. In practice it means LoRA is forgiving about learning rate (a good thing when you're tuning on a budget) but structurally incapable of fixes that need the full weight space (the reason it underperforms on far-out-of-distribution tasks).&lt;/p&gt;

&lt;h2&gt;
  
  
  Two real runs, measured honestly
&lt;/h2&gt;

&lt;p&gt;The numbers above are arithmetic. These two are real training runs on Gemma 3 1B with Keras + JAX, both published in the last month:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Medical Q&amp;amp;A on a Kaggle TPU.&lt;/strong&gt; ChatDoctor data, 1,800 training samples and 200 validation, sequence length 256, LoRA rank 16, SGD at lr 1e-4, 1 epoch. The run finished on a TPU v5e-8 in &lt;strong&gt;under a minute&lt;/strong&gt;. The honest result: qualitative answers improved more than benchmark accuracy — the fine-tuned model answered like a clinician, but its MedMCQA score barely moved. Fine-tuning changed &lt;em&gt;style and format&lt;/em&gt; far more than it changed &lt;em&gt;knowledge&lt;/em&gt;, which is exactly what rank-16 LoRA is good at.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Grant-abstract reviser.&lt;/strong&gt; 1,808 (unoptimized, optimized) pairs of NIH grant abstracts, LoRA rank 8, 5 epochs, AdamW at lr 5e-5, sequence length 1024, Keras 3 with the JAX backend. Same shape: a small, clean, task-shaped dataset and a small rank, producing a model that does one job noticeably better.&lt;/p&gt;

&lt;p&gt;Both runs share the pattern that decides whether your LoRA run works: &lt;strong&gt;the dataset is the product&lt;/strong&gt;. 1,800 well-formed examples beat 100,000 noisy ones; a rank-16 adapter trained on sloppy data learns sloppy behavior with great efficiency.&lt;/p&gt;

&lt;h2&gt;
  
  
  When LoRA loses: four failure modes
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Rank too low for the task.&lt;/strong&gt; If the behavior change needs more directions than r allows, the adapter underfits no matter how long you train. Symptom: training loss plateaus well above the full-fine-tuning baseline. Fix: raise the rank, or widen the target modules to include the MLP.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Catastrophic forgetting.&lt;/strong&gt; LoRA constrains the update, but it doesn't prevent it: train too long or too hot on a narrow dataset and the model gets worse at everything else. The medical Q&amp;amp;A run's 1 epoch is the tell — one pass over 1,800 examples was enough. If your eval on general capability drops, stop earlier or lower the learning rate.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Learning rate too high.&lt;/strong&gt; LoRA tolerates 10x the full-FT learning rate, not 100x. Push to 1e-3 and the adapter's small matrices swing wildly — the loss looks fine while the outputs degrade. The Keras docs' example uses SGD rather than AdamW partly for this reason: SGD's lack of adaptive scaling is a feature when the trainable set is tiny.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Wrong tool for the job.&lt;/strong&gt; LoRA adapts; it doesn't teach. If your task needs knowledge the base model never saw — a new language, a proprietary API, a domain with its own vocabulary — no rank will conjure it. That is continued pretraining (or retrieval) territory, not adapter territory. The decision rule: if a good prompt gets the model 80% of the way there, LoRA closes the gap; if a good prompt gets you nowhere, LoRA won't save you.&lt;/p&gt;

&lt;h2&gt;
  
  
  The serving angle: merged vs multi-adapter
&lt;/h2&gt;

&lt;p&gt;After training you have a choice that connects directly to GDE #28 (Dec 16, LoRA serving in vLLM). &lt;strong&gt;Merge&lt;/strong&gt; the adapter — fold BA back into W — and serving is identical to the base model: zero overhead, one artifact, no special infrastructure. Or &lt;strong&gt;keep adapters separate&lt;/strong&gt; and serve many of them from one base model (vLLM's Punica-style multi-adapter serving), swapping adapters per request at the cost of a small routing layer. Merge when you have one task and one model; keep adapters separate when you have ten tasks and one GPU. Either way, the adapter artifact is megabytes — the rank-16 Gemma 3 1B adapter is about 5 MB in bf16 — so versioning and shipping adapters is a file-copy problem, not a model-deployment problem.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;LoRA trains 0.26% of Gemma 3 1B at rank 16 (2.6M of 999.9M parameters)&lt;/strong&gt; — and a real medical Q&amp;amp;A fine-tune finished on a Kaggle TPU v5e-8 in under a minute.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Rank 8–16 is the sweet spot.&lt;/strong&gt; The rank sweep shows error collapsing at the true rank and flatlining after; past it, extra rank buys memory, not quality.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The memory win is 5.9x on a 1B model (12.0 GB → 2.0 GB) and grows with size&lt;/strong&gt; — a 12B model goes from ~144 GB to ~24 GB, which is the difference between multi-GPU and one GPU.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;LoRA tolerates 10x the learning rate&lt;/strong&gt; because its update lives in a flatter subspace — but it can never fix directions outside that subspace, so far-out-of-distribution tasks still need full fine-tuning or retrieval.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The dataset is the product.&lt;/strong&gt; Both real runs used ~1,800 clean examples; LoRA amplifies data quality in both directions.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Merge for one task, serve adapters separately for many&lt;/strong&gt; — the adapter is ~5 MB, so the deployment question is routing, not storage.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Honesty note: trainable counts are computed from Gemma 3 1B's published architecture (hidden 2048, 26 layers, GQA) in the companion notebook; the 2,609,152 figure is the community-reported count from a Kaggle TPU run with narrower module targeting — your count depends on which matrices you adapt. The rank sweep and learning-rate charts are toy models run locally, not Gemma training runs. The medical Q&amp;amp;A and grant-abstract results are the authors' own reports (Nov 2026), not independently replicated; the MedMCQA observation — style improved more than benchmark accuracy — is the authors' own caveat. Keras 3.13.2 / JAX 0.9.2 versions checked Nov 2026. No excluded-vendor content, per the standing exclusion.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Companion notebook:&lt;/strong&gt; the runnable tutorial for this post — &lt;a href="https://danielsamfdo.github.io/blog/assets/lora_gemma_keras.ipynb" rel="noopener noreferrer"&gt;download it here&lt;/a&gt; (open in Colab/Jupyter).&lt;/p&gt;

</description>
      <category>vllm</category>
      <category>llm</category>
      <category>googlecloud</category>
      <category>keras</category>
    </item>
    <item>
      <title>System Design, Plainly — Season 3, Part 4: Search: Inverted Indexes, Plainly</title>
      <dc:creator>Daniel Sam Pete Thiyagu</dc:creator>
      <pubDate>Thu, 03 Dec 2026 17:10:38 +0000</pubDate>
      <link>https://dev.to/danielsamfdo/system-design-plainly-season-3-part-4-search-inverted-indexes-plainly-1m1i</link>
      <guid>https://dev.to/danielsamfdo/system-design-plainly-season-3-part-4-search-inverted-indexes-plainly-1m1i</guid>
      <description>&lt;p&gt;Ask a search engine for "inverted index" and it answers in &lt;strong&gt;5–50 milliseconds&lt;/strong&gt; — across 10 million documents. Ask &lt;code&gt;grep&lt;/code&gt; the same question over the same 10 million documents and you wait minutes, because &lt;code&gt;grep&lt;/code&gt; reads every document and the search engine reads almost none of them. The difference is one data structure, invented before the web existed, and still the beating heart of every search box you use: the &lt;strong&gt;inverted index&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;This is Season 3, Part 4. Season 1 covered B-trees and database indexes; this is the other index — the one that maps &lt;em&gt;words to documents&lt;/em&gt; instead of keys to rows, and makes "find the needle" a lookup instead of a scan.&lt;/p&gt;

&lt;h2&gt;
  
  
  The ELI5 version
&lt;/h2&gt;

&lt;p&gt;A normal index — the one in the back of a textbook — maps a topic to page numbers. "Inverted index: pages 42, 87, 130." A search engine's inverted index is the same idea, scaled up: every distinct word in the corpus maps to the list of documents containing it. That list is called a &lt;strong&gt;posting list&lt;/strong&gt;, and each entry (a &lt;strong&gt;posting&lt;/strong&gt;) records the document ID, how many times the word appears, and where.&lt;/p&gt;

&lt;p&gt;A query is then not a scan but a &lt;strong&gt;set intersection&lt;/strong&gt;: "inverted" AND "index" means walk the two posting lists together and keep the document IDs that appear in both. Both lists are sorted, so the merge is a single linear pass — and with the compression and skip tricks below, it is sub-millisecond even when the lists are millions of entries long. The work is proportional to the number of &lt;em&gt;matching&lt;/em&gt; documents, never to the size of the corpus. That is the whole trick.&lt;/p&gt;

&lt;h2&gt;
  
  
  Anatomy: dictionary, postings, and three layers of clever
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftq622h1165ks176ifn3x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftq622h1165ks176ifn3x.png" alt="A term dictionary maps each word to its posting list of sorted document IDs; a two-term query intersects the lists. Query cost scales with matches, not corpus size." width="800" height="368"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The term dictionary.&lt;/strong&gt; Every distinct token in the corpus gets one entry. Lucene stores the dictionary as a finite-state transducer (FST) — a compressed automaton — so looking up a term costs &lt;strong&gt;O(|term|)&lt;/strong&gt;, proportional to the length of the word, regardless of whether the vocabulary has ten thousand terms or ten million. The dictionary is the only part that grows with vocabulary size; everything else grows with the corpus.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Posting lists and delta encoding.&lt;/strong&gt; A posting list is a sorted sequence of document IDs. Storing raw 32-bit IDs wastes space, so Lucene stores &lt;em&gt;gaps&lt;/em&gt; between consecutive IDs instead — small numbers compress well. The gaps are packed in blocks of 128 with Frame-of-Reference (FOR) encoding: take the largest gap in the block, use exactly that many bits for every gap in the block, and let a few oversized gaps be exceptions (PForDelta). The result is a few bits per document ID instead of 32. The notebook measures this on a toy corpus: raw IDs at 32 bits each vs delta gaps averaging 5.1 bits and FOR-packed blocks at 8.2 bits — a &lt;strong&gt;~4x compression&lt;/strong&gt; that also makes the lists faster to scan, because less data crosses the memory bus.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fq95xlwarakr2r8lwdvbm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fq95xlwarakr2r8lwdvbm.png" alt="Posting-list compression on a 5,000-posting toy list: raw 32-bit IDs vs delta-encoded gaps (5.1 bits avg) vs FOR bit-packing in 128-doc blocks (8.2 bits avg) — 3.9x smaller." width="800" height="391"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Skip lists.&lt;/strong&gt; For an AND query, the naive merge walks both lists from the start. Skip lists store jump pointers every 128 documents, so the merge can leap past whole blocks that cannot match. Combined with galloping search (exponential probing into the longer list), the intersection of a rare term and a common term costs roughly the size of the &lt;em&gt;shorter&lt;/em&gt; list, not the longer one. This is why "obscure-word AND the" is fast: the engine walks the rare term's short list and gallops through "the"'s enormous one.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwrutf9qejivubjnonsms.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwrutf9qejivubjnonsms.png" alt="Query time vs corpus size on a log scale: a linear scan grows with the corpus; an inverted-index lookup stays flat. At 10M documents the scan takes minutes and the index takes milliseconds." width="800" height="391"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Ranking: BM25, or why "the" doesn't win
&lt;/h2&gt;

&lt;p&gt;Retrieval finds the candidates; ranking orders them. The industry default is &lt;strong&gt;BM25&lt;/strong&gt;, and it rests on three intuitions:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Term frequency saturates.&lt;/strong&gt; A document that says "cache" 10 times is more relevant than one that says it once — but not 10x more. BM25's &lt;code&gt;k1&lt;/code&gt; parameter (default &lt;strong&gt;1.2&lt;/strong&gt;) bends the curve so the 2nd mention matters much more than the 20th.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Rare terms outweigh common ones.&lt;/strong&gt; "Inverted" appearing in 100 documents is far more discriminating than "the" appearing in 9 million. Inverse document frequency (IDF) weights the rare term up.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Short documents count more.&lt;/strong&gt; A match in a 50-word note beats the same match buried in a 5,000-word page. The &lt;code&gt;b&lt;/code&gt; parameter (default &lt;strong&gt;0.75&lt;/strong&gt;) normalizes for document length.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fjfjjwhwhn0pk12260ewo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fjfjjwhwhn0pk12260ewo.png" alt="BM25 score vs term frequency for a short document and a long one, with k1=1.2, b=0.75. The curve saturates: the 20th mention adds almost nothing, and the short document scores higher throughout." width="800" height="391"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The defaults — &lt;code&gt;k1=1.2, b=0.75&lt;/code&gt; — work surprisingly well out of the box, which is why almost nobody tunes them until relevance becomes a product problem. In 2026 BM25 has a second life as the sparse half of hybrid RAG: embeddings catch meaning, BM25 catches exact identifiers, error codes, part numbers, and rare tokens that embeddings blur. Production retrieval stacks run both and merge the results.&lt;/p&gt;

&lt;h2&gt;
  
  
  The write path: immutable segments
&lt;/h2&gt;

&lt;p&gt;Lucene never updates an index in place. New documents buffer in memory and, at refresh (default every &lt;strong&gt;1 second&lt;/strong&gt;), flush as a new &lt;strong&gt;segment&lt;/strong&gt; — a self-contained mini inverted index with its own dictionary, postings, stored fields, and doc values. Segments are immutable, which buys three things: no read locks (readers never block writers), aggressive caching (a segment's data never changes under the cache), and crash safety (a half-written segment is simply discarded).&lt;/p&gt;

&lt;p&gt;The cost is merge debt. A busy index accumulates hundreds of small segments, and a background merge process continuously compacts them into larger ones — the same log-structured-merge idea as LSM trees, applied to search. Deletes are tombstones, not removals: a document is marked deleted and physically disappears only when its segment merges. The trade-off is visible in production as merge I/O competing with query latency, and it is the first thing to tune when p99 latency creeps up.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why it breaks: four failure modes
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Hot terms.&lt;/strong&gt; A term in 90% of documents has a posting list nearly as long as the corpus. Every query touching it pays for that list. The fix is tiered: skip lists and Block-Max WAND let the engine prune blocks whose maximum possible score can't make the top-K, so it never fully decodes the hot list. If your p99 is dominated by one term, check whether it should be a stop word — or a filter, not a scored term.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mapping explosions.&lt;/strong&gt; In Elasticsearch, every new field name becomes a mapping entry, and a single bad client that sends &lt;code&gt;user_48291&lt;/code&gt; as a field name can create tens of thousands of fields — each with its own dictionary. The fix is strict mappings and &lt;code&gt;index.mapping.total_fields.limit&lt;/code&gt;, set &lt;em&gt;before&lt;/em&gt; the incident, not after.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Deep pagination.&lt;/strong&gt; Page 1 of results is cheap; page 10,000 is not, because the engine must score and sort everything before it. &lt;code&gt;search_after&lt;/code&gt; (a cursor) replaces offset pagination in every production system that survived its first incident.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Shard hotspots.&lt;/strong&gt; Sharding splits the index by document, and queries fan out to every shard. If one shard holds the popular documents — a celebrity's posts, this week's news — it becomes the bottleneck for every query. Routing by a balanced key, or splitting hot content into its own index, is the fix; adding shards to a cold index is not.&lt;/p&gt;

&lt;h2&gt;
  
  
  The interview angle
&lt;/h2&gt;

&lt;p&gt;"Design a search engine" is a system-design staple, and the inverted index is the answer's center of gravity. The strong answer starts here: dictionary (FST) + posting lists (delta + FOR, blocks of 128) + skip lists, then BM25 on top, then segments and merges for the write path, then sharding for scale. The follow-ups that separate candidates: what breaks when one term is in 90% of documents, how you paginate past page 1,000, and why you would add a vector index beside the inverted one instead of replacing it (hint: exact tokens vs meaning — the 2026 hybrid answer).&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;An inverted index turns search from a scan into a lookup.&lt;/strong&gt; Work scales with matches, not corpus size: 10M documents answer in 5–50 ms.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Compression is performance, not just storage.&lt;/strong&gt; Delta + FOR packing in blocks of 128 cuts posting lists to ~8 bits per doc ID — ~4x smaller and faster to scan.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;BM25's three intuitions — saturation (&lt;code&gt;k1=1.2&lt;/code&gt;), rarity (IDF), length normalization (&lt;code&gt;b=0.75&lt;/code&gt;) — are the ranking defaults the whole industry runs on&lt;/strong&gt;, and in 2026 they are the sparse half of hybrid RAG.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Segments are immutable; merges are the tax.&lt;/strong&gt; No read locks and crash safety on the write path, merge I/O on the read path.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The failure modes are operational, not algorithmic:&lt;/strong&gt; hot terms, mapping explosions, deep pagination, shard hotspots — all four are fixed at index-design time, not query time.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Follow for the next part — Season 3, Part 5 is Bloom filters and probabilistic structures, and Part 6 takes on data lakes vs warehouses vs lakehouses. More on dev.to: &lt;a href="https://dev.to/danielsamfdo"&gt;@danielsamfdo&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Companion notebook:&lt;/strong&gt; the runnable tutorial for this post — &lt;a href="https://danielsamfdo.github.io/blog/assets/inverted_index_search.ipynb" rel="noopener noreferrer"&gt;download it here&lt;/a&gt; (open in Colab/Jupyter).&lt;/p&gt;

</description>
      <category>systemdesign</category>
      <category>architecture</category>
      <category>programming</category>
      <category>softwareengineering</category>
    </item>
    <item>
      <title>The $0.94 Question: TPU Inference, Measured in Dollars per Million Tokens</title>
      <dc:creator>Daniel Sam Pete Thiyagu</dc:creator>
      <pubDate>Thu, 03 Dec 2026 17:10:33 +0000</pubDate>
      <link>https://dev.to/danielsamfdo/the-094-question-tpu-inference-measured-in-dollars-per-million-tokens-4bgp</link>
      <guid>https://dev.to/danielsamfdo/the-094-question-tpu-inference-measured-in-dollars-per-million-tokens-4bgp</guid>
      <description>&lt;p&gt;On a like-for-like Llama 70B serving workload at on-demand list prices, Google Cloud's Trillium (TPU v6e) costs about &lt;strong&gt;$0.94 per million output tokens&lt;/strong&gt; — and an AWS H100 costs about &lt;strong&gt;$0.91&lt;/strong&gt;. A dead heat. But put Trillium on a three-year commitment and the same workload drops to &lt;strong&gt;$0.42 per million tokens&lt;/strong&gt;, less than half the H100's price. Same silicon, same model, 55% cheaper — because on TPUs, &lt;em&gt;how you buy the hardware&lt;/em&gt; matters as much as which hardware you buy.&lt;/p&gt;

&lt;p&gt;This is GDE post #15, and it is the hardware-decision post for the whole TPU lane. GDE #8 covered the framework half — running vLLM on TPU, TorchTPU, XLA compile times, kernel gaps. This post covers the silicon underneath it: what a TPU actually is, what changes when you move inference from a GPU to a TPU, and the dollars-per-million-tokens arithmetic that decides which one wins for your workload. Every number below is recomputed in the companion notebook from Google Cloud's published price list (checked September–November 2026) and Qovery's October 2026 Llama 70B comparison.&lt;/p&gt;

&lt;h2&gt;
  
  
  The ELI5 version
&lt;/h2&gt;

&lt;p&gt;A GPU is a flexible workshop: thousands of small workers that can each do almost any job, so it handles whatever code you throw at it. A TPU is an assembly line built for exactly one job — matrix multiplication. Its core, the Matrix Multiply Unit (MXU), is a systolic array: numbers flow through a grid of multipliers like parts down a conveyor belt, each one doing its multiply-add as the data passes, instead of fetching operands from memory for every operation. For the dense matmuls that dominate LLM inference, that conveyor belt is brutally efficient. For anything that &lt;em&gt;isn't&lt;/em&gt; a dense matmul — a custom kernel, a weird activation, a sparse op — the assembly line stalls, and the flexible workshop wins.&lt;/p&gt;

&lt;p&gt;That single trade-off explains nearly everything that follows: TPUs win when your workload is dense matmuls at large batch sizes on committed capacity. GPUs win when it is anything else.&lt;/p&gt;

&lt;h2&gt;
  
  
  The silicon ladder: four TPUs, one GPU
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhf6scj16urjr01a9a86s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhf6scj16urjr01a9a86s.png" alt="Peak bf16 TFLOPS and on-demand price per chip-hour for TPU v5e, v5p, Trillium (v6e), Ironwood (v7), and NVIDIA H100. Trillium: 918 TFLOPS at $2.70/hr. Ironwood: 2,307 TFLOPS at $12.00/hr. H100: 989 TFLOPS at $6.88/hr." width="799" height="305"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Google's current lineup, from the published price list:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Chip&lt;/th&gt;
&lt;th&gt;Peak bf16 TFLOPS&lt;/th&gt;
&lt;th&gt;HBM per chip&lt;/th&gt;
&lt;th&gt;HBM bandwidth&lt;/th&gt;
&lt;th&gt;Max pod&lt;/th&gt;
&lt;th&gt;On-demand $/chip-hr&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;TPU v5e&lt;/td&gt;
&lt;td&gt;197&lt;/td&gt;
&lt;td&gt;16 GB&lt;/td&gt;
&lt;td&gt;800 GB/s&lt;/td&gt;
&lt;td&gt;256 chips&lt;/td&gt;
&lt;td&gt;$1.20&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;TPU v5p&lt;/td&gt;
&lt;td&gt;459&lt;/td&gt;
&lt;td&gt;95 GiB&lt;/td&gt;
&lt;td&gt;2.77 TB/s&lt;/td&gt;
&lt;td&gt;8,960 chips&lt;/td&gt;
&lt;td&gt;$4.20&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Trillium (v6e)&lt;/td&gt;
&lt;td&gt;918&lt;/td&gt;
&lt;td&gt;32 GB&lt;/td&gt;
&lt;td&gt;1.64 TB/s&lt;/td&gt;
&lt;td&gt;256 chips&lt;/td&gt;
&lt;td&gt;$2.70&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Ironwood (v7)&lt;/td&gt;
&lt;td&gt;2,307 (4,614 fp8)&lt;/td&gt;
&lt;td&gt;192 GiB&lt;/td&gt;
&lt;td&gt;7.37 TB/s&lt;/td&gt;
&lt;td&gt;9,216 chips&lt;/td&gt;
&lt;td&gt;$12.00&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;NVIDIA H100 (AWS)&lt;/td&gt;
&lt;td&gt;989&lt;/td&gt;
&lt;td&gt;80 GB&lt;/td&gt;
&lt;td&gt;3.35 TB/s&lt;/td&gt;
&lt;td&gt;8 GPUs/node&lt;/td&gt;
&lt;td&gt;~$6.88&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Three things jump out. First, Trillium has nearly the H100's peak compute (918 vs 989 TFLOPS) at 39% of the hourly price — but only 32 GB of HBM against the H100's 80 GB, and half the memory bandwidth. Second, Ironwood is the generational jump: 6x Trillium's HBM and 2.5x its bf16 compute, priced at $12/hr. Third, v5p is the odd one: more memory (95 GiB) and a far bigger pod (8,960 chips) than Trillium, but less compute per dollar — it is a training chip that happens to serve, not a serving chip.&lt;/p&gt;

&lt;h2&gt;
  
  
  What actually changes: five differences that decide the bill
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. You compile; you don't write kernels.&lt;/strong&gt; GPUs run CUDA kernels, and the ecosystem has spent a decade hand-optimizing them (FlashAttention, fused kernels, custom ops). TPUs run XLA: your model is compiled ahead of time into a static graph, and the compiler — not you — decides how the MXU is fed. The upside is that a compiled model runs at near-peak MXU utilization with no kernel-launch overhead. The price is &lt;em&gt;static shapes&lt;/em&gt;: variable-length sequences get padded to the largest bucket, and every new shape triggers a recompile. GDE #8 measured the compile-cache effect directly — recompiles are the tax you pay for the assembly line.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. The memory wall is the binding constraint.&lt;/strong&gt; LLM decoding is memory-bandwidth-bound, not compute-bound: each generated token reads the whole model and the whole KV cache. So the number that caps your concurrency is HBM per chip, not TFLOPS. For an 8B GQA model at 4K-token sequences (128 KB of KV per token, FP8 weights), one chip holds about &lt;strong&gt;16 concurrent sequences on v5e, 48 on Trillium, 174 on v5p, 368 on Ironwood, and 144 on an H100&lt;/strong&gt;. v5e's 16 GB is so small that the model weights alone eat half of it. Trillium is 3x v5e's concurrency at 2.25x the price — a genuine improvement, but still a third of the H100's. Ironwood is the first TPU where memory stops being the story.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F69yjgu6ul1ckk4g85qsj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F69yjgu6ul1ckk4g85qsj.png" alt="Concurrent 4K-token sequences per chip for an 8B GQA model with FP8 weights: v5e 16, Trillium 48, v5p 174, Ironwood 368, H100 144. Memory, not FLOPS, caps concurrency." width="800" height="391"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Prefill loves TPUs; decode is a negotiation.&lt;/strong&gt; Prefill is compute-bound (big matmuls over the whole prompt), so the MXU shines and Trillium's $0.29/hr per 100 peak TFLOPS — the cheapest peak compute on the list — turns into real throughput. Decode is bandwidth-bound (one token at a time, streaming weights and KV), so HBM bandwidth and capacity decide, and the H100's 3.35 TB/s and 80 GB fight back. That is exactly why the measured Gemma 4 result from GDE #8 split the way it did: Trillium delivered 1.62–1.68x a v5e chip's throughput on workloads that fit in 16 GB, and 2.32–2.77x on workloads that didn't. The hardware that wins depends on which phase dominates your traffic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Scale-out is a different machine.&lt;/strong&gt; TPUs connect over Google's Inter-Chip Interconnect (ICI) into pods: 256 chips for v5e/Trillium, 8,960 for v5p, 9,216 for Ironwood. A pod is one machine from the compiler's point of view — no per-node networking code, no NCCL tuning. For serving, that matters less than for training, but it is why the largest dense deployments (Gemini serving, for example) sit on TPUs: the interconnect is part of the chip's design, not an afterthought.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. You buy capacity, not servers.&lt;/strong&gt; TPUs are priced per chip-hour &lt;em&gt;including the host VM&lt;/em&gt;, sold as slices (v6e-1, v6e-8, and so on), with three discounts stacked on top of on-demand: Flex-start (dynamic work queues) at 50% off, 1-year commitments at 30% off, 3-year at 55% off. Trillium's $2.70/hr becomes &lt;strong&gt;$1.35 flex-start, $1.89 on one year, $1.22 on three years&lt;/strong&gt;. GPUs on AWS are priced per instance-hour with their own reservation system, but the TPU discount ladder is steeper — and it is the whole reason the committed $/1M-token number ($0.42) is less than half the on-demand one ($0.94).&lt;/p&gt;

&lt;h2&gt;
  
  
  The dollars-per-million-tokens math
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fy6i7xrwrsby3fktibzvh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fy6i7xrwrsby3fktibzvh.png" alt="Cost per million output tokens on a Llama 70B workload: H100 on-demand $0.91, Trillium on-demand $0.94, Trillium 1-year $0.66, Trillium 3-year $0.42. The commitment, not the chip, is the discount." width="800" height="391"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The Qovery comparison (October 2026, Llama 70B, on-demand list prices) is the cleanest head-to-head published: &lt;strong&gt;Trillium $0.94 vs H100 $0.91 per million output tokens&lt;/strong&gt;. Neither chip is cheaper by default. The notebook turns that into the decision rule: cost per million tokens is just (chips × $/chip-hour) ÷ (tokens per hour) × 1M, so the winner is whoever sustains more tokens per dollar. An 8-chip Trillium host costs $21.60/hr on demand ($9.76/hr on a 3-year commitment), and either way it must sustain ~6,400 tokens/s across the host (~800 per chip) to hit its tier's $/1M figure — the commitment doesn't make the chip faster, it lowers the price at any fixed throughput by 55%.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9idpixxry3g44c17mfcz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9idpixxry3g44c17mfcz.png" alt="On-demand cost per hour per 100 peak bf16 TFLOPS: Trillium $0.29, Ironwood $0.52, v5e $0.61, H100 $0.70, v5p $0.92. Cheapest peak FLOPS is not cheapest tokens." width="800" height="391"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And the trap to avoid: cheapest peak FLOPS is not cheapest tokens. Trillium is the cheapest peak compute on the list at &lt;strong&gt;$0.29/hr per 100 TFLOPS&lt;/strong&gt;, against $0.52 for Ironwood, $0.61 for v5e, $0.70 for the H100, and $0.92 for v5p. But the third-party Gemma 4 measurement found Trillium's value vs v5e was only &lt;strong&gt;0.73x when the workload fit in 16 GB&lt;/strong&gt; — you pay 2.25x the chip-hour for 1.62–1.68x the throughput — and &lt;strong&gt;1.13x when it didn't fit&lt;/strong&gt;. FLOPS per dollar is a price tag; tokens per dollar is the bill.&lt;/p&gt;

&lt;h2&gt;
  
  
  When TPU wins, when GPU wins
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Workload&lt;/th&gt;
&lt;th&gt;Pick&lt;/th&gt;
&lt;th&gt;Why&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Large-batch dense serving, committed capacity&lt;/td&gt;
&lt;td&gt;Trillium / Ironwood&lt;/td&gt;
&lt;td&gt;Cheapest $/token at scale; MXU utilization high; 55% commitment cut&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Small model that fits in 16 GB&lt;/td&gt;
&lt;td&gt;v5e&lt;/td&gt;
&lt;td&gt;$1.20/hr is the cheapest accelerator-hour Google sells; 0.73x value trap doesn't apply if you stay on v5e&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Prefill-heavy traffic (long prompts, RAG)&lt;/td&gt;
&lt;td&gt;Trillium&lt;/td&gt;
&lt;td&gt;Compute-bound phase, MXU at peak&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Custom kernels, sparse ops, new architectures&lt;/td&gt;
&lt;td&gt;H100 / GPU&lt;/td&gt;
&lt;td&gt;CUDA ecosystem; XLA recompile and kernel gaps bite&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Small batch / latency-sensitive decode&lt;/td&gt;
&lt;td&gt;H100&lt;/td&gt;
&lt;td&gt;80 GB HBM + 3.35 TB/s bandwidth; more KV headroom per chip&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Training at pod scale&lt;/td&gt;
&lt;td&gt;v5p / Ironwood&lt;/td&gt;
&lt;td&gt;8,960–9,216-chip pods, ICI interconnect&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Bursty, unpredictable traffic&lt;/td&gt;
&lt;td&gt;GPU spot / Flex-start TPU&lt;/td&gt;
&lt;td&gt;On-demand TPU pricing punishes idle chips; flex-start halves it&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;TPU vs GPU is a $0.94 vs $0.91 question on demand, and a $0.42 vs $0.91 question on a 3-year commitment.&lt;/strong&gt; The purchase mode is the discount, not the chip.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Memory, not FLOPS, caps TPU serving.&lt;/strong&gt; 16 GB (v5e) to 32 GB (Trillium) to 192 GB (Ironwood) is the ladder that matters; KV concurrency goes 16 → 48 → 368 sequences per chip for an 8B model.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Prefill loves TPUs, decode negotiates.&lt;/strong&gt; The phase mix of your traffic decides the winner more than the spec sheet does.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Cheapest peak FLOPS ≠ cheapest tokens.&lt;/strong&gt; Trillium at $0.29/hr per 100 TFLOPS still loses on value (0.73x) to v5e when the workload fits in 16 GB.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Ironwood changes the memory story.&lt;/strong&gt; 192 GiB per chip is the first TPU where HBM stops being the binding constraint for serving — watch its vLLM support mature; as of the October release, vLLM tests Ironwood in CI while v6e/v5e/v5p support in &lt;code&gt;vllm-torchtpu&lt;/code&gt; is still experimental.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Honesty note: prices are Google Cloud / AWS published list rates checked September–November 2026 and vary by region and commitment; the H100 figure is an AWS list price via Qovery, October 2026. The $0.94/$0.91/$0.42 per-million-token figures are Qovery's Llama 70B comparison, one workload, not a controlled A/B. Throughput thresholds in the notebook are arithmetic from list prices, not measured throughput. Gemma 4 throughput ratios are third-party measurements on one model and one output length — read them as shape, not delta. No excluded-vendor content, per the standing exclusion.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Companion notebook:&lt;/strong&gt; the runnable tutorial for this post — &lt;a href="https://danielsamfdo.github.io/blog/assets/tpu_inference_cost.ipynb" rel="noopener noreferrer"&gt;download it here&lt;/a&gt; (open in Colab/Jupyter).&lt;/p&gt;

</description>
      <category>vllm</category>
      <category>llm</category>
      <category>googlecloud</category>
      <category>tpu</category>
    </item>
    <item>
      <title>System Design, Plainly — Season 3, Part 3: Event Sourcing &amp; CQRS</title>
      <dc:creator>Daniel Sam Pete Thiyagu</dc:creator>
      <pubDate>Wed, 02 Dec 2026 17:01:49 +0000</pubDate>
      <link>https://dev.to/danielsamfdo/system-design-plainly-season-3-part-3-event-sourcing-cqrs-4d68</link>
      <guid>https://dev.to/danielsamfdo/system-design-plainly-season-3-part-3-event-sourcing-cqrs-4d68</guid>
      <description>&lt;p&gt;Part 2 settled the delivery question: a message arrives at-least-once, and idempotency does the rest. This part asks the question that comes the moment you stop and look at your database: &lt;strong&gt;what do you actually store — the current state, or the history that produced it?&lt;/strong&gt; Most systems store the state: the balance is $100. Event sourcing stores the history instead: &lt;code&gt;Deposited(+50)&lt;/code&gt;, &lt;code&gt;Deposited(+70)&lt;/code&gt;, &lt;code&gt;Withdrawn(-20)&lt;/code&gt; — and $100 is what you get when you add them up. CQRS is the companion split: one model for writes, a different model for reads, each shaped for its own job.&lt;/p&gt;

&lt;p&gt;The season's benchmark hook is the price of that choice, measured in the companion notebook's seeded simulation (seed 42, 200,000 events across 1,000 accounts): replaying the whole log takes &lt;strong&gt;about 0.1 seconds&lt;/strong&gt;; running a non-idempotent projection twice doubles every balance to exactly &lt;strong&gt;2.00x&lt;/strong&gt; with no error; a snapshot makes a 100,000-event aggregate &lt;strong&gt;60x&lt;/strong&gt; faster to rebuild and a 200-event aggregate &lt;strong&gt;9.3x slower&lt;/strong&gt;; and a point query on the read model is roughly &lt;strong&gt;5,800x&lt;/strong&gt; faster than recomputing from the log. The pattern is powerful and the failure modes are silent — which is exactly why it deserves its own part.&lt;/p&gt;

&lt;h2&gt;
  
  
  The ELI5 version
&lt;/h2&gt;

&lt;p&gt;A normal database is a whiteboard: it shows the current balance, and every update erases what was there before. If someone asks "what was the balance last Tuesday?" or "who changed this, and when?", the whiteboard shrugs. An event-sourced system is a ledger: every change is a new line that never gets erased, and the current balance is the sum of the lines. The ledger can answer any question about the past, because the past is still there.&lt;/p&gt;

&lt;p&gt;CQRS is the second idea, and it is independent — you can use it without event sourcing. &lt;strong&gt;Command Query Responsibility Segregation&lt;/strong&gt; means the write side and the read side are different models. Writes go to the ledger, validated against business rules. Reads come from a &lt;strong&gt;read model&lt;/strong&gt;: a precomputed view shaped exactly like the screen that needs it, rebuilt from the ledger by a projector. The write side is optimized for correctness; the read side is optimized for speed. They meet only through events.&lt;/p&gt;

&lt;p&gt;The catch, and the reason this pattern has a reputation for eating teams alive, is the word "eventually": the read model is updated &lt;em&gt;after&lt;/em&gt; the write lands, so for a short window the two disagree. That lag is a number, not a mystery — the notebook prices it below — and whether you can live with it decides whether this pattern fits your system at all.&lt;/p&gt;

&lt;h2&gt;
  
  
  Store the history, derive the state
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ffncwsqpjarw82mv4v2ws.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ffncwsqpjarw82mv4v2ws.png" alt="Replay time vs event count: 10K events 12 ms, 50K 60 ms, 100K 120 ms, 200K 240 ms (model), 1M 1,200 ms. Measured: 104 ms for 200K events in a pure-Python fold." width="799" height="459"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The first objection to event sourcing is always performance: "you want me to replay a million events every time I need a balance?" The answer is that replay is a linear fold, and linear folds are fast. The notebook's pure-Python loop replays 200,000 events in about 0.1 seconds — measured 85–115 ms across runs — and a vectorized fold does it in 17 ms. A million events is about 1.2 seconds in the slow path and a rounding error in the fast one. Replay at this scale is routine, not an emergency operation: an independent measurement (js-tools' Lesson 14, 200,000 events on PostgreSQL) reports 235 ms for the same job.&lt;/p&gt;

&lt;p&gt;That changes the shape of the decision. The cost of event sourcing is not replay speed — it is everything around it: storing the log (9.6 MB of events vs 8 KB of current state in the notebook's simulation, a 1,200x storage ratio), evolving event schemas over years, and building the projector that keeps the read model in sync. The log is cheap to read and expensive to &lt;em&gt;live with&lt;/em&gt;. Teams that adopt the pattern for the audit trail and then discover they also bought a schema-migration discipline are the ones that regret it; teams that adopt it &lt;em&gt;because&lt;/em&gt; they need the audit trail never look back.&lt;/p&gt;

&lt;p&gt;The honest rule: event sourcing earns its keep for a handful of core aggregates — money, orders, permissions — where the history itself is the product. It does not earn its keep for the whole system. Store the history where the history matters; store the state everywhere else.&lt;/p&gt;

&lt;h2&gt;
  
  
  Idempotency is not optional — it is the whole game
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fiarrw9or9fe5w84dgfuh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fiarrw9or9fe5w84dgfuh.png" alt="Total balance across 1,000 accounts: true $18,024,591; naive projection run twice $36,049,182 (2.00x); idempotent projection run twice $18,024,591 (exact)." width="799" height="482"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here is the failure mode that defines this pattern. A projector crashes halfway through rebuilding the read model, restarts, and replays the same events again. If the projection is not idempotent — if applying an event twice changes the result — the read model is now wrong, and nothing tells you. In the notebook, the naive projection run twice produces a total balance of &lt;strong&gt;$36,049,182 instead of $18,024,591: exactly 2.00x&lt;/strong&gt;, with no error thrown, no exception, no warning. Every account looks plausible. Every account is wrong.&lt;/p&gt;

&lt;p&gt;The fix is one rule, applied everywhere: &lt;strong&gt;a projection must be a function of the event, not of how many times it ran.&lt;/strong&gt; In practice that means deduplicating by event ID — the notebook's idempotent projector tracks seen IDs and the double run lands exactly on the truth, $0 of error — or designing the update to be naturally idempotent (set the status to &lt;code&gt;SHIPPED&lt;/code&gt; rather than incrementing a counter). This is the same idempotency Part 1 demanded for message delivery, now inside your own database: at-least-once delivery plus a non-idempotent projector is a corruption machine with a friendly API.&lt;/p&gt;

&lt;p&gt;Test it the way the notebook does: run the projector twice over the same log and diff the read model against the truth. If the diff is nonzero, you do not have a projection bug — you have a data-corruption bug that will fire the first time a deploy restarts mid-replay. That test belongs in CI, not in a runbook.&lt;/p&gt;

&lt;h2&gt;
  
  
  Snapshots: a conditional tool, not a mandatory step
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fe32vpvymutuz5hf76uw7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fe32vpvymutuz5hf76uw7.png" alt="Snapshot speedup vs full replay by aggregate length: 200 events 0.11x, 1,000 events 0.60x, 2,000 events 1.20x, 10,000 events 6.00x, 100,000 events 60.00x (log scale)." width="800" height="448"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The standard answer to "replay is slow for long aggregates" is snapshots: every 1,000 events, save the aggregate's state, so a rebuild loads the latest snapshot and replays only what came after. The standard answer is half right. In the notebook's model — 1.2 µs per event folded, 2.0 ms to fetch and deserialize a snapshot — a snapshot &lt;em&gt;loses&lt;/em&gt; on short aggregates: at 200 events it is 0.11x the speed of a plain replay, i.e. &lt;strong&gt;9.3x slower&lt;/strong&gt;, because you pay the full snapshot fetch to skip 200 events. At 1,000 events it is still slower (0.60x). It breaks even around 2,000 events, wins &lt;strong&gt;6x at 10,000&lt;/strong&gt;, and &lt;strong&gt;60x at 100,000&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The independent measurement agrees on the shape, if not the exact numbers: js-tools' Lesson 14 finds a snapshot 6.6x faster on a 100,000-event aggregate and 2.6x slower on a 200-event one. The lesson is the same in both: &lt;strong&gt;snapshot the aggregates that are long, and only those.&lt;/strong&gt; A snapshot policy applied blindly to every aggregate is a tax on the short ones — and most aggregates in a real system are short. Snapshot by measured length, not by policy.&lt;/p&gt;

&lt;h2&gt;
  
  
  CQRS: the read model is a cache you rebuild
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbveh5dzznjg92m4m10r3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbveh5dzznjg92m4m10r3.png" alt="Point-query latency: materialized view 2.9 µs vs recompute-from-log 16,471 µs (log scale, ~5,800x); projection lag at a 50K events/s projector: 1K-event burst 0.02 s, 10K 0.20 s, 50K 1.00 s." width="800" height="428"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is what the split buys you. A point query — "what is account 417's balance?" — takes &lt;strong&gt;2.9 µs against the materialized view and 16.5 ms recomputed from the log&lt;/strong&gt;, roughly 5,800x faster. That gap is the entire CQRS pitch: the read model is shaped exactly like the query, so the query is a lookup instead of a computation. The published EventStoreDB numbers tell the same story at production scale: materialized-view reads at 2.1 ms p99 versus 45 ms for live aggregation and 120 ms for traditional JOINs.&lt;/p&gt;

&lt;p&gt;The price is the lag, and the lag is a number you can put in a service-level agreement. At a projector applying 50,000 events per second, a 1,000-event burst leaves the read model 0.02 s stale; a 10,000-event burst, 0.20 s; a 50,000-event burst, a full second. That is the eventual-consistency bill, and it arrives in the user experience as "I just paid and my balance hasn't changed." If your product cannot tolerate a one-second stale read after a burst, CQRS is the wrong pattern — or the projector needs to be faster, the bursts need batching, or the read that must be fresh needs to go to the write side. All three are legitimate answers; pretending the lag is zero is not.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why it breaks: the failure modes, ranked
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Schema evolution.&lt;/strong&gt; Events are forever, and your understanding of them is not. A &lt;code&gt;PriceChanged&lt;/code&gt; event from 2024 means something different from the same event in 2026, and the log contains both. The fix is &lt;strong&gt;upcasting&lt;/strong&gt; — a translation layer that rewrites old events into the current schema on read — and the upcasting layer only ever grows. Budget for it on day one.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Ordering across partitions.&lt;/strong&gt; Inside one aggregate's stream, order is total and safe. Across aggregates, it is not: two services can emit events "at the same time" and no clock will tell you which came first. If a business rule spans aggregates, you need a saga (Season 2, Part 4) or you need to rethink the boundary.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The dual-write problem.&lt;/strong&gt; Writing the event &lt;em&gt;and&lt;/em&gt; updating a read model in the same request is two writes pretending to be one. If the first succeeds and the second fails, the models diverge silently. The fix is the outbox pattern (Season 2, Part 4): write the event and the outbox row in one transaction, let a relay publish from the outbox. Never dual-write without it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The immutable log meets the right to be forgotten.&lt;/strong&gt; An append-only log and a deletion request are in direct conflict. The standard answers — crypto-shredding (encrypt personal data with a per-user key, delete the key) or tombstone events that the projector honors — both work, and both need to be designed in before the first regulator asks, not after.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Ad-hoc queries die.&lt;/strong&gt; The cheapest thing in a CRUD system — "just run a query" — is the most expensive thing here, because the read model only answers the questions it was built to answer. Every new question is a new projection, a new deployment, and a backfill. Teams that live in ad-hoc SQL will hate this pattern daily.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Store the history where the history is the product.&lt;/strong&gt; Replay is fast — 200,000 events in ~0.1 s — so the cost of event sourcing is schema evolution and projector discipline, not replay speed.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A non-idempotent projection is a corruption machine.&lt;/strong&gt; Run twice, every balance doubles to exactly 2.00x, silently. Deduplicate by event ID, and test the double-run in CI.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Snapshots are conditional.&lt;/strong&gt; They lose 9.3x on a 200-event aggregate and win 60x on a 100,000-event one. Snapshot by measured length, not by policy.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;CQRS buys a ~5,800x faster point query and charges a priced lag.&lt;/strong&gt; A 50,000-event burst at a 50K-events/s projector means a 1.00 s stale read — put that number in the SLA or don't use the pattern.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;CQRS does not require event sourcing, and event sourcing does not require CQRS.&lt;/strong&gt; The expensive part is the log, not the split. Adopt each half only where it pays.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Next in Season 3: Part 4 — Search: inverted indexes, plainly. Follow &lt;a href="https://dev.to/danielsamfdo"&gt;danielsamfdo on dev.to&lt;/a&gt; for the next part.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Honesty note: replay, idempotency, snapshot, storage, and query-latency figures are measured in the companion notebook (seed 42, 200,000 events, 1,000 accounts, in-memory Python fold; replay 85–115 ms across runs, quoted as ~0.1 s; point-query ratio 5,600–6,000x across runs, quoted as ~5,800x). Snapshot figures use the notebook's stated model (1.2 µs/event fold, 2.0 ms snapshot fetch/deserialize, snapshots every 1,000 events) — a model, not a production measurement. The js-tools Lesson 14 figures (235 ms replay, 6.6x snapshot win / 2.6x loss) and EventStoreDB p99 figures (2.1 ms vs 45 ms vs 120 ms) are independent published measurements, cited as such. The 48-bytes-per-event storage figure is an assumed event size for illustration. No Meta content per the standing exclusion.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Companion notebook:&lt;/strong&gt; the runnable tutorial for this post — &lt;a href="https://danielsamfdo.github.io/blog/assets/event_sourcing_cqrs.ipynb" rel="noopener noreferrer"&gt;download it here&lt;/a&gt; (open in Colab/Jupyter).&lt;/p&gt;

</description>
      <category>systemdesign</category>
      <category>architecture</category>
      <category>programming</category>
      <category>softwareengineering</category>
    </item>
    <item>
      <title>Keras 3: One Model, Three Backends, Zero Rewrites</title>
      <dc:creator>Daniel Sam Pete Thiyagu</dc:creator>
      <pubDate>Wed, 02 Dec 2026 17:01:45 +0000</pubDate>
      <link>https://dev.to/danielsamfdo/keras-3-one-model-three-backends-zero-rewrites-1hl1</link>
      <guid>https://dev.to/danielsamfdo/keras-3-one-model-three-backends-zero-rewrites-1hl1</guid>
      <description>&lt;p&gt;In March 2026, TensorFlow went into maintenance mode: Google now commits only security fixes, critical bug fixes, and dependency updates, and recommends Keras 3, JAX, or PyTorch for new generative AI work. That sounds like a framework war. It isn't — because Keras 3 already ended it. Keras 3.15.1 (July 29, 2026) runs the same model code on TensorFlow, JAX, or PyTorch, switched by a single environment variable. One independent test in October 2026 ran the same 20-line model on all three backends and got &lt;strong&gt;96.4% (TensorFlow), 96.9% (JAX), 96.9% (PyTorch)&lt;/strong&gt; — a maximum spread of 0.5 percentage points. The backend changes the engine, not the answer. This is GDE post #14, and it is the decision post for the whole Keras lane: which backend to pick, what it costs to switch, and when the whole abstraction breaks down.&lt;/p&gt;

&lt;p&gt;Every number below is recomputed in the companion notebook from published sources: the Keras team's own A100 benchmark, Neurohive's October 2026 three-backend run, and PyPI download counts.&lt;/p&gt;

&lt;h2&gt;
  
  
  The ELI5 version
&lt;/h2&gt;

&lt;p&gt;Think of a deep-learning framework as a car engine and your model code as the car. In the Keras 2 era, the car was welded to one engine: TensorFlow. Want a different engine? Rebuild the car. Keras 3 unbolts the engine. You write the model once — layers, loss, optimizer — and pick the engine with one line before you import Keras:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;
&lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;environ&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"KERAS_BACKEND"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"jax"&lt;/span&gt;  &lt;span class="c1"&gt;# or "tensorflow" / "torch"&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;keras&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That is the entire switch. No model code changes, no layer rewrites, no second code path. Under the hood Keras translates your &lt;code&gt;keras.layers.Dense&lt;/code&gt; and &lt;code&gt;keras.ops&lt;/code&gt; calls into the backend's native ops, and it guarantees the numerics match to about 1e-7 in float32. The notebook verifies the same idea on a toy model: the same weights through two different computation paths agree to 0.00e+00 — the promise is real, not marketing.&lt;/p&gt;

&lt;h2&gt;
  
  
  The parity proof: 0.5 percentage points across three engines
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fpij91hpi5mqxe2rx65ky.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fpij91hpi5mqxe2rx65ky.png" alt="Test accuracy of the same 20-line Keras 3.15.1 model on three backends: TensorFlow 96.4%, JAX 96.9%, PyTorch 96.9%. Max spread 0.5 pp." width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Neurohive's October 2026 guide ran every code example with PyTorch 2.14, TensorFlow 2.21, and Keras 3.15, and the three-backend Keras run is the cleanest result in the piece: identical code, identical data, 96.4% vs 96.9% vs 96.9%. A 0.5-point spread is inside training noise — different random seeds on the &lt;em&gt;same&lt;/em&gt; backend would move the number by more than that. The practical meaning: you can develop on the backend your laptop has and deploy on the backend your cluster has, and the model you ship is the model you tested.&lt;/p&gt;

&lt;p&gt;That is new. In Keras 2, switching frameworks meant rewriting the model. In raw PyTorch or raw JAX, switching meant rewriting the model &lt;em&gt;and&lt;/em&gt; the training loop. Keras 3 is the first widely used API where the framework is a deployment decision you can make after the model works, not before.&lt;/p&gt;

&lt;h2&gt;
  
  
  The speed payoff: 2.27x faster than Keras 2, on either backend
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8sf7lo97qwcqqu6bty2w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8sf7lo97qwcqqu6bty2w.png" alt="BERT training step time on one A100: Keras 2 (TensorFlow) 486.00 ms, Keras 3 (TensorFlow) 214.49 ms, Keras 3 (JAX) 222.37 ms. Keras 3 is 2.27x and 2.19x faster." width="800" height="470"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The Keras team's own benchmark (one NVIDIA A100, milliseconds per step, averaged over 100 steps) is the reason to upgrade even if you never switch backends. BERT training: &lt;strong&gt;486.00 ms/step on Keras 2 vs 214.49 ms on Keras 3 (TensorFlow) and 222.37 ms on Keras 3 (JAX)&lt;/strong&gt; — 2.27x and 2.19x faster for the same model, same hardware, same data. A 100-hour Keras 2 training job becomes a 44.1-hour job on Keras 3. That is 55.9 hours of GPU time back per run, and at A100 rental rates it is real money, not a benchmark trophy.&lt;/p&gt;

&lt;p&gt;Note the honest wrinkle in the same table: on BERT training, Keras 3 on TensorFlow (214.49 ms) is slightly &lt;em&gt;faster&lt;/em&gt; than Keras 3 on JAX (222.37 ms) — 1.037x. JAX is usually the fastest backend in Keras's benchmarks, but "usually" is doing work there. The backend that wins depends on the model, and the whole point of Keras 3 is that you can measure all three in an afternoon instead of arguing about it for a quarter. The notebook recomputes both speedups and the hours-saved arithmetic.&lt;/p&gt;

&lt;h2&gt;
  
  
  The ecosystem reality: PyTorch downloads 5x TensorFlow
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Foinmtniogqcb62nxq350.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Foinmtniogqcb62nxq350.png" alt="PyPI downloads in the 30 days to Oct 28, 2026: PyTorch 59.0M, TensorFlow 11.9M, Keras 11.4M, JAX 8.7M." width="800" height="449"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;PyPI downloads in the 30 days to October 28, 2026: &lt;strong&gt;PyTorch 59.0M, TensorFlow 11.9M, Keras 11.4M, JAX 8.7M&lt;/strong&gt;. PyTorch is downloaded about 5 times more than TensorFlow and 5.2 times more than Keras; roughly 14 times more models on Hugging Face are tagged PyTorch than TensorFlow. Keras itself is 12.5% of the four-way total — small as a download, large as a bridge, because every Keras download is a model that can run on any of the other three.&lt;/p&gt;

&lt;p&gt;This is why the maintenance-mode news matters and also why it doesn't panic anyone: the ecosystem already voted. TensorFlow's role is now the stable production runtime for the models already running on it, and Keras 3 is the migration path that doesn't require rewriting them. If you are starting a new project in December 2026, the default is PyTorch for the ecosystem, JAX for TPU and raw speed, and Keras 3 on top of either so the choice stays reversible.&lt;/p&gt;

&lt;h2&gt;
  
  
  The code: the same model, three engines
&lt;/h2&gt;

&lt;p&gt;The full pattern fits in one screen. Define once, train anywhere:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;
&lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;environ&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"KERAS_BACKEND"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"jax"&lt;/span&gt;  &lt;span class="c1"&gt;# swap to "tensorflow" or "torch"&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;keras&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;keras&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;layers&lt;/span&gt;

&lt;span class="n"&gt;model&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;keras&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Sequential&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="n"&gt;layers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Dense&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;128&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;activation&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"relu"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;layers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Dense&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;activation&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"softmax"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;compile&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;optimizer&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"adam"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;loss&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"sparse_categorical_crossentropy"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
              &lt;span class="n"&gt;metrics&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"accuracy"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x_train&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;y_train&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;epochs&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three things to know before you run it. First, set &lt;code&gt;KERAS_BACKEND&lt;/code&gt; &lt;em&gt;before&lt;/em&gt; importing Keras — it is read at import time, and setting it later silently does nothing. Second, prefer &lt;code&gt;keras.ops&lt;/code&gt; over backend-specific calls inside custom layers: &lt;code&gt;keras.ops.matmul&lt;/code&gt; works on all three backends, a raw backend call does not, and that is the one place a model can accidentally lock itself to a single engine. Third, &lt;code&gt;keras.distribution&lt;/code&gt; is the 2026 answer to multi-GPU and TPU training — data and model parallelism without rewriting the loop — and it is JAX-first, which is the practical reason the rest of this lane assumes the JAX backend.&lt;/p&gt;

&lt;h2&gt;
  
  
  Which backend, when?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftzv01ob4kwhxs08h9143.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftzv01ob4kwhxs08h9143.png" alt="Decision matrix (scores 1-5, editorial judgement): JAX leads on TPU and GPU speed; TensorFlow leads on production serving; PyTorch leads on ecosystem and debugging." width="800" height="446"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The matrix is judgement, scored from the evidence in this post — not a benchmark. The rules behind it:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;JAX when the hardware is a TPU or the model is compute-bound.&lt;/strong&gt; It is the backend Google DeepMind trains Gemini with, it tops most of Keras's speed tables, and &lt;code&gt;keras.distribution&lt;/code&gt; is built for it. Pick it for the Lane B Gemma posts that follow.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;TensorFlow when the model is already in production.&lt;/strong&gt; &lt;code&gt;tf.serving&lt;/code&gt;, TFLite, and a decade of deployment tooling still belong to this backend. Maintenance mode means no new features, not no support — and Keras 3 is how you keep those models alive without freezing your stack in 2026.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;PyTorch when the team, the hiring pool, or the ecosystem matters most.&lt;/strong&gt; Five times the downloads, the Hugging Face default, the debugging experience everyone already knows. For most new teams, this is the right default — and Keras 3 means choosing it costs you nothing if the hardware changes later.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The common mistake is picking on ideology. The numbers say the accuracy is identical to 0.5 points and the speed gap between backends is a few percent on any given model. Pick on hardware and team, measure the other two in an afternoon, and let the env var do the work.&lt;/p&gt;

&lt;h2&gt;
  
  
  When Keras loses
&lt;/h2&gt;

&lt;p&gt;Two situations. First, throughput serving: Keras loads one model and generates one sequence at a time, which is perfect for local development and hopeless for a production endpoint — that is what vLLM (Lane A) is for. Second, framework-native features: if you need a PyTorch-only library or a JAX-only transformation (&lt;code&gt;jit&lt;/code&gt;, &lt;code&gt;grad&lt;/code&gt;, &lt;code&gt;pmap&lt;/code&gt; — see GDE post #11), Keras adds a translation layer you will eventually want to remove. Keras is the lab and the bridge; the native framework is the destination when one backend wins outright.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;One model, three backends, zero rewrites.&lt;/strong&gt; Keras 3.15.1 on TensorFlow, JAX, and PyTorch scores 96.4% / 96.9% / 96.9% on the same 20-line model — a 0.5 pp spread, inside training noise.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Keras 3 is 2.27x faster per BERT training step than Keras 2&lt;/strong&gt; (214.49 ms vs 486.00 ms on one A100), and 2.19x on JAX. A 100-hour Keras 2 job becomes 44.1 hours.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The ecosystem already voted:&lt;/strong&gt; PyTorch 59.0M PyPI downloads in 30 days vs TensorFlow 11.9M, Keras 11.4M, JAX 8.7M. TensorFlow is in maintenance mode since March 2026; Keras 3 is the migration path that doesn't require a rewrite.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Pick on hardware and team, not ideology.&lt;/strong&gt; JAX for TPU/speed, TensorFlow for existing production, PyTorch for ecosystem — and measure all three, because the switch is one environment variable.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The switch costs one line.&lt;/strong&gt; &lt;code&gt;KERAS_BACKEND&lt;/code&gt; before import; &lt;code&gt;keras.ops&lt;/code&gt; inside custom layers; &lt;code&gt;keras.distribution&lt;/code&gt; for multi-device. That is the whole migration.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Honesty note: accuracy figures (96.4/96.9/96.9%) and PyPI download counts are Neurohive's October 2026 published run (Keras 3.15.1, PyTorch 2.14, TensorFlow 2.21), not this notebook's measurements — the notebook recomputes the spreads and ratios from those published figures. BERT step times (486.00 / 214.49 / 222.37 ms) are the Keras team's published A100 benchmark, averaged over 100 steps; "usually JAX is fastest" is the Keras team's summary claim, and BERT is the counterexample in their own table. TensorFlow maintenance-mode status is Google's March 2026 position as reported by Neurohive. The decision-matrix scores are editorial judgement, labelled as such. No Meta content per the standing exclusion.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Companion notebook: &lt;code&gt;keras3_backends.ipynb&lt;/code&gt; — backend accuracy-parity check, BERT speedup recompute with the 100-hour job arithmetic, PyPI download ratios, and a same-weights/same-answer toy verification across two computation paths, all exec-tested.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Companion notebook:&lt;/strong&gt; the runnable tutorial for this post — &lt;a href="https://danielsamfdo.github.io/blog/assets/keras3_backends.ipynb" rel="noopener noreferrer"&gt;download it here&lt;/a&gt; (open in Colab/Jupyter).&lt;/p&gt;

</description>
      <category>keras</category>
      <category>llm</category>
      <category>googlecloud</category>
      <category>machinelearning</category>
    </item>
    <item>
      <title>System Design, Plainly — Season 3, Part 2: Stream Processing: Windows, Watermarks &amp; Late Data</title>
      <dc:creator>Daniel Sam Pete Thiyagu</dc:creator>
      <pubDate>Tue, 01 Dec 2026 17:00:47 +0000</pubDate>
      <link>https://dev.to/danielsamfdo/system-design-plainly-season-3-part-2-stream-processing-windows-watermarks-late-data-1kl3</link>
      <guid>https://dev.to/danielsamfdo/system-design-plainly-season-3-part-2-stream-processing-windows-watermarks-late-data-1kl3</guid>
      <description>&lt;p&gt;Part 1 settled the delivery question: a message arrives at-least-once, and idempotency does the rest. This part is the question that comes the moment you &lt;em&gt;aggregate&lt;/em&gt; a stream: &lt;strong&gt;when is a 5-minute window finished?&lt;/strong&gt; The data does not arrive in order — a phone goes into a tunnel and buffers ninety seconds of events, a partition stalls, a clock skews — so the window that closed at 10:05 is missing the event stamped 10:04:30 that shows up at 10:07. The season's benchmark hook is the price of that decision: in the companion notebook's seeded simulation (seed 42, 100,000 events over one hour, 1.9% stragglers delayed 60–600 s), a 10-second watermark bound drops 2.05% of events, and the first result undercounts revenue by 2.2% — $101,785 missing from $4,577,683 — in &lt;em&gt;every&lt;/em&gt; window.&lt;/p&gt;

&lt;p&gt;The numbers below come from that simulation: late fractions at six watermark bounds, allowed-lateness rescue rates, first-fire vs. true revenue per window, and session counts at three gap sizes.&lt;/p&gt;

&lt;h2&gt;
  
  
  The ELI5 version
&lt;/h2&gt;

&lt;p&gt;A stream is a river of events, each stamped with the time it &lt;em&gt;happened&lt;/em&gt;. A window is a bucket you hold under the river for a fixed stretch — say, 10:00 to 10:05 — and then you count what landed in it. The problem is the bucket has no lid: events stamped 10:04 keep arriving after 10:05, because the network, not the clock, decides when they show up.&lt;/p&gt;

&lt;p&gt;So streaming systems cut the river with &lt;strong&gt;three kinds of windows&lt;/strong&gt;, and then decide when each bucket is done:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tumbling windows&lt;/strong&gt; are fixed, non-overlapping buckets: 10:00–10:05, 10:05–10:10, one event in exactly one bucket. The default for "revenue per 5 minutes."&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Sliding windows&lt;/strong&gt; overlap: a 5-minute window that slides every minute gives you a fresh 5-minute total every 60 seconds. Same aggregation, 5x the window-state writes — every event lands in 5 windows instead of 1.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Session windows&lt;/strong&gt; have no fixed size at all: a new window starts when activity resumes after a quiet gap. The gap &lt;em&gt;is&lt;/em&gt; the definition — pick 5 minutes and one user's evening is 4 sessions; pick 15 minutes and it is 1.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fngpfqle0gu5nmq1e3r9o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fngpfqle0gu5nmq1e3r9o.png" alt="Three ways to cut a stream into windows: tumbling buckets that never overlap, sliding windows that overlap on a 1-minute slide, and session windows that start after a quiet gap." width="800" height="320"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Event time vs. processing time: the only distinction that matters
&lt;/h2&gt;

&lt;p&gt;Every event carries two clocks. &lt;strong&gt;Event time&lt;/strong&gt; is when the thing happened, stamped into the event itself. &lt;strong&gt;Processing time&lt;/strong&gt; is when your system saw it. The gap between them is skew, and late data is just skew that exceeds your tolerance.&lt;/p&gt;

&lt;p&gt;Window on processing time and your results depend on how fast your cluster ran that day — replay the same input and you get different windows. Window on event time and the results are reproducible: the same input always produces the same windows, no matter how slow the ingestion was. The rule, almost without exception: &lt;strong&gt;window and aggregate on event time.&lt;/strong&gt; Processing-time windows are fine for operational metrics ("events ingested per second"), but the moment a business cares about "revenue in the 10:00 hour," you need event time — and the moment you need event time, you need a way to decide when a window is done.&lt;/p&gt;

&lt;h2&gt;
  
  
  Watermarks: a promise about the past
&lt;/h2&gt;

&lt;p&gt;A &lt;strong&gt;watermark&lt;/strong&gt; is the streaming system's estimate of event-time progress. A watermark of &lt;code&gt;T&lt;/code&gt; is an assertion: &lt;em&gt;"I believe I have seen all events with timestamp ≤ T; anything older that shows up now is late."&lt;/em&gt; It is a promise, not a fact — and like all promises about distributed systems, it is sometimes broken. That is the point: the watermark is the policy knob that decides where you draw the line between "on time" and "late."&lt;/p&gt;

&lt;p&gt;The most common strategy is &lt;strong&gt;bounded out-of-orderness&lt;/strong&gt;: assume events can be at most &lt;code&gt;N&lt;/code&gt; seconds out of order, and set the watermark to &lt;code&gt;max event time seen − N&lt;/code&gt;. In Flink:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;WatermarkStrategy
    .&amp;lt;Event&amp;gt;forBoundedOutOfOrderness(Duration.ofSeconds(10))
    .withTimestampAssigner((event, ts) -&amp;gt; event.getOccurredAtMillis())
    // critical for partitioned sources: don't let a quiet partition
    // stall the global watermark forever
    .withIdleness(Duration.ofMinutes(1));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;An operator with several inputs takes the &lt;strong&gt;minimum&lt;/strong&gt; of their watermarks — one slow Kafka partition holds the whole watermark back — which is why &lt;code&gt;withIdleness&lt;/code&gt; exists: a silent partition must not freeze every window downstream.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Frp5jab5gfxh05ky83g9p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Frp5jab5gfxh05ky83g9p.png" alt="One 5-minute window seen through the watermark: the window fires when the watermark passes 10:05, and the event stamped 10:04:30 that arrives after that is late and dropped." width="800" height="440"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The bound is a latency-vs-completeness dial
&lt;/h2&gt;

&lt;p&gt;The choice of &lt;code&gt;N&lt;/code&gt; is a direct trade: a bigger bound waits longer before emitting results (more latency) and drops fewer late events (more completeness). The simulation measures it. With 100,000 events, a 5-minute window, median arrival delay 5.7 s but a p99 of 329.6 s (the stragglers), the late fraction falls steeply at first, then flattens — because the tail is not normal lateness, it is a different population:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fw8wdowufa22sevj5os4v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fw8wdowufa22sevj5os4v.png" alt="Events dropped as late against the watermark bound: 3.64% at 0 s, 2.05% at 10 s, 1.29% at 60 s, 0.47% at 300 s — the curve flattens because the tail is stragglers, not jitter." width="800" height="460"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;At a 0-second bound, 3.64% of events are late. At 10 seconds — the value most tutorials start with — 2.05%. At 60 seconds, 1.29%. At 300 seconds, 0.47%. Notice what the curve says: going from 10 s to 300 s buys you 30x the latency for a 4x reduction in drops. The last half-percent is stragglers with 60–600 s of extra delay, and no reasonable bound catches them — you would have to hold every window for ten minutes to get them all, which is not a streaming system anymore, it is a batch job with extra steps.&lt;/p&gt;

&lt;p&gt;Choose the bound from data, not from a tutorial: measure how late events actually arrive, per source, and pick a bound that covers the bulk of them. The shape of your delay distribution is the answer; the default is a guess.&lt;/p&gt;

&lt;h2&gt;
  
  
  The money version: first results lie by a fixed percentage
&lt;/h2&gt;

&lt;p&gt;The revenue version makes the cost concrete. Each event in the simulation is an order worth ~$50 (lognormal). At a 10-second bound with no allowed lateness, the first result for each 5-minute window undercounts the true revenue by 2.0–2.5% — every window, not just the bad ones. Across the hour, the first-fire total is $4,475,898 against a true $4,577,683: &lt;strong&gt;$101,785 missing, 2.22%&lt;/strong&gt;, silently, on a dashboard that shows no error. The first result is not wrong in a way anyone notices — it is wrong by the exact percentage of events that were late, which is why it is dangerous: it is stable, plausible, and short by the same amount every day, until someone reconciles against the batch numbers and finds the gap has been there for months.&lt;/p&gt;

&lt;h2&gt;
  
  
  Allowed lateness: rescue the stragglers, pay in corrections
&lt;/h2&gt;

&lt;p&gt;Whatever the bound, some events arrive after the watermark passes their window. Flink offers three ways to handle them, and they combine:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Drop them&lt;/strong&gt; — the default for windows. Fine when a small loss doesn't matter, such as dashboards.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Allowed lateness&lt;/strong&gt;: keep the window's state for a while after it fires, and emit an updated result when a straggler arrives. Downstream must accept updates — an upsert sink keyed by window, or a consumer that handles corrections. Allowed lateness applies only to event-time windows; the default is &lt;code&gt;0&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A side output&lt;/strong&gt;: route anything later still to a separate stream, to be stored, counted, or reconciled in batch (&lt;code&gt;sideOutputLateData&lt;/code&gt;). The too-late events don't vanish; they go somewhere you can audit.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The simulation, at a 10-second bound: a 60-second allowed lateness rescues 798 of the 2,049 late events (drops fall to 1,251) and emits 798 corrected results. A 300-second lateness rescues 1,611 (drops fall to 438). A 600-second lateness rescues all 2,049 — zero drops — and emits 2,049 re-fires, one per straggler.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fek4p567b1r0cm6poz3nm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fek4p567b1r0cm6poz3nm.png" alt="Allowed lateness at a 10-second watermark bound: drops fall from 2,049 to 0 as lateness grows to 600 s, while window re-fires rise from 0 to 2,049 — every rescued event is a corrected result downstream must handle." width="800" height="460"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;That is the real price of allowed lateness: not state (though windows live longer, so state grows with it), but &lt;strong&gt;multiplicity&lt;/strong&gt;. The same window emits several results, and every consumer downstream must treat them as updates. An append-only sink that sums every result it receives will double-count every correction — the fix for late data becomes a bug in the dashboard. The reconciliation pattern from the late-data literature is the honest end state: stream the fast-but-approximate result, then reconcile it against a batch recompute (or an Iceberg table fed by the side output) and let the slow-but-correct number win.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why it breaks: the failure modes, ranked
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;The bound chosen from a tutorial, not from the delay distribution.&lt;/strong&gt; A 10-second bound on a source whose p99 delay is 330 seconds drops 2% of events forever, and the dashboard never flags it — the loss is silent by design.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The idle partition that freezes the watermark.&lt;/strong&gt; One quiet Kafka partition holds the minimum watermark back, no window fires, and the whole pipeline looks stalled. &lt;code&gt;withIdleness&lt;/code&gt; is a one-line fix that most pipelines learn about in production.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Allowed lateness into an append-only sink.&lt;/strong&gt; The window re-fires with a corrected total; the sink adds it to the first total; revenue is now overstated by the correction. The lateness fix and the sink contract have to be designed together.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Session gaps picked by feel.&lt;/strong&gt; A 60-second gap splits one user's evening into 7 sessions; a 900-second gap merges it into 1. The gap is not a tuning parameter — it is the definition of a session, and it changes the answer by 7x.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Sliding windows priced as if they were free.&lt;/strong&gt; A 5-minute window on a 1-minute slide is 5x the window-state writes of the tumbling equivalent. Freshness has a state bill, and it arrives as checkpoint size and recovery time.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Processing-time windows for business numbers.&lt;/strong&gt; The results change with cluster speed, replays disagree with production, and nobody can explain why Tuesday's revenue differs from the rerun of Tuesday's revenue.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;A watermark is a promise about the past, not a fact.&lt;/strong&gt; &lt;code&gt;max event time seen − N&lt;/code&gt; is the policy knob; &lt;code&gt;N&lt;/code&gt; trades latency for completeness, and the shape of your delay distribution — not a tutorial default — picks it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The late fraction falls steeply, then flattens.&lt;/strong&gt; 3.64% at a 0 s bound, 2.05% at 10 s, 0.47% at 300 s. The tail is stragglers (60–600 s), and no reasonable bound catches them.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;First results undercount by the late rate, silently.&lt;/strong&gt; At a 10 s bound: $101,785 missing from $4,577,683 (2.22%), every window 2.0–2.5% short. Reconcile against batch, or the gap lives for months.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Allowed lateness trades drops for corrections.&lt;/strong&gt; 600 s of lateness rescues all 2,049 late events and emits 2,049 re-fires — downstream must upsert, not append.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The session gap is the definition.&lt;/strong&gt; 60 s → 7 sessions, 300 s → 4, 900 s → 1, from the same 66 events. And a 1-minute slide on a 5-minute window costs 5x the state of tumbling.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Follow for Season 3, Part 3 — event sourcing &amp;amp; CQRS — on &lt;a href="https://dev.to/danielsamfdo"&gt;dev.to/danielsamfdo&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Honesty note: late fractions, allowed-lateness rescue rates, revenue undercounts, and session counts are this notebook's seeded simulation (seed 42, N=100,000 events over 1 hour, 5-minute tumbling windows, arrival delay exponential with an 8 s mean, 1.9% stragglers with 60–600 s extra delay, order values lognormal ~$50) — toy-model measurements, not production telemetry. Flink semantics (bounded out-of-orderness, &lt;code&gt;withIdleness&lt;/code&gt;, minimum-of-inputs watermarks, allowed lateness, side outputs) are from Flink's documented behavior as of the 2026 write-ups cited in the research; Kafka Streams and Spark Structured Streaming share the concepts with different defaults. No Meta content per the standing exclusion.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Companion notebook: &lt;code&gt;stream_windows_watermarks.ipynb&lt;/code&gt; — delay distribution, late fraction vs. bound, allowed-lateness trade-off, first-fire vs. true revenue, session-gap sensitivity, sliding-vs-tumbling state cost, all exec-tested.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Companion notebook:&lt;/strong&gt; the runnable tutorial for this post — &lt;a href="https://danielsamfdo.github.io/blog/assets/stream_windows_watermarks.ipynb" rel="noopener noreferrer"&gt;download it here&lt;/a&gt; (open in Colab/Jupyter).&lt;/p&gt;

</description>
      <category>systemdesign</category>
      <category>architecture</category>
      <category>programming</category>
      <category>softwareengineering</category>
    </item>
    <item>
      <title>Cutting Your LLM API Bill: 5 Levers, Measured</title>
      <dc:creator>Daniel Sam Pete Thiyagu</dc:creator>
      <pubDate>Tue, 01 Dec 2026 03:57:28 +0000</pubDate>
      <link>https://dev.to/danielsamfdo/cutting-your-llm-api-bill-5-levers-measured-1107</link>
      <guid>https://dev.to/danielsamfdo/cutting-your-llm-api-bill-5-levers-measured-1107</guid>
      <description>&lt;p&gt;Token prices keep falling and your bill keeps rising. That is not a paradox — it is arithmetic. Agentic workflows burn 5 to 30 times more tokens per task than a chatbot query, so consumption outruns the price drop. Enterprise generative AI spend hit $37 billion in 2025, up 3.2x in a year, and a 2026 survey of 101 enterprise technology leaders found 43% already spending more on AI than they budgeted. The fix is not a cheaper model. It is five levers, each with a measured payoff, that stack. This is GDE post #13, and it answers one question: &lt;strong&gt;what does each lever actually save on a real workload?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The numbers below are measured arithmetic, not quoted: every figure comes from the companion notebook, computed from published provider list prices checked Nov 30, 2026. The workload is a support agent doing 1,000,000 requests a month — 2,400 input tokens per request (1,800 stable system prompt and docs, 600 fresh) and 500 output tokens, on Claude Sonnet 5.5. The headline: &lt;strong&gt;the baseline bill is $9,800 a month, and the four cheap levers cut it to $3,088 — a 68.5% cut — before self-hosting is even on the table.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The ELI5 version
&lt;/h2&gt;

&lt;p&gt;An LLM bill is two numbers multiplied: tokens times price per token. Input tokens cost less than output tokens — on Sonnet 5.5, $2 versus $10 per million — and every lever attacks one side of that multiplication. Caching makes repeated input tokens nearly free. Batching halves the price of work that can wait. Routing sends easy requests to cheap models. Token discipline sends fewer tokens. Self-hosting replaces the price per token with a GPU you own. None of these is exotic. The expensive habit is the default: every request to the frontier model, uncached, synchronously, with the full conversation history attached.&lt;/p&gt;

&lt;h2&gt;
  
  
  Lever 1: prompt caching — the cheapest 33%
&lt;/h2&gt;

&lt;p&gt;Every time you resend a system prompt, tool definitions, or a document, you pay full input price for the model to read it again. Caching lets the provider skip the re-read — and the discount is the largest of any lever on the tokens it touches.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0lxuxi209jh1ah1ju955.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0lxuxi209jh1ah1ju955.png" alt="Cache read price versus full input price by provider: Sonnet 5.5 $0.10 vs $2.00, GPT-5 $0.125 vs $1.25, Gemini 2.5 Pro $0.125 vs $1.25, Gemini 2.5 Flash $0.03 vs $0.30." width="800" height="409"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;On Sonnet 5.5 a cache read costs $0.10 per million tokens against a $2.00 input price — 5% of the price, a 95% discount. OpenAI caches automatically at roughly 50% off, and its cached GPT-5 tokens list at $0.125 against $1.25 input. Gemini 2.5 Pro lists cached input at $0.125 against $1.25, and explicit caching through Vertex AI drops cached tokens to 10% of the standard input rate. The rule that makes it work: put stable content first. System prompts, tool definitions, and reference documents go at the top of the context window, before anything that changes request to request.&lt;/p&gt;

&lt;p&gt;On the workload, 75% of input is a stable prefix. Caching takes the bill from $9,800 to $6,605 — a 32.6% cut from one change. The honest caveat is the write cost: writing the cache costs 1.25x the input price, so churn matters. The notebook runs the sensitivity: even if 20% of cached tokens are re-written every month, the bill is $7,280 — still a 25.7% cut. At 50% churn it is $8,630, and the lever is nearly dead. Caching pays when the same prefix is re-read many times between writes, which is exactly what chat and agent workloads do. One-off requests with no repeated structure get nothing from it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Lever 2: batching — the free 50%
&lt;/h2&gt;

&lt;p&gt;If a workload can tolerate a delay, batching is close to a free discount. OpenAI's Batch API and Anthropic's Message Batches API both cut input and output token prices by 50% in exchange for a processing window of up to 24 hours instead of a real-time response.&lt;/p&gt;

&lt;p&gt;Good candidates: model evals and offline test runs, bulk classification, document summarization that does not feed a live user, nightly data enrichment. Bad candidates: anything a user is waiting on — live chat, real-time agent responses, interactive coding assistants. The mistake teams make is leaving async-eligible work on the synchronous API out of habit.&lt;/p&gt;

&lt;p&gt;On the workload, 35% of requests are async-eligible. Moving them to batch takes the bill from $6,605 to $5,449 — a 44.4% cumulative cut — with zero quality tradeoff. Same model, same tokens, half the price. This is the lever with the least to argue about: if the work does not need an answer now, it should not pay the synchronous price.&lt;/p&gt;

&lt;h2&gt;
  
  
  Lever 3: model routing — the 100x spread
&lt;/h2&gt;

&lt;p&gt;The price spread between the cheapest usable model and the frontier runs to roughly 100x, and on the models in the notebook it is 300x: GPT-5 nano lists $0.05 per million input tokens, GPT-5 Pro lists $15. Most requests do not need the $15 model. Routing is the lever that exploits that spread.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Femy0tbkujgnlswaxsvoa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Femy0tbkujgnlswaxsvoa.png" alt="Input price per million tokens across ten models, log scale: GPT-5 nano $0.05, Gemini 2.5 Flash-Lite $0.10, GPT-5 mini $0.25, Gemini 2.5 Flash $0.30, DeepSeek V4 Pro $0.435, GPT-5 $1.25, Gemini 2.5 Pro $1.25, Claude Sonnet 5.5 $2.00, Claude Sonnet 4.5 $3.00, GPT-5 Pro $15.00." width="800" height="462"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Two approaches work. Static rules classify requests ahead of time: simple extraction and formatting go to a cheap model, multi-step reasoning goes to the frontier model. Learned routers do it per request: the RouteLLM framework showed a trained router choosing between a strong and weak model cut costs by more than 2x on benchmarks without compromising response quality, and the result held up even when the underlying models were swapped at test time. In production, teams running a tuned routing layer report bill reductions of 40 to 85%. Ramp's internally built router processes more than 2.75 trillion tokens a month and cut internal LLM costs by 30% with no drop in performance.&lt;/p&gt;

&lt;p&gt;On the workload, 55% of synchronous requests are simple — classification, extraction, FAQ — and they move to Gemini 2.5 Flash at $0.30/$2.50. One request costs $0.006605 on Sonnet 5.5 and $0.001518 on Flash, 4.4x cheaper. The bill goes from $5,449 to $3,630, a 63.0% cumulative cut. The risk is quality regression: a router tuned on the wrong signal sends hard requests to a cheap model. Test it against a held-out set of your actual hard cases, not average traffic, before you trust it in production.&lt;/p&gt;

&lt;h2&gt;
  
  
  Lever 4: token discipline — free, and it compounds
&lt;/h2&gt;

&lt;p&gt;This lever costs nothing to implement. If your system prompt is 2,000 tokens and you resend it uncached on every one of 200 calls in a session, that is 400,000 tokens spent re-reading the same instructions. Three habits fix most of the waste: trim conversation history — summarize or truncate once a conversation passes a reasonable length instead of sending the whole log; set output token limits — an unbounded max-tokens setting on a verbose model is an invitation to overpay for output nobody reads; and compact context in agentic loops — periodically compress accumulated tool outputs and intermediate reasoning into a summary instead of carrying the full trace forward.&lt;/p&gt;

&lt;p&gt;On the workload, trimming fresh input 20% (600 to 480 tokens) and capping output 15% (500 to 425) takes the bill from $3,630 to $3,088. It is the smallest single cut, but it compounds with every other lever because it shrinks the tokens the other levers price. None of this requires new infrastructure. It requires someone to actually look at what is in the context window on a representative request and ask whether it needs to be there.&lt;/p&gt;

&lt;h2&gt;
  
  
  Lever 5: self-hosting — only past the threshold
&lt;/h2&gt;

&lt;p&gt;Self-hosting is the lever with the highest setup cost and the biggest potential payoff, but only past a real volume threshold. The notebook does the crossover math on owned hardware: one RTX 4090-class GPU ($1,600) runs Gemma 3 27B in 4-bit at about 60 tokens/s sustained — 5.18M tokens a day. Amortized over 24 months plus power at $0.12/kWh, that GPU costs about $3.20 a day. The API charges this workload $3.38 per million tokens blended. Divide one by the other and the crossover is about 0.95M tokens a day: below it the API wins, above it owned hardware wins.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8o2j0ciyplgqctxpryfp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8o2j0ciyplgqctxpryfp.png" alt="Monthly cost versus daily token volume, log-log: the API line and the owned-GPU step line cross at about 0.95M tokens per day." width="800" height="409"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The payback numbers explain why the threshold is where it is. A single GPU pays for itself in about 91 days against Sonnet 5.5's blended price — and in about 10 days against a premium API at roughly $30 per million blended, which is where the often-quoted 0.3-month break-even for small open models comes from. But the workload tells the harder truth: this workload burns 96.7M tokens a day, which needs 19 GPUs. Rented at $1 an hour, that fleet costs $13,680 a month — worse than the tuned API bill of $3,088. Owned, it costs $1,841 a month — but that takes $30,400 of capex, operations labor, and a model-quality swap: a 27B open model is not Sonnet 5.5. Self-hosting is the right lever when volume is high, the open model is good enough for the task, and you are willing to operate GPUs. It is the wrong lever as a first move.&lt;/p&gt;

&lt;h2&gt;
  
  
  The stack, in order
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F90ze7d2552jmosxp0mi0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F90ze7d2552jmosxp0mi0.png" alt="Monthly bill after each lever: baseline $9,800, caching $6,605, batching $5,449, routing $3,630, token discipline $3,088, self-hosting owned $1,841 with $30,400 capex." width="800" height="409"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The levers stack, and they stack in a sensible order. Start with caching and token discipline — near-zero implementation cost, applies to almost any workload immediately. Add batching for anything async-eligible. Add routing once traffic has volume and variety, because a router only pays off once you have enough request diversity to tell easy from hard. Consider self-hosting only past the volume or compliance threshold — below roughly 1 to 2 million tokens a day, the API is still cheaper once labor is counted. A team running the first four levers is not doing anything exotic. It is just not leaving money on the table at any layer of the stack — $9,800 down to $3,088, and $1,841 if the volume and the model justify owning the hardware.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Caching is the cheapest lever.&lt;/strong&gt; 75% of this workload's input is a stable prefix; cache reads at 5–10% of input price take the bill from $9,800 to $6,605.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Batching is a free 50%.&lt;/strong&gt; 35% async-eligible traffic, same model, same tokens: $6,605 to $5,449.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Routing exploits a 100–300x spread.&lt;/strong&gt; 55% of sync requests to Gemini 2.5 Flash: $5,449 to $3,630. Per request, $0.006605 on Sonnet 5.5 versus $0.001518 on Flash.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Token discipline compounds.&lt;/strong&gt; 20% less fresh input, 15% less output: $3,630 to $3,088 — a 68.5% total cut from the four cheap levers.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Self-hosting has a threshold, about 1M tokens a day.&lt;/strong&gt; Below it the API wins; above it owned hardware wins. Renting GPUs at $1/hr loses to the tuned API stack on this workload.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The default is the expensive habit.&lt;/strong&gt; Every request to the frontier model, uncached, synchronously, is a choice — and it costs $9,800 where $3,088 does the job.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Honesty note: all dollar figures are computed in the notebook from published provider list prices checked Nov 30, 2026 (Anthropic Sonnet 5.5 $2/$10, cache read $0.10, batch $1/$5; OpenAI GPT-5 $1.25/$10, cached $0.125; Gemini 2.5 Pro $1.25/$10, Flash $0.30/$2.50, cached $0.03; DeepSeek V4 Pro $0.435/$0.87 from a June 2026 listing). Sonnet 4.5 ($3/$15) retired Nov 30, 2026, so Sonnet 5.5 is the anchor. The workload is a stated model — 1M requests/month, 2,400 in / 500 out tokens — not production telemetry; cache churn (5%), async share (35%), and routed share (55%) are stated assumptions, with a churn sensitivity table in the notebook. GPU throughput (60 tok/s sustained) is a working number under the GDE #12 roofline of ~74 tok/s; GPU rental at $1/hr and power at $0.12/kWh are stated assumptions. Enterprise spend and survey figures are reported figures from a 2026 survey of 101 enterprise technology leaders, not this notebook's measurements. Prices move — re-check the provider pages before you budget. No Meta content per the standing exclusion.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Companion notebook: &lt;code&gt;llm_api_cost_levers.ipynb&lt;/code&gt; — published price table with blended 3:1 costs and the 300x routing spread, baseline bill, caching with churn sensitivity, batching, routing by per-request cost, token discipline, the stacked waterfall, and the self-hosting crossover and payback math, all exec-tested.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Companion notebook:&lt;/strong&gt; the runnable tutorial for this post — &lt;a href="https://danielsamfdo.github.io/blog/assets/llm_api_cost_levers.ipynb" rel="noopener noreferrer"&gt;download it here&lt;/a&gt; (open in Colab/Jupyter).&lt;/p&gt;

</description>
      <category>vllm</category>
      <category>llm</category>
      <category>googlecloud</category>
      <category>agents</category>
    </item>
    <item>
      <title>System Design, Plainly — Season 3, Part 1: Message Queues: At-Least-Once vs Exactly-Once</title>
      <dc:creator>Daniel Sam Pete Thiyagu</dc:creator>
      <pubDate>Mon, 30 Nov 2026 17:12:04 +0000</pubDate>
      <link>https://dev.to/danielsamfdo/system-design-plainly-season-3-part-1-message-queues-at-least-once-vs-exactly-once-6c3</link>
      <guid>https://dev.to/danielsamfdo/system-design-plainly-season-3-part-1-message-queues-at-least-once-vs-exactly-once-6c3</guid>
      <description>&lt;p&gt;Season 3 opens where Season 1 left off. Part 4 of Season 1 introduced message queues — the async decoupling that lets a service answer in 2 ms instead of 200. This part is the question every queue eventually forces on you: &lt;strong&gt;when a message is sent, how many times does it actually get processed?&lt;/strong&gt; The answers have names — at-most-once, at-least-once, exactly-once — and the season's benchmark hook is the price of each: at a 1% crash rate, at-least-once duplicates ~1,000 messages per 100,000, and at $50 an order that is $50,000 a day of double charges unless something downstream catches them.&lt;/p&gt;

&lt;p&gt;The numbers below come from the companion notebook's seeded simulation (seed 42, 100,000 messages): duplicates and losses scale linearly with the crash rate, a 5-minute dedup window lets 1 retry in 22,000 escape, and the outbox pattern is the only construction here that reaches zero inconsistency — 101 inconsistent orders without it, 0 with it.&lt;/p&gt;

&lt;h2&gt;
  
  
  The ELI5 version
&lt;/h2&gt;

&lt;p&gt;A message queue is a post office for services. The producer drops a letter in the box; the broker holds it; the consumer picks it up and does the work. The problem is the crash in the middle: the producer sends the letter, the broker receives it, and then the producer crashes &lt;em&gt;before it hears the confirmation&lt;/em&gt;. Did the letter arrive? The producer cannot know — so it has to choose a policy, and every policy is a trade.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;At-most-once&lt;/strong&gt; means the producer sends once and never retries: if the letter was lost, it is gone forever. Fast, simple, and wrong for anything that matters — a lost payment confirmation is a customer who paid and got nothing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;At-least-once&lt;/strong&gt; means the producer retries until it gets a confirmation: the letter always arrives, but sometimes twice. The consumer has to handle the duplicate — charge the card once, not twice — which is where idempotency comes in.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exactly-once&lt;/strong&gt; means the letter arrives once and is processed once, even across crashes. It is real inside a single system (Kafka can do it, end to end, within Kafka), and it is a polite fiction the moment the work leaves that system — the consumer that charges a credit card cannot un-charge it if it crashes halfway through. The honest version of exactly-once is &lt;strong&gt;at-least-once delivery plus an idempotent consumer&lt;/strong&gt;: duplicates may arrive, but they produce no visible effect.&lt;/p&gt;

&lt;h2&gt;
  
  
  The math: duplicates scale with the crash rate
&lt;/h2&gt;

&lt;p&gt;The simulation sends 100,000 messages with a crash after the send but before the acknowledgment, at crash rates from 0.1% to 5%. Under at-least-once, every crash becomes exactly one duplicate on retry — the count is linear in the crash rate, which is why the failure mode is so predictable and so easy to underestimate.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fj9jgyvtxvubldyeqwygx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fj9jgyvtxvubldyeqwygx.png" alt="Expected duplicates per 100,000 messages against crash rate: at-least-once goes from 104 duplicates at 0.1% to 5,064 at 5%, while an idempotent consumer shows zero visible duplicates at every rate." width="800" height="416"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;At 0.1% — a healthy system — that is 104 duplicates per 100,000 messages: background noise, easy to dismiss. At 1%, it is 998. At 5%, during a bad deploy or a flapping network, it is 5,064 — one message in twenty processed twice. The same count is the loss under at-most-once: 998 messages per 100,000 simply never arrive. The two policies are mirror images, and the mirror is the crash: &lt;strong&gt;at-most-once loses what at-least-once duplicates&lt;/strong&gt;, and the rate is the same number.&lt;/p&gt;

&lt;p&gt;The money version: 100,000 orders a day at $50 each, a 1% crash rate, no idempotency. That is ~1,000 double charges a day, $50,000 a day of duplicate exposure, and every one of them looks like a successful order on the dashboard. This is why payment systems were the first to standardize idempotency keys — Stripe retains them for 24 hours, and the pattern is now an IETF draft (draft-ietf-httpapi-idempotency-key-header-07, October 2025).&lt;/p&gt;

&lt;h2&gt;
  
  
  Idempotency keys and the dedup window
&lt;/h2&gt;

&lt;p&gt;An idempotency key is a promise attached to the work: &lt;em&gt;this request is order #48291, and if you see it again, return the first answer instead of doing it again.&lt;/em&gt; The consumer keeps a table of keys it has already processed, and a duplicate is a lookup, not a second charge. Three rules make it work: the key must be generated by the &lt;em&gt;caller&lt;/em&gt; (a retry reuses the same key; a new request gets a new one), the stored result must include the response (so the retry returns the same answer, not just a shrug), and the key must live longer than the longest possible retry.&lt;/p&gt;

&lt;p&gt;That last rule is where dedup windows bite. SQS FIFO deduplicates within a 5-minute window; Stripe keeps keys for 24 hours. If a retry arrives after the window closes, the key is gone and the duplicate sails through. The notebook models retry delay as exponential with a 30-second mean: a 60-second window lets 13.5% of retries escape, a 5-minute window lets 1 in 22,000 through, and a 24-hour window is effectively zero.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0yaum0f64yp5yt77o7s2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0yaum0f64yp5yt77o7s2.png" alt="Probability a retry arrives after the dedup window closes, against window length: 13.5% at 60 seconds, 1 in 22,000 at 5 minutes (SQS FIFO), effectively zero at 24 hours (Stripe)." width="800" height="416"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The window is a trade, not a detail: a short window is cheap storage and a small escape hatch; a long window is a bigger table and a smaller hatch. Pick the window from your retry policy, not from the default — if your client retries for an hour, a 5-minute window is a hole, not a guarantee.&lt;/p&gt;

&lt;h2&gt;
  
  
  Exactly-once, honestly: Kafka's three mechanisms
&lt;/h2&gt;

&lt;p&gt;Kafka is the system that gets closest to true exactly-once, and it does it in three layers, each extending the guarantee one step further:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;The idempotent producer&lt;/strong&gt; (default since Kafka 3.0): every producer gets an ID, every message gets a sequence number per partition, and the broker drops a retried duplicate. Cost: negligible. Limit: it only covers one producer session — restart the producer and the sequence resets.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The transactional producer&lt;/strong&gt;: a &lt;code&gt;transactional.id&lt;/code&gt; that survives restarts, a transaction coordinator, and commit/abort markers on every partition. The producer can write to multiple partitions and commit its consumer offsets in the same atomic transaction — the consume-transform-produce pattern. This is real exactly-once, but only within Kafka.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Exactly-once in Kafka Streams&lt;/strong&gt; (&lt;code&gt;processing.guarantee=exactly_once_v2&lt;/code&gt;): the same machinery, packaged for stream processing.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The cost is real and measurable. An independent 2026 benchmark (3 brokers, replication factor 3, 1 KB messages) put transactions at 850K → 600K messages/s — a 29% throughput drop — and p99 latency at 15 → 45 ms, a 3x increase. Confluent's original 2017 figures were kinder: ~3% throughput cost versus ordered at-least-once, ~20% versus acks=1. Kafka Streams shows the shape of the trade clearly: 15–30% overhead at a 100 ms commit interval, dropping to near zero at a 30-second interval. The knob is the commit interval — overhead is per-commit, so longer intervals amortize it, at the price of longer replays on recovery.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fajxbwq0yj59kwm1537bs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fajxbwq0yj59kwm1537bs.png" alt="Kafka exactly-once cost from the 2026 benchmark: producer throughput 850K to 600K messages/s, a 29% drop; p99 latency 15 to 45 ms, a 3x increase." width="800" height="416"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And the boundary matters more than the benchmark. Kafka's own docs say transactions give exactly-once delivery when reading, processing, and writing Kafka topics, and that exactly-once for other destination systems "generally requires cooperation with such systems." The moment your consumer calls a payment gateway, sends an SMS, or writes to a database outside the Kafka transaction, the guarantee ends at the topic boundary. Kleppmann's one-line summary of the field is the honest version: &lt;strong&gt;exactly-once means retry plus idempotence or deduplication.&lt;/strong&gt; Everything else is scope.&lt;/p&gt;

&lt;h2&gt;
  
  
  The outbox pattern: exactly-once effects without exactly-once delivery
&lt;/h2&gt;

&lt;p&gt;The most common place exactly-once dies is the dual-write: the service writes a row to its database, then publishes an event to the queue, and crashes between the two. The row exists; the event never happened. Downstream services never learn about the order, the inventory never decrements, and nothing in the logs says anything failed — because from each system's point of view, nothing did.&lt;/p&gt;

&lt;p&gt;The outbox pattern fixes it with one atomic transaction: the service writes the business row &lt;em&gt;and&lt;/em&gt; an outbox row in the same database transaction, and a separate relayer reads the outbox and publishes to the queue, retrying until it succeeds. The crash can happen anywhere — before the transaction, after it, mid-publish — and the outcome is the same: the event is published exactly once &lt;em&gt;in effect&lt;/em&gt;, because the outbox row survives any crash and the relayer retries until the broker confirms.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fo1hzh2r5xbanx7rlx5l9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fo1hzh2r5xbanx7rlx5l9.png" alt="Dual-write versus outbox: a crash between the database write and the publish leaves the event lost; the outbox writes both rows in one transaction and a relayer publishes until confirmed." width="800" height="448"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The simulation makes the difference concrete: 10,000 orders, a 1% crash between the database write and the publish. Dual-write leaves 101 orders with a committed row and no event — invisible to every downstream system. The outbox leaves 0. The relayer's retries can still duplicate the &lt;em&gt;publish&lt;/em&gt;, so the consumer still needs an idempotency key — the outbox guarantees the event exists, the key guarantees it is processed once. The two patterns are a pair, not alternatives.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why it breaks: the failure modes, ranked
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;The retry without a key.&lt;/strong&gt; A retried payment, a retried order, a retried side effect — the duplicate that looked like a success on every dashboard. The fix is an idempotency key on every non-idempotent operation, generated by the caller.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The dedup window shorter than the retry horizon.&lt;/strong&gt; A client that retries for an hour against a 5-minute window will eventually duplicate, and the duplicate will arrive on the quietest day, months after the window was chosen.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The dual-write.&lt;/strong&gt; Two systems, one crash between them, and an inconsistency that no retry can repair because the first write already committed. The outbox is the fix, and it is a one-table change.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Exactly-once claimed past its boundary.&lt;/strong&gt; A pipeline that is exactly-once inside Kafka and at-least-once the moment it calls an external API — and the team that believed the label until the duplicate charge.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Ordering assumed, not enforced.&lt;/strong&gt; At-least-once with retries reorders: the retry of message 5 can arrive after message 6. If order matters, the consumer needs a sequence number per key, or a single partition per key — the ordering problem from Season 1, Part 4, wearing a new coat.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;At-most-once loses what at-least-once duplicates, at the same rate.&lt;/strong&gt; 1% crash rate on 100K messages: 998 lost or 998 duplicated. Pick the failure you can afford, then engineer away the other one.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Exactly-once is at-least-once plus an idempotent consumer.&lt;/strong&gt; Kafka's transactions are real, but they end at the topic boundary — the moment work leaves Kafka, the key is the guarantee.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The dedup window must outlive the retry horizon.&lt;/strong&gt; 5 minutes lets 1 retry in 22,000 escape; 24 hours is effectively zero. Size the window from your retry policy, not the default.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Transactions cost 29% of throughput and 3x p99 latency in the 2026 benchmark&lt;/strong&gt; — or ~3% in Confluent's figures against ordered at-least-once. The knob is the commit interval: 15–30% overhead at 100 ms in Kafka Streams, near zero at 30 s.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The outbox is the one-table fix for dual-writes.&lt;/strong&gt; 101 inconsistent orders per 10,000 became 0 in the simulation — and the consumer still needs its idempotency key, because the relayer can duplicate the publish.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Follow for Season 3, Part 2 — stream processing: windows, watermarks &amp;amp; late data — on &lt;a href="https://dev.to/danielsamfdo"&gt;dev.to/danielsamfdo&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Honesty note: duplicate/loss counts, dedup-window escape probabilities, and the outbox comparison are this notebook's seeded simulation (seed 42, N=100,000 messages / 10,000 orders, crash rates 0.1–5%, retry delay exponential with a 30 s mean) — toy-model measurements, not production telemetry. Kafka transaction costs are cited: the 2026 independent benchmark (850K→600K msgs/s, p99 15→45 ms, 3 brokers, RF=3, 1 KB msgs) and Confluent's 2017 figures (3% vs ordered at-least-once, 20% vs acks=1; Streams 15–30% at 100 ms commit, ~0 at 30 s). SQS FIFO's 5-minute dedup window and Stripe's 24-hour key retention are vendor-documented; the IETF idempotency-key draft is draft-07 (October 2025, not yet an RFC). No Meta content per the standing exclusion.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Companion notebook: &lt;code&gt;delivery_semantics.ipynb&lt;/code&gt; — duplicate/loss scaling, dedup-window escape math, outbox vs dual-write simulation, Kafka transaction cost table, all exec-tested.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Companion notebook:&lt;/strong&gt; the runnable tutorial for this post — &lt;a href="https://danielsamfdo.github.io/blog/assets/delivery_semantics.ipynb" rel="noopener noreferrer"&gt;download it here&lt;/a&gt; (open in Colab/Jupyter).&lt;/p&gt;

</description>
      <category>systemdesign</category>
      <category>architecture</category>
      <category>programming</category>
      <category>softwareengineering</category>
    </item>
    <item>
      <title>Gemma 3 with Keras: Run It Locally, Measure It Honestly</title>
      <dc:creator>Daniel Sam Pete Thiyagu</dc:creator>
      <pubDate>Mon, 30 Nov 2026 17:11:57 +0000</pubDate>
      <link>https://dev.to/danielsamfdo/gemma-3-with-keras-run-it-locally-measure-it-honestly-22lm</link>
      <guid>https://dev.to/danielsamfdo/gemma-3-with-keras-run-it-locally-measure-it-honestly-22lm</guid>
      <description>&lt;p&gt;Gemma 3 is the model Google designed to run on &lt;em&gt;your&lt;/em&gt; hardware: 1B, 4B, 12B, and 27B sizes, a 128K context window, and — the part nobody quotes — a sliding-window attention design that makes the KV cache nearly flat as context grows. Keras 3 is the way in: one &lt;code&gt;from_preset&lt;/code&gt; call loads any size, and the same code runs on JAX, TensorFlow, or PyTorch. This is GDE post #12, and it answers the only question that matters before you download 54 GB of weights: &lt;strong&gt;what fits on my machine, and how fast will it go?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The numbers below are measured arithmetic, not quoted: every figure comes from the companion notebook, computed from Gemma 3's published config and cross-checked against an independent memory figure (27B KV cache at 128K: 11.2 GB computed here vs 11.4 GB reported). The headline: &lt;strong&gt;4B in bf16 needs 9.4 GB total at 32K context — it fits a 12 GB card — and 27B in 4-bit needs 16.7 GB, so it fits a 24 GB card.&lt;/strong&gt; The 27B in full bf16 needs 57.5 GB and does not fit any single consumer GPU. That split is the whole post.&lt;/p&gt;

&lt;h2&gt;
  
  
  The ELI5 version
&lt;/h2&gt;

&lt;p&gt;Running a model locally is three numbers added together: the &lt;strong&gt;weights&lt;/strong&gt; (the model itself, fixed size), the &lt;strong&gt;KV cache&lt;/strong&gt; (the model's working memory for the conversation, grows with context length), and a little overhead. Weights dominate. A 4B model in bf16 is 8.6 GB — 4.3 billion parameters times 2 bytes each — and that number does not change no matter how long you chat. The KV cache starts at zero and grows one entry per token per layer, which is why long conversations eventually run out of memory even when the weights fit comfortably.&lt;/p&gt;

&lt;p&gt;Keras 3 is the loading dock. &lt;code&gt;keras_hub.models.Gemma3CausalLM.from_preset("gemma3_instruct_1b")&lt;/code&gt; downloads the weights, builds the model, and hands you a &lt;code&gt;generate()&lt;/code&gt; method — three lines from zero to a working chatbot. The preset names are the sizes: &lt;code&gt;gemma3_1b&lt;/code&gt;, &lt;code&gt;gemma3_4b_text&lt;/code&gt;, &lt;code&gt;gemma3_instruct_4b_text&lt;/code&gt;, plus a 270M model for phones and a 300M embedding model. And Keras 3 has one more trick: &lt;code&gt;keras.config.set_backend("jax")&lt;/code&gt; switches the compute engine under the same model code, so the notebook from yesterday's JAX post and today's Gemma post are the same stack.&lt;/p&gt;

&lt;p&gt;Quantization is the lever that moves models down a tier. bf16 is 2 bytes per parameter; int8 is 1 byte; 4-bit is half a byte. A 27B model goes from 54.4 GB to 13.6 GB, which is the difference between "needs an H100" and "fits a 4090." Google publishes QAT (quantization-aware trained) builds of Gemma 3, trained so they lose less accuracy at 4-bit than a model quantized after the fact — if you run 4-bit, use the QAT build.&lt;/p&gt;

&lt;h2&gt;
  
  
  The weight ladder: size times precision
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fkfocmc6e19q2b0kzg4l9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fkfocmc6e19q2b0kzg4l9.png" alt="Gemma 3 weight memory by size and precision: 1B is 2.0 GB in bf16 and 0.5 GB in 4-bit; 4B is 8.6 GB and 2.1 GB; 12B is 24.4 GB and 6.1 GB; 27B is 54.4 GB and 13.6 GB." width="800" height="416"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The ladder is linear — double the parameters, double the bytes — so the decision is which rung your hardware reaches. A 12 GB card holds 4B in bf16 with room to spare, or 12B in 4-bit. A 24 GB card holds 12B in bf16, or 27B in 4-bit. Nothing consumer-grade holds 27B in bf16: 54.4 GB of weights alone, before a single token of cache.&lt;/p&gt;

&lt;p&gt;The 270M model deserves a mention because it is the one that runs &lt;em&gt;anywhere&lt;/em&gt;: 0.54 GB in bf16, designed for task-specific fine-tuning on a phone or a Raspberry Pi. It is the same architecture, the same Keras preset pattern (&lt;code&gt;gemma3_270m&lt;/code&gt;), and the right answer when the task is narrow — classification, extraction, a single skill — rather than open-ended chat.&lt;/p&gt;

&lt;h2&gt;
  
  
  The KV cache trick: 5 local layers, 1 global layer
&lt;/h2&gt;

&lt;p&gt;Here is the number that changes the fit math. Gemma 3 uses interleaved sliding-window attention: five layers look back only 1,024 tokens, and every sixth layer attends to the full context. At 128K context, 52 of the 27B model's 62 layers stop growing after 1,024 tokens — only 10 layers pay the full-context price.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fpwa29w4dnlqtswgjxuct.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fpwa29w4dnlqtswgjxuct.png" alt="KV cache in bf16 against context length: 27B with the sliding window reaches 11.2 GB at 128K, versus 66.6 GB for dense attention; 4B reaches 2.8 GB at 128K." width="800" height="416"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The arithmetic: each token costs 2 (K+V) × 16 KV heads × 128 head-dim × 2 bytes = 8,192 bytes per layer for 27B. Ten global layers at 128K is 10.7 GB; the 52 local layers cap out at 0.44 GB. Total 11.2 GB — and the independent figure is 11.4 GB, a 2% cross-check that the config math is right. Without the sliding window it would be 66.6 GB, a 6x penalty. For 4B the same math gives 2.8 GB at 128K, which is why the 4B model barely notices long conversations: weights 8.6 GB, cache 2.8 GB, total 11.4 GB at maximum context.&lt;/p&gt;

&lt;p&gt;This is the design lesson worth carrying into the TPU post on Dec 2: &lt;strong&gt;the cache is a choice, not a law.&lt;/strong&gt; Gemma 3 trades a little long-range recall in 5 of 6 layers for a cache that grows 6x slower. When you size a deployment, the cache curve matters as much as the weight size — and most models publish only the weights.&lt;/p&gt;

&lt;h2&gt;
  
  
  How fast: decode is memory-bound
&lt;/h2&gt;

&lt;p&gt;Text generation is a memory problem, not a compute problem. Each generated token reads the entire weight matrix once, so tokens per second is roughly memory bandwidth divided by weight bytes. The notebook computes that roofline — an upper bound, not a promise — for four machines:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fz1w5runlxubw563t1n2u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fz1w5runlxubw563t1n2u.png" alt="Roofline decode speed by hardware: 4B bf16 runs ~5 tokens/s on a laptop CPU, ~14 on an Apple M4, ~117 on an RTX 4090, ~225 on an A100; 27B 4-bit runs ~3, ~9, ~74, and ~142 tokens/s." width="800" height="416"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Two reads. First, the 4B model on an RTX 4090 roofs at ~117 tokens/s — faster than anyone reads, which is why 4B feels instant on a gaming GPU. Second, the 27B in 4-bit roofs at ~74 tokens/s on the same card: still faster than reading speed, which is the honest answer to "can my laptop run a 27B model" — yes, quantized, at usable speed, &lt;em&gt;if&lt;/em&gt; it fits in VRAM. On a laptop CPU the same 4B roofs at ~5 tokens/s: usable for a demo, painful for a conversation. The roofline is an upper bound — real speed is lower once attention, kernels, and overhead are counted — so treat these as the ceiling and measure your own with the &lt;code&gt;generate()&lt;/code&gt; timing code in the notebook.&lt;/p&gt;

&lt;h2&gt;
  
  
  What fits where
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fzsfzdgs002yozn68r41r.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fzsfzdgs002yozn68r41r.png" alt="Total memory (weights plus KV cache at 32K context) per model and precision, against 12, 16, 24, 40, and 80 GB device lines: 1B bf16 2.3 GB, 4B bf16 9.4 GB, 12B bf16 26.9 GB, 27B bf16 57.5 GB; 4-bit totals 0.8, 2.9, 8.6, and 16.7 GB." width="800" height="448"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The fit table, weights plus KV cache at 32K context:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;1B bf16, 2.3 GB total&lt;/strong&gt; — fits anything, including a 4 GB card and a Raspberry Pi 5 (which runs it at 12–19 tokens/s in 4-bit, per independent measurements).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;4B bf16, 9.4 GB total&lt;/strong&gt; — fits a 12 GB card with headroom. This is the sweet spot for local development.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;12B bf16, 26.9 GB total&lt;/strong&gt; — needs a 32 GB card or a 40 GB datacenter GPU; in 4-bit (8.6 GB) it fits a 12 GB card.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;27B bf16, 57.5 GB total&lt;/strong&gt; — needs an 80 GB H100 or two 40 GB cards; in 4-bit (16.7 GB) it fits a 24 GB card.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The pattern to remember: &lt;strong&gt;quantization moves a model down one hardware tier, and the sliding-window cache means context length almost never changes the tier.&lt;/strong&gt; Pick the size by quality, pick the precision by your GPU, and the cache takes care of itself.&lt;/p&gt;

&lt;h2&gt;
  
  
  The code: three lines to a chatbot
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;keras&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;keras_hub&lt;/span&gt;

&lt;span class="n"&gt;keras&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;config&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;set_backend&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"jax"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# or "tensorflow" / "torch"&lt;/span&gt;
&lt;span class="n"&gt;lm&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;keras_hub&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Gemma3CausalLM&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;from_preset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"gemma3_instruct_1b"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;lm&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;generate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Explain gravity in one sentence."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;max_length&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;64&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three things to know before you run it. First, Gemma weights need a one-time Kaggle authentication — &lt;code&gt;from_preset&lt;/code&gt; downloads from Kaggle Models, ~2 GB for 1B, ~54 GB for 27B in bf16. Second, the backend line is optional but worth setting deliberately: JAX is the fastest path on TPU and the backend the rest of this lane assumes. Third, &lt;code&gt;generate()&lt;/code&gt; takes &lt;code&gt;max_length&lt;/code&gt;, &lt;code&gt;temperature&lt;/code&gt;, and &lt;code&gt;top_p&lt;/code&gt; — and the notebook's timing loop (time a &lt;code&gt;generate()&lt;/code&gt; call, divide tokens by seconds) is how you replace the roofline estimate above with your real number.&lt;/p&gt;

&lt;h2&gt;
  
  
  When Keras loses
&lt;/h2&gt;

&lt;p&gt;Two situations. First, throughput serving: Keras loads one model and generates one sequence at a time, which is perfect for local development and hopeless for a production endpoint — that is what vLLM (Lane A) is for. Second, the biggest models: Keras will happily try to load 27B bf16 on a 24 GB card and fail with an out-of-memory error, where a serving engine would have told you the fit math first. Keras is the lab; vLLM is the factory. Use each where it wins.&lt;/p&gt;

&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;4B bf16 fits a 12 GB card (9.4 GB total at 32K); 27B 4-bit fits a 24 GB card (16.7 GB).&lt;/strong&gt; 27B bf16 needs 57.5 GB — an 80 GB GPU or two cards.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The KV cache is nearly flat.&lt;/strong&gt; Gemma 3's 5:1 sliding window holds 27B cache to 11.2 GB at 128K, versus 66.6 GB for dense attention — a 6x saving, cross-checked against the independent 11.4 GB figure.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Decode speed is bandwidth divided by weights.&lt;/strong&gt; Roofline: 4B bf16 ~117 tokens/s on an RTX 4090, ~14 on an Apple M4, ~5 on a laptop CPU. Measure your own with the notebook's timing loop.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Keras 3 is three lines to a chatbot&lt;/strong&gt;, one backend switch (&lt;code&gt;jax&lt;/code&gt; / &lt;code&gt;tensorflow&lt;/code&gt; / &lt;code&gt;torch&lt;/code&gt;), and presets for every size from 270M to 27B. Use QAT builds at 4-bit.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Keras is the lab, vLLM is the factory.&lt;/strong&gt; Local runs and fine-tuning here; batched serving in Lane A.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Honesty note: weight and KV-cache figures are computed in the notebook from Gemma 3's published config (layers, KV heads, head dim, 5:1 sliding window of 1,024 tokens) and cross-checked against the independent 27B KV figure of ~11.4 GB at 128K (computed 11.2 GB). Roofline tokens/s is a memory-bandwidth upper bound, not a measured benchmark — real speed is lower. Raspberry Pi 12–19 tokens/s is an independent measurement, not this notebook's. Gemma 3 sizes are the published 1B/4B/12B/27B (plus 270M); parameter counts are the published totals. No Meta content per the standing exclusion.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Companion notebook: &lt;code&gt;gemma3_keras_local.ipynb&lt;/code&gt; — weight-memory ladder, sliding-window KV-cache arithmetic with the 11.4 GB cross-check, fit table, roofline decode model, and the real Keras &lt;code&gt;from_preset&lt;/code&gt; + &lt;code&gt;generate&lt;/code&gt; code, all exec-tested.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Companion notebook:&lt;/strong&gt; the runnable tutorial for this post — &lt;a href="https://danielsamfdo.github.io/blog/assets/gemma3_keras_local.ipynb" rel="noopener noreferrer"&gt;download it here&lt;/a&gt; (open in Colab/Jupyter).&lt;/p&gt;

</description>
      <category>llm</category>
      <category>googlecloud</category>
      <category>machinelearning</category>
      <category>ai</category>
    </item>
  </channel>
</rss>
