<?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 Abhiram Dodda on Medium]]></title>
        <description><![CDATA[Stories by Abhiram Dodda on Medium]]></description>
        <link>https://medium.com/@abhiramdodda?source=rss-a0eeb0ee0600------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1bwQu9UHBokCrfZdUlvE_Q@2x.jpeg</url>
            <title>Stories by Abhiram Dodda on Medium</title>
            <link>https://medium.com/@abhiramdodda?source=rss-a0eeb0ee0600------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 11:47:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhiramdodda/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[Columnar results, and the ingest bottleneck that wasn’t the network]]></title>
            <link>https://medium.com/@abhiramdodda/columnar-results-and-the-ingest-bottleneck-that-wasnt-the-network-e25bd2bd0364?source=rss-a0eeb0ee0600------2</link>
            <guid isPermaLink="false">https://medium.com/p/e25bd2bd0364</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[apache-parquet]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <dc:creator><![CDATA[Abhiram Dodda]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 00:22:21 GMT</pubDate>
            <atom:updated>2026-08-13T00:22:21.038Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 3 of a series on the internals of a distributed image-processing platform.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mH1v6Qs0R_T6MBk26IlB0Q.png" /></figure><p>This post tells two stories that turn out to teach the same lesson. Measure the real cost, then let the measurement pick the design. One story is about how results leave the system. The other is about how data comes into it, and a slow spot that turned out to be a lock nobody had thought to look at.</p><h3>Story one. Results are stored as Parquet, and making them so costs almost nothing</h3><p>Task results get consumed by two very different audiences. Machine-learning training tools want one shape of data, and SQL query engines want another. If you pick a single generic format like JSON, every consumer has to convert it first, and you throw away the speed that comes from a format each tool reads natively. Training tools like tf.data want TFRecord. Query engines like Spark, Athena, and DuckDB want columnar Parquet.</p><p>So the committed result path writes Parquet. Each task stages a small single-row-group Parquet object, and the coordinator promotes it into the results tree using the exactly-once commit from Part 1. The nice outcome is that a finished job is queryable right away with no extra load step. You can point a query engine straight at it.</p><pre>SELECT shard, images_processed, bytes_read<br>FROM &#39;results/job-abc/*.parquet&#39;<br>WHERE images_processed &gt; 0;</pre><p>No conversion job, no separate warehouse import. The bytes the worker staged <em>are</em> the thing you query.</p><h3>Why this change was so safe to make</h3><p>Remember from Part 1 that the staged object is write-only as far as the platform is concerned. Nothing in the commit path ever reads it back and tries to understand it. The coordinator just copies it, byte for byte, from the staging spot to its final spot. It does not care what is inside.</p><p>That single fact is what made switching the staged format from JSON to columnar Parquet almost risk-free. The worker now builds a one-row Parquet file instead of a JSON blob, and the commit path did not change at all, because it never looked inside the object in the first place. Here is the staging write.</p><pre>// internal/worker, the staging write, simplified<br>var body bytes.Buffer<br>_ = formats.WriteResultsParquet(&amp;body, []formats.ResultRow{{<br>    TaskID: a.TaskID,<br>    Shard: a.Shard,<br>    OutputKey: finalKey,<br>    ImagesProcessed: processed,<br>    BytesRead: totalBytes,<br>}})<br>_ = w.store.Put(ctx, stagingKey, bytes.NewReader(body.Bytes()),<br>    &quot;application/vnd.apache.parquet&quot;)</pre><p>One row group per task matches the “one result object per task” design exactly, and the query engines happily read across the whole tree of Parquet files. The result names even carry the format in their extension now, ending in .parquet, and nothing broke, because the tests refer to the name helpers by calling them rather than hard-coding a .json string to compare against.</p><h3>The honest bit</h3><p>The formats package also has working, tested writers for TFRecord, for WebDataset tar shards, and for Apache Arrow batches. But only Parquet is actually wired into a live path right now. The others are ready to plug into the same stage-then-commit path as their consumers show up, for example a real tf.data training job or a PyTorch data loader.</p><p>I want the docs to say that plainly rather than let “supports five formats” imply five live producers. It is one live producer and four honest, tested writers. The value of the setup is that adding the next live format is a worker-side change against a commit path that already does not care what the bytes are. But the map is not the territory, and the writeup says so.</p><h3>Story two. 91 percent of ingest time was a lock</h3><p>Ingest walks a local folder, and for each image it does four things. It opens and stats the file. It checksums the file with SHA-256. It uploads the file to the object store. And it records a metadata row in a small SQLite database. The natural assumption is that the upload dominates the time, since it is the one step that goes over the network and everything else is local.</p><p>That assumption was wrong. The only reason we know is that the pipeline is instrumented to attribute busy time to each of the four steps. Here is the struct that carries those numbers back.</p><pre>// internal/ingestion/pipeline.go<br>type Progress struct {<br>    Processed int64<br>    Failed int64<br>    Bytes int64<br>    // Total busy time per step across all workers, in nanoseconds. This is the<br>    // relative cost breakdown of open+stat vs checksum vs upload vs DB insert,<br>    // which answers &quot;where does ingest time actually go&quot; without guessing.<br>    OpenNanos int64<br>    ChecksumNanos int64<br>    UploadNanos int64<br>    IndexNanos int64<br>}</pre><p>The measurement was blunt and surprising. The SQLite insert step was about 91 percent of all ingest busy time. Not the upload. Not the hashing. The database write.</p><h3>Two root causes, one obvious and one hidden in a driver</h3><p><strong>Cause one was a wrong pragma string in the database setup.</strong> The metadata store uses the modernc.org/sqlite driver, which expects settings written in a specific form. The code had been written using a different, older driver&#39;s form, which this driver <em>silently ignores</em>. The effect was that write-ahead logging never actually turned on, and the busy timeout was left at zero. So when two ingest workers tried to write at the same time, one got an instant &quot;database is busy&quot; error and dropped its row, instead of waiting a moment and retrying. The fix is one line, but you only find it by looking.</p><pre>// internal/metadata/index.go<br>db, err := sql.Open(&quot;sqlite&quot;,<br>    path+&quot;?_pragma=journal_mode(WAL)&amp;_pragma=busy_timeout(30000)&quot;)</pre><p>Write-ahead logging lets readers and a writer work at the same time, and a 30-second busy timeout means a bulk ingest of millions of files <em>waits out</em> write contention instead of dropping the occasional row.</p><p><strong>Cause two was the design itself.</strong> Even with the settings fixed, SQLite allows only one writer at a time. If every one of the many upload workers writes its own row directly, they all fight over that single writer lock, and each one pays the cost of forcing its write to disk. The uploads run in parallel beautifully, but the writes line up one behind another, and that lining up was hidden behind a lock nobody was profiling.</p><h3>The fix. Split the parallel part from the serial part</h3><p>Redesign the pipeline so the two halves are separate. The upload workers do the part that parallelizes well, which is open, checksum, and upload, and then hand the finished record off to a single writer goroutine. They never touch SQLite themselves. Here is the shape.</p><pre>// internal/ingestion/pipeline.go, inside IngestDir<br>for i := 0; i &lt; p.workers; i++ {<br>    go func() {<br>        for job := range jobs {<br>            rec, n, t, err := p.uploadFile(ctx, job)<br>            // ... fold each step&#39;s timing into shared atomic counters ...<br>            if err != nil { failed.Add(1); continue }<br>            records &lt;- indexReq{rec: rec, size: n}  // hand off, never write SQLite here<br>        }<br>    }()<br>}</pre><pre>// The single writer. This is the whole reason ingest stopped being 91 percent<br>// lock-wait. It drains records and commits them in batches.<br>go func() {<br>    batch := make([]metadata.DataRecord, 0, p.batchSize)<br>    flush := func() {<br>        // ... one transaction, one prepared statement, one disk flush per batch ...<br>        _ = p.idx.InsertBatch(ctx, batch)<br>        batch = batch[:0]<br>    }<br>    for req := range records {<br>        batch = append(batch, req.rec)<br>        if len(batch) &gt;= p.batchSize { flush() }<br>    }<br>    flush()  // final partial batch<br>}()</pre><p>Two good things happen here.</p><p><strong>First</strong>, the single writer is now used by exactly one caller. SQLite’s one-writer rule stops being a fight, because there is only ever one goroutine holding the lock. The lock-wait that was 91 percent of the time is simply not in the path anymore.</p><p><strong>Second</strong>, inserts are batched. InsertBatch groups a batch of records, 500 by default, into one transaction with one prepared statement, so the writer takes its lock and forces to disk <em>once per batch instead of once per image</em>. Spreading that one disk flush across 500 rows is the difference between a per-row and a per-batch durability cost. Here is that batch write.</p><pre>// internal/metadata/index.go, one lock, one disk flush, whole batch atomic<br>func (idx *Index) InsertBatch(ctx context.Context, recs []DataRecord) error {<br>    tx, _ := idx.db.BeginTx(ctx, nil)<br>    stmt, _ := tx.PrepareContext(ctx, `INSERT OR REPLACE INTO records (...) VALUES (...)`)<br>    for _, r := range recs {<br>        if _, err := stmt.ExecContext(ctx /* ...12 columns... */); err != nil {<br>            tx.Rollback()<br>            return err<br>        }<br>    }<br>    return tx.Commit()  // the whole batch commits or rolls back together<br>}</pre><p>The channel that carries records to the writer is buffered generously, so an upload worker never has to wait to hand off a finished record while the writer is mid-commit. And the shutdown order matters. First close the jobs channel, then wait for all uploads to finish, so no more records can be sent, then close the records channel so the writer drains what is left and flushes the final partial batch, then wait for the writer to report it is done. Get that order wrong and you either deadlock or lose the tail of the last batch.</p><h3>The lesson both stories share</h3><p>The result-format story and the ingest story are the same move made twice.</p><p>On the way <em>out</em>, do not pick a format from a gut feeling about what consumers want. Pick the one the query engines read natively, which is Parquet, and design the commit path so it never depends on the format, so the choice is cheap to make and cheap to change later.</p><p>On the way <em>in</em>, do not pick a bottleneck from a gut feeling about what is slow, which everyone assumed was the network. Instrument every step, and let the measurement point at the real culprit, which was a silently-ignored setting and a single-writer lock. The fix that follows, parallel uploads feeding one batched writer, is only obvious once the 91 percent number exists.</p><p>Both are the same discipline. Make the system tell you where the cost really is, then let that answer drive the design instead of your assumptions.</p><p>Links:<br><a href="https://medium.com/@abhiramdodda/exactly-once-results-in-an-ap-system-two-phase-commit-raft-and-the-window-you-cant-close-916fe73c4e59?sharedUserId=abhiramdodda">Part 1: Exactly-once results in an AP system: two-phase commit, Raft, and the window you can’t close</a></p><p><a href="https://medium.com/@abhiramdodda/bounded-leases-and-bounded-queues-8554a921d828?sharedUserId=abhiramdodda">Part 2: Bounded leases and bounded queues</a></p><p>Codebase: <a href="https://github.com/AbhiramDodda/distributed-image-processing-system">https://github.com/AbhiramDodda/distributed-image-processing-system</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e25bd2bd0364" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bounded leases and bounded queues]]></title>
            <link>https://medium.com/@abhiramdodda/bounded-leases-and-bounded-queues-8554a921d828?source=rss-a0eeb0ee0600------2</link>
            <guid isPermaLink="false">https://medium.com/p/8554a921d828</guid>
            <category><![CDATA[backpressure]]></category>
            <category><![CDATA[work-stealing]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Abhiram Dodda]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 16:43:56 GMT</pubDate>
            <atom:updated>2026-08-13T00:28:48.288Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 2 of a series on the internals of a distributed image-processing platform. Read </em><a href="https://medium.com/@abhiramdodda/exactly-once-results-in-an-ap-system-two-phase-commit-raft-and-the-window-you-cant-close-916fe73c4e59?sharedUserId=abhiramdodda"><em>Part 1</em></a><em> first, since this post builds on the lease generation idea from there.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dp0K5-FmVyYl8pJgvcMCYA.png" /></figure><p>This post covers two scheduling problems that look unrelated but share a backbone. The first is about keeping one oversized chunk of work from dragging down a whole job. The second is about keeping the scheduler from drowning when too much work arrives at once. Both come down to <em>refusing to be greedy</em> at one specific spot, because being greedy there would cost you a guarantee you care about.</p><h3>Problem one. The one giant shard</h3><p>Work is split by a hash of the image name into 256 buckets called shards, and one shard is one task. Splitting this way keeps the buckets roughly even in <em>count</em>, and the system already balances tasks across workers fine.</p><p>What it cannot handle on its own is when one shard is far <em>bigger</em> than the others. A shard that holds 50 times the data of its neighbors is a single task that one worker has to grind through alone while everyone else sits idle. The slowest shard sets how long the whole job takes. This is the kind of problem a dashboard of average timings hides, right up until a lopsided dataset shows up and the job runs for hours.</p><p>What we want is for a second worker to <em>help finish</em> a big shard, without ever processing the same image twice.</p><h3>Why the intuitive fixes fail</h3><p><strong>Split every shard into K pieces up front.</strong> Now you have to guess K. Guess too high and you add overhead to the thousands of small shards that never needed splitting. Guess too low and you have not helped the big ones. And a fixed guess cannot react to how fast workers actually turn out to be at runtime.</p><p><strong>Put every tiny piece of work into one central queue.</strong> This balances load naturally, but now the coordinator has to list and track every single piece. With billions of images that is a huge amount of state to hold, and it throws away the whole “do the work where the data already lives” idea that made sharding worthwhile.</p><p><strong>Steal work based on how far the victim says it has gotten.</strong> This one is tempting and it is <em>wrong</em>. Say the victim last reported it was at image number 1000, so you steal everything from 1000 onward and hand it to a helper. The problem is that reports arrive late. The victim might already be at image 1200 and just not have told you yet. Now the helper redoes images 1000 through 1200. The reported position is a <em>floor</em> on real progress, and you cannot safely steal against a floor.</p><h3>The design. Lease only a bounded chunk at a time</h3><p>The fix is to make the steal boundary track a <em>ceiling</em> on the victim’s progress that the scheduler <em>controls</em>, instead of a floor that the victim <em>reports</em>.</p><p>Each task owns a half-open range of the shard, written as start up to but not including end, plus a lease. The key move is that when a worker renews its lease, the scheduler grants it only the next small chunk of items. A worker is not allowed to touch anything past its granted point until it renews and gets more. Here is that renewal.</p><pre>// internal/scheduler/scheduler.go<br>func (s *Scheduler) RenewLease(taskID string, req RenewLeaseRequest) (LeaseRenewal, error) {<br>    // ...<br>    // Move the reported frontier forward only. A late or stale report can<br>    // never push it backwards.<br>    if req.Frontier &gt; t.Frontier {<br>        t.Frontier = req.Frontier<br>    }<br>    // Grant the next chunk. This is the furthest the worker may now reach<br>    // before it has to renew again.<br>    s.grantLocked(t)<br>    return LeaseRenewal{<br>        Generation: t.Generation,<br>        Bound: t.Granted,<br>        Stolen: req.Generation &lt; t.Generation,<br>    }, nil<br>}</pre><p>That gives us the rule the whole design leans on. Written out, the four positions always sit in this order.</p><pre>RangeStart  &lt;=  Frontier  &lt;=  Granted  &lt;=  RangeEnd</pre><p>Frontier is where the worker <em>says</em> it is. Granted is the furthest it is <em>allowed</em> to be. The worker&#39;s true position is somewhere between those two, but it can never go past Granted, because it is required to renew before touching anything beyond it. So everything from Granted to RangeEnd is <em>guaranteed untouched</em>. That untouched tail is the only region the scheduler ever steals from. Here is the steal.</p><pre>// internal/scheduler/scheduler.go, inside stealLocked<br>tail := t.RangeEnd - t.Granted // the region the worker has not been leased yet<br>// ... pick the victim with the largest such tail ...<br>split := victim.Granted + bestTail/2<br>stolen := &amp;Task{<br>    // ... same JobID and Shard ...<br>    RangeStart: split,<br>    RangeEnd: victim.RangeEnd,<br>    Frontier: split,<br>    Granted: split,<br>    Split: true,<br>}<br>victim.RangeEnd = split<br>victim.Generation++   // bump so the victim learns it was stolen from on its next renewal<br>victim.Split = true</pre><p>A steal splits the untouched tail in half, shrinks the victim’s end, and bumps the victim’s lease generation. That generation bump is the same fencing token from Part 1. The victim finds out it was stolen from on its <em>next</em> renewal, where it sees Stolen come back true, and it simply stops early at the new boundary. No message has to interrupt it mid-work. The truth reaches it lazily through the renewal it was going to do anyway.</p><p>Three things make this clean.</p><ul><li><strong>Nothing is processed twice.</strong> The split point is at or past Granted, so no image the victim <em>might</em> have already touched is ever handed to someone else.</li><li><strong>No gaps and no overlap.</strong> The two ranges, start to split and split to end, sit right next to each other and never share an item.</li><li><strong>No shared state beyond a few integers.</strong> S3 lists names in sorted order, so the victim and the helper both count into the <em>same</em> sorted list of images. The only thing they share is the range numbers.</li></ul><p>And it fits the exactly-once commit from Part 1 for free. FinalResultKey already puts the range into the result name, so each split piece commits to its own separate, idempotent spot. Stealing needed zero changes to the commit path.</p><h3>The cost, said plainly</h3><p>Workers have to renew, which is extra back-and-forth roughly proportional to the work divided by the chunk size. The chunk size is a dial. Small chunks mean finer stealing but more renewals. That is a deliberate trade. A little extra chatter in exchange for a <em>provable</em> promise that nothing is ever processed twice. The other designs were cheaper in messages and simply wrong.</p><h3>Problem two. A thousand jobs land at the same moment</h3><p>Submit a thousand jobs and you have just scheduled a quarter of a million tasks. With no admission control the scheduler’s in-progress pile explodes and response times climb with no ceiling. Multi-tenancy adds a second demand on top. One tenant’s burst must not starve another tenant.</p><h3>Why an unbounded queue is a trap</h3><p>The reflex is “accept everything, hold it in an internal queue, and drain it as fast as we can”. That is exactly the setup for a latency collapse. There is a simple rule from queueing theory, Little’s Law, that says the amount of work sitting in a queue equals the arrival rate times the wait time. If work arrives as fast as or faster than you can finish it, the queue and the wait both grow with no limit. The system looks perfectly healthy at a steady trickle, then falls over the moment a burst hits. And it falls over in the worst way, by getting slower and slower rather than by clearly saying no.</p><p>Rate limiting alone does not save you either. A token bucket limits the <em>rate</em> of arrivals, not the <em>amount</em> of work in progress. A steady, within-limit stream of long jobs still piles up without bound. You have to limit the thing that actually hurts you, which is how much is in flight, not how fast requests come in.</p><h3>The design. Turn work away instead of queueing it</h3><p>There is a global cap on how many jobs can be in flight at once. Past that cap, a new submission is turned away with a 429 and a Retry-After header, rather than being queued. Here is the check.</p><pre>// internal/admission/controller.go<br>func (c *Controller) Admit(tenant string) (*Ticket, error) {<br>    // ... check the tenant&#39;s weighted share AND the global cap, then reserve ...<br>    if c.total+1 &gt; c.cfg.MaxInFlight {<br>        return nil, fmt.Errorf(&quot;global in-flight cap %d reached: %w&quot;,<br>            c.cfg.MaxInFlight, ErrRejected)<br>    }<br>    // ...<br>}</pre><p>Because this caps the <em>amount of work in progress</em>, it caps the wait time no matter how fast requests arrive. That is the property an unbounded queue can never give you. A held slot is freed the instant a job reaches a final state, through a scheduler hook that runs when the job is done, so capacity keeps cycling without any cleanup sweeper.</p><p>Multi-tenancy is layered on with weights. Capacity is split across tenants in proportion to their weight, with a floor of one so a low-weight tenant is never squeezed down to nothing. Here is the share calculation.</p><pre>// internal/admission/controller.go, inside shareLocked<br>s := c.cfg.MaxInFlight * cl.Weight / c.totalWeight</pre><p>Here is the part I find genuinely nice. Once you turn work away instead of queueing it, each tenant behaves like a well-studied model called an Erlang-B loss system. Its rejection rate is a plain formula of how much load it offers and how big its share is. That means the fraction of requests you will reject under a given load is a number you can work out <em>ahead of time from the config</em>, not a nasty surprise you discover during an outage. Choosing to shed did not just bound latency. It made the overload behavior something you can predict on paper.</p><h3>The trade-off, written down</h3><p>Hard per-tenant shares favor <em>isolation over utilization</em>. A quiet tenant’s reserved slots sit empty rather than being lent to a busy neighbor. There is a fancier scheme, weighted fair queuing, that would lend out that idle capacity. But it needs a real async queue, which brings back the unbounded-wait risk you just got rid of, and it puts fairness bookkeeping on the hot path. The loss-system design is simpler, predictable, and you can analyze it with a formula, which is the right default for a platform whose main multi-tenant job is stopping one tenant from hurting another. If squeezing out more utilization ever became the top priority, weighted fair queuing is the written-down next step. But you would be trading a proven ceiling for a better average, with your eyes open.</p><h3>The backbone both problems share</h3><p>Both are solved by refusing to be greedy at exactly one spot.</p><ul><li>Work stealing takes only from the <em>guaranteed untouched</em> tail, never the region the victim might be inside, even though grabbing more would balance faster.</li><li>Admission <em>turns work away</em> past a cap, never queues it, even though queueing would reject fewer submissions.</li></ul><p>In both cases the greedy choice buys a better average and a worse guarantee. The platform takes the guarantee. Nothing processed twice, and a bounded in-progress pile whose overload behavior you can predict. That is the running theme of this series. A provable ceiling beats an optimistic average when the average’s failure mode has no bottom.</p><p>Part 3: <a href="https://medium.com/@abhiramdodda/columnar-results-and-the-ingest-bottleneck-that-wasnt-the-network-e25bd2bd0364?sharedUserId=abhiramdodda">Columnar results, and the ingest bottleneck that wasn’t the network</a></p><p>Codebase: <a href="https://github.com/AbhiramDodda/distributed-image-processing-system">https://github.com/AbhiramDodda/distributed-image-processing-system</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8554a921d828" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exactly-once results in an AP system: two-phase commit, Raft, and the window you can’t close]]></title>
            <link>https://medium.com/@abhiramdodda/exactly-once-results-in-an-ap-system-two-phase-commit-raft-and-the-window-you-cant-close-916fe73c4e59?source=rss-a0eeb0ee0600------2</link>
            <guid isPermaLink="false">https://medium.com/p/916fe73c4e59</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[exactly-once-semantics]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Abhiram Dodda]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 16:05:10 GMT</pubDate>
            <atom:updated>2026-08-13T00:29:53.479Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 1 of a series on the internals of a distributed image-processing platform.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0VWDNQDPD480AcMWJp73KQ.png" /></figure><h3>What problem are we actually solving?</h3><p>The platform runs image-processing code over a huge pile of images stored in an object store like S3. A worker grabs a slice of work, does the computation, and then has to save its result somewhere.</p><p>The tricky part is how the work gets handed out. Workers pull jobs on their own. There is no central boss telling each worker exactly what to do and making sure nobody overlaps. This is a deliberate choice. It keeps the system available even when the network splits, and it avoids a coordination step on every single task, which would be slow at this scale.</p><p>The price of that choice is that the <em>same task can run more than once</em>. This is not a rare bug. It is built into how the system works. Here are the normal ways it happens.</p><ul><li>A worker finishes a task and reports it, but the network drops the reply, so it reports again.</li><li>A big shard gets split so a second worker can help finish it, and the two workers briefly overlap on the boundary.</li><li>The coordinator crashes and a new one takes over, re-handing-out work whose result was still on its way in.</li></ul><p>Every one of those is a feature we want. And every one of them can end with two workers trying to save the same result at the same time. So the real question is this. How do we make sure a result lands in its final place <strong>exactly once</strong>, even though the work behind it might run several times.</p><h3>Why the easy answers do not work</h3><p>Before the real design, it helps to see why the obvious options fail, because each one fails in a way that teaches you what the design has to protect against.</p><p><strong>Have the worker write straight to the final location, then report done.</strong> This is the simplest thing. It is also broken. Someone reading the result can catch it half-written. And two workers running the same task both write to the same spot with no agreed rule for who wins. You have not removed the race. You have pushed it downstream onto whoever reads the results.</p><p><strong>Have the workers talk to each other to decide who writes.</strong> Now you have added a coordination step back onto the fast path. That is the exact cost the pull-based design was trying to avoid, so this defeats the point.</p><p><strong>Wrap the write in a database transaction.</strong> Object stores and databases are separate systems and cannot commit together as one atomic step. You would also be putting a database in the path of every result write, which is slow and fragile.</p><p>None of these is good enough, so the platform does something with two steps instead of one.</p><h3>The design. Stage first, then commit</h3><p>The idea is to separate <em>producing</em> a result from <em>publishing</em> it.</p><p><strong>Step one is staging.</strong> The worker writes its output to a private staging location that no reader ever looks at. The location is named after the task. Here is the helper that builds that name.</p><pre>// internal/scheduler/commit.go<br>func StagingResultKey(jobID, taskID string) string {<br>    return fmt.Sprintf(&quot;staging/%s/%s.parquet&quot;, jobID, taskID)<br>}</pre><p>One thing worth noticing early. Nothing in the system ever reads this staged object back and tries to understand it. It is write-only as far as the platform is concerned. That fact turns out to matter a lot later, and it is why we could later change what format the staged bytes are in without touching any of this commit logic.</p><p><strong>Step two is committing.</strong> The coordinator makes the result visible by copying it, inside the object store, to its real final location. Here is the helper that builds that final name.</p><pre>// internal/scheduler/commit.go<br>func FinalResultKey(jobID, shard string, rng Range) string {<br>    if !rng.Split {<br>        return fmt.Sprintf(&quot;results/%s/%s.parquet&quot;, jobID, shard)<br>    }<br>    return fmt.Sprintf(&quot;results/%s/%s/%012d-%012d.parquet&quot;, jobID, shard, rng.Start, rng.End)<br>}</pre><p>Now look closely at what FinalResultKey depends on. It is built only from the <em>identity of the work itself</em>, which is the job, the shard, and the range of items covered. It does <strong>not</strong> depend on which worker did the job, which attempt this was, or how many times the task has been retried. So no matter how many times the same logical work runs, they all compute the <em>same</em> final destination.</p><p>Put the two steps together and the exactly-once behavior falls out.</p><ul><li>A re-run stages a brand new object under its own task-named staging spot, so retries never clobber each other while they are still in progress.</li><li>But committing is a copy into a <em>fixed</em> final spot.</li><li>Copying into a fixed spot twice leaves you with one object, not two. The second copy just overwrites the first with identical bytes.</li></ul><p>So duplicates at the compute layer quietly collapse into a single result at the storage layer. Readers only ever see finished, committed results, because staging lives under a prefix they never look at.</p><p>One practical detail. The copy happens <em>outside</em> the scheduler’s main lock, guarded by a simple check that the task is not already done. A within-the-store copy is slow compared to the scheduler’s normal work, and holding the main lock across it would make every other task wait behind object-store latency. Because a duplicate copy is harmless, it is safe to run it without the lock held.</p><h3>Making the decision itself happen once, not just the bytes</h3><p>The idempotent copy gives us a result that lands once. It does <strong>not</strong>, by itself, give us one agreed answer to the question “which attempt won and is this task now done”.</p><p>In a setup with more than one coordinator for high availability, that gap is dangerous. Two coordinators might each think they own the same task. The copy still dedups the bytes, but the two coordinators now disagree about whether the task is finished. And a new coordinator taking over after a crash rebuilds its own answer from its own local log, which might not match. This is the classic split-brain situation.</p><p>So the “this task is committed” decision is not just written to local disk. When a decider is attached, that decision is proposed into a replicated <strong>Raft</strong> log, which is a way for several coordinators to agree on a single ordered history of decisions. Here is the shape of it.</p><pre>// internal/scheduler/commit.go<br>type CommitDecision struct {<br>    TaskID string<br>    JobID string<br>    Generation int64   // the lease generation, used as a fencing token<br>    FinalKey string<br>}</pre><pre>type CommitDecider interface {<br>    // Decide must be idempotent and fenced. Calling it twice for the same task<br>    // returns the same winner, and a decision carrying an older Generation than<br>    // one already recorded loses to it.<br>    Decide(ctx context.Context, d CommitDecision) (winner CommitDecision, err error)<br>}</pre><p>Routing the decision through Raft buys three things at once.</p><ul><li><strong>One agreed answer across all coordinators.</strong> The replicated log has a single order, so there is exactly one “task X committed” entry. No split-brain.</li><li><strong>Old attempts get fenced out.</strong> Generation is a number that only goes up. A stale attempt, for example one that was split away from and does not know it yet, carries an older generation and loses. That is why Decide can hand back a winner that is different from what you asked about, when a newer attempt already won.</li><li><strong>The decision survives crashes.</strong> It is stored on a majority of nodes, so a new coordinator inherits a trustworthy record of what is done and never re-hands-out a finished task.</li></ul><p>The payoff is that recovery is not guesswork. Whether a task is committed is a fact a majority already agreed on, not something a single node reconstructs and hopes is right.</p><h3>The one gap you cannot close, and how to make it safe anyway</h3><p>Here is the honest part, and it is the part that separates a real design from a hand-wave.</p><p>Consensus makes the <em>result bytes</em> and the <em>commit decision</em> happen exactly once. It does <strong>not</strong> make arbitrary <em>side effects</em> happen exactly once. Look at the order of operations. First we copy, then we decide. If the coordinator crashes in the tiny gap <em>between</em> the copy and the decision, the task runs again. The result is fine, because copying is idempotent. But if the task also did something to the outside world, like charging a card or calling a webhook or pushing to a downstream queue, that outside action happens a second time.</p><p>You cannot fix this by adding more consensus, and it is worth understanding why, because the reflex is always “add another log entry”. The object store, the Raft log, and the downstream system are three separate systems. No single action touches all three at once as one atomic step. This is a fundamental limit, the same reason two-phase commit across independent systems can get stuck. You do not get to wish it away.</p><p>So instead of trying to deliver a side effect <em>exactly</em> once, which is impossible here, the platform makes re-delivery <em>safe</em>. It delivers the side effect <em>at least</em> once, but stamps it with a stable idempotency key, and lets the receiver throw away duplicates. At least once delivery plus a receiver that ignores repeats equals effectively once.</p><p>The key, like the final result location, is built from the identity of the work. Here is how it is derived.</p><pre>// internal/scheduler/commit.go<br>func SideEffectKey(jobID, shard string, rng Range) string {<br>    sum := sha256.Sum256([]byte(FinalResultKey(jobID, shard, rng)))<br>    return &quot;sfx-&quot; + hex.EncodeToString(sum[:16])<br>}</pre><p>It is the side-effect version of FinalResultKey, and it is even built from it. The same &quot;does not depend on the attempt or the worker&quot; property that makes the result copy idempotent also makes this a stable handle for throwing away duplicates. Every re-run of the same logical work, whether from a retry, a rebalance, or a failover, computes the <em>same</em> key. That is exactly the handle a downstream needs to collapse the repeats that re-running produces. And because it is just an opaque hash, it is safe to hand to untrusted algorithm code as PETABYTE_IDEMPOTENCY_KEY and safe to forward to any downstream, since it leaks nothing about internal layout.</p><p>The platform uses this key at three levels.</p><ol><li><strong>One key per unit of work</strong>, built from the job, shard, and range.</li><li><strong>Passed into untrusted algorithm code</strong> as PETABYTE_IDEMPOTENCY_KEY, so an algorithm that writes to some downstream can stamp its own writes with it and have those deduped too. This is the general case the platform cannot reach on its own.</li><li><strong>Enforced for effects the platform itself sends</strong>, by firing the side effect after the commit is agreed but before the final local mark, so delivery is at least once, with an idempotency ledger in front of it that lets each key through only once. That ledger stands in for whatever the real downstream offers, like a unique constraint or a broker dedup window.</li></ol><h3>The guarantee, stated plainly</h3><p>It is layered, because that is what it honestly is.</p><ul><li>The result bytes land exactly once, from the idempotent copy into an identity-based location.</li><li>The commit decision is made exactly once, from Raft, fenced by generation.</li><li>Side effects are effectively once for any receiver that honors the key we generate.</li></ul><p>The one thing that can still repeat is the <em>computation</em> itself. Never a duplicated committed result, and never a double-applied keyed effect. That leftover is not a bug to be fixed. It is the unavoidable cost of spanning three systems that cannot commit together as one. The real skill is knowing exactly where the guarantee ends, and making the part past that line <em>safe</em> instead of pretending it is impossible.</p><p>Part 2: <a href="https://medium.com/@abhiramdodda/bounded-leases-and-bounded-queues-8554a921d828?sharedUserId=abhiramdodda">Bounded leases and bounded queues</a></p><p>Codebase: <a href="https://github.com/AbhiramDodda/distributed-image-processing-system">https://github.com/AbhiramDodda/distributed-image-processing-system</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=916fe73c4e59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern C++ Memory Management: Smart Pointers, RAII, and Move Semantics]]></title>
            <link>https://medium.com/@abhiramdodda/modern-c-memory-management-smart-pointers-raii-and-move-semantics-545f135cb365?source=rss-a0eeb0ee0600------2</link>
            <guid isPermaLink="false">https://medium.com/p/545f135cb365</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[modern-cpp]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Abhiram Dodda]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 18:37:08 GMT</pubDate>
            <atom:updated>2026-03-12T18:41:15.157Z</atom:updated>
            <content:encoded><![CDATA[<p>A Deep Dive into How C++ Evolved to Make Memory Safe, Efficient, and Expressive</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttRyBEvnUuVxjR2h3HmITQ.png" /><figcaption>Generated using Gemini</figcaption></figure><h3>1. The Old World: Manual Memory Management in C and Early C++</h3><p>To truly appreciate what modern C++ brings to the table, you need to feel the pain of what came before. Before C++11, memory management in C++ was largely inherited from C .Programmer was entirely responsible for every byte of memory allocated and freed.</p><p>In C, dynamic memory worked like this:</p><pre>// C-style dynamic memory<br>int* arr = (int*)malloc(10 * sizeof(int));<br>if (arr == NULL) {<br>    // handle allocation failure<br>}<br><br>// ... use arr ...<br><br>free(arr);   // You MUST remember this<br>arr = NULL;  // Best practice, but not enforced</pre><p>C++ introduced <strong>new</strong> and <strong>delete</strong> as typed, constructor-aware alternatives:</p><pre>// Early C++ style<br>int* p = new int(42);<br>std::string* s = new std::string(&quot;hello&quot;);<br><br>// ... use p and s ...<br><br>delete p;<br>delete s;</pre><p>And for arrays:</p><pre>int* arr = new int[100];<br>// ...<br>delete[] arr;   // Note: MUST use delete[], not delete</pre><p>This was an improvement over malloc/free because constructors and destructors were called, and you didn&#39;t need to manually compute sizes. But the fundamental problem remained: <strong>the programmer was solely responsible for ensuring every allocation had exactly one corresponding deallocation.</strong></p><h3>2. The Problems That Demanded a Solution</h3><p>Manual memory management seems straightforward in toy examples. In real codebases with thousands of lines, multiple developers, complex control flow, and exception handling, it becomes a minefield. Here are the specific problems that made C++ unsafe and brittle.</p><h4>2.1 Memory Leaks</h4><p>A memory leak happens when you allocate memory but never free it. The memory remains occupied for the lifetime of the process. In long-running programs, servers, games, desktop apps, leaks accumulate until the system runs out of memory.</p><pre>void processData() {<br>    int* buffer = new int[1024];<br>    <br>    if (someConditionFails()) {<br>        return;   // LEAK! buffer is never deleted<br>    }<br>    <br>    // ... do work ...<br>    <br>    delete[] buffer;<br>}</pre><p>This looks harmless, but every early return path must remember to delete the buffer. Add more branches, and the problem multiplies exponentially.</p><h4>2.2 Dangling Pointers</h4><p>A dangling pointer is a pointer that refers to memory that has already been freed. Using it is undefined behavior, it might crash, silently corrupt data, or appear to work correctly and fail later in an unrelated location.</p><pre>int* p = new int(10);<br>delete p;<br><br>*p = 20;   // UNDEFINED BEHAVIOR — p is dangling<br>std::cout &lt;&lt; *p;  // May print garbage, may crash, may appear to work</pre><p>A subtler version arises when multiple pointers point to the same object:</p><pre>int* a = new int(5);<br>int* b = a;   // b and a point to the same object<br><br>delete a;<br>// Now b is dangling — but nothing tells you this<br>std::cout &lt;&lt; *b;  // Disaster</pre><h4>2.3 Double Free</h4><p>If you delete the same pointer twice, you corrupt the heap. This is a serious bug that can lead to crashes, data corruption, or security vulnerabilities.</p><pre>int* p = new int(42);<br>delete p;<br>delete p;   // DOUBLE FREE — undefined behavior, heap corruption</pre><h4>2.4 Exception Safety</h4><p>Before C++11, writing exception-safe code with raw pointers was genuinely hard. If an exception was thrown between a <strong>new</strong> and its corresponding <strong>delete</strong>, the memory leaked.</p><pre>void riskyFunction() {<br>    int* data = new int[500];<br>    <br>    doSomethingThatMightThrow();  // If this throws, data leaks forever<br>    <br>    delete[] data;<br>}</pre><p>You could try/catch, but that turned every function into a mess of cleanup logic:</p><pre>void riskyFunction() {<br>    int* data = new int[500];<br>    try {<br>        doSomethingThatMightThrow();<br>    } catch (...) {<br>        delete[] data;  // Don&#39;t forget this in every catch block<br>        throw;<br>    }<br>    delete[] data;<br>}</pre><p>This is verbose, error-prone, and completely unscalable when you have multiple resources.</p><h4>2.5 Ownership Ambiguity</h4><p>Raw pointers carry no information about ownership. When you see a function like this:</p><pre>void process(int* data);</pre><p>You cannot tell:</p><ul><li>Does <strong>process</strong> own <strong>data</strong> and should delete it?</li><li>Is <strong>data</strong> borrowed and the caller retains ownership?</li><li>Is <strong>data</strong> shared between multiple owners?</li></ul><p>This ambiguity led to entire classes of bugs where memory was freed by one part of a program while another part was still using it, or where neither part freed it at all.</p><h4>2.6 The auto_ptr Mistake (C++98)</h4><p>C++98 introduced <strong>std::auto_ptr</strong> as an early attempt at a smart pointer with automatic cleanup. It had a fatal flaw: its &quot;copy&quot; semantics were actually <strong>move</strong> semantics — copying an <strong>auto_ptr</strong> would transfer ownership from the source to the destination, leaving the source as null.</p><pre>std::auto_ptr&lt;int&gt; a(new int(42));<br>std::auto_ptr&lt;int&gt; b = a;  // a is now NULL — destructive copy!<br><br>std::cout &lt;&lt; *a;  // CRASH — a is null</pre><p>This made <strong>auto_ptr</strong> incompatible with standard containers (like std::vector), which relied on copy semantics. It was deprecated in C++11 and removed in C++17. But its existence showed the community what was needed: a pointer type that could transfer ownership safely — and that required move semantics to do it correctly.</p><h3>3. RAII — Resource Acquisition Is Initialization</h3><p>RAII is the foundational philosophy behind all of modern C++ resource management. The principle is simple:</p><p><em>Tie the lifetime of a resource to the lifetime of an object. Acquire the resource in the constructor. Release it in the destructor.</em></p><p>When a C++ object goes out of scope, its destructor is called automatically, even if an exception is thrown. This means that if you wrap a resource (memory, file handle, mutex lock, network socket) in an object, cleanup becomes automatic and foolproof.</p><pre>class ManagedBuffer {<br>public:<br>    explicit ManagedBuffer(size_t size)<br>        : data_(new int[size]), size_(size) {<br>        std::cout &lt;&lt; &quot;Resource acquired\n&quot;;<br>    }<br><br>    ~ManagedBuffer() {<br>        delete[] data_;<br>        std::cout &lt;&lt; &quot;Resource released\n&quot;;<br>    }<br><br>    int* get() { return data_; }<br>    size_t size() const { return size_; }<br><br>    // Prevent copying (for now)<br>    ManagedBuffer(const ManagedBuffer&amp;) = delete;<br>    ManagedBuffer&amp; operator=(const ManagedBuffer&amp;) = delete;<br><br>private:<br>    int* data_;<br>    size_t size_;<br>};<br><br>void useBuffer() {<br>    ManagedBuffer buf(1024);  // Resource acquired here<br>    <br>    doSomethingThatMightThrow();  // Even if this throws...<br>    <br>    // ... buf&#39;s destructor is ALWAYS called when it goes out of scope<br>    // Resource is always released — no leak possible<br>}</pre><p>RAII also works beautifully with mutexes:</p><pre>class LockGuard {<br>public:<br>    explicit LockGuard(std::mutex&amp; m) : mutex_(m) {<br>        mutex_.lock();<br>    }<br>    ~LockGuard() {<br>        mutex_.unlock();  // Always released, even on exception<br>    }<br>private:<br>    std::mutex&amp; mutex_;<br>};<br><br>std::mutex globalMutex;<br><br>void threadSafeOperation() {<br>    LockGuard lock(globalMutex);  // Lock acquired<br>    <br>    // ... do work ...<br>    <br>    // Lock is automatically released at end of scope<br>}</pre><p>The standard library provides <strong>std::lock_guard</strong> and <strong>std::unique_lock</strong> for exactly this purpose.</p><p><strong>RAII is not just a pattern, it is the design philosophy that makes all of modern C++ memory management possible.</strong></p><h3>4. Smart Pointers: The Modern Answer</h3><p>Smart pointers are RAII wrappers around raw pointers. They live in the<strong> &lt;memory&gt;</strong> header, introduced properly in C++11. They automatically delete the pointed-to object when appropriate, encode ownership semantics in the type system, and eliminate the need for manual <strong>delete</strong> in nearly all cases.</p><p>The three smart pointers are:</p><ul><li><strong>std::unique_ptr</strong> — sole ownership</li><li><strong>std::shared_ptr</strong> — shared ownership with reference counting</li><li><strong>std::weak_ptr</strong> — non-owning observer of a shared_ptr</li></ul><h4>4.1 std::unique_ptr</h4><p><strong>unique_ptr</strong> represents <strong>exclusive ownership</strong>. At any point in time, exactly one <strong>unique_ptr</strong> owns the underlying object. When the <strong>unique_ptr</strong> is destroyed (goes out of scope), the owned object is deleted. It cannot be copied — only moved.</p><pre>#include &lt;memory&gt;<br>#include &lt;iostream&gt;<br><br>int main() {<br>    std::unique_ptr&lt;int&gt; p = std::make_unique&lt;int&gt;(42);<br>    <br>    std::cout &lt;&lt; *p &lt;&lt; &quot;\n&quot;;  // 42<br>    std::cout &lt;&lt; p.get() &lt;&lt; &quot;\n&quot;;  // Raw pointer address<br>    <br>    // No need to call delete — automatic cleanup<br>    return 0;<br>}</pre><p>Always prefer<strong> std::make_unique</strong> over <strong>new</strong>. It is safer (exception-safe) and more readable.</p><pre>// Prefer this:<br>auto p = std::make_unique&lt;MyClass&gt;(arg1, arg2);<br><br>// Over this:<br>std::unique_ptr&lt;MyClass&gt; p(new MyClass(arg1, arg2));</pre><h4>Ownership Transfer</h4><p><strong>unique_ptr </strong>cannot be copied, but it can be moved:</p><pre>auto a = std::make_unique&lt;int&gt;(100);<br><br>// std::unique_ptr&lt;int&gt; b = a;  // ERROR — copy is deleted<br><br>std::unique_ptr&lt;int&gt; b = std::move(a);  // OK — transfer ownership<br><br>// a is now null<br>// b owns the int<br><br>if (!a) {<br>    std::cout &lt;&lt; &quot;a is empty\n&quot;;<br>}<br>std::cout &lt;&lt; *b &lt;&lt; &quot;\n&quot;;  // 100</pre><h4>Returning from Functions</h4><p>Returning unique_ptr from functions is idiomatic and efficient. Named Return Value Optimization (NRVO) or move semantics ensure no copies happen:</p><pre>std::unique_ptr&lt;std::string&gt; createGreeting(const std::string&amp; name) {<br>    return std::make_unique&lt;std::string&gt;(&quot;Hello, &quot; + name + &quot;!&quot;);<br>}<br><br>int main() {<br>    auto greeting = createGreeting(&quot;Alice&quot;);<br>    std::cout &lt;&lt; *greeting &lt;&lt; &quot;\n&quot;;  // Hello, Alice!<br>}</pre><h4>unique_ptr with Custom Deleters</h4><p>Sometimes the cleanup logic isn’t just delete. You can provide a custom deleter:</p><pre>#include &lt;cstdio&gt;<br><br>// Custom deleter as a lambda<br>auto fileDeleter = [](FILE* f) {<br>    if (f) {<br>        std::cout &lt;&lt; &quot;Closing file\n&quot;;<br>        fclose(f);<br>    }<br>};<br><br>void readFile(const std::string&amp; path) {<br>    std::unique_ptr&lt;FILE, decltype(fileDeleter)&gt; file(<br>        fopen(path.c_str(), &quot;r&quot;),<br>        fileDeleter<br>    );<br>    <br>    if (!file) {<br>        throw std::runtime_error(&quot;Could not open file&quot;);<br>    }<br>    <br>    // Use file...<br>    // Automatically closed when file goes out of scope<br>}</pre><p>unique_ptr with Arrays</p><pre>// Manages a dynamically allocated array<br>auto arr = std::make_unique&lt;int[]&gt;(10);<br><br>for (int i = 0; i &lt; 10; i++) {<br>    arr[i] = i * i;<br>}<br><br>std::cout &lt;&lt; arr[5] &lt;&lt; &quot;\n&quot;;  // 25<br>// delete[] called automatically</pre><h4>When to Use unique_ptr</h4><ul><li>When you have sole, non-shared ownership of a resource</li><li>As data members that represent owned sub-objects</li><li>As factory function return values</li><li>Essentially as the default choice for any heap-allocated object</li></ul><h4>4.2 std::shared_ptr</h4><p><strong>shared_ptr</strong> represents <strong>shared ownership</strong>. Multiple <strong>shared_ptr</strong> instances can point to the same object. Internally, a reference count tracks how many shared_ptr’s own the object. When the last one is destroyed or reset, the object is deleted.</p><pre>#include &lt;memory&gt;<br>#include &lt;iostream&gt;<br><br>int main() {<br>    auto sp1 = std::make_shared&lt;int&gt;(99);<br>    <br>    std::cout &lt;&lt; sp1.use_count() &lt;&lt; &quot;\n&quot;;  // 1<br>    <br>    {<br>        auto sp2 = sp1;  // sp2 is a copy — both own the object<br>        std::cout &lt;&lt; sp1.use_count() &lt;&lt; &quot;\n&quot;;  // 2<br>        <br>        auto sp3 = sp1;<br>        std::cout &lt;&lt; sp1.use_count() &lt;&lt; &quot;\n&quot;;  // 3<br>    }<br>    // sp2 and sp3 go out of scope — reference count drops to 1<br>    <br>    std::cout &lt;&lt; sp1.use_count() &lt;&lt; &quot;\n&quot;;  // 1<br>    std::cout &lt;&lt; *sp1 &lt;&lt; &quot;\n&quot;;  // 99 — still valid!<br>    <br>    // When sp1 goes out of scope, count → 0, object deleted<br>}</pre><h4>How shared_ptr Works Internally</h4><p>shared_ptr maintains a <strong>control block</strong> alongside the managed object. The control block contains:</p><ul><li>The strong reference count (number of shared_ptrs)</li><li>The weak reference count (number of weak_ptrs, plus one if strong count &gt; 0)</li><li>A pointer to the managed object</li><li>A custom deleter (if provided)</li></ul><p>Using std::make_shared allocates the object and the control block in a single memory allocation, which is more efficient than shared_ptr&lt;T&gt;(new T(…):</p><pre>// Single allocation (preferred):<br>auto sp = std::make_shared&lt;MyClass&gt;(args...);<br><br>// Two separate allocations (avoid unless you need custom deleter):<br>std::shared_ptr&lt;MyClass&gt; sp(new MyClass(args...));</pre><pre>struct Node {<br>    int value;<br>    std::shared_ptr&lt;Node&gt; next;<br>    <br>    Node(int v) : value(v) {}<br>};<br><br>void buildList() {<br>    auto head = std::make_shared&lt;Node&gt;(1);<br>    auto second = std::make_shared&lt;Node&gt;(2);<br>    auto third = std::make_shared&lt;Node&gt;(3);<br>    <br>    head-&gt;next = second;<br>    second-&gt;next = third;<br>    <br>    // All nodes are automatically cleaned up when head goes out of scope,<br>    // since it&#39;s the last remaining owner of the chain<br>}</pre><h4>shared_ptr Across Threads</h4><p>The reference count in shared_ptr is updated atomically, making it safe to copy and destroy shared_ptr instances across threads. However, the <strong>pointed-to object itself</strong> is not protected. You still need synchronization to safely read and write the object from multiple threads.</p><pre>std::shared_ptr&lt;int&gt; globalData = std::make_shared&lt;int&gt;(0);<br><br>void threadA() {<br>    auto localCopy = globalData;  // Thread-safe: ref count update is atomic<br>    *localCopy = 42;              // NOT thread-safe without external sync<br>}</pre><h4>When to Use shared_ptr</h4><ul><li>When multiple, independent owners need to share an object</li><li>When the lifetime of an object is not clearly tied to any single scope</li><li>For implementing shared caches, shared configurations, or shared resources in concurrent programs</li><li>Nodes in graphs where multiple edges point to the same node</li></ul><h4>4.3 std::weak_ptr</h4><p>weak_ptr is a <strong>non-owning observer</strong> of an object managed by shared_ptr. It holds a reference to the object but does not participate in the reference count. This means the object can be destroyed even while weak_ptrs exist.</p><p>To use the object, you must <strong>lock</strong> the weak_ptr, which promotes it to a shared_ptr. If the object has already been destroyed, lock() returns an empty shared_ptr.</p><pre>#include &lt;memory&gt;<br>#include &lt;iostream&gt;<br><br>int main() {<br>    std::weak_ptr&lt;int&gt; wp;<br>    <br>    {<br>        auto sp = std::make_shared&lt;int&gt;(55);<br>        wp = sp;  // wp observes the object but doesn&#39;t own it<br>        <br>        std::cout &lt;&lt; sp.use_count() &lt;&lt; &quot;\n&quot;;  // 1 — wp doesn&#39;t count<br>        <br>        if (auto locked = wp.lock()) {<br>            std::cout &lt;&lt; *locked &lt;&lt; &quot;\n&quot;;  // 55 — object still alive<br>        }<br>    }<br>    // sp goes out of scope — object is destroyed (use_count → 0)<br>    <br>    if (wp.expired()) {<br>        std::cout &lt;&lt; &quot;Object has been destroyed\n&quot;;<br>    }<br>    <br>    if (auto locked = wp.lock()) {<br>        // This block is NOT entered<br>    } else {<br>        std::cout &lt;&lt; &quot;lock() returned empty shared_ptr\n&quot;;<br>    }<br>}</pre><h4>The Circular Reference Problem</h4><p>The most important use case for weak_ptr is breaking <strong>circular references</strong>, which would otherwise prevent shared_ptr from ever freeing objects.</p><p>Consider a parent-child relationship where parents own their children and children need to refer back to their parent:</p><pre>struct Child;<br><br>struct Parent {<br>    std::string name;<br>    std::shared_ptr&lt;Child&gt; child;  // Parent owns child (strong)<br>    <br>    ~Parent() { std::cout &lt;&lt; name &lt;&lt; &quot; destroyed\n&quot;; }<br>};<br><br>struct Child {<br>    std::string name;<br>    std::shared_ptr&lt;Parent&gt; parent;  // PROBLEM: Child also owns Parent (strong)<br>    <br>    ~Child() { std::cout &lt;&lt; name &lt;&lt; &quot; destroyed\n&quot;; }<br>};<br><br>void createFamily() {<br>    auto parent = std::make_shared&lt;Parent&gt;();<br>    parent-&gt;name = &quot;Parent&quot;;<br>    <br>    auto child = std::make_shared&lt;Child&gt;();<br>    child-&gt;name = &quot;Child&quot;;<br>    <br>    parent-&gt;child = child;   // parent&#39;s ref count: 1 (from &#39;parent&#39; variable)<br>    child-&gt;parent = parent;  // parent&#39;s ref count: 2 (from &#39;child-&gt;parent&#39;)<br>    <br>    // When &#39;parent&#39; goes out of scope: ref count 2 -&gt;1 (still &gt; 0, NOT deleted)<br>    // When &#39;child&#39; goes out of scope: ref count 1 -&gt;0 (parent deleted? NO!)<br>    //   Because child still exists (ref count 1 from parent-&gt;child)<br>    // MEMORY LEAK — neither object is ever deleted<br>}</pre><p>The fix: make the back-pointer a weak_ptr:</p><pre>struct Child;<br><br>struct Parent {<br>    std::string name;<br>    std::shared_ptr&lt;Child&gt; child;  // Strong ownership<br>    <br>    ~Parent() { std::cout &lt;&lt; name &lt;&lt; &quot; destroyed\n&quot;; }<br>};<br><br>struct Child {<br>    std::string name;<br>    std::weak_ptr&lt;Parent&gt; parent;  // Weak reference — no ownership<br>    <br>    ~Child() { std::cout &lt;&lt; name &lt;&lt; &quot; destroyed\n&quot;; }<br>    <br>    void greetParent() {<br>        if (auto p = parent.lock()) {<br>            std::cout &lt;&lt; &quot;Hello from child to &quot; &lt;&lt; p-&gt;name &lt;&lt; &quot;\n&quot;;<br>        } else {<br>            std::cout &lt;&lt; &quot;Parent is gone\n&quot;;<br>        }<br>    }<br>};<br><br>void createFamily() {<br>    auto parent = std::make_shared&lt;Parent&gt;();<br>    parent-&gt;name = &quot;Parent&quot;;<br>    <br>    auto child = std::make_shared&lt;Child&gt;();<br>    child-&gt;name = &quot;Child&quot;;<br>    <br>    parent-&gt;child = child;<br>    child-&gt;parent = parent;  // weak_ptr — doesn&#39;t affect ref count<br>    <br>    child-&gt;greetParent();<br>    <br>    // When &#39;parent&#39; goes out of scope: ref count 1 → 0 → Parent DELETED<br>    // When &#39;child&#39; goes out of scope: ref count 1 → 0 → Child DELETED<br>    // No leak!<br>}</pre><pre>Hello from child to Parent<br>Parent destroyed<br>Child destroyed</pre><h4>When to Use weak_ptr</h4><ul><li>To break circular references in graphs, trees with back-pointers, or observer patterns</li><li>When you need to optionally access an object that may have been destroyed</li><li>For implementing caches where you hold references to objects without preventing their cleanup</li></ul><h3>5. Move Semantics: Eliminating Unnecessary Copies</h3><h4>5.1 The Problem: Expensive Copies</h4><p>Before C++11, the language had only one way to transfer data between objects: <strong>copying</strong>. This was fine for small, cheap types like int or double. For objects that manage heap-allocated resources, strings, vectors, file buffers, copying meant allocating new memory and duplicating all the data, even when the original was going to be discarded immediately.</p><pre>std::vector&lt;int&gt; createHugeVector() {<br>    std::vector&lt;int&gt; v;<br>    for (int i = 0; i &lt; 10000000; i++) {<br>        v.push_back(i);<br>    }<br>    return v;  // In C++03: this copies 10 million ints on return!<br>}<br><br>int main() {<br>    std::vector&lt;int&gt; myVec = createHugeVector();  // Another copy here!<br>}</pre><h4>5.2 Lvalues and Rvalues</h4><p>To understand move semantics, you need to understand <strong>lvalues</strong> and <strong>rvalues</strong>.</p><p>An <strong>lvalue</strong> (historically “left-hand value”) is an expression that has a persistent identity — it has a name, and you can take its address:</p><pre>int x = 5;       // x is an lvalue<br>std::string s;   // s is an lvalue<br>int* p = &amp;x;     // You can take the address of an lvalue</pre><p>An rvalue (historically “right-hand value”) is a temporary expression with no persistent identity — it will be destroyed at the end of the expression:</p><pre>int y = 5 + 3;           // (5 + 3) is an rvalue — a temporary<br>std::string t = &quot;hello&quot;; // &quot;hello&quot; is an rvalue<br>createHugeVector();      // The return value is an rvalue — a temporary</pre><p>The key insight: <strong>if an expression is an rvalue, nobody else is using it. We can safely steal its resources instead of copying them.</strong></p><p>C++11 introduced <strong>rvalue references</strong>, written as T&amp;&amp;, which bind exclusively to rvalues:</p><pre>int x = 5;<br>int&amp; lref = x;    // OK: lvalue reference to x<br>int&amp;&amp; rref = 5;   // OK: rvalue reference to temporary<br>// int&amp;&amp; r2 = x;  // ERROR: rvalue reference can&#39;t bind to lvalue</pre><h4>5.3 The Move Constructor and Move Assignment Operator</h4><p>The move constructor takes an rvalue reference to the same type, “steals” the resources from the source, and leaves the source in a valid but empty state:</p><pre>class DynamicArray {<br>public:<br>    int* data;<br>    size_t size;<br><br>    // Regular constructor<br>    explicit DynamicArray(size_t n)<br>        : data(new int[n]), size(n) {<br>        std::cout &lt;&lt; &quot;Constructing array of size &quot; &lt;&lt; n &lt;&lt; &quot;\n&quot;;<br>    }<br><br>    // Copy constructor — deep copy<br>    DynamicArray(const DynamicArray&amp; other)<br>        : data(new int[other.size]), size(other.size) {<br>        std::copy(other.data, other.data + size, data);<br>        std::cout &lt;&lt; &quot;Copying array of size &quot; &lt;&lt; size &lt;&lt; &quot;\n&quot;;<br>    }<br><br>    // Move constructor — steal resources, O(1) regardless of size<br>    DynamicArray(DynamicArray&amp;&amp; other) noexcept<br>        : data(other.data), size(other.size) {<br>        other.data = nullptr;  // Leave source in valid state<br>        other.size = 0;<br>        std::cout &lt;&lt; &quot;Moving array of size &quot; &lt;&lt; size &lt;&lt; &quot;\n&quot;;<br>    }<br><br>    // Copy assignment<br>    DynamicArray&amp; operator=(const DynamicArray&amp; other) {<br>        if (this != &amp;other) {<br>            delete[] data;<br>            data = new int[other.size];<br>            size = other.size;<br>            std::copy(other.data, other.data + size, data);<br>        }<br>        return *this;<br>    }<br><br>    // Move assignment<br>    DynamicArray&amp; operator=(DynamicArray&amp;&amp; other) noexcept {<br>        if (this != &amp;other) {<br>            delete[] data;        // Free our old resource<br>            data = other.data;    // Steal theirs<br>            size = other.size;<br>            other.data = nullptr; // Leave source valid but empty<br>            other.size = 0;<br>        }<br>        return *this;<br>    }<br><br>    ~DynamicArray() {<br>        delete[] data;<br>    }<br>};</pre><p>The noexcept annotation is important: it tells the compiler and standard library containers that this operation will not throw, allowing them to use moves in places where exceptions would be problematic (like std::vector reallocation).</p><h3>5.4 std::move</h3><p>std::move does <strong>not</strong> actually move anything. It is a cast that tells the compiler &quot;treat this lvalue as an rvalue&quot;, giving permission for move operations to occur:</p><pre>#include &lt;utility&gt;  // for std::move<br><br>DynamicArray a(1000);   // Construct<br>DynamicArray b(500);    // Construct<br><br>b = a;                  // Copy — a is still valid, expensive<br>b = std::move(a);       // Move — a is now empty, a.data == nullptr<br><br>// WARNING: Do not use &#39;a&#39; after moving from it, <br>// except to reassign or destroy it</pre><p>The most common use of std::move is with unique_ptr (since it can only be moved, not copied):</p><pre>auto owner = std::make_unique&lt;std::string&gt;(&quot;hello&quot;);<br><br>// Transfer ownership to a container<br>std::vector&lt;std::unique_ptr&lt;std::string&gt;&gt; vec;<br>vec.push_back(std::move(owner));<br><br>// &#39;owner&#39; is now null — vec owns the string</pre><p>And in the Rule of Five: if you define a destructor, you should think about all five special member functions:</p><pre>class Resource {<br>public:<br>    Resource();                              // Constructor<br>    ~Resource();                             // Destructor<br>    Resource(const Resource&amp;);               // Copy constructor<br>    Resource&amp; operator=(const Resource&amp;);    // Copy assignment<br>    Resource(Resource&amp;&amp;) noexcept;           // Move constructor     (C++11)<br>    Resource&amp; operator=(Resource&amp;&amp;) noexcept;// Move assignment      (C++11)<br>};</pre><h4>5.5 Move Semantics in Action with Standard Containers</h4><p>Standard library types like std::String, std::vector, and std::map all implement move semantics. This makes returning them from functions highly efficient:</p><pre>#include &lt;vector&gt;<br>#include &lt;string&gt;<br>#include &lt;iostream&gt;<br><br>std::vector&lt;std::string&gt; buildWordList() {<br>    std::vector&lt;std::string&gt; words;<br>    words.reserve(5);<br>    words.push_back(&quot;alpha&quot;);<br>    words.push_back(&quot;beta&quot;);<br>    words.push_back(&quot;gamma&quot;);<br>    words.push_back(&quot;delta&quot;);<br>    words.push_back(&quot;epsilon&quot;);<br>    return words;  // Move semantics or NRVO — no deep copy<br>}<br><br>int main() {<br>    auto list = buildWordList();  // Efficient!<br>    for (const auto&amp; w : list) {<br>        std::cout &lt;&lt; w &lt;&lt; &quot;\n&quot;;<br>    }<br>}</pre><p>std::vector::push_back also benefits from move semantics when inserting temporaries or moved-from values:</p><pre>std::vector&lt;std::string&gt; names;<br><br>std::string name = &quot;Alice&quot;;<br>names.push_back(name);             // Copy — name is still valid<br>names.push_back(std::move(name));  // Move — name is now &quot;&quot;<br>names.push_back(&quot;Bob&quot;);            // &quot;Bob&quot; is a temporary (rvalue), moved in</pre><h4>5.6 Perfect Forwarding and std::forward</h4><p>When writing generic code (templates), you often need to pass arguments through to another function while preserving whether they were lvalues or rvalues. This is called <strong>perfect forwarding</strong>:</p><pre>// Without perfect forwarding — always copies:<br>template&lt;typename T, typename Arg&gt;<br>std::unique_ptr&lt;T&gt; makeObject(Arg arg) {<br>    return std::make_unique&lt;T&gt;(arg);  // arg is always an lvalue here<br>}<br><br>// With perfect forwarding — preserves the value category:<br>template&lt;typename T, typename... Args&gt;<br>std::unique_ptr&lt;T&gt; makeObject(Args&amp;&amp;... args) {<br>    return std::make_unique&lt;T&gt;(std::forward&lt;Args&gt;(args)...);<br>}</pre><p>std::forward&lt;T&gt;(arg) casts arg back to an rvalue if it was originally an rvalue, or leaves it as an lvalue if it was originally an lvalue. This is how std::make_shared and std::make_unique are implemented, they forward your arguments directly to the constructor with no extra copies.</p><pre>struct Point {<br>    double x, y;<br>    Point(double x, double y) : x(x), y(y) {}<br>};<br><br>// Using perfect forwarding in make_unique:<br>auto p = std::make_unique&lt;Point&gt;(3.0, 4.0);<br>// 3.0 and 4.0 are rvalues — forwarded as rvalues to Point&#39;s constructor</pre><h3>6. Real-World Use Cases</h3><h4>6.1 A Thread-Safe Resource Cache with shared_ptr and weak_ptr</h4><pre>#include &lt;memory&gt;<br>#include &lt;unordered_map&gt;<br>#include &lt;mutex&gt;<br>#include &lt;string&gt;<br><br>class TextureCache {<br>    std::unordered_map&lt;std::string, std::weak_ptr&lt;Texture&gt;&gt; cache_;<br>    std::mutex mutex_;<br><br>public:<br>    std::shared_ptr&lt;Texture&gt; load(const std::string&amp; path) {<br>        std::lock_guard&lt;std::mutex&gt; lock(mutex_);<br><br>        auto it = cache_.find(path);<br>        if (it != cache_.end()) {<br>            if (auto existing = it-&gt;second.lock()) {<br>                return existing;  // Return cached if still alive<br>            }<br>        }<br><br>        // Load fresh — cache doesn&#39;t keep it alive<br>        auto texture = std::make_shared&lt;Texture&gt;(path);<br>        cache_[path] = texture;  // Stored as weak_ptr<br>        return texture;<br>    }<br>};</pre><h4>6.3 Building a Tree with unique_ptr</h4><p>A binary search tree where each node exclusively owns its children:</p><pre>#include &lt;memory&gt;<br>#include &lt;optional&gt;<br>#include &lt;iostream&gt;<br><br>template&lt;typename T&gt;<br>struct TreeNode {<br>    T value;<br>    std::unique_ptr&lt;TreeNode&lt;T&gt;&gt; left;<br>    std::unique_ptr&lt;TreeNode&lt;T&gt;&gt; right;<br><br>    explicit TreeNode(T v) : value(std::move(v)) {}<br>};<br><br>template&lt;typename T&gt;<br>class BinarySearchTree {<br>    std::unique_ptr&lt;TreeNode&lt;T&gt;&gt; root_;<br><br>    void insertHelper(std::unique_ptr&lt;TreeNode&lt;T&gt;&gt;&amp; node, T value) {<br>        if (!node) {<br>            node = std::make_unique&lt;TreeNode&lt;T&gt;&gt;(std::move(value));<br>        } else if (value &lt; node-&gt;value) {<br>            insertHelper(node-&gt;left, std::move(value));<br>        } else if (value &gt; node-&gt;value) {<br>            insertHelper(node-&gt;right, std::move(value));<br>        }<br>    }<br><br>    void inorderHelper(const TreeNode&lt;T&gt;* node) const {<br>        if (!node) return;<br>        inorderHelper(node-&gt;left.get());<br>        std::cout &lt;&lt; node-&gt;value &lt;&lt; &quot; &quot;;<br>        inorderHelper(node-&gt;right.get());<br>    }<br><br>public:<br>    void insert(T value) {<br>        insertHelper(root_, std::move(value));<br>    }<br><br>    void inorder() const {<br>        inorderHelper(root_.get());<br>        std::cout &lt;&lt; &quot;\n&quot;;<br>    }<br><br>    // Destructor not needed — unique_ptr handles recursive cleanup<br>};<br><br>int main() {<br>    BinarySearchTree&lt;int&gt; bst;<br>    bst.insert(5);<br>    bst.insert(3);<br>    bst.insert(7);<br>    bst.insert(1);<br>    bst.insert(4);<br><br>    bst.inorder();  // 1 3 4 5 7<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=545f135cb365" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering C++ OOP: The Four Pillars with Examples]]></title>
            <link>https://medium.com/@abhiramdodda/mastering-c-oop-the-four-pillars-with-examples-355898cf1b87?source=rss-a0eeb0ee0600------2</link>
            <guid isPermaLink="false">https://medium.com/p/355898cf1b87</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Abhiram Dodda]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 22:45:46 GMT</pubDate>
            <atom:updated>2026-01-15T22:45:46.463Z</atom:updated>
            <content:encoded><![CDATA[<p>C++ is a powerful, high-performance language that fully supports <strong>Object-Oriented Programming (OOP)</strong>. Unlike procedural programming, which focuses on functions and logic, OOP focuses on <strong>objects</strong> that combine data and behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Lzf2zqmCUfi1-SORwuC0w.png" /><figcaption>Image generated using Gemini for illustrative purposes</figcaption></figure><h3>1. Encapsulation</h3><p>Encapsulation is the process of bundling data (variables) and the methods (functions) that operate on that data into a single unit called a <strong>Class</strong>. It also involves “Information Hiding” using access specifiers like private and public.</p><pre>#include &lt;iostream&gt;<br>#include &lt;string&gt;<br><br>class BankAccount {<br>private:<br>    double balance; // Hidden from outside world<br><br>public:<br>    void deposit(double amount) {<br>        if (amount &gt; 0) balance += amount;<br>    }<br><br>    double getBalance() { // Controlled access<br>        return balance;<br>    }<br>};</pre><h3>2. Abstraction</h3><p>Abstraction means showing only the essential features of an object and hiding the complex background details. In C++, we achieve this using <strong>Abstract Classes</strong> and <strong>Interfaces</strong> (classes with pure virtual functions).</p><pre>class Appliance {<br>public:<br>    virtual void turnOn() = 0; // Pure virtual function (Abstraction)<br>};<br><br>class Fan : public Appliance {<br>public:<br>    void turnOn() override {<br>        std::cout &lt;&lt; &quot;Fan is spinning...&quot; &lt;&lt; std::endl;<br>    }<br>};</pre><h3>3. Inheritance</h3><p>Inheritance allows a new class (Derived Class) to inherit the properties and behaviors of an existing class (Base Class). This promotes <strong>code reusability</strong>.</p><pre>class Animal {<br>public:<br>    void eat() { std::cout &lt;&lt; &quot;Eating...&quot; &lt;&lt; std::endl; }<br>};<br><br>// Dog inherits from Animal<br>class Dog : public Animal {<br>public:<br>    void bark() { std::cout &lt;&lt; &quot;Woof!&quot; &lt;&lt; std::endl; }<br>};</pre><h3>4. Polymorphism</h3><p>Polymorphism means “many forms.” It allows one interface to be used for a general class of actions. The most common type is <strong>Runtime Polymorphism</strong>, achieved through function overriding.</p><pre>class Shape {<br>public:<br>    virtual void draw() { std::cout &lt;&lt; &quot;Drawing a shape.&quot; &lt;&lt; std::endl; }<br>};<br><br>class Circle : public Shape {<br>public:<br>    void draw() override { std::cout &lt;&lt; &quot;Drawing a circle.&quot; &lt;&lt; std::endl; }<br>};<br><br>int main() {<br>    Shape* myShape = new Circle();<br>    myShape-&gt;draw(); // Outputs: Drawing a circle.<br>    return 0;<br>}</pre><h3>The friend Keyword: Controlled Breach</h3><p>Sometimes, you need an external function or class to access private members of a class. C++ allows this via the friend keyword. <strong>Use this sparingly</strong>, as it breaks strict encapsulation.</p><pre>class Box {<br>private:<br>    double width;<br><br>public:<br>    Box(double w) : width(w) {}<br>    <br>    // Granting access to a specific function<br>    friend void printWidth(Box box);<br>};<br><br>void printWidth(Box box) {<br>    // We can access &#39;width&#39; directly despite it being private<br>    std::cout &lt;&lt; &quot;Width of box: &quot; &lt;&lt; box.width &lt;&lt; std::endl;<br>}</pre><h4>const Correctness</h4><p>Marking member functions as const ensures they do not modify the object&#39;s state. This is crucial for passing objects by reference safely.</p><pre>class User {<br>private:<br>    std::string name;<br>public:<br>    // This function promises NOT to change any member variables<br>    std::string getName() const {<br>        return name;<br>    }<br>};</pre><h3>The Diamond Problem (Virtual Inheritance)</h3><p>When a class inherits from two classes that both inherit from the same base class, you get the “Diamond Problem.” This causes ambiguity: which copy of the base class functions should be used?</p><p><strong>The Solution:</strong> Virtual Inheritance.</p><pre>class Device {<br>public:<br>    int id;<br>};<br><br>// &#39;virtual&#39; ensures only one copy of Device exists in the final class<br>class Computer : virtual public Device { };<br>class Monitor : virtual public Device { };<br><br>class Laptop : public Computer, public Monitor {<br>public:<br>    void setID(int i) {<br>        id = i; // No ambiguity thanks to virtual inheritance<br>    }<br>};</pre><h3>Access Specifiers in Inheritance</h3><p>How you inherit matters. Changing public to protected or private during inheritance changes the visibility of the parent&#39;s members in the child.</p><ul><li><strong>Public Inheritance:</strong> public stays public, protected stays protected.</li><li><strong>Protected Inheritance:</strong> public and protected become protected.</li><li><strong>Private Inheritance:</strong> Everything becomes private (Has-a relationship implemented via inheritance).</li></ul><h3>Polymorphism &amp; The Virtual Table (vptr/vtable)</h3><p>How does C++ know which function to call at runtime? It uses a <strong>Virtual Table (vtable)</strong>.</p><p>When a class has a virtual function:</p><ol><li>The compiler creates a static table (vtable) containing function pointers for that class.</li><li>The object gets a hidden pointer (vptr) pointing to this table.</li><li>At runtime, the program looks up the correct function address in the table.</li></ol><h4>The Essential Special Case: Virtual Destructors</h4><p>If you delete a derived object through a base pointer, the <strong>base class destructor</strong> must be virtual. If it isn’t, the derived class’s destructor will never fire, causing memory leaks.</p><pre>class Base {<br>public:<br>    // Without &#39;virtual&#39;, ~Derived() would strictly NOT be called<br>    virtual ~Base() { <br>        std::cout &lt;&lt; &quot;Base Destructor&quot; &lt;&lt; std::endl; <br>    }<br>};<br><br>class Derived : public Base {<br>public:<br>    ~Derived() { <br>        std::cout &lt;&lt; &quot;Derived Destructor&quot; &lt;&lt; std::endl; <br>    }<br>};<br><br>int main() {<br>    Base* ptr = new Derived();<br>    delete ptr; // Safely calls ~Derived() then ~Base()<br>    return 0;<br>}</pre><h3>Compile-Time Polymorphism (Operator Overloading)</h3><p>Polymorphism isn’t just about virtual functions (runtime). It also happens at compile time via <strong>Operator Overloading</strong>. This allows you to define how operators like +, -, or &lt;&lt; behave with your custom objects.</p><pre>class Complex {<br>private:<br>    int real, imag;<br>public:<br>    Complex(int r = 0, int i = 0) : real(r), imag(i) {}<br><br>    // Overloading the + operator<br>    Complex operator + (Complex const &amp;obj) {<br>        Complex res;<br>        res.real = real + obj.real;<br>        res.imag = imag + obj.imag;<br>        return res;<br>    }<br>};<br><br>int main() {<br>    Complex c1(10, 5), c2(2, 4);<br>    Complex c3 = c1 + c2; // Using + on custom objects!<br>}</pre><p>References:<br>1) <a href="https://learning.oreilly.com/library/view/c-primer-fifth/9780133053043/">https://learning.oreilly.com/library/view/c-primer-fifth/9780133053043/</a><br>2) <a href="https://en.cppreference.com/">https://en.cppreference.com/</a><br>3) “The C++ Programming Language” by Bjarne Stroustrup</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=355898cf1b87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Production-Grade Distributed Inference System in C++ — Part 2]]></title>
            <link>https://medium.com/@abhiramdodda/building-a-production-grade-distributed-inference-system-in-c-part-2-50d0d3ba290d?source=rss-a0eeb0ee0600------2</link>
            <guid isPermaLink="false">https://medium.com/p/50d0d3ba290d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[inference-engine]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[cache]]></category>
            <dc:creator><![CDATA[Abhiram Dodda]]></dc:creator>
            <pubDate>Tue, 13 Jan 2026 16:45:11 GMT</pubDate>
            <atom:updated>2026-01-13T16:46:08.034Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Production-Grade Distributed Inference System in C++ — Part 2</h3><p>This is the second part of the <a href="https://medium.com/@abhiramdodda/building-a-production-grade-distributed-inference-system-in-c-part-1-11b933d9216f">blog</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_BYlS7WupqhMgAo0OaZ-nA.png" /><figcaption>Image generated using AI for illustrative purposes to depict distributed computing systems.</figcaption></figure><h3>Component 4: Dynamic Batching</h3><h3>What is Dynamic Batching?</h3><p>Dynamic batching collects multiple individual requests and processes them as a single batch, improving GPU/CPU utilization. Instead of processing requests one-by-one, we wait a short time to accumulate requests.</p><h3>Why Batching for Inference?</h3><p>Modern hardware (especially GPUs) achieves peak performance when processing multiple samples simultaneously. Consider matrix multiplication:</p><ul><li>Single inference: 10ms, GPU utilization 20%</li><li>Batch of 32: 25ms total, GPU utilization 80%</li><li>Per-sample latency: 0.78ms (13x faster)</li></ul><p>The challenge is balancing throughput (large batches) with latency (small wait times).</p><h3>Implementation</h3><pre>template&lt;typename Request, typename Response&gt;<br>class BatchProcessor {<br>public:<br>    using BatchCallback = std::function&lt;<br>        std::vector&lt;Response&gt;(const std::vector&lt;Request&gt;&amp;)<br>    &gt;;<br>    <br>    BatchProcessor(<br>        size_t max_batch_size,<br>        std::chrono::milliseconds timeout,<br>        BatchCallback callback<br>    );<br>    <br>    Response process(const Request&amp; request);<br>    <br>private:<br>    void processingLoop();<br>    <br>    size_t max_batch_size_;<br>    std::chrono::milliseconds timeout_;<br>    BatchCallback callback_;<br>    <br>    std::queue&lt;std::pair&lt;Request, std::promise&lt;Response&gt;&gt;&gt; request_queue_;<br>    std::mutex queue_mutex_;<br>    std::condition_variable queue_cv_;<br>    <br>    std::thread worker_thread_;<br>    std::atomic&lt;bool&gt; running_;<br>};</pre><p>Why promises and futures? Each request gets a promise that will be fulfilled when the batch completes. The caller waits on the future, blocking until their result is ready.</p><p>Processing a request:</p><pre>Response process(const Request&amp; request) {<br>    std::promise&lt;Response&gt; promise;<br>    std::future&lt;Response&gt; future = promise.get_future();<br>    <br>    {<br>        std::lock_guard&lt;std::mutex&gt; lock(queue_mutex_);<br>        request_queue_.push({request, std::move(promise)});<br>        total_requests_++;<br>    }<br>    <br>    queue_cv_.notify_one();<br>    <br>    return future.get();  // Block until batch completes<br>}</pre><p>Why notify_one? We only need to wake the batch processor thread. Using notify_all would waste CPU cycles.</p><p>The batch processing loop:</p><pre>void processingLoop() {<br>    std::vector&lt;std::pair&lt;Request, std::promise&lt;Response&gt;&gt;&gt; batch;<br>    batch.reserve(max_batch_size_);<br>    <br>    while (running_) {<br>        std::unique_lock&lt;std::mutex&gt; lock(queue_mutex_);<br>        <br>        // Wait for requests or timeout<br>        bool timeout = !queue_cv_.wait_for(<br>            lock,<br>            timeout_,<br>            [this] { return !request_queue_.empty() || !running_; }<br>        );<br>        <br>        if (!running_) break;<br>        <br>        // Collect batch<br>        batch.clear();<br>        while (!request_queue_.empty() &amp;&amp; batch.size() &lt; max_batch_size_) {<br>            batch.push_back(std::move(request_queue_.front()));<br>            request_queue_.pop();<br>        }<br>        <br>        lock.unlock();<br>        <br>        if (!batch.empty()) {<br>            processBatch(batch, timeout);<br>        }<br>    }<br>}</pre><p>Why wait_for with a predicate? This handles spurious wakeups correctly. The predicate ensures we only proceed when there’s actually work to do.</p><p>The batch triggers on two conditions:</p><ol><li>Batch full (32 requests): Process immediately for throughput</li><li>Timeout (20ms): Process partial batch to limit latency</li></ol><p>Processing the batch:</p><pre>void processBatch(<br>    std::vector&lt;std::pair&lt;Request, std::promise&lt;Response&gt;&gt;&gt;&amp; batch,<br>    bool is_timeout<br>) {<br>    try {<br>        // Extract requests<br>        std::vector&lt;Request&gt; requests;<br>        requests.reserve(batch.size());<br>        for (auto&amp; item : batch) {<br>            requests.push_back(item.first);<br>        }<br>        <br>        // Process batch<br>        auto responses = callback_(requests);<br>        <br>        // Fulfill promises<br>        for (size_t i = 0; i &lt; batch.size(); ++i) {<br>            if (i &lt; responses.size()) {<br>                batch[i].second.set_value(responses[i]);<br>            } else {<br>                batch[i].second.set_exception(<br>                    std::make_exception_ptr(<br>                        std::runtime_error(&quot;No response for batched request&quot;)<br>                    )<br>                );<br>            }<br>        }<br>        <br>        // Update metrics<br>        total_batches_++;<br>        if (is_timeout) {<br>            timeout_batches_++;<br>        } else {<br>            full_batches_++;<br>        }<br>    } catch (const std::exception&amp; e) {<br>        // Set exception for all promises<br>        for (auto&amp; item : batch) {<br>            try {<br>                item.second.set_exception(std::current_exception());<br>            } catch (...) {}<br>        }<br>    }<br>}</pre><p>Why separate timeout and full batch metrics? This helps tune the timeout parameter. If most batches are timeout-triggered, the timeout might be too short.</p><h3>Component 5: ONNX Runtime Integration</h3><h3>What is ONNX Runtime?</h3><p>ONNX Runtime is a high-performance inference engine for ONNX (Open Neural Network Exchange) models. It supports multiple execution providers (CPU, CUDA, TensorRT) and optimizes model execution.</p><h3>Why ONNX Runtime?</h3><p>ONNX Runtime provides:</p><ul><li>Multi-platform support (Linux, Windows, macOS)</li><li>Hardware acceleration (GPU, NPU)</li><li>Graph optimizations (operator fusion, constant folding)</li><li>Quantization support</li></ul><p>Alternative inference engines like TensorFlow Lite or PyTorch have framework lock-in. ONNX is framework-agnostic.</p><h3>Implementation</h3><pre>class InferenceEngine {<br>public:<br>    explicit InferenceEngine(const std::string&amp; model_path, int shard_id = 0);<br>    <br>    std::vector&lt;float&gt; predict(const std::vector&lt;float&gt;&amp; input);<br>    std::vector&lt;std::vector&lt;float&gt;&gt; batchPredict(<br>        const std::vector&lt;std::vector&lt;float&gt;&gt;&amp; inputs<br>    );<br>    <br>private:<br>    void initializeSession();<br>    <br>    std::unique_ptr&lt;Ort::Env&gt; env_;<br>    std::unique_ptr&lt;Ort::Session&gt; session_;<br>    std::unique_ptr&lt;Ort::SessionOptions&gt; session_options_;<br>    <br>    std::vector&lt;std::string&gt; input_name_strings_;<br>    std::vector&lt;std::string&gt; output_name_strings_;<br>    std::vector&lt;const char*&gt; input_names_;<br>    std::vector&lt;const char*&gt; output_names_;<br>    <br>    std::vector&lt;int64_t&gt; input_shape_;<br>    std::vector&lt;int64_t&gt; output_shape_;<br>    <br>    std::mutex mutex_;<br>};</pre><p>Why store both strings and char pointers? ONNX Runtime’s C API requires const char* pointers, but these must remain valid. Storing std::string ensures the underlying memory persists.</p><p>Session initialization:</p><pre>void initializeSession() {<br>    std::lock_guard&lt;std::mutex&gt; lock(mutex_);<br>    <br>    session_options_ = std::make_unique&lt;Ort::SessionOptions&gt;();<br>    session_options_-&gt;SetIntraOpNumThreads(4);<br>    session_options_-&gt;SetGraphOptimizationLevel(<br>        GraphOptimizationLevel::ORT_ENABLE_EXTENDED<br>    );<br>    <br>    // Try CUDA, fallback to CPU<br>    try {<br>        OrtCUDAProviderOptions cuda_options;<br>        cuda_options.device_id = 0;<br>        session_options_-&gt;AppendExecutionProvider_CUDA(cuda_options);<br>        std::cout &lt;&lt; &quot;CUDA Provider loaded&quot; &lt;&lt; std::endl;<br>    } catch (const Ort::Exception&amp; e) {<br>        std::cerr &lt;&lt; &quot;CUDA failed, using CPU: &quot; &lt;&lt; e.what() &lt;&lt; std::endl;<br>    }<br>    <br>    session_ = std::make_unique&lt;Ort::Session&gt;(<br>        *env_, model_path_.c_str(), *session_options_<br>    );<br>}</pre><p>Why extended optimizations? ORT_ENABLE_EXTENDED enables aggressive optimizations like operator fusion and layout transformation, improving performance at the cost of longer initialization time.</p><p>Why try-catch for CUDA? Not all systems have CUDA available. Catching the exception and falling back to CPU ensures the system works everywhere.</p><p>Getting input/output metadata:</p><pre>Ort::AllocatorWithDefaultOptions allocator;<br><br>// Get input name and shape<br>auto input_name_allocated = session_-&gt;GetInputNameAllocated(0, allocator);<br>input_name_strings_.push_back(std::string(input_name_allocated.get()));<br>input_names_.push_back(input_name_strings_[0].c_str());<br><br>auto input_type_info = session_-&gt;GetInputTypeInfo(0);<br>auto tensor_info = input_type_info.GetTensorTypeAndShapeInfo();<br>input_shape_ = tensor_info.GetShape();<br><br>// Handle dynamic dimensions<br>for (auto&amp; dim : input_shape_) {<br>    if (dim == -1) {<br>        dim = 1;  // Default batch size<br>    }<br>}</pre><p>Why handle -1 dimensions? ONNX models often have dynamic batch dimensions represented as -1. We default to batch size 1 for single inference, but override it for batch inference.</p><p>Running inference:</p><pre>std::vector&lt;float&gt; predict(const std::vector&lt;float&gt;&amp; input) {<br>    std::lock_guard&lt;std::mutex&gt; lock(mutex_);<br>    <br>    auto memory_info = Ort::MemoryInfo::CreateCpu(<br>        OrtArenaAllocator, OrtMemTypeDefault<br>    );<br>    <br>    std::vector&lt;float&gt; input_copy = input;<br>    <br>    Ort::Value input_tensor = Ort::Value::CreateTensor&lt;float&gt;(<br>        memory_info,<br>        input_copy.data(),<br>        input_copy.size(),<br>        input_shape_.data(),<br>        input_shape_.size()<br>    );<br>    <br>    auto output_tensors = session_-&gt;Run(<br>        Ort::RunOptions{nullptr},<br>        input_names_.data(),<br>        &amp;input_tensor,<br>        1,<br>        output_names_.data(),<br>        1<br>    );<br>    <br>    float* output_data = output_tensors[0].GetTensorMutableData&lt;float&gt;();<br>    auto output_shape = output_tensors[0].GetTensorTypeAndShapeInfo().GetShape();<br>    <br>    int64_t output_size = std::accumulate(<br>        output_shape.begin(),<br>        output_shape.end(),<br>        1LL,<br>        std::multiplies&lt;int64_t&gt;()<br>    );<br>    <br>    return std::vector&lt;float&gt;(output_data, output_data + output_size);<br>}</pre><p>Why copy input? ONNX Runtime modifies the input buffer during inference. Copying protects the caller’s data.</p><p>Why mutex? ONNX Runtime sessions are not thread-safe. The mutex ensures only one inference runs at a time per session.</p><h3>Component 6: Gateway Routing</h3><h3>What is the Gateway?</h3><p>The gateway is a reverse proxy that receives client requests, determines which worker should handle them, checks circuit breakers, and routes the request.</p><h3>Why a Gateway Pattern?</h3><p>Without a gateway, clients would need to:</p><ul><li>Implement consistent hashing</li><li>Track worker health</li><li>Handle retries</li><li>Manage circuit breakers</li></ul><p>The gateway centralizes this complexity, providing a simple API to clients.</p><h3>Implementation</h3><pre>class Gateway {<br>public:<br>    explicit Gateway(const std::vector&lt;std::string&gt;&amp; workers);<br>    <br>    json routeRequest(const json&amp; request);<br>    json getStats();<br>    <br>private:<br>    std::optional&lt;json&gt; tryNode(const std::string&amp; node, const json&amp; request);<br>    std::pair&lt;std::string, int&gt; parseUrl(const std::string&amp; url);<br>    <br>    ConsistentHash hash_ring_;<br>    std::map&lt;std::string, std::unique_ptr&lt;CircuitBreaker&gt;&gt; circuit_breakers_;<br>    std::map&lt;std::string, std::unique_ptr&lt;httplib::Client&gt;&gt; clients_;<br>};</pre><p>Request routing:</p><pre>json routeRequest(const json&amp; request) {<br>    std::string request_id = request[&quot;request_id&quot;];<br>    <br>    // Get target node using consistent hashing<br>    std::string target_node = hash_ring_.getNode(request_id);<br>    <br>    if (target_node.empty()) {<br>        throw std::runtime_error(&quot;No workers available&quot;);<br>    }<br>    <br>    // Try primary node with circuit breaker<br>    auto result = tryNode(target_node, request);<br>    if (result.has_value()) {<br>        return *result;<br>    }<br>    <br>    // Primary failed, try other nodes<br>    auto all_nodes = hash_ring_.getAllNodes();<br>    for (const auto&amp; node : all_nodes) {<br>        if (node != target_node) {<br>            auto retry_result = tryNode(node, request);<br>            if (retry_result.has_value()) {<br>                return *retry_result;<br>            }<br>        }<br>    }<br>    <br>    throw std::runtime_error(&quot;All workers failed or circuit breakers open&quot;);<br>}</pre><p>Why try all workers on failure? If the primary worker is down, we want to serve the request anyway. Trying other workers provides automatic failover.</p><p>Trying a node:</p><pre>std::optional&lt;json&gt; tryNode(const std::string&amp; node, const json&amp; request) {<br>    auto&amp; breaker = circuit_breakers_[node];<br>    <br>    // Check circuit breaker<br>    if (!breaker-&gt;allowRequest()) {<br>        std::cout &lt;&lt; &quot;Circuit breaker OPEN for &quot; &lt;&lt; node &lt;&lt; std::endl;<br>        return std::nullopt;<br>    }<br>    <br>    try {<br>        auto result = clients_[node]-&gt;Post(<br>            &quot;/infer&quot;,<br>            request.dump(),<br>            &quot;application/json&quot;<br>        );<br>        <br>        if (result &amp;&amp; result-&gt;status == 200) {<br>            breaker-&gt;recordSuccess();<br>            return json::parse(result-&gt;body);<br>        } else {<br>            breaker-&gt;recordFailure();<br>            return std::nullopt;<br>        }<br>    } catch (const std::exception&amp; e) {<br>        breaker-&gt;recordFailure();<br>        return std::nullopt;<br>    }<br>}</pre><p>Why check circuit breaker first? This prevents wasting time on network calls to dead workers. The check is O(1) while network calls are milliseconds.</p><h3>Component 7: Worker Node</h3><h3>What is a Worker Node?</h3><p>A worker node is an HTTP server that receives inference requests, checks the cache, batches requests, runs inference, and returns results.</p><pre>Request arrives<br>    │<br>    ▼<br>Check cache ─── Hit ──→ Return cached result (50μs)<br>    │<br>    Miss<br>    │<br>    ▼<br>Add to batch queue<br>    │<br>    ▼<br>Batch processor (wait for 32 requests or 20ms)<br>    │<br>    ▼<br>Run batch inference (1-10ms per sample)<br>    │<br>    ▼<br>Cache results<br>    │<br>    ▼<br>Return to clients</pre><pre>class WorkerNode {<br>public:<br>    WorkerNode(<br>        const std::string&amp; node_id, <br>        int port, <br>        const std::string&amp; model_path<br>    );<br>    <br>    json handleInfer(const json&amp; request);<br>    json getHealth();<br>    <br>private:<br>    std::vector&lt;InferenceResponse&gt; processBatch(<br>        const std::vector&lt;InferenceRequest&gt;&amp; requests<br>    );<br>    <br>    std::string node_id_;<br>    int port_;<br>    InferenceEngine engine_;<br>    LRUCache&lt;std::vector&lt;float&gt;, std::vector&lt;float&gt;, VectorHash&gt; cache_;<br>    BatchProcessor&lt;InferenceRequest, InferenceResponse&gt; batch_processor_;<br>    <br>    std::atomic&lt;int64_t&gt; total_requests_;<br>    std::atomic&lt;int64_t&gt; cache_hits_;<br>};</pre><p>Handling inference:</p><pre>json handleInfer(const json&amp; request) {<br>    total_requests_++;<br>    <br>    std::string request_id = request[&quot;request_id&quot;];<br>    std::vector&lt;float&gt; input_data = request[&quot;input_data&quot;];<br>    <br>    // Check cache first<br>    auto cached = cache_.get(input_data);<br>    if (cached.has_value()) {<br>        cache_hits_++;<br>        <br>        json response;<br>        response[&quot;request_id&quot;] = request_id;<br>        response[&quot;output_data&quot;] = *cached;<br>        response[&quot;node_id&quot;] = node_id_;<br>        response[&quot;cached&quot;] = true;<br>        response[&quot;inference_time_us&quot;] = 50;<br>        <br>        return response;<br>    }<br>    <br>    // Cache miss - use batch processor<br>    InferenceRequest inf_req{request_id, input_data};<br>    InferenceResponse inf_resp = batch_processor_.process(inf_req);<br>    <br>    // Store in cache<br>    cache_.put(input_data, inf_resp.output_data);<br>    <br>    json response;<br>    response[&quot;request_id&quot;] = inf_resp.request_id;<br>    response[&quot;output_data&quot;] = inf_resp.output_data;<br>    response[&quot;node_id&quot;] = node_id_;<br>    response[&quot;cached&quot;] = false;<br>    response[&quot;inference_time</pre><p>Processing batches:</p><pre>std::vector&lt;InferenceResponse&gt; processBatch(<br>    const std::vector&lt;InferenceRequest&gt;&amp; requests<br>) {<br>    auto start = std::chrono::high_resolution_clock::now();<br>    <br>    // Extract inputs<br>    std::vector&lt;std::vector&lt;float&gt;&gt; inputs;<br>    inputs.reserve(requests.size());<br>    for (const auto&amp; req : requests) {<br>        inputs.push_back(req.input_data);<br>    }<br>    <br>    // Batch inference<br>    auto outputs = engine_.batchPredict(inputs);<br>    <br>    auto end = std::chrono::high_resolution_clock::now();<br>    auto duration = std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(<br>        end - start<br>    ).count();<br>    <br>    // Create responses<br>    std::vector&lt;InferenceResponse&gt; responses;<br>    responses.reserve(requests.size());<br>    <br>    int64_t per_request_time = duration / requests.size();<br>    <br>    for (size_t i = 0; i &lt; requests.size(); ++i) {<br>        InferenceResponse resp;<br>        resp.request_id = requests[i].request_id;<br>        resp.output_data = outputs[i];<br>        resp.inference_time_us = per_request_time;<br>        resp.cached = false;<br>        responses.push_back(resp);<br>    }<br>    <br>    return responses;<br>}</pre><p>Why amortize timing? The batch inference time is divided equally among all requests. This gives each request credit for the efficiency gained through batching.</p><h3><strong>Performance Results</strong></h3><p><strong>Test Configuration</strong></p><p>Gateway: 1 instance on port 8000 <br>Workers: 3 instances on ports 8001–8003 <br>Model: ONNX neural network (size varies by test) <br>Hardware: CPU-based inference <br>Test load: 10,000 requests, 50 concurrent threads</p><p><strong>Throughput Results<br></strong>Total requests: 10,000 <br>Successful: 10,000 <br>Failed: 0 <br>Success rate: 100.00% T<br>otal time: 19.13s <br>Requests/sec: 522.64<br>The system maintained zero failures across 10,000 requests, demonstrating the effectiveness of circuit breakers and retry logic.</p><p><strong>Latency Distribution<br></strong>Mean: 86.82ms <br>Median: 84.60ms <br>Stddev: 28.71ms <br>Min: 3.68ms <br>Max: 216.51ms<br>Percentiles: <br>p50: 84.61ms <br>p90: 124.49ms <br>p95: 137.59ms <br>p99: 164.29ms</p><p><strong>Cache Performance<br></strong>Worker 1 (46.81% load): <br>Total requests: 4,681 Cache hits: 4,670 Cache hit rate: 99.77%</p><p>Worker 2 (24.71% load): <br>Total requests: 2,471 Cache hits: 2,461 Cache hit rate: 99.60%</p><p>Worker 3 (38.53% load): <br>Total requests: 3,853 Cache hits: 3,843 Cache hit rate: 99.74%</p><p>First part: <a href="https://medium.com/@abhiramdodda/building-a-production-grade-distributed-inference-system-in-c-part-1-11b933d9216f">https://medium.com/@abhiramdodda/building-a-production-grade-distributed-inference-system-in-c-part-1-11b933d9216f</a></p><h3><strong>References</strong></h3><p>ONNX Runtime &amp; C++ Implementation<br><a href="https://onnxruntime.ai/docs/tutorials/api-basics.html">https://onnxruntime.ai/docs/tutorials/api-basics.html</a></p><p>Complete Code:<br><a href="https://github.com/AbhiramDodda/distributed-inference-engine-cpp">https://github.com/AbhiramDodda/distributed-inference-engine-cpp</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50d0d3ba290d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Production-Grade Distributed Inference System in C++ — Part 1]]></title>
            <link>https://medium.com/@abhiramdodda/building-a-production-grade-distributed-inference-system-in-c-part-1-11b933d9216f?source=rss-a0eeb0ee0600------2</link>
            <guid isPermaLink="false">https://medium.com/p/11b933d9216f</guid>
            <category><![CDATA[inference-engine]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Abhiram Dodda]]></dc:creator>
            <pubDate>Tue, 13 Jan 2026 03:55:08 GMT</pubDate>
            <atom:updated>2026-01-13T16:45:41.062Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Production-Grade Distributed Inference System in C++ — Part 1</h3><p>This project implements a production-grade distributed inference system in C++ that uses consistent hashing to route requests to worker nodes for optimal cache utilization, circuit breakers to handle failures gracefully, LRU caching to avoid redundant computation, and dynamic batching to maximize hardware efficiency during model inference. The architecture combines a central gateway that manages request routing and fault tolerance with multiple worker nodes that each run ONNX Runtime engines wrapped in caching and batching layers. There is a lot of code in this blog</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_BYlS7WupqhMgAo0OaZ-nA.png" /><figcaption>Image generated using AI for illustrative purposes to depict distributed computing systems.</figcaption></figure><p>Machine learning inference at scale presents unique challenges. A single model server can become a bottleneck, requests may fail unpredictably, and cache misses can waste precious compute cycles. This article details the design and implementation of a production-grade distributed inference system that addresses these challenges through consistent hashing, circuit breakers, LRU caching, and dynamic batching.</p><p>The system achieves 522 requests per second with 99.7% cache hit rates and sub-100ms latency at the 90th percentile, while maintaining 100% uptime through intelligent fault tolerance.</p><h3>System Architecture Overview</h3><p>The architecture follows a gateway-worker pattern where a central gateway routes requests to multiple worker nodes using consistent hashing. Each worker node runs an ONNX Runtime inference engine with an LRU cache and dynamic batch processor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*A4HLJ1EMEy6nmHQMOPAVFw.png" /></figure><h3>Component 1: Consistent Hashing</h3><h3>What is Consistent Hashing?</h3><p>Consistent hashing is a distributed hashing scheme that minimizes key redistribution when nodes are added or removed. Unlike traditional modulo hashing, where adding a node would require rehashing all keys, consistent hashing only affects a small fraction of keys.</p><h3>Why Consistent Hashing?</h3><p>In a distributed inference system, we want requests with the same input to hit the same worker node to maximize cache effectiveness. Traditional load balancing (round-robin, random) would distribute identical requests across different workers, wasting cache space.</p><p>Consider this scenario:</p><ul><li>Request A with input [1, 2, 3] arrives</li><li>Worker 1 processes it and caches the result</li><li>Request B with the same input [1, 2, 3] arrives</li><li>With round-robin: might go to Worker 2 (cache miss)</li><li>With consistent hashing: goes to Worker 1 (cache hit)</li></ul><h3>How It Works</h3><p>The consistent hash ring maps both nodes and keys onto a circular space (0 to 2³²). To find which node handles a key, we hash the key and find the first node clockwise on the ring.</p><p>Virtual nodes improve distribution. Instead of placing each physical node once on the ring, we place it multiple times with different hash values.</p><pre>class ConsistentHash {<br>public:<br>    explicit ConsistentHash(int virtual_nodes = 150);<br>    <br>    void addNode(const std::string&amp; node);<br>    void removeNode(const std::string&amp; node);<br>    std::string getNode(const std::string&amp; key) const;<br>    <br>private:<br>    uint32_t hash(const std::string&amp; key) const;<br>    <br>    int virtual_nodes_;<br>    std::map&lt;uint32_t, std::string&gt; ring_;<br>    mutable std::mutex mutex_;<br>};</pre><p>The hash function uses FNV-1a, chosen for its speed and good distribution:</p><pre>uint32_t ConsistentHash::hash(const std::string&amp; key) const {<br>    uint32_t h = 2166136261u;  // FNV offset basis<br>    for (char c : key) {<br>        h ^= static_cast&lt;uint32_t&gt;(c);<br>        h *= 16777619u;  // FNV prime<br>    }<br>    return h;<br>}</pre><p>Why FNV-1a? It provides excellent avalanche properties (small input changes cause large hash changes) with minimal CPU cost compared to cryptographic hashes like SHA-256.</p><p>Adding a node creates virtual nodes:</p><pre>void ConsistentHash::addNode(const std::string&amp; node) {<br>    std::lock_guard&lt;std::mutex&gt; lock(mutex_);<br>    for (int i = 0; i &lt; virtual_nodes_; ++i) {<br>        std::string vnode = node + &quot;#&quot; + std::to_string(i);<br>        uint32_t h = hash(vnode);<br>        ring_[h] = node;<br>    }<br>}</pre><p>Finding a node uses binary search on the sorted map:</p><pre>std::string ConsistentHash::getNode(const std::string&amp; key) const {<br>    std::lock_guard&lt;std::mutex&gt; lock(mutex_);<br>    if (ring_.empty()) {<br>        return &quot;&quot;;<br>    }<br>    <br>    uint32_t h = hash(key);<br>    auto it = ring_.lower_bound(h);<br>    <br>    // Wrap around to beginning if we reached the end<br>    if (it == ring_.end()) {<br>        it = ring_.begin();<br>    }<br>    <br>    return it-&gt;second;<br>}</pre><p>The lower_bound function finds the first position greater than or equal to the hash value, achieving O(log n) lookup time.</p><h3>Component 2: Circuit Breakers</h3><h3>What are Circuit Breakers?</h3><p>Circuit breakers prevent cascading failures in distributed systems by monitoring request success rates and temporarily blocking requests to failing services. The pattern comes from electrical engineering where circuit breakers protect against overload.</p><h3>Why Circuit Breakers?</h3><p>Without circuit breakers, when a worker fails:</p><ul><li>Gateway continues sending requests to the dead worker</li><li>Requests timeout, wasting client time and gateway resources</li><li>The gateway itself can become overloaded with hanging connections</li><li>Clients experience degraded service across the board</li></ul><p>With circuit breakers:</p><ul><li>Failed workers are detected quickly</li><li>Requests route to healthy workers</li><li>Failed workers get time to recover</li><li>System maintains overall availability</li></ul><p>The Three States:</p><pre>CLOSED (Normal)<br>    │<br>    │ failures &gt;= threshold<br>    ▼<br>OPEN (Blocking)<br>    │<br>    │ timeout expires<br>    ▼<br>HALF_OPEN (Testing)<br>    │<br>    ├─ success &gt;= threshold → CLOSED<br>    └─ any failure → OPEN</pre><pre>enum class CircuitState {<br>    CLOSED,      // Normal operation<br>    OPEN,        // Failing, reject requests<br>    HALF_OPEN    // Testing if service recovered<br>};<br><br>class CircuitBreaker {<br>public:<br>    CircuitBreaker(<br>        int failure_threshold = 5,<br>        int success_threshold = 2,<br>        std::chrono::seconds timeout = std::chrono::seconds(30)<br>    );<br>    <br>    bool allowRequest();<br>    void recordSuccess();<br>    void recordFailure();<br>    CircuitState getState() const;<br>    <br>private:<br>    std::atomic&lt;CircuitState&gt; state_;<br>    std::atomic&lt;int&gt; failure_count_;<br>    std::atomic&lt;int&gt; success_count_;<br>    <br>    int failure_threshold_;<br>    int success_threshold_;<br>    std::chrono::seconds timeout_;<br>    <br>    std::chrono::steady_clock::time_point last_failure_time_;<br>    mutable std::mutex mutex_;<br>};</pre><p>Why atomic state? The state variable is read by allowRequest() without a lock for performance, while state transitions use locks for correctness.</p><p>The request gating logic:</p><pre>bool CircuitBreaker::allowRequest() {<br>    std::lock_guard&lt;std::mutex&gt; lock(mutex_);<br>    <br>    if (state_ == CircuitState::OPEN) {<br>        auto now = std::chrono::steady_clock::now();<br>        if (now - last_failure_time_ &gt;= timeout_) {<br>            // Timeout expired, try one request<br>            state_ = CircuitState::HALF_OPEN;<br>            success_count_ = 0;<br>            return true;<br>        }<br>        return false;  // Still cooling down<br>    }<br>    return true;  // CLOSED or HALF_OPEN<br>}</pre><p>Why check timeout in allowRequest()? This implements a lazy state transition. Instead of using a timer thread, we check the timeout when requests arrive, simplifying the design.</p><p>Recording failures:</p><pre>void CircuitBreaker::recordFailure() {<br>    std::lock_guard&lt;std::mutex&gt; lock(mutex_);<br>    failure_count_++;<br>    last_failure_time_ = std::chrono::steady_clock::now();<br>    // Open immediately in HALF_OPEN state<br>    if (failure_count_ &gt;= failure_threshold_ || <br>        state_ == CircuitState::HALF_OPEN) {<br>        state_ = CircuitState::OPEN;<br>    }<br>}</pre><p>Why fail fast in HALF_OPEN? If a test request fails, the service likely hasn’t recovered. Opening immediately prevents wasting more requests.</p><p>Recording successes:</p><pre>void CircuitBreaker::recordSuccess() {<br>    std::lock_guard&lt;std::mutex&gt; lock(mutex_);<br>    if (state_ == CircuitState::HALF_OPEN) {<br>        success_count_++;<br>        if (success_count_ &gt;= success_threshold_) {<br>            state_ = CircuitState::CLOSED;<br>            failure_count_ = 0;<br>        }<br>    } else {<br>        failure_count_ = 0;  // Reset failure count on success<br>    }<br>}</pre><p>Why require multiple successes in HALF_OPEN? A single successful request might be a fluke. Requiring 2+ successes provides confidence the service has truly recovered.</p><h3>Component 3: LRU Cache</h3><h3>What is an LRU Cache?</h3><p>A Least Recently Used cache evicts the least recently accessed item when full. It combines a hash map for O(1) lookup with a doubly-linked list for O(1) eviction.</p><h3>Why LRU for Inference?</h3><p>Machine learning inference exhibits temporal locality. If someone requests inference for input X, they’re likely to request it again soon. LRU exploits this pattern.</p><p>Consider a recommendation system:</p><ul><li>User A’s profile gets embedded multiple times during a session</li><li>Without caching: 100ms per embedding, 10 requests = 1000ms</li><li>With caching: 100ms first request, 0.05ms cached = 100.45ms</li><li>Cache provides good speedup</li></ul><pre>template&lt;typename Key, typename Value, typename Hash = std::hash&lt;Key&gt;&gt;<br>class LRUCache {<br>public:<br>    explicit LRUCache(size_t capacity);<br>    <br>    std::optional&lt;Value&gt; get(const Key&amp; key);<br>    void put(const Key&amp; key, const Value&amp; value);<br>    <br>    double getHitRate() const;<br>    <br>private:<br>    size_t capacity_;<br>    std::list&lt;std::pair&lt;Key, Value&gt;&gt; cache_list_;<br>    std::unordered_map&lt;Key, <br>        typename std::list&lt;std::pair&lt;Key, Value&gt;&gt;::iterator, <br>        Hash&gt; cache_map_;<br>    <br>    mutable std::mutex mutex_;<br>    std::atomic&lt;size_t&gt; hits_;<br>    std::atomic&lt;size_t&gt; misses_;<br>};</pre><p>Why std::list? It provides O(1) insertion and deletion at any position when you have an iterator. This is crucial for moving accessed items to the front.</p><p>The get operation:</p><pre>std::optional&lt;Value&gt; get(const Key&amp; key) {<br>    std::lock_guard&lt;std::mutex&gt; lock(mutex_);<br>    <br>    auto it = cache_map_.find(key);<br>    if (it == cache_map_.end()) {<br>        misses_++;<br>        return std::nullopt;<br>    }<br>    <br>    // Move to front (most recently used)<br>    cache_list_.splice(cache_list_.begin(), cache_list_, it-&gt;second);<br>    <br>    hits_++;<br>    return it-&gt;second-&gt;second;<br>}</pre><p>Why splice? The splice operation moves a list element without copying or reallocating. It just updates pointers, achieving true O(1) time complexity.</p><p>The put operation:</p><pre>void put(const Key&amp; key, const Value&amp; value) {<br>    std::lock_guard&lt;std::mutex&gt; lock(mutex_);<br>    <br>    auto it = cache_map_.find(key);<br>    <br>    if (it != cache_map_.end()) {<br>        // Update existing entry<br>        it-&gt;second-&gt;second = value;<br>        cache_list_.splice(cache_list_.begin(), cache_list_, it-&gt;second);<br>        return;<br>    }<br>    <br>    // Add new entry<br>    if (cache_list_.size() &gt;= capacity_) {<br>        // Evict least recently used (back of list)<br>        auto last = cache_list_.back();<br>        cache_map_.erase(last.first);<br>        cache_list_.pop_back();<br>    }<br>    <br>    cache_list_.emplace_front(key, value);<br>    cache_map_[key] = cache_list_.begin();<br>}</pre><p>Why capacity check before insertion? This ensures we never exceed capacity even during updates.</p><h3>Hashing Vectors</h3><p>For inference caching, we need to hash input vectors. A naive approach would hash every element, but this is expensive for large vectors.</p><pre>struct VectorHash {<br>    size_t operator()(const std::vector&lt;float&gt;&amp; vec) const {<br>        size_t hash = 0;<br>        std::hash&lt;float&gt; hasher;<br>        <br>        // Sample hash - hash first, last, and middle elements<br>        if (!vec.empty()) {<br>            hash ^= hasher(vec[0]) + 0x9e3779b9 + (hash &lt;&lt; 6) + (hash &gt;&gt; 2);<br>            hash ^= hasher(vec[vec.size()/2]) + 0x9e3779b9 + (hash &lt;&lt; 6) + (hash &gt;&gt; 2);<br>            hash ^= hasher(vec.back()) + 0x9e3779b9 + (hash &lt;&lt; 6) + (hash &gt;&gt; 2);<br>        }<br>        <br>        return hash;<br>    }<br>};</pre><p>Why sample only 3 elements? For typical inference inputs (hundreds of floats), hashing 3 elements provides good distribution with minimal overhead. The magic number 0x9e3779b9 is the golden ratio constant used in many hash functions to improve bit mixing.</p><p>Remaining components are continued in Part — 2 :)</p><p>Second part: <a href="https://medium.com/@abhiramdodda/building-a-production-grade-distributed-inference-system-in-c-part-2-50d0d3ba290d">https://medium.com/@abhiramdodda/building-a-production-grade-distributed-inference-system-in-c-part-2-50d0d3ba290d</a></p><h3><strong>References:</strong></h3><p><strong>Consistent hashing:</strong><br><a href="https://youtu.be/UF9Iqmg94tk?si=MvemgGWE5jfDgnF1">https://youtu.be/UF9Iqmg94tk?si=MvemgGWE5jfDgnF1</a><br><a href="https://ably.com/blog/implementing-efficient-consistent-hashing">https://ably.com/blog/implementing-efficient-consistent-hashing</a><br><a href="https://celerdata.com/glossary/consistent-hashing">https://celerdata.com/glossary/consistent-hashing</a></p><p><strong>Dynamic Batching:<br></strong><a href="https://modal.com/blog/batching-whisper">https://modal.com/blog/batching-whisper</a><br><a href="https://docs.nvidia.com/deeplearning/triton-inference-server/user-guide/docs/tutorials/Conceptual_Guide/Part_2-improving_resource_utilization/README.html">https://docs.nvidia.com/deeplearning/triton-inference-server/user-guide/docs/tutorials/Conceptual_Guide/Part_2-improving_resource_utilization</a></p><p>LRU Cache:<br><a href="https://leetcode.com/problems/lru-cache/description/">https://leetcode.com/problems/lru-cache/description/</a><br><a href="https://softwareengineering.stackexchange.com/questions/63595/tea-algorithm-constant-0x9e3779b9-said-to-be-derived-from-golden-ratio-but-the">https://softwareengineering.stackexchange.com/questions/63595/tea-algorithm-constant-0x9e3779b9-said-to-be-derived-from-golden-ratio-but-the</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11b933d9216f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Distributed ML Inference System]]></title>
            <link>https://medium.com/@abhiramdodda/building-a-distributed-ml-inference-system-6d8d48ad873a?source=rss-a0eeb0ee0600------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d8d48ad873a</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Abhiram Dodda]]></dc:creator>
            <pubDate>Sun, 04 Jan 2026 20:28:07 GMT</pubDate>
            <atom:updated>2026-01-04T20:28:07.999Z</atom:updated>
            <content:encoded><![CDATA[<p>Building a Distributed ML Inference System with Consistent Hashing and Batching</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OWXVGjTs6klN_GaHaE9TtA.jpeg" /><figcaption>AI generated image</figcaption></figure><p>Scaling machine learning models for production requires more than just a powerful GPU. It requires a distributed architecture capable of handling high throughput while maintaining low latency. This post explores the implementation of a distributed inference system utilizing consistent hashing for load balancing and dynamic request batching for efficiency.</p><h3><strong>System Architecture</strong></h3><p>The system is comprised of three primary components working in tandem to process requests efficiently:<br><strong>Gateway Server:</strong> Acts as the entry point and routes requests using consistent hashing.<br><strong>Worker Nodes:</strong> Distributed processing units that handle the actual model inference.<br><strong>Batch Processor:</strong> A mechanism within each worker that groups individual requests into optimized batches.</p><h3><strong>Load Balancing with Consistent Hashing</strong></h3><p>To ensure requests are distributed evenly across nodes and to handle worker availability, we implement consistent hashing with 150 virtual nodes. This approach minimizes remapping when nodes are added or removed.</p><pre>def add_node(self, node):<br>    if node in self.nodes:<br>        return<br>    self.nodes.add(node)<br>    for i in range(self.virtual_nodes):<br>        virtual_key = f&quot;{node}#{i}&quot;<br>        hash_value = self._hash(virtual_key)<br>        self.ring[hash_value] = node<br>    self.sorted_keys = sorted(self.ring.keys())</pre><h3><strong>Dynamic Request Batching</strong></h3><p>Inference efficiency is significantly improved by processing requests in batches rather than individually. <em>BatchProcessor</em> uses a combination of <em>max_batch_size</em> and a <em>timeout_ms</em> window to trigger processing. For example, if the batch size of 32 is not met within 20ms, the current batch is processed regardless to prevent excessive latency.</p><pre>def _processing_loop(self):<br>    while self.running:<br>        try:<br>            elapsed = time.perf_counter() - last_batch_time<br>            timeout_remaining = max(0, self.timeout_ms - elapsed)<br>            request, result_queue = self.request_queue.get(timeout=timeout_remaining)<br>            batch.append(request)<br>            if len(batch) &gt;= self.max_batch_size:<br>                self._process_batch(batch, result_queues, timeout=False)<br>        except Empty:<br>            if batch:<br>                self._process_batch(batch, result_queues, timeout=True)</pre><h3><strong>Model Sharding and Vectorization</strong></h3><p>Efficiency also comes from the <em>InferenceEngine</em>, which uses vectorized operations for batch predictions. By converting a list of inputs into a single matrix for matrix multiplication, we maximize CPU/GPU utilization.</p><pre>def batch_predict(self, inputs, shapes):<br>    batch_array = np.zeros((batch_size, self.hidden_size), dtype=np.float32)<br>    for i, inp in enumerate(inputs):<br>        arr = np.array(inp, dtype=np.float32)[:self.hidden_size]<br>        batch_array[i, :len(arr)] = arr<br>    # Vectorized MatMul<br>    x = batch_array<br>    for _ in range(5):<br>        x = np.matmul(x, self.weights)<br>        x = np.tanh(x)</pre><h3><strong>Performance Metrics</strong></h3><p>Benchmarking results demonstrate the effectiveness of this architecture compared to a single node baseline.<br>Throughput: Achieved 4 requests per second.<br>Latency (p50): 4001.2ms.<br>Resource Efficiency: 62% memory reduction per node via model sharding.<br>Load Balance: 7.14% variance across nodes.</p><h3><strong>Conclusion</strong></h3><p>By combining consistent hashing, model sharding, and dynamic batching, we built a system that offers horizontal scaling and near linear throughput increases. This architecture provides a robust foundation for production ML services.</p><p>Reference:<br>You can access the full code at: <a href="https://github.com/AbhiramDodda/Distributed-Inference">https://github.com/AbhiramDodda/Distributed-Inference</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d8d48ad873a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Matrix Algebra — The Tip of the Ice Berg]]></title>
            <link>https://medium.com/@abhiramdodda/matrix-algebra-the-tip-of-the-ice-berg-f5b984242726?source=rss-a0eeb0ee0600------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5b984242726</guid>
            <category><![CDATA[matrix-algebra]]></category>
            <category><![CDATA[matrix]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Abhiram Dodda]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 11:20:54 GMT</pubDate>
            <atom:updated>2025-02-13T11:20:54.472Z</atom:updated>
            <content:encoded><![CDATA[<h3>Matrix Algebra — The Tip of the Ice Berg</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5A-6AwlF0GHJplFtYxqlWw.jpeg" /></figure><h3>Introduction — What is a matrix?</h3><p>Let us begin with the very definition of a matrix. A matrix is a rectangular array of numbers, symbols, or expressions. The representation of a matrix is as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*0gGQWt4MALPO3oZ98loScg.png" /></figure><p>A matrix has rows and columns. A row is a horizontal array while a column is a vertical array of numbers. The shape of a matrix is defined by the rows and the columns, for example, in the above illustration the matrix has 3 rows and 3 columns so it is a 3x3 matrix (x → is pronounced as by).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*SgnVaCCGvXq1UpWfOoD4Qw.png" /></figure><p>In the above illustration, the matrix has m rows and n columns so it is an m\times n matrix. A matrix is denoted by uppercase letters as A[mxn].</p><h3>Types of Matrices</h3><h4>Row Matrix</h4><p>A matrix with a single row is a row matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/1*-eyp4sQJYuz3qXt9e26-lQ.png" /></figure><h4>Column matrix</h4><p>A matrix with a single column is a column matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/70/1*lw-JJMqSt22Sjx-Zbo4Vjg.png" /></figure><h4>Rectangular Matrix</h4><p>A matrix A is called a rectangular matrix if it has an unequal number of rows and columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/131/1*uxy6cnswUq4lN7XenBBsvg.png" /></figure><h4>Square Matrix</h4><p>A matrix with an equal number of rows and columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*mjWD9tc-6TneCoSH7FgDlA.png" /></figure><h4>Diagonal Matrix</h4><p>A diagonal matrix is a square matrix with all the elements except the principle diagonal elements as 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*MVyMN3l8MooqA1PYtsII6Q.png" /></figure><h4>Identity Matrix</h4><p>An identity matrix is a diagonal matrix with all the principal diagonal elements as follows: 1. Identity matrices are represented as $I_{n\times n}$ in matrix algebra.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*qJGHAi9EuBInREmOjY8Liw.png" /></figure><h4>Upper Triangular Matrix</h4><p>A square matrix is called an upper triangular matrix if all the elements below the principle diagonal are 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*92OKZrLWsHLeDg7_szql-g.png" /></figure><h4>Lower Triangular Matrix</h4><p>A square matrix is called a lower triangular matrix if all the elements above the principal diagonal are 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*5njv1h4TldrKQmmlzcl_iw.png" /></figure><h4>Symmetrix Matrix</h4><p>A matrix with A = A^T property is called a Symmetrix matrix. It must be a square matrix; otherwise, the dimensions change, and it is impossible to equate matrices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/1*wTCODs43mmAEQWLRKKnLJA.png" /></figure><p>If matrix A is symmetric then A^n is symmetric for all natural numbers.</p><h4>Skew-Symmetric Matrix</h4><p>A square matrix is called a skew-symmetric matrix if A = -A^T.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*9ucEuUzF-ThEFbnN8HcOtg.png" /></figure><p>If matrix A is skew-symmetric then A^{2n} is symmetric and A^{2n+1} is skew-symmetric.</p><h4>Diagonal Matrix</h4><p>A <strong>diagonal matrix</strong> is a special type of square matrix where <strong>all the non-diagonal elements are zero</strong>, meaning only the <strong>principal diagonal</strong> (from the top-left to the bottom-right) can have nonzero values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*_HTxA-sRRs2mmp2D1DSlXQ.png" /></figure><p>This means:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*DngIR8gBtEE2KNwmyuXO1w.png" /></figure><p>where d[i,j] (for i = 1, 2, … ,n) are the only possible non-zero elements.</p><p>Examples:</p><p>2 x 2 Diagonal Matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/116/1*NBUUgmNQiYT_UV5qjDgo_g.png" /></figure><p>3 x 3 Diagonal Matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*s1-Ww24Wfgk5VDdcQGHp6w.png" /></figure><h4>Properties of Diagonal Matrices</h4><p>Multiplication of two diagonal matrices If D1 and D2 are diagonal matrices, their product is also a diagonal matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*wc0QdB12X57jcjGuJH8uSA.png" /></figure><p>Inverse of a diagonal matrix If all diagonal elements d[i,j] not equal to 0, then the inverse of D is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*8HCgoHUXm8AnMyFxiLlqyg.png" /></figure><p>Eigenvalues of a diagonal matrix The eigenvalues of a diagonal matrix are simply the diagonal elements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*z5LBsnK0d1mRGl08M1DU3Q.png" /></figure><p>Power of a diagonal matrix Raising D to the power of k results in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*3zQ3P45q-Me1jRVV7x8_Jg.png" /></figure><h4>Identity Matrix</h4><p>A diagonal matrix where all diagonal elements are 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*8V7KMcgsmLgeUVeU31g3xg.png" /></figure><h4>Scalar Matrix</h4><p>A diagonal matrix where all diagonal elements are the same constant c.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*a8NdIo7r3FghoEexUNmIVQ.png" /></figure><h3>Addition and Subtraction of Matrices</h3><p>Matrix addition and subtraction are fundamental operations in linear algebra, representing element-wise operations between two matrices of the same dimension. If we have two matrices A and B both of the size m x n then their sum of difference is computed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*QZsXu6wfmWXdIIwh6LZNJg.png" /></figure><p>This means that for each element at row i, column j , we individually add or subtract corresponding elements from matrices A and B.</p><p>Consider the below example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*SQxM5kcCuwegA_PB2w86Nw.png" /></figure><h3>Algebraic Properties of Matrix Addition</h3><ol><li>Commutativity: A+B = B+A</li><li>Associativity: (A+B)+C = A+(B+C)</li><li>Additive Identity: There exists a zero matrix O such that A+O = A</li><li>Additive Inverse: A+(-A) = O, where -A is the matrix with negated elements.</li></ol><h3>Trace of a Matrix</h3><p>The sum of the elements of a square matrix A lying along the principal diagonal is called the trace of A denoted as tr(A) or tr.A</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*M6i1MKl2FjlO179aGhvfBA.png" /></figure><h3>Matrix Multiplication</h3><p>Matrix multiplication is more than just multiplying numbers — it’s about linear transformations, vector projections, and the composition of functions. For matrix multiplication to work column size of the first matrix and the row size of the second matrix must be the same.</p><p>Given two matrices:</p><ul><li>A of size m x n</li><li>B of size n x p</li></ul><p>Their product C = AB results in a new matrix of size m x p, where each element c[i,j] is computed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*m7l4aE2TvSBEVyzKiRd6YQ.png" /></figure><p>This means that each element of C is obtained by taking the dot product of the ith row of A and the jth column of B.</p><h3>Geometric Interpretation</h3><p>Matrix multiplication can be thought as applying a linear transformation.</p><ol><li>Each row of A represents a linear combination of the columns of B.</li><li>Each columns of B represents a basis transformation applied to the rows of A.</li><li>The product matrix C is formed by projecting the rows of A onto the columns of B.</li></ol><p>Examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*2xRw3eoMhL4APqruAaladA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*6vG-BAsTbDR9BYLjUQZ3tg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*ZA8Q6I2CcXsD640tBN_jww.png" /></figure><h3>Algebraic properties of matrix multiplication</h3><p>Unlike addition, matrix multiplication does not always commute! That is:</p><p>AB is not equal to BA</p><p>However, it does satisfy:</p><ol><li>Associativity: (AB)C = A(BC)</li><li>Distributivity: A(B+C) = AB+AC</li><li>Identity Matrix: AI = A and IA = A</li></ol><h3>Matrix Transpose</h3><p>The transpose of a matrix A, denoted as A^T, is obtained by swapping the rows and columns of A. If A is an m x n matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*FSaVZduYsj7MrkDiaZxbNw.png" /></figure><p>Then its transpose is an n x m matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*XvB3ujKt2AXOWXK6_rkmtg.png" /></figure><h3>Properties of a Transpose</h3><p><strong>Double Transpose</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/106/1*mLpDjRmfidp1HVAd_gsTZg.png" /></figure><p><strong>Transpose of a Sum</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*C94R6MGy5zRzKtkYng6Z2g.png" /></figure><p><strong>Transpose of a Scalar Multiple</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/132/1*c9kt9HriJjTWJZD9mN3cPA.png" /></figure><p><strong>Transpose of a Product</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/1*JI7khdkL6q8O4F2CM580Fg.png" /></figure><p><strong>Transpose of an Inverse</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*RpmiCS-oOLDXBWAUB4THIA.png" /></figure><p><strong>Determinant</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*MiDP_G1jyVX2POs-rQ-Y3w.png" /></figure><h3>Examples:</h3><p>Given:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*XtIGIdAxJtBqjBhILLRY_A.png" /></figure><h3>Adjoint of a Matrix</h3><p>An adjoint matrix of a matrix A is the transpose of the cofactor C of A. An adjoint matrix is also called an adjugate matrix.</p><p>Cofactor matrix C is obtained by replacing each element of matrix A with its corresponding cofactor.</p><h3>Cofactor</h3><p>Cofactor of an element a[i, j]in a matrix is the signed determinant of the minor matrix obtained by removing ith row and jth column from the original matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/166/1*JoiVZK-7N1GctdvhxuTZig.png" /></figure><p>where M[i, j] is the minor, which is the determinant of the submatrix obtained by deleting ith row and jth column.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*CI_DgImEPzlkFXCem9q4Eg.png" /></figure><p>Let C[i, j] be cofactor of a[i, j] in A.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*Eoiv4M2yQZCIpQryG6Vz3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*KjpR3xjzh4VxGxs_0ZBsVQ.png" /></figure><h3>Properties of Adjoint Matrix</h3><ol><li>If A is a non-singular square matrix of order n, then |adj.A| = |A|^{n-1}</li><li>If A is a non-singular square matrix, then adj.(adj.A) = |A|^{n-2}A</li><li>If A and B are non-singular square matrices of the same order, then adj.(AB) = (adj.A)(adj.B)</li><li>adj.(A^T) = (adj(A))^T</li><li>adj(kA) = k^{n-1}adj(A) where k is a scalar.</li></ol><h3>Inverse of a Square Matrix</h3><p>The inverse of a square matrix $A$ denoted by $A^{-1}$, is a matrix such that when multiplied by $A$, it results in the identity matrix $I$. That is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*bfGGW_iSrRcFc867jH18Xg.png" /></figure><p>A matrix A has an inverse if and only if it is non-singular, i.e., its determinant is non-zero:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/104/1*sCFwneHq_V7B2-evNYaPBA.png" /></figure><h3>Two ways of calculating the inverse of a square matrix:</h3><h3>Gauss-Jordan Elimination:</h3><p>This method involves augmenting the given matrix $A$ with the identity matrix $I$ and then applying row operations to transform A into I. The transformed identity matrix turns into $A^{-1}$.</p><ol><li>Augment A with the identity matrix and apply row operations</li><li>Convert A into I and the right part of the augmentation becomes A^{-1}.</li></ol><p>Examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*OzGS-UZxmwbWaUwxtLI-xA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*jnXY50kLlsOlOzU9GQaWeA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/1*fpihsZx1EJE7rF6fIaRkdA.png" /></figure><p>Step 1: Augment the matrix with identity matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*ANjZHwV-2Oyo_7MndXRIlg.png" /></figure><p>Step 2: Swap R1 and R3 to get a leading 1 in the first column</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*2imow0fHNhjVSHWlNIKDgg.png" /></figure><p>Step 3: Make the first column’s second and third entries zero R2 -&gt;R_2 — R1, and R3 -&gt;R_3–2R1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*XcGaQSml-1HiNalWnvkEcg.png" /></figure><p>Step 4: Make the second column’s third entry zero R3 -&gt; R_3–(1/3)R2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*63hH83bHbbiNzuNrn1K3Gw.png" /></figure><p>Step 5: Scale R3 to make the pivot 1. R3 -&gt; 3R3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*Xkjq7jZ2vhTDMRh6rPNKWA.png" /></figure><p>Step 6: Make second entry of third column 0. R2 -&gt;R2–2R3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*t0lxZpYf0j96aJ-UFfw6yA.png" /></figure><p>Step 7: Scale second row to make the pivot 1. R2 -&gt; R2/3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*X0Ot8j6HD09N1jtc0Re39g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*a6mVTLe2hAntTB5YlaCPyw.png" /></figure><h3>Adjoint Method (Co-factor Method)</h3><p>The inverse of a matrix A can be found using the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*GWUwB4a9bgY0w12jVgh_eQ.png" /></figure><p>where det(A) is the determinant of A and adj(A) is the adjugate (transpose of the cofactor matrix)</p><p>For a 2 x 2 matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/1*ezLShT29eFJcBuzFmW0T6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*FZdJ26JVjdkZ6I5vYO6oJA.png" /></figure><p>Examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*d20l7AhDVpMGAs-fHuDiIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*BM32MkjL_aSjJFsYnSSVrg.png" /></figure><p>Compute cofactor matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*VQabxVyUle0ZDM1hcRwXTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/154/1*Zw73PKXRG5I1IdJ9Z17GsQ.png" /></figure><p>Step 1: Compute the determinant</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*jemp_rzcKDRv84s5XTOFlQ.png" /></figure><p>Step 2: Compute the cofactor matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*Luld0s6syMD01AJQbKwFfg.png" /></figure><p>Step 3: Compute the adjugate (transpose of cofactor matrix)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*1dFgAuiQZutcKvhaRGcewg.png" /></figure><p>Step 4: Compute B^{-1}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*Xzw4SdU290LiCEX1LMF-iA.png" /></figure><h3>Some Special Matrices</h3><h4>Orthogonal Matrix</h4><p>A square matrix A of order n is said to be orthogonal if</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*RuM2FbzKKyBLZ8QDVqmIrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*iq9K5WtYa9jEtQIgayoABQ.png" /></figure><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*KbYhFJqGE_FIQ6VBTIwVPg.png" /></figure><p>Properties of Orthogonal Matrix:</p><p><strong>Inverse equals Transpose</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/99/1*uZu5m4S36Oe97bAaKA-LSQ.png" /></figure><p><strong>Preserves Norm (length of vectors)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/122/1*Hd0XwhgHf3dYwu9OxnxrQw.png" /></figure><p>for any vector x, meaning that orthogonal matrices do not change vector magnitudes.</p><p><strong>Preserves Orthogonality</strong></p><p>If two vectors u and v are orthogonal then after after multiplication by an orthogonal matrix they remain orthogonal.</p><p><strong>Preserves Inner Product</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/166/1*E5tKWs97oxciW8HlOsKXBA.png" /></figure><p>meaning that an orthogonal matrix preserves angles and distances.</p><p><strong>Eigenvalues have absolute value 1</strong></p><p>The eigenvalues of an orthogonal matrix satisfy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/66/1*yZTu7fLrYmM1HJiVgPfaFA.png" /></figure><p><strong>Rotation and Reflection properties</strong></p><ul><li>Orthogonal matrices represent rotations if det(Q) = 1</li><li>Orthogonal matrices represent reflection if det(Q) = -1</li></ul><h4>Idempotent Matrix</h4><p>A square matrix is called an idempotent matrix if A² = A.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*ZniT1cRH8PSAHy5yQmefnA.png" /></figure><h4>Involuntary Matrix</h4><p>A square matrix is called involuntary if A² = I</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*kA6PPPtf4HtPlhT0hsM8WA.png" /></figure><h4>Nilpotent Matrix</h4><p>A square matrix A is called a nilpotent matrix if there exists a positive integer m such that A^m = O. If m is the least positive integer such that A^m = O, them m is called the index of the matrix.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5b984242726" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Networks — game changers]]></title>
            <link>https://medium.com/@abhiramdodda/neural-networks-game-changers-951e0231126e?source=rss-a0eeb0ee0600------2</link>
            <guid isPermaLink="false">https://medium.com/p/951e0231126e</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[recurrent-neural-network]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Abhiram Dodda]]></dc:creator>
            <pubDate>Fri, 03 Jan 2025 07:29:05 GMT</pubDate>
            <atom:updated>2025-01-03T07:29:05.041Z</atom:updated>
            <content:encoded><![CDATA[<h3>Neural Networks — game changers</h3><p>The Architects of the AI Revolution: A Short Mathematical Perspective</p><h3>Introduction</h3><p>The field of artificial intelligence has witnessed a remarkable transformation over the past decade, largely driven by the resurgence and evolution of neural networks. From their humble beginnings as simple perceptrons to today’s sophisticated deep learning architectures, neural networks have revolutionized how we approach complex problems across diverse domains. This article delves into the mathematical foundations, historical development, and cutting-edge applications of neural networks.</p><h3>The Foundation: The Perceptron</h3><p>The story begins with Frank Rosenblatt’s perceptron, introduced in 1958. This fundamental building block of neural networks mirrors the basic functioning of a biological neuron. Mathematically, a perceptron can be expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*hiKav4n1ahmGSnCMrBRWVw.png" /><figcaption>Mathematical equation for perceptron</figcaption></figure><p>The activation function introduces non-linearity, traditionally using the step function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*5PPuX00wQ4KgqcCOVAMF8w.png" /><figcaption>Activation function: step function</figcaption></figure><h3>Hopfield Networks: The Power of Recurrence</h3><p>Hopfield networks, introduced by John Hopfield in 1982, demonstrated how recurrent connections could enable neural networks to serve as content-addressable memory systems. The energy function of a Hopfield network is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*t3IkBPsT518VZZKpWXYaag.png" /><figcaption>Hopfield energy equation</figcaption></figure><p>The network minimizes this energy function, converging to stable states that represent stored memories. The weight matrix is typically constructed using the Hebbian learning rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*y5KAqfG1XfLuAoPmOhH_Pw.png" /><figcaption>Hebbian learning rule</figcaption></figure><h3>Modern Neural Networks: Deep Learning Architecture</h3><p><strong>Feedforward Neural Networks</strong></p><p>Modern deep neural networks build upon these foundations, incorporating multiple layers of neurons. The output of each layer in a feedforward network can be expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*do08WZebRrjfuOmXeaoefg.png" /><figcaption>Feed-forward neural network equation</figcaption></figure><p><strong>Backpropagation: The Learning Algorithm</strong></p><p>The breakthrough that enabled efficient training of deep networks came with backpropagation. The algorithm minimizes a loss function <em>L</em> through gradient descent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*09w-V8buF-0otoMkjQ_97w.png" /><figcaption>Error calculation and propagation</figcaption></figure><h3>Recent Advancements and Applications</h3><p><strong>Transformer Architecture</strong></p><p>The transformer architecture, introduced in “Attention Is All You Need” (Vaswani et al., 2017), revolutionized natural language processing. The self-attention mechanism is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*PIS9-cAiU0Nx_z79LPs3EA.png" /></figure><p>This architecture has enabled breakthrough models like BERT, GPT, and their successors.</p><p><strong>Convolutional Neural Networks in Computer Vision</strong></p><p>CNNs have dominated computer vision tasks. The convolution operation is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*u_MUjAIZZeof2HKesavL_w.png" /></figure><p>In discrete form for image processing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*u_MUjAIZZeof2HKesavL_w.png" /></figure><p><strong>Recurrent Neural Networks: Processing Sequential Data</strong></p><p>Recurrent Neural Networks represent a powerful architecture designed specifically for sequential data — whether it’s text, time series, or any data where order matters. Unlike feedforward networks, RNNs maintain an internal state (memory) that gets updated as they process each element in a sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*SImmEBjDEvYGBrdkH0zZWw.png" /></figure><p>The output at each time step is then computed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*vQP3zJba6aYyk8AKfR1qdQ.png" /></figure><h4><strong>The Vanishing Gradient Problem and LSTM Solution</strong></h4><p>However, basic RNNs suffer from the vanishing gradient problem during training, making it difficult to capture long-term dependencies. Long Short-Term Memory (LSTM) networks were developed to address this limitation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*n4BQ6Ndw33-5QTk2PiQSsg.png" /><figcaption>Information flow equations in an LSTM</figcaption></figure><p>An LSTM cell uses three gates (forget, input, and output) and a memory cell to control information flow, forget gate(ft), input gate(it), and output gate(ot).</p><h4>Gated Recurrent Units (GRUs)</h4><p>GRUs offer a simplified version of LSTM, using only two gates while maintaining similar performance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*Y5HwiBqxaMGo_0-qAsSzWg.png" /></figure><h4>Bidirectional RNNs</h4><p>For tasks where future context is as important as past context, bidirectional RNNs process sequences in both directions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*IuIntWHIz_meeclZyHyz-Q.png" /></figure><h3><strong>Applications in Various Domains</strong></h3><p><strong>1. Healthcare</strong><br> — Medical image analysis using CNNs<br> — Drug discovery through molecular graph neural networks<br> — Patient outcome prediction using recurrent networks</p><p><strong>2. Finance</strong><br> — High-frequency trading<br> — Risk assessment<br> — Fraud detection</p><p><strong>3. Climate Science</strong><br> — Weather prediction<br> — Climate model downscaling<br> — Extreme event prediction</p><h3><strong>Future Directions</strong></h3><p>The field continues to evolve with promising developments in:<br>- Energy-efficient neural architectures<br>- Few-shot and zero-shot learning<br>- Interpretable AI<br>- Neuromorphic computing</p><h3>Conclusion</h3><p>Neural networks have evolved from simple perceptrons to sophisticated architectures that power modern AI systems. Their mathematical foundations, combined with increased computational power and data availability, have enabled breakthroughs across numerous fields. As we continue to advance our understanding and capabilities, neural networks will undoubtedly remain at the forefront of technological innovation.</p><h4><strong>References</strong></h4><p>1. Rosenblatt, F. (1958). “The Perceptron: A Probabilistic Model for Information Storage and Organization in the Brain.” Psychological Review.</p><p>2. Hopfield, J. J. (1982). “Neural networks and physical systems with emergent collective computational abilities.” Proceedings of the National Academy of Sciences.</p><p>3. Vaswani, A., et al. (2017). “Attention Is All You Need.” Advances in Neural Information Processing Systems.</p><p>4. LeCun, Y., Bengio, Y., &amp; Hinton, G. (2015). “Deep learning.” Nature.</p><p>5. Krizhevsky, A., Sutskever, I., &amp; Hinton, G. E. (2012). “ImageNet Classification with Deep Convolutional Neural Networks.” Advances in Neural Information Processing Systems.</p><p>Mathematical equations were rendered in <a href="https://latexeditor.lagrida.com/">Lagrida Latex editor</a> and pasted as images.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=951e0231126e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>