<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vivek on Medium]]></title>
        <description><![CDATA[Stories by Vivek on Medium]]></description>
        <link>https://medium.com/@vg010623?source=rss-85ddbe8b7465------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*CEgHJC71d4ZCQtaR</url>
            <title>Stories by Vivek on Medium</title>
            <link>https://medium.com/@vg010623?source=rss-85ddbe8b7465------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 20:38:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vg010623/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Harness Engineering From First Principles (Part 1)]]></title>
            <link>https://medium.com/@vg010623/harness-engineering-from-first-principles-part-1-2cc07f6473d2?source=rss-85ddbe8b7465------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cc07f6473d2</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Vivek]]></dc:creator>
            <pubDate>Sat, 31 Oct 2026 10:35:49 GMT</pubDate>
            <atom:updated>2026-10-31T10:35:49.160Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_yOhJ4IkLUSgcvwu0nzmQ.png" /></figure><p>Everyone online is saying “harness” right now. Harness engineering, agent harness, “the model is a commodity, the harness is the product.” I’m a software engineer with about a year and a half of experience, I use AI workflows at work, and I realized I had no real idea what people meant. I was nodding along to words I couldn’t explain.</p><p>So I did what I always do when a buzzword annoys me: I kept asking “but why?” until it broke down into things I already understand.</p><p>This is Part 1 of a short series. I’m not an expert, and I haven’t shipped a production agent. This is a learner’s map: what a harness is, built from the ground up, in the order the questions occurred to me. In later parts I’ll go deeper into the hard problems, and then I’ll try to build one myself and tell you what went wrong.</p><p>If you’re a developer who keeps hearing these words and wants the mental model, this is for you.</p><h3>Start here: a model is just a function</h3><p>An LLM takes text in and gives text out. That’s the whole interface. A few consequences follow, and everything else in this article comes from them:</p><ul><li>It has no hands. It can’t open a file, run a command, or call an API.</li><li>It has no memory between calls. Every call starts from zero.</li><li>It can only read a limited amount of text at once, called the context window.</li></ul><p>So if you ask it to fix a bug in your repo, it can’t see your repo. All it can do is write text that looks like a fix.</p><h3>Put the function in a loop</h3><p>To make it do real work, you wrap it in a loop:</p><ol><li>Give the model a task, plus a list of tools it may “call” (read_file, run_tests, edit_file).</li><li>The model replies by asking for a tool, in structured text.</li><li>Your program, not the model, actually runs that tool.</li><li>Your program feeds the result into the next model call.</li><li>Repeat until the model says it’s done.</li></ol><p>That’s an agent. The model supplies judgment, and your program supplies the hands and eyes. That program around the model is the <strong>harness</strong>. The popular one-liner is:</p><p><strong>Agent = Model + Harness</strong></p><p>The horse metaphor helps: the model is raw power, and the harness is what lets you put it to work without it bolting. Claude Code, Codex and Cursor are all harnesses. So “harness engineering” just means engineering everything except the model weights: what goes in, what happens to what comes out, what’s remembered, what’s allowed.</p><h3>Wait, wasn’t the very first ChatGPT already a harness?</h3><p>This was my first “aha” question, and the answer is yes. Even the first chatbot product was a thin harness:</p><ul><li><strong>A hidden system prompt</strong> was added before your text.</li><li><strong>Conversation history</strong> was re-sent on every message, because the model doesn’t remember anything. The “chat” illusion is harness code.</li><li><strong>Output handling</strong>: the model streamed text back, and the app displayed and filtered it.</li></ul><p>Take a table as an example. The model doesn’t draw tables. It writes markdown like | Name | Role |, which it has seen a huge amount of in training. The deterministic UI code turns that text into an actual rendered table. The model writes the syntax, and the harness draws it.</p><p>So harnesses were always there. What changed is the size and the stakes. Once models got tools and loops, the harness started deciding what actions run, what gets verified, and what is remembered. When the model can edit your files, the code around it matters a lot more, and that’s why it earned a name.</p><h3>Who is actually driving: code or intelligence?</h3><p>I’d assumed the model was running the show. The more accurate answer is that the loop is deterministic, but the decisions inside it are not.</p><p>The loop itself is a plain while loop: call the model, check if it asked for a tool, run the tool, append the result, stop if a step limit is hit. No intelligence, and it behaves the same every time. But at each iteration the model decides what happens next: which tool, with what arguments, and whether it&#39;s done. The code just carries that out and enforces limits.</p><p>This is also the difference between two patterns you’ll hear about:</p><ul><li><strong>Workflow</strong>: the code decides the path (step 1 summarize, step 2 classify, step 3 send), and the model only fills in each step. Predictable, but rigid.</li><li><strong>Agent</strong>: the model decides the path at runtime, and the code provides the loop, tools and guardrails. Flexible, but less predictable.</li></ul><p>A picture that worked for me: the model is the driver, and the harness is the car, the road, the speed limiter and the brakes. Much of harness engineering is deciding how much freedom to give the driver for a given task.</p><h3>How can one harness handle every language and command?</h3><p>This was the question that confused me most. People use tools like Claude Code with any language, framework or command. Surely nobody wrote code for every case?</p><p>They didn’t. The harness only provides a small set of generic tools, roughly a dozen:</p><ul><li><strong>Bash</strong>: run any shell command</li><li><strong>Read</strong>: return a file’s contents</li><li><strong>Edit / Write</strong>: modify or create a file</li><li><strong>Glob / Grep</strong>: find files and search content</li><li><strong>Web search / fetch</strong>: look things up</li></ul><p>The shell tool is the key. The harness has no idea what gcc, cargo or kubectl does. It just runs the command and hands the output back to the model. The operating system already has a universal interface, the command line, so the harness borrows it instead of reimplementing it. The model has seen enormous amounts of shell usage in training, so the knowledge of which command fits which language lives in the model, and the generic execution lives in the harness.</p><p>A browser works the same way. It doesn’t know about every website. It knows HTTP and HTML, and websites bring the variety.</p><h3>What “edit this line” actually looks like</h3><p>The harness describes each tool to the model in the API request, with a name and a schema for its arguments:</p><pre>{ &quot;name&quot;: &quot;edit_file&quot;,<br>  &quot;description&quot;: &quot;Replace an exact string in a file&quot;,<br>  &quot;input_schema&quot;: { &quot;file_path&quot;: &quot;string&quot;, &quot;old_string&quot;: &quot;string&quot;, &quot;new_string&quot;: &quot;string&quot; } }</pre><p>The model replies with something like edit_file(file_path=&quot;auth.ts&quot;, old_string=&quot;return false&quot;, new_string=&quot;return true&quot;). The harness side is ordinary code:</p><pre>def edit_file(path, old, new):<br>    text = open(path).read()<br>    if text.count(old) != 1:<br>        return &quot;Error: old_string not found or not unique&quot;<br>    open(path, &quot;w&quot;).write(text.replace(old, new))<br>    return &quot;ok&quot;</pre><p>Two details I liked. When something fails, the error is returned to the model as text, so it can read it and try again. And the edit uses an exact string instead of a line number, because line numbers shift as a file changes.</p><p>Because every tool has the same shape (name, schema, function), the harness can keep them in a registry. Adding a capability means registering one more entry. A standard called MCP extends this idea so that third parties can ship tools that any harness can plug in.</p><h3>But the model’s output isn’t controllable. What if it says change_file instead of edit_file?</h3><p>My next worry was the obvious one. The model can say anything, so what stops it from inventing a tool name or getting the arguments wrong? The answer comes in layers:</p><ol><li><strong>Training.</strong> Models are explicitly trained for tool calling. They see many examples where the tools are listed in the request and the correct reply uses exactly those names. They’re copying a pattern that sits in their input, not choosing names freely.</li><li><strong>A structured API.</strong> The provider’s server detects the special tool-call output and hands your code a clean structured object. Some providers can also constrain generation so a name outside the allowed list can’t be produced.</li><li><strong>Validation in the harness.</strong> Even so, the harness assumes the output can be wrong. If the tool name is unknown or an argument is missing, it returns an error as text, and the model reads it and retries.</li></ol><p>The design principle that clicked for me: treat the model’s output as untrusted input, like user input in a web app. You don’t control what the model says, but you fully control what the harness will do about it.</p><h3>Permissions live in the harness, not the model</h3><p>The same idea covers permissions. Before running anything, the harness checks the proposed action against rules in plain code: allow npm test, ask before rm, never touch files outside this folder. It often runs commands in a sandbox too. The model can&#39;t bypass any of this, because the check happens in code before the command executes. The model proposes, and deterministic code decides.</p><h3>So is the product only as good as its harness?</h3><p>Mostly, with caveats. Imagine two teams using the same top model. The one with the better harness builds the better product, because the harness decides how well the model’s intelligence gets used: what context it sees, whether its work gets verified, how it recovers from errors, what it’s allowed to do. A weak harness wastes a strong model.</p><p>The caveats:</p><ul><li><strong>The model sets the ceiling.</strong> A great harness raises reliability, but it can’t add intelligence the model doesn’t have.</li><li><strong>Models and harnesses are co-designed.</strong> Labs train models on their own harness’s tools, which is part of why a model can work especially well in its maker’s own tool.</li><li><strong>Harnesses are easy to copy.</strong> The core loop is small, and some harness tricks become unnecessary as models improve. On its own the harness is a thin moat, and the durable products also have data, distribution or deep workflow integration.</li></ul><p>For me, the takeaway is practical. A harness is software built around a model. It’s a backend problem with one unusual dependency: a component that is non-deterministic, sometimes wrong, and has real power once you give it tools. Retries, validation, permissions, state, logging, testing: skills most of us already have. The buzzword is wrapping a very familiar discipline.</p><h3>What’s next</h3><p>This article covers the foundation, but the interesting part is how you do it well. There are three hard problems I still want to understand properly:</p><ul><li><strong>Context management.</strong> The model re-reads the whole history on every step, and that history keeps growing. What do you keep, trim, summarize or move to files?</li><li><strong>Evals.</strong> The model is non-deterministic, so one successful run proves nothing. How do you measure whether a change to your harness actually helped?</li><li><strong>Safety and cost.</strong> Sandboxing, approvals, and not burning money on a runaway loop.</li></ul><p>Part 2 will dig into those. Part 3 is where I build a small harness myself and write honestly about what breaks. If I’ve got something wrong here, tell me in the comments as corrections are the point.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cc07f6473d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bytes In, Bytes Out: What HTTP Actually Looks Like]]></title>
            <link>https://medium.com/@vg010623/bytes-in-bytes-out-what-http-actually-looks-like-6bc67876fb65?source=rss-85ddbe8b7465------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bc67876fb65</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Vivek]]></dc:creator>
            <pubDate>Sat, 01 Aug 2026 19:35:42 GMT</pubDate>
            <atom:updated>2026-08-01T19:35:42.560Z</atom:updated>
            <content:encoded><![CDATA[<h3>HTTP Is Just Bytes: What Every Backend Engineer Should Know About Protocols</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*athoCMIstEJO8NpYXqOYPA.png" /></figure><p>Most web developers use HTTP every day without knowing what it actually is. We fire off fetch() calls, spin up Express servers, and install database drivers — but if someone asked you &quot;what is HTTP, <em>really</em>?&quot; could you explain it at the byte level?</p><p>I couldn’t, until recently. This article walks through the entire chain — from what bytes are, to how HTTP works at the wire level, to how your database driver speaks a completely different protocol, to building your own custom protocol from scratch. By the end, you’ll understand networking at a level most engineers never bother to reach.</p><h3>Start at the Bottom: TCP Is Just a Byte Pipe</h3><p>Before HTTP, before any protocol — there’s TCP. And TCP is shockingly simple in concept. It’s a reliable, two-way pipe between two programs. You open a connection, send bytes, receive bytes, close the connection. That’s it.</p><p>TCP guarantees two things: your bytes arrive in order, and nothing gets lost. What it does <em>not</em> do is give those bytes any meaning. It has no concept of “requests,” “headers,” “URLs,” or “methods.” It’s just: here are some numbers, delivered reliably.</p><p>A <strong>TCP socket</strong> is simply the programming object that represents your end of that pipe — think of it like a phone call. When you write socket.write(data), you&#39;re speaking into the phone. When you listen on socket.on(&#39;data&#39;), you&#39;re hearing what the other side says. The connection stays open until someone hangs up.</p><p>Everything we’ll talk about from here is built on top of this pipe.</p><h3>Everything Is a Number</h3><p>Your computer doesn’t know what the letter “A” is. At the hardware level, it only understands numbers — specifically, numbers stored as binary. A <strong>byte</strong> is a group of 8 bits, which can represent a number from 0 to 255.</p><p>When we say “the browser sends bytes,” we literally mean it sends a sequence of numbers. The letter G is the number 71. E is 69. T is 84. A space is 32. This mapping from numbers to characters is defined by ASCII (and its bigger sibling, UTF-8).</p><p>So when the browser sends GET /users/42 HTTP/1.1, what actually travels over the wire is:</p><pre>71 69 84 32 47 117 115 101 114 115 47 52 50 32 72 84 84 80 47 49 46 49 13 10<br>G  E  T  _  /  u   s   e   r   s   /  4  2  _  H  T  T  P  /  1  .  1  \r \n</pre><p>Just numbers. The \r (carriage return, number 13) and \n (line feed, number 10) together mark the end of a line — an arbitrary rule that HTTP chose.</p><h3>So What Is HTTP, Really?</h3><p>HTTP is a <strong>protocol</strong> — which is just a fancy word for “an agreement about what the bytes mean.”</p><p>The HTTP specification is essentially a document that says: “If you want to request something, format your bytes like this. If you want to respond, format them like that.” Nothing more.</p><p>Here’s the agreement in action. When you use fetch(&#39;/users/42&#39;) in the browser, it constructs and sends these bytes over TCP:</p><pre>GET /users/42 HTTP/1.1\r\n<br>Host: myapp.com\r\n<br>Accept: application/json\r\n<br>\r\n</pre><p>The rules that make this HTTP are precise:</p><ul><li>First line: METHOD PATH VERSION, separated by spaces, ending with \r\n</li><li>Following lines: HeaderName: HeaderValue, each ending with \r\n</li><li>An empty line (\r\n on its own) signals &quot;headers are done&quot;</li><li>Everything after the empty line is the body (empty for GET requests)</li></ul><p>The server responds with the same idea, different structure:</p><pre>HTTP/1.1 200 OK\r\n<br>Content-Type: application/json\r\n<br>Content-Length: 56\r\n<br>\r\n<br>{&quot;id&quot;:42,&quot;name&quot;:&quot;Vivek&quot;,&quot;email&quot;:&quot;vivek@example.com&quot;}</pre><p>That’s HTTP. Not a magical transport layer. Not something baked into the hardware. Just a set of formatting rules for bytes flowing through a TCP pipe.</p><h3>How Does Parsing Actually Work?</h3><p>When bytes arrive on a TCP socket in Node.js, you get a Buffer — literally an array of numbers:</p><pre>const net = require(&#39;net&#39;);</pre><pre>const server = net.createServer((socket) =&gt; {<br>  socket.on(&#39;data&#39;, (buffer) =&gt; {<br>    console.log(buffer[0]); // 71 — the number for &#39;G&#39;<br>    console.log(buffer[1]); // 69 — the number for &#39;E&#39;<br>    console.log(buffer[2]); // 84 — the number for &#39;T&#39;<br>  });<br>});</pre><p>“Parsing” just means applying the protocol’s rules to extract structured data from those numbers. For a text protocol like HTTP, the steps are straightforward — convert bytes to a string, then split on the delimiters the protocol defines:</p><pre>socket.on(&#39;data&#39;, (buffer) =&gt; {<br>  const text = buffer.toString(&#39;utf-8&#39;);<br>  const lines = text.split(&#39;\r\n&#39;);</pre><pre>  // Rule: first line is METHOD PATH VERSION<br>  const [method, path, version] = lines[0].split(&#39; &#39;);</pre><pre>  // Rule: subsequent lines until empty line are headers<br>  const headers = {};<br>  for (let i = 1; i &lt; lines.length; i++) {<br>    if (lines[i] === &#39;&#39;) break;<br>    const [key, value] = lines[i].split(&#39;: &#39;);<br>    headers[key] = value;<br>  }<br>});</pre><p>This is essentially what Node’s built-in HTTP parser does — except it’s written in C (called llhttp) for performance, and handles hundreds of edge cases. But the core logic is the same: scan bytes, find the patterns the spec defines, extract structured data.</p><p>Here’s what’s interesting: <strong>you’ve been doing byte parsing all along without realizing it.</strong> When you call JSON.parse(), JavaScript is scanning through bytes looking for { (byte 123), &quot; (byte 34), : (byte 58), splitting on them, and building objects. When you call parseInt(&quot;42&quot;), it reads byte 52 (4) and byte 50 (2) and computes 4×10 + 2 = 42. String parsing IS byte parsing — JavaScript just hides the conversion layer.</p><h3>You Don’t Need C to Write a Parser</h3><p>A common misconception: since Node’s HTTP parser (llhttp) is written in C, you might assume all protocol parsers need to be written in low-level languages. They don&#39;t.</p><p>The reason llhttp is in C is purely performance. HTTP parsing happens on every single request — if your server handles 10,000 requests per second, that parser runs 10,000 times per second. At that scale, the speed difference between C and JavaScript matters. It&#39;s an optimization choice, not a requirement.</p><p>Plenty of real-world parsers are written in high-level languages. The ioredis npm package parses Redis&#39;s protocol (RESP) in pure JavaScript. Go&#39;s entire standard library — including its HTTP parser — is written in Go, not C. Go is fast enough that they didn&#39;t need to drop down.</p><p>If you’re building a custom protocol, write the parser in whatever language you’re already using. You’d only rewrite it in C or Rust if you profiled your application and found that parsing was your actual bottleneck — which for most applications, it won’t be. The general principle: <strong>optimize to a lower-level language only when you have measured evidence that it’s too slow.</strong></p><h3>Text Protocols vs Binary Protocols</h3><p>HTTP is a <strong>text protocol</strong> — its bytes represent human-readable characters. You can open a packet sniffer and read GET /users/42 HTTP/1.1 with your eyes.</p><p>But not every protocol works this way. PostgreSQL, MongoDB, Kafka, and many others use <strong>binary protocols</strong>, where bytes represent numbers directly — not characters.</p><p>Here’s what PostgreSQL’s wire protocol looks like when your database returns a query result:</p><pre>Byte 0:      &#39;T&#39;  (84)      → message type: row description<br>Bytes 1-4:   00 00 00 2F    → message length: 47 bytes<br>Bytes 5-6:   00 03          → field count: 3 fields coming<br>...field definitions...</pre><pre>Byte 0:      &#39;D&#39;  (68)      → message type: data row<br>Bytes 1-4:   [length]       → message length<br>...row data...</pre><pre>Byte 0:      &#39;C&#39;  (67)      → message type: command complete<br>Byte 0:      &#39;Z&#39;  (90)      → message type: ready for next query</pre><p>No GET, no headers, no URLs. Just a type byte, a length, and the payload. Parsing this doesn&#39;t involve string splitting — you read numbers directly by position:</p><pre>const messageType = buffer[0];          // read byte 0 as type<br>const length = buffer.readInt32BE(1);   // read bytes 1-4 as a 32-bit integer<br>const fieldCount = buffer.readInt16BE(5); // read bytes 5-6 as a 16-bit integer</pre><p>Binary protocols are more compact and faster to parse — but completely unreadable to humans. The tradeoff depends on the use case: HTTP chose readability (you’re debugging web requests all the time), PostgreSQL chose performance (database queries happen millions of times per second internally).</p><h3>Your Node Server Is Bilingual</h3><p>Here’s where it all connects. In a typical web app, your Node.js server maintains two completely different TCP connections using two completely different protocols:</p><pre>Browser ─── HTTP over TCP:3000 ───→ Node Server ─── PG Protocol over TCP:5432 ───→ PostgreSQL<br>        ←── HTTP over TCP:3000 ───              ←── PG Protocol over TCP:5432 ───</pre><p>When a browser hits GET /users/42:</p><ol><li>The browser constructs HTTP-formatted bytes, sends them over TCP</li><li>Node’s HTTP parser reads those bytes, recognizes the HTTP format, gives you req.method, req.url, etc.</li><li>Your route handler calls pool.query(&#39;SELECT * FROM users WHERE id = $1&#39;, [42])</li><li>The pg library constructs PostgreSQL-formatted bytes (type byte + length + SQL string), sends them over a <em>different</em> TCP connection to port 5432</li><li>PostgreSQL parses those bytes using its protocol rules, executes the query</li><li>PostgreSQL sends the result back as its own byte format (T, D, C, Z messages)</li><li>The pg library parses those bytes into a JavaScript object: { rows: [{ id: 42, name: &#39;Vivek&#39; }] }</li><li>Express constructs HTTP-formatted bytes with the JSON response, sends them back to the browser</li></ol><p>Your server is a translator, sitting between two protocols.</p><p><strong>This is what every database library is.</strong> When you npm install pg, you&#39;re installing a PostgreSQL protocol translator. mongodb is a MongoDB protocol translator. ioredis is a Redis protocol translator. kafkajs is a Kafka protocol translator. They all open raw TCP connections and format/parse bytes according to their system&#39;s published protocol specification.</p><p>That’s what these libraries <em>are for</em>.</p><h3>Building Your Own Protocol</h3><p>Now that we understand the fundamentals, let’s build one. Say you have a Node.js backend that needs to talk to a separate notification service. Instead of HTTP, you design a simple binary protocol:</p><p><strong>The rules (our protocol spec):</strong></p><ul><li>Byte 0: action type (1 = send notification, 2 = check status)</li><li>Bytes 1–2: payload length (16-bit unsigned integer, big-endian)</li><li>Bytes 3+: JSON payload</li></ul><p>That’s the entire protocol. Both sides must follow these exact rules — the sender formats bytes this way, the receiver reads bytes this way.</p><h3>The Protocol Module</h3><pre>// lib/my-protocol.js</pre><pre>function encode(actionType, payload) {<br>  const jsonBytes = Buffer.from(JSON.stringify(payload), &#39;utf-8&#39;);<br>  const buffer = Buffer.alloc(1 + 2 + jsonBytes.length);</pre><pre>  buffer[0] = actionType;                    // byte 0: action type<br>  buffer.writeUInt16BE(jsonBytes.length, 1);  // bytes 1-2: payload length<br>  jsonBytes.copy(buffer, 3);                  // bytes 3+: the JSON payload</pre><pre>  return buffer;<br>}</pre><pre>function decode(buffer) {<br>  const actionType = buffer[0];<br>  const payloadLength = buffer.readUInt16BE(1);<br>  const payload = JSON.parse(<br>    buffer.slice(3, 3 + payloadLength).toString(&#39;utf-8&#39;)<br>  );<br>  return { actionType, payload };<br>}</pre><pre>module.exports = { encode, decode };</pre><h3>The Notification Service (Raw TCP Server)</h3><pre>// notification-service/index.js<br>const net = require(&#39;net&#39;);<br>const { decode, encode } = require(&#39;../lib/my-protocol&#39;);</pre><pre>const server = net.createServer((socket) =&gt; {<br>  socket.on(&#39;data&#39;, (buffer) =&gt; {<br>    const message = decode(buffer);</pre><pre>    if (message.actionType === 1) {<br>      console.log(`Notifying user ${message.payload.userId}: ${message.payload.text}`);<br>      socket.write(encode(200, { status: &#39;sent&#39; }));<br>    }<br>  });<br>});</pre><pre>server.listen(4000);<br>// No Express. No HTTP. Just raw TCP on port 4000.</pre><h3>The API Server (HTTP + Custom Protocol)</h3><pre>// api-server/index.js<br>const express = require(&#39;express&#39;);<br>const net = require(&#39;net&#39;);<br>const { encode, decode } = require(&#39;../lib/my-protocol&#39;);</pre><pre>const app = express();</pre><pre>app.post(&#39;/send-notification&#39;, (req, res) =&gt; {<br>  const socket = net.createConnection({ port: 4000 }, () =&gt; {<br>    socket.write(encode(1, {<br>      userId: req.body.userId,<br>      text: req.body.message,<br>    }));<br>  });</pre><pre>  socket.on(&#39;data&#39;, (buffer) =&gt; {<br>    const response = decode(buffer);<br>    res.json(response.payload);<br>  });<br>});</pre><pre>app.listen(3000);</pre><p>The API server is bilingual — HTTP on one side (Express, port 3000), your custom protocol on the other (raw TCP, port 4000):</p><pre>Browser ─── HTTP ───→ API Server (3000) ─── YourProtocol ───→ Notification Service (4000)<br>        ←── HTTP ───                    ←── YourProtocol ───</pre><p>This is the same pattern as the PostgreSQL example, except now the protocol on the right side is one you invented.</p><h3>Why Browsers Lock You Into HTTP</h3><p>A question you might be asking: “Why can’t I just use my custom protocol between the browser and the server?”</p><p>Because browsers are not general-purpose network clients. They’re HTTP clients. When you use fetch() or Axios, the browser constructs HTTP-formatted bytes, sends them over TCP, and expects HTTP-formatted bytes back. That&#39;s hardcoded — you can&#39;t change it.</p><p>Browsers don’t expose raw TCP sockets to JavaScript (for security reasons). So if you invented “MyProtocol,” the browser literally has no API to send bytes in your format.</p><p>The one escape hatch is <strong>WebSocket</strong>, which starts as an HTTP connection (the browser can initiate it) and then “upgrades” to a raw bidirectional byte stream. If you really wanted a browser client for your custom protocol, you could tunnel your protocol’s bytes over a WebSocket connection. But at that point, you’re adding complexity — not removing it.</p><p>This is exactly why HTTP dominates the web. It’s not because HTTP is technically optimal for every use case. It’s because browsers speak it natively, and the entire ecosystem — Axios, Express, CDNs, proxies, load balancers, API gateways — is built around it. Using a custom protocol means rebuilding all of that infrastructure yourself.</p><h3>Where Custom Protocols Actually Live</h3><p>So if HTTP rules the browser-to-server world, where do custom protocols show up?</p><p><strong>Between backend services.</strong> This is the key insight. Custom protocols live in the spaces where browsers aren’t involved:</p><ul><li><strong>Database connections</strong>: PostgreSQL, MongoDB, MySQL, Redis — all have their own TCP protocols. The npm drivers (pg, mongodb, ioredis) are protocol translators.</li><li><strong>Message queues</strong>: Kafka, RabbitMQ — custom binary protocols optimized for high-throughput message passing.</li><li><strong>RPC frameworks</strong>: gRPC uses HTTP/2 as its transport but defines its own message format with Protocol Buffers on top.</li><li><strong>Game servers</strong>: Custom UDP protocols (not even TCP) for low-latency real-time communication.</li></ul><p>In every case, the client is not a browser — it’s a purpose-built library that knows how to format and parse bytes according to that system’s protocol.</p><h3>The Mental Model</h3><p>The entire world of networked systems boils down to this:</p><ol><li>Two programs open a TCP connection (a reliable byte pipe)</li><li>They agree on rules for structuring bytes (a protocol)</li><li>They send bytes back and forth according to those rules</li><li>Client libraries (pg, axios, kafkajs) exist to hide the byte-level details behind friendly APIs</li></ol><p>HTTP is one set of rules. PostgreSQL’s wire protocol is another. You can invent your own. The rules are arbitrary — what matters is that both sides agree.</p><p>Every time you call fetch(), a library is formatting bytes according to HTTP&#39;s rules. Every time you call pool.query(), a library is formatting bytes according to PostgreSQL&#39;s rules. Every time you npm install a database driver, you&#39;re installing a protocol translator.</p><p>Once you see this, you can’t unsee it. The network stack stops being magical and becomes mechanical — just bytes in a pipe, following rules that humans wrote down in a document.</p><p><em>If this helped you understand something you’d been fuzzy about, share it with another developer who might have the same questions. These fundamentals don’t get talked about enough.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bc67876fb65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Never Understood Why Rust Is “Fast” — Until I Learned Where the Garbage Collector Actually Lives]]></title>
            <link>https://medium.com/@vg010623/i-never-understood-why-rust-is-fast-until-i-learned-where-the-garbage-collector-actually-lives-e40b2a31b171?source=rss-85ddbe8b7465------2</link>
            <guid isPermaLink="false">https://medium.com/p/e40b2a31b171</guid>
            <category><![CDATA[systems-programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Vivek]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 16:16:35 GMT</pubDate>
            <atom:updated>2026-07-22T16:16:35.551Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*p0NQX0z9YX33o7w5H3P3HQ.png" /></figure><p>I’m a full-stack engineer who works primarily with JavaScript and Node.js. For years, I kept hearing the same things: “Rust is blazing fast,” “C++ gives you control,” “Java and JS have overhead because of garbage collection.”</p><p>I nodded along. I kind of got it. But I never <em>really</em> understood it. What overhead? Where? What exactly is sitting in my machine’s memory when I run a Node server versus a Rust server? Where does the garbage collector live? If Rust has a compiler and JS also has a compiler, what’s actually different?</p><p>Then I spent a few hours pulling on these threads, and everything clicked. If you’ve ever had the same fuzzy understanding, this article is for you.</p><h3>Let’s Start With What Your Computer Actually Does</h3><p>Before we talk about languages, we need to agree on one thing: <strong>your CPU only understands machine code</strong>. That’s it. Binary instructions like 0x48 0x89 0xe5. It doesn&#39;t know what a for loop is. It doesn&#39;t know what an object is. It doesn&#39;t know JavaScript or Rust or Python.</p><p>Every programming language, no matter how high-level, has to eventually get turned into these machine instructions. The <em>way</em> it gets turned into machine instructions — and <em>when</em> — is the fundamental difference that separates languages into two camps.</p><h3>Camp 1: Ahead-of-Time Compilation (Rust, C, C++, Go)</h3><p>You write your code. You run a compiler. The compiler reads your source code, analyzes it, optimizes it, and spits out a <strong>binary file</strong> — a file full of machine code that your CPU can execute directly.</p><p>Here’s the important part: <strong>the compiler then exits.</strong> It’s done. It’s not running anymore. It’s not in memory. The binary it produced is a self-contained, standalone program. When you run that binary, it loads into RAM and talks directly to the CPU. There is no middleman.</p><p>The compiler is like a translator who converts an English book into Hindi, hands you the Hindi book, and walks away. You can read the Hindi book forever. The translator is not sitting next to you while you read.</p><h3>Camp 2: Just-in-Time Compilation with a Runtime (JavaScript, Java, Python)</h3><p>You write your code. You run a command like node app.js. But here, something very different happens. A <strong>runtime environment</strong> loads into your machine&#39;s RAM — and it <em>stays there</em> for the entire lifetime of your program.</p><p>For JavaScript, that runtime is Node.js (or the browser). For Java, it’s the JVM. This runtime is a large, complex program written in C/C++ that does everything your code needs to function: it reads your source code, compiles it on the fly, manages memory, runs a garbage collector, and provides access to system resources like the filesystem and network.</p><p>The runtime is like a simultaneous interpreter sitting next to you in a meeting, translating every sentence as it’s spoken. If the interpreter leaves, you can’t understand anything anymore. <strong>The interpreter must stay for the entire meeting.</strong></p><h3>OK, But Let’s Get Concrete. What Exactly Happens When I Run node app.js?</h3><p>Let’s say you have a file called app.js on your disk:</p><pre>let users = [<br>  { name: &quot;Alice&quot;, age: 30 },<br>  { name: &quot;Bob&quot;, age: 25 }<br>];<br>users.push({ name: &quot;Charlie&quot;, age: 35 });<br>console.log(users);</pre><p>Right now, this is just a text file. Characters on a disk. It means absolutely nothing to your CPU.</p><p>You open your terminal and type node app.js. Here&#39;s what happens, step by step:</p><p><strong>Step 1: The OS loads the Node binary into RAM.</strong></p><p>When you installed Node on your machine, it placed an executable file at a path like /usr/bin/node. This file is a compiled C++ program — the result of compiling the entire Node.js project (which includes V8, libuv, and a bunch of C++ bindings) into one executable. This single binary file is typically around 50–80MB.</p><p>The operating system reads this file from disk and loads it into RAM. Now V8 (the JavaScript engine), libuv (the event loop), and the garbage collector are all sitting in your machine’s memory as compiled machine code, ready to execute.</p><p><strong>Step 2: V8 reads your JavaScript file.</strong></p><p>V8 reads the text of app.js from disk into memory. At this point it&#39;s still just a string of characters. V8 parses this string into an internal data structure called an AST (Abstract Syntax Tree) — a tree representation of your program&#39;s structure.</p><p><strong>Step 3: V8 compiles your code to machine code — in memory.</strong></p><p>V8’s JIT (Just-In-Time) compiler takes the AST and generates actual CPU instructions from it. But unlike Rust’s compiler, V8 doesn’t write these instructions to a file on disk. The machine code is generated <strong>directly in RAM</strong>. There is no intermediate binary file.</p><p><strong>Step 4: The CPU executes those instructions.</strong></p><p>When it hits let users = [...], V8&#39;s memory allocator (C++ code) asks the OS for a chunk of RAM and stores the array objects there. V8 keeps track of every allocation internally.</p><p><strong>Step 5: The garbage collector does its thing.</strong></p><p>The GC is C++ code that’s part of V8, sitting in RAM inside the same Node process as your code. Periodically, it wakes up, scans through all the objects V8 has allocated, figures out which ones are no longer reachable from your code, and frees that memory. <strong>While the GC is scanning, your JavaScript code is paused.</strong> This is the infamous “GC pause” or “stop-the-world” pause that people talk about.</p><p><strong>Step 6: The event loop keeps everything alive.</strong></p><p>libuv (a C library, part of the Node binary) is running an infinite loop: “Are there pending I/O callbacks? Timers? Network events?” As long as there’s something to wait for (like an HTTP server listening for requests), Node keeps running. The moment there’s nothing left, the process exits.</p><h3>So what’s sitting in RAM while your Node server runs?</h3><ul><li>The entire V8 engine (parser, JIT compiler, garbage collector, memory manager) — compiled C++ machine code</li><li>libuv (the event loop) — compiled C code</li><li>The machine code that V8 generated from your JavaScript — sitting in RAM, no file on disk</li><li>All the JavaScript objects your code created (the users array, the objects inside it) — on V8&#39;s managed heap in RAM</li><li>V8’s internal bookkeeping structures (object maps, type feedback, optimization metadata)</li></ul><p>All of this together easily starts at <strong>50–100MB of RAM</strong> before your application logic has done anything meaningful. For a simple Express.js “Hello World” server, you’re already using 30–50MB just to keep the runtime alive.</p><h3>Now Let’s Do the Same Thing With Rust</h3><p>You have a file called main.rs:</p><pre>use std::net::TcpListener;</pre><pre>fn main() {<br>    let listener = TcpListener::bind(&quot;0.0.0.0:8080&quot;).unwrap();<br>    for stream in listener.incoming() {<br>        // handle each connection<br>    }<br>}</pre><p>Again, just text on disk. Here’s what happens — but notice how different the process is.</p><p><strong>Step 1: You compile on your own machine (or in CI).</strong></p><p>You run cargo build --release. The OS loads the Rust compiler (rustc) into RAM. rustc reads your source code, parses it, runs type checking, runs the borrow checker (Rust&#39;s ownership rules are enforced here), and hands everything off to LLVM (a compiler backend written in C++).</p><p>LLVM optimizes the code and generates a binary file — let’s call it my_server. This file is written to disk. It&#39;s maybe 5–10MB. It contains raw machine code.</p><p><strong>And then the compiler exits.</strong> The rustc process is gone. It&#39;s not in memory anymore. Its job is done.</p><p><strong>Step 2: You deploy just the binary.</strong></p><p>You copy my_server to your server (an EC2 instance, a Docker container, whatever). Note: you don&#39;t need to install Rust on the server. You don&#39;t need rustc. You don&#39;t need Cargo. The binary is completely self-contained.</p><p><strong>Step 3: You run the binary.</strong></p><p>You run ./my_server. The OS loads the binary into RAM. The CPU starts executing the machine instructions directly. When the code creates a TcpListener, the compiled code makes a system call (socket(), bind(), listen()) directly to the OS kernel. No middleware. No runtime.</p><p><strong>Step 4: Memory is managed deterministically — no GC.</strong></p><p>When a value goes out of scope in Rust, the compiler has already inserted cleanup code (a drop call) at exactly the right point in the binary. There&#39;s no garbage collector scanning the heap. There&#39;s no &quot;stop-the-world&quot; pause. Memory is freed the instant it&#39;s no longer needed, because the compiler figured out when that would be at compile time and baked the instructions right into the binary.</p><h3>So what’s sitting in RAM while your Rust server runs?</h3><ul><li>Your compiled binary’s machine code</li><li>Whatever memory your program explicitly allocates (connection buffers, request data, response bodies)</li></ul><p>That’s it. No runtime engine. No JIT compiler. No garbage collector process. <strong>Maybe 5–10MB total</strong> for a basic HTTP server.</p><h3>The EC2 Mental Model</h3><p>This is where it all comes together. Imagine two EC2 instances in a data center, both running HTTP servers that do the same thing.</p><h3>The Node.js EC2 Instance</h3><p>Somewhere in a rack in us-east-1, there&#39;s a physical machine. In its RAM, the following things are loaded and running 24/7:</p><ul><li>The V8 JavaScript engine (~20MB of compiled C++ code)</li><li>V8’s JIT compiler, continuously analyzing and recompiling hot code paths</li><li>V8’s garbage collector, periodically waking up to scan the heap and free dead objects (pausing your code while it does so)</li><li>libuv’s event loop</li><li>Your JavaScript source code (loaded as text, compiled to machine code in memory by V8)</li><li>All the runtime bookkeeping (type feedback vectors, hidden classes, optimization metadata)</li><li>Your application’s actual data (request/response objects, database connections, etc.)</li></ul><p><strong>Total baseline memory: 50–100MB+</strong></p><h3>The Rust EC2 Instance</h3><p>Same data center, same rack, different machine. In its RAM:</p><ul><li>Your compiled binary (~5–10MB of machine code)</li><li>Your application’s actual data</li></ul><p><strong>Total baseline memory: 5–10MB</strong></p><p>No runtime. No garbage collector. No JIT compiler. Nothing else. The machine code runs directly on the CPU, allocates memory when it needs to, frees it the instant it’s done, and never pauses for anything.</p><p>This is why when <strong>Discord rewrote their Read States service from Go to Rust</strong>, their tail latencies dropped dramatically — Go’s garbage collector was causing periodic latency spikes. The Rust version had completely predictable, flat latency because there’s no GC to interrupt execution.</p><p>This is why <strong>Cloudflare runs Rust at the edge</strong> for their Workers runtime — when you’re processing millions of requests per second, every megabyte of RAM overhead per process matters.</p><h3>“But Wait — JS Also Has a Compiler, and Rust Also Has a Compiler. So What’s Different?”</h3><p>This was the question that confused me the most. Let me make it razor sharp.</p><h3>Rust’s compiler (rustc)</h3><ul><li>Runs <strong>before</strong> your program executes</li><li>Reads source code → produces a binary file on disk → <strong>exits</strong></li><li>Is not present at runtime</li><li>Does its work once, ahead of time</li></ul><p>This is called <strong>Ahead-of-Time (AOT) compilation</strong>.</p><h3>V8’s compiler (inside Node.js)</h3><ul><li>Runs <strong>during</strong> your program’s execution</li><li>Reads source code → produces machine code <strong>in RAM</strong> (no file on disk) → <strong>stays alive</strong></li><li>Might recompile functions multiple times as it learns about types and hot paths</li><li>Is just one component of a larger runtime that must remain in memory</li></ul><p>This is called <strong>Just-in-Time (JIT) compilation</strong>.</p><p>The word “compiler” is doing very different jobs in these two contexts. Rust’s compiler is a standalone tool that produces a finished product. V8’s compiler is an internal organ of a living runtime that continuously does work while your program runs.</p><p><strong>Think of it this way:</strong></p><p>Rust’s compiler is a <strong>factory</strong> that builds a car. The car drives off the lot and drives forever. The factory doesn’t ride along inside the car.</p><p>Node/V8 is a factory that’s <strong>built into the car itself</strong>, continuously manufacturing and replacing engine parts while the car is driving down the highway. More capable in some ways, but the car is a lot heavier.</p><h3>“If Rust Is So Much Better, Why Doesn’t Everyone Use It?”</h3><p>Because the tradeoff is <strong>developer productivity and iteration speed</strong>.</p><p>In JavaScript, you write code, save the file, and the changes are running in seconds. The runtime figures everything out for you — memory, types, compilation. You don’t think about any of it. For a startup building a CRUD API or a web app, this is exactly right. The bottleneck is almost never CPU or memory — it’s network I/O, database queries, and developer time. The 50MB of runtime overhead is irrelevant when your server has 8GB of RAM and spends 95% of its time waiting for Postgres to respond.</p><p>In Rust, you have to think about ownership, lifetimes, borrowing, and type constraints. The compiler is famously strict — it will refuse to compile code that might have a memory bug, even if you know it’s fine. Compilation takes longer. The learning curve is steep. But in exchange, you get a binary that’s small, fast, memory-efficient, and free from an entire class of bugs.</p><p><strong>The right question isn’t “which language is better?” It’s “where is the overhead worth caring about?”</strong></p><ul><li>Building a SaaS dashboard? Use JS/TS. The runtime overhead doesn’t matter. Ship faster.</li><li>Building a database engine processing millions of queries per second? Use Rust. Every microsecond and every megabyte matters.</li><li>Building a game engine rendering 60 frames per second? Use C++/Rust. You can’t afford GC pauses mid-frame.</li><li>Building an OS kernel? Use C/Rust. There’s no runtime to run a runtime on.</li><li>Building an API gateway handling 100k concurrent connections at the edge? Use Rust. Memory per connection is the bottleneck.</li></ul><h3>One More Mind-Bending Detail</h3><p>Remember how I said V8 (the JavaScript engine) is written in C++? And the JVM (Java’s runtime) is written in C and C++?</p><p>The garbage collector that manages memory <em>for</em> JS and Java is itself written in a language that manages memory <em>manually</em>. The runtime that makes your high-level code easy to write is built on a low-level foundation where someone had to worry about every allocation and deallocation.</p><p>And the Rust compiler? It’s written in Rust. The very first version was written in OCaml, and once it could compile Rust code, they rewrote the compiler in Rust and compiled it with the old version. Each new version of rustc is compiled by the previous version. This is called <strong>bootstrapping</strong> — and it&#39;s how most mature compilers work.</p><p>Even VS Code — the editor you’re probably writing code in — is an Electron app, which is a Chromium browser (written in C++) running a JavaScript/TypeScript frontend. Under the hood, your code editor is running on C++ code.</p><p><strong>It’s systems languages all the way down.</strong></p><h3>The Takeaway</h3><p>The next time someone tells you “Rust is fast” or “JS has overhead,” you now know exactly what that means at a physical level:</p><ul><li>It means there’s a 50MB C++ program (V8) sitting in your server’s RAM 24/7, constantly doing work alongside your code.</li><li>It means a garbage collector periodically pauses your application to scan for dead objects.</li><li>It means machine code is being generated and regenerated on the fly in memory.</li><li>And that a Rust binary doing the same job would be a fraction of the size, with no pauses, no runtime, and no middleman between your logic and the CPU.</li></ul><p>None of this makes JS or Java “bad.” They made a deliberate tradeoff: take on runtime overhead to give developers a simpler, faster development experience. That’s an excellent tradeoff for most applications.</p><p>But now when you make that choice, you’re making it with full understanding of what’s actually happening inside the machine. And that understanding is what separates an engineer from someone who just writes code.</p><p><em>If this helped you understand something you’d been fuzzy about, share it with another developer who might have the same questions. These fundamentals don’t get talked about enough.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e40b2a31b171" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>