<?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 Deepanshuemblinux on Medium]]></title>
        <description><![CDATA[Stories by Deepanshuemblinux on Medium]]></description>
        <link>https://medium.com/@deepanshuemblinux?source=rss-240bf57904aa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*x84hoh-xA2n6OTxK</url>
            <title>Stories by Deepanshuemblinux on Medium</title>
            <link>https://medium.com/@deepanshuemblinux?source=rss-240bf57904aa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:40:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deepanshuemblinux/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[Designing Idempotent APIs: From Idempotency Keys to Durable Idempotency Records]]></title>
            <link>https://medium.com/@deepanshuemblinux/designing-idempotent-apis-from-idempotency-keys-to-durable-idempotency-records-48ded6199548?source=rss-240bf57904aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/48ded6199548</guid>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Deepanshuemblinux]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 21:14:16 GMT</pubDate>
            <atom:updated>2026-07-24T21:14:16.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J7jhWxGuqbeg_wAe3Cq4Sg.png" /></figure><h3>How to prevent duplicate jobs when clients retry, requests race, and application instances run concurrently</h3><p>Imagine that we expose an asynchronous job-submission API:</p><pre>POST /jobs</pre><p>When the request succeeds, the API creates a job and returns:</p><pre>HTTP/1.1 202 Accepted<br>Location: /jobs/job-101</pre><p>The client sends a request, but the response never reaches it.</p><p>Perhaps:</p><ul><li>the client’s network connection breaks;</li><li>a load balancer times out;</li><li>the API processes the request but crashes before returning;</li><li>the response reaches an intermediary but not the client.</li></ul><p>The client now faces a difficult question:</p><blockquote><em>Was the job created, or should I try again?</em></blockquote><p>Retriable APIs must assume that clients will send the same logical operation more than once.</p><p>Without idempotency, this retry can create two jobs:</p><pre>First request  → job-101<br>Retry request  → job-102</pre><p>The client intended to submit one job, but the system accepted two.</p><p>This is the problem that idempotency keys and idempotency records are designed to solve.</p><h3>1. What Idempotency Means</h3><p>An operation is <strong>idempotent</strong> when repeating the same logical operation does not produce additional business effects.</p><p>For example:</p><pre>First submission:<br>Create one job</pre><pre>Repeated submission:<br>Return the already-created job</pre><p>The second request may still be processed by the API, but it must not create another independent job.</p><p>Idempotency does not necessarily mean that every response is byte-for-byte identical.</p><p>It means the externally visible business result remains equivalent.</p><p>For our job API:</p><pre>POST with key K-123<br>        ↓<br>Create job-101</pre><pre>POST again with key K-123<br>        ↓<br>Return job-101</pre><p>The important guarantee is:</p><pre>One logical submission<br>=<br>One logical job</pre><h3>2. Why Clients Retry Successful Operations</h3><p>A client may retry even when the server successfully completed the original request.</p><p>Consider this timeline:</p><pre>Client ── POST /jobs ──▶ API<br>                         API creates job-101<br>Client ◀── response is lost</pre><p>From the API’s perspective, the operation succeeded.</p><p>From the client’s perspective, the outcome is unknown.</p><p>A timeout tells the client:</p><blockquote><em>I did not receive the response.</em></blockquote><p>It does not necessarily mean:</p><blockquote><em>The server did not execute the operation.</em></blockquote><p>This is an <strong>ambiguous outcome</strong>.</p><p>The client therefore retries:</p><pre>Client ── retry POST /jobs ──▶ API</pre><p>If the API treats the retry as a new request, it creates job-102.</p><p>Idempotency gives the server a way to recognise that both requests represent the same intended operation.</p><h3>3. The Idempotency Key</h3><p>The client attaches a unique token to the operation:</p><pre>POST /jobs<br>Idempotency-Key: K-123</pre><p>The key means:</p><blockquote><em>Requests carrying this key represent the same logical operation.</em></blockquote><p>The server stores a durable mapping:</p><pre>K-123 → job-101</pre><p>When the key appears again, the server looks up the mapping and returns the same result.</p><p>A more realistic mapping is scoped by the caller:</p><pre>tenant-A + K-123 → job-101</pre><p>This is important because different customers may independently generate the same key.</p><p>Without tenant scoping:</p><pre>Tenant A uses K-123<br>Tenant B uses K-123</pre><p>The requests could incorrectly collide.</p><p>A typical uniqueness boundary is therefore:</p><pre>tenant_id + idempotency_key</pre><p>Depending on the API, the scope may also include the operation or endpoint:</p><pre>tenant_id + operation_name + idempotency_key</pre><p>The exact scope is part of the API contract.</p><h3>4. Why Returning 409 Conflict Is Not Enough</h3><p>Suppose the retry reaches the API and the API notices that K-123 already exists.</p><p>Could it simply return:</p><pre>409 Conflict</pre><p>It could, but that would not fully satisfy the purpose of idempotency.</p><p>The client does not merely need to know that the key already exists.</p><p>It needs to know the outcome of the original operation.</p><p>A bare 409 leaves several questions unanswered:</p><ul><li>Was the original request accepted?</li><li>Which job was created?</li><li>Is the job still pending?</li><li>Did the original request fail?</li><li>Should the client retry with another key?</li></ul><p>A better idempotent response is:</p><pre>HTTP/1.1 202 Accepted<br>Location: /jobs/job-101</pre><p>or:</p><pre>{<br>  &quot;jobId&quot;: &quot;job-101&quot;,<br>  &quot;status&quot;: &quot;PENDING&quot;<br>}</pre><p>The retry receives the same logical job reference as the original request.</p><h3>When is 409 Conflict appropriate?</h3><p>409 Conflict is useful when the same idempotency key is reused for a different logical request.</p><p>For example:</p><pre>First request:<br>Key: K-123<br>Payload: Generate report for January</pre><pre>Second request:<br>Key: K-123<br>Payload: Delete customer account</pre><p>The server must not silently return the result of the first operation as though the second operation were equivalent.</p><p>In that case, the client has violated the idempotency-key contract.</p><p>A useful rule is:</p><pre>Same key + same logical request<br>→ return the original result</pre><pre>Same key + different logical request<br>→ reject with 409 Conflict</pre><h3>5. The Idempotency Record</h3><p>The server needs more than a temporary in-memory set of keys.</p><p>It needs an <strong>idempotency record</strong> that connects the key to the accepted business operation.</p><p>At minimum, the record may contain:</p><pre>tenant_id<br>idempotency_key<br>job_id<br>request_fingerprint<br>created_at</pre><p>Conceptually:</p><pre>tenant-A<br>+<br>K-123<br>+<br>request fingerprint H-789<br>→<br>job-101</pre><p>The most important fields serve different purposes.</p><h3>tenant_id</h3><p>Defines who owns the key.</p><pre>tenant-A + K-123</pre><p>is different from:</p><pre>tenant-B + K-123</pre><h3>idempotency_key</h3><p>Identifies the client’s logical operation.</p><h3>job_id</h3><p>Connects retries to the original job.</p><h3>request_fingerprint</h3><p>Allows the server to determine whether a repeated key carries the same logical request.</p><h3>created_at</h3><p>Supports auditing and any future retention policy.</p><p>The idempotency record is not merely a marker saying:</p><pre>K-123 was seen</pre><p>It should tell the system:</p><pre>K-123 represents job-101</pre><p>That mapping lets the retry recover the original outcome.</p><h3>6. Why the Request Fingerprint Matters</h3><p>Suppose the server stores only:</p><pre>K-123 → job-101</pre><p>A client accidentally reuses K-123 with a different request.</p><p>Without remembering anything about the original request, the server cannot distinguish:</p><pre>A legitimate retry</pre><p>from:</p><pre>Accidental key reuse</pre><p>A request fingerprint solves this.</p><p>For example:</p><pre>request_fingerprint = SHA-256(canonical request representation)</pre><p>The server can compare the incoming request to the stored fingerprint.</p><pre>Stored fingerprint == incoming fingerprint<br>→ legitimate retry</pre><pre>Stored fingerprint != incoming fingerprint<br>→ conflicting key reuse</pre><p>This makes the idempotency record a binding between three things:</p><pre>Caller<br>+<br>Logical request<br>+<br>Created resource</pre><h3>7. Logically Equivalent JSON May Not Produce the Same Raw Hash</h3><p>Consider these JSON requests:</p><pre>{<br>  &quot;name&quot;: &quot;Deepanshu&quot;,<br>  &quot;age&quot;: 30<br>}</pre><p>and:</p><pre>{<br>  &quot;age&quot;: 30,<br>  &quot;name&quot;: &quot;Deepanshu&quot;<br>}</pre><p>They represent the same JSON object because object-field order is not semantically significant.</p><p>However, the raw byte strings are different.</p><p>Therefore:</p><pre>SHA-256(raw JSON 1)</pre><p>may differ from:</p><pre>SHA-256(raw JSON 2)</pre><p>A hash function does not understand JSON semantics. It hashes bytes.</p><p>To generate the same fingerprint for logically equivalent requests, the server needs a <strong>canonical representation</strong>.</p><p>A canonicalisation process might:</p><ul><li>parse the JSON;</li><li>sort object keys consistently;</li><li>use a consistent number representation;</li><li>use a consistent string-escaping format;</li><li>decide how to treat omitted versus explicit default fields;</li><li>serialise the canonical structure;</li><li>hash the resulting bytes.</li></ul><p>Conceptually:</p><pre>Raw request<br>    ↓<br>Parse JSON<br>    ↓<br>Normalise representation<br>    ↓<br>Canonical JSON<br>    ↓<br>SHA-256</pre><p>For example, both requests could be converted to:</p><pre>{&quot;age&quot;:30,&quot;name&quot;:&quot;Deepanshu&quot;}</pre><p>The server then hashes this canonical form.</p><p>The precise normalisation rules must match the API’s definition of logical equivalence.</p><p>For example, are these equivalent?</p><pre>{&quot;priority&quot;: null}</pre><p>and:</p><pre>{}</pre><p>The answer depends on the application contract.</p><p>Canonicalisation should not invent equivalence rules that the business API does not actually support.</p><h3>8. The Check-Then-Insert Race</h3><p>A naive implementation might do this:</p><pre>if (!idempotencyMap.containsKey(key)) {<br>    createJob();<br>    idempotencyMap.put(key, jobId);<br>}</pre><p>This is not safe under concurrency.</p><p>Suppose two requests carrying K-123 arrive together:</p><pre>Request A checks map → key absent<br>Request B checks map → key absent<br>Request A creates job-101<br>Request B creates job-102<br>Request A stores K-123 → job-101<br>Request B overwrites or conflicts</pre><p>Both requests passed the check because the check and insert were separate operations.</p><p>This is a classic <strong>check-then-act race condition</strong>.</p><p>The operation we actually need is:</p><blockquote><em>Insert this key only if it is still absent, as one atomic action.</em></blockquote><h3>9. ConcurrentHashMap.putIfAbsent()</h3><p>Inside a single Java process, we can use:</p><pre>JobReference existing =<br>        idempotencyMap.putIfAbsent(key, newJobReference);</pre><p>putIfAbsent() performs the logical operation atomically:</p><pre>If key is absent:<br>    insert the value</pre><pre>If key already exists:<br>    return the existing value</pre><p>Two concurrent requests cannot both successfully become the first inserter for the same key.</p><p>Conceptually:</p><pre>Request A ─┐<br>           ├── putIfAbsent(K-123)<br>Request B ─┘<br>                 ↓<br>Exactly one insertion wins</pre><h3>Does it lock the entire map?</h3><p>No. ConcurrentHashMap is designed to avoid placing one global lock around every operation.</p><p>The exact implementation varies by Java version, but modern implementations use techniques such as:</p><ul><li>compare-and-set operations;</li><li>synchronisation around a particular bucket or bin when necessary;</li><li>specialised handling while resizing;</li><li>fine-grained coordination rather than one map-wide mutex.</li></ul><p>The important API guarantee is not the internal locking strategy.</p><p>The important guarantee is:</p><pre>putIfAbsent() is atomic for that mapping operation</pre><p>Different keys can usually be operated on concurrently.</p><p>Requests targeting the same internal region or undergoing structural changes may still contend, but the whole map is not simply locked for every insertion.</p><h3>10. Per-Key Synchronisation</h3><p>Another possible single-process design is to serialise requests that use the same idempotency key.</p><p>Conceptually:</p><pre>Lock for K-123<br>    ↓<br>Check whether K-123 exists<br>    ↓<br>Create or return job<br>    ↓<br>Release lock</pre><p>Requests using different keys may proceed independently:</p><pre>K-123 → lock A<br>K-999 → lock B</pre><p>This is <strong>per-key synchronisation</strong>.</p><p>It is better than one global lock because unrelated requests do not block each other.</p><p>However, implementing it correctly has its own difficulties:</p><ul><li>where are the lock objects stored?</li><li>when are unused locks removed?</li><li>can lock cleanup race with new requests?</li><li>what happens when the process crashes?</li><li>how does another application instance share the same lock?</li></ul><p>Per-key synchronisation is useful inside one process, but it does not by itself solve the distributed case.</p><h3>11. Why In-Memory Idempotency Fails Across Application Instances</h3><p>Suppose the service runs two instances behind a load balancer:</p><pre>┌──▶ API instance A<br>Client ── LB ┤<br>             └──▶ API instance B</pre><p>Each instance has its own ConcurrentHashMap.</p><pre>Instance A memory:<br>K-123 absent</pre><pre>Instance B memory:<br>K-123 absent</pre><p>Two duplicate requests can be routed to different instances:</p><pre>Request A → instance A → creates job-101<br>Request B → instance B → creates job-102</pre><p>Both local maps are thread-safe.</p><p>The system is still incorrect because the maps do not share state.</p><p>This illustrates an important distinction:</p><blockquote><em>Thread safety protects concurrent access to one process’s memory. It does not coordinate independent processes.</em></blockquote><p>A distributed service needs a shared authority for claiming the idempotency key.</p><p>A relational database can provide that authority.</p><h3>12. Enforcing Idempotency with a Database Unique Constraint</h3><p>The database table can enforce:</p><pre>UNIQUE (tenant_id, idempotency_key)</pre><p>For example:</p><pre>CREATE TABLE idempotency_records (<br>    tenant_id           VARCHAR(100) NOT NULL,<br>    idempotency_key     VARCHAR(200) NOT NULL,<br>    request_fingerprint VARCHAR(64)  NOT NULL,<br>    job_id              UUID         NOT NULL,<br>    created_at          TIMESTAMP    NOT NULL,</pre><pre>    CONSTRAINT uq_idempotency_key<br>        UNIQUE (tenant_id, idempotency_key)<br>);</pre><p>Now consider two application instances inserting the same key concurrently:</p><pre>Instance A:<br>INSERT tenant-A, K-123, job-101</pre><pre>Instance B:<br>INSERT tenant-A, K-123, job-102</pre><p>The database serialises the conflicting uniqueness decision.</p><p>Only one committed row can satisfy the unique constraint.</p><p>Conceptually:</p><pre>One transaction wins<br>The other encounters a uniqueness conflict</pre><p>The losing request then reads the existing record:</p><pre>tenant-A + K-123 → job-101</pre><p>and returns job-101 instead of creating job-102.</p><h3>What happens while the winning transaction is uncommitted?</h3><p>The precise mechanism depends on the database.</p><p>Conceptually, the database cannot immediately allow another committed row with the same unique key.</p><p>The conflicting transaction may wait for the first transaction’s outcome.</p><p>If the first transaction commits:</p><pre>Second insert → unique-constraint violation</pre><p>If the first transaction rolls back:</p><pre>Second insert may proceed</pre><p>This is why the database uniqueness constraint is stronger than an application-side query such as:</p><pre>SELECT ...</pre><p>followed later by:</p><pre>INSERT ...</pre><p>The unique constraint makes the final ownership decision inside the database’s concurrency-control mechanism.</p><h3>13. The Idempotency Record and Job Must Be Atomic</h3><p>Suppose we insert the idempotency record first:</p><pre>K-123 → job-101</pre><p>and then crash before creating job-101.</p><p>The system now says the key belongs to a job that does not exist.</p><p>The opposite order is also unsafe:</p><pre>Create job-101<br>        ↓<br>Crash before inserting K-123</pre><p>A retry does not find the key and may create job-102.</p><p>Therefore, the idempotency mapping and job record should be inserted in one database transaction:</p><pre>BEGIN;</pre><pre>INSERT INTO idempotency_records (...);</pre><pre>INSERT INTO jobs (...);</pre><pre>COMMIT;</pre><p>The guarantee becomes:</p><pre>Either:<br>- K-123 maps to job-101;<br>- job-101 exists;</pre><pre>Or:<br>- neither record exists.</pre><p>This prevents two broken states:</p><pre>Idempotency key exists<br>but job does not exist</pre><p>and:</p><pre>Job exists<br>but retry cannot discover it</pre><p>When the system also uses a transactional outbox, the same transaction can contain:</p><pre>Idempotency record<br>+<br>Job record<br>+<br>Outbox event</pre><p>The outbox handles reliable publication and is the subject of the second article.</p><h3>14. A Complete Idempotent Request Flow</h3><p>A robust request flow looks like this:</p><pre>Client submits request<br>with tenant-A + K-123<br>        │<br>        ▼<br>Canonicalise request<br>        │<br>        ▼<br>Calculate request fingerprint<br>        │<br>        ▼<br>Start database transaction<br>        │<br>        ▼<br>Attempt to insert:<br>tenant-A + K-123<br>fingerprint H-789<br>job-101<br>        │<br>        ├── insert succeeds<br>        │       ↓<br>        │   insert job-101<br>        │       ↓<br>        │   commit transaction<br>        │       ↓<br>        │   return job-101<br>        │<br>        └── unique conflict<br>                ↓<br>            read existing record<br>                ↓<br>            compare fingerprints<br>                │<br>                ├── same fingerprint<br>                │       ↓<br>                │   return existing job<br>                │<br>                └── different fingerprint<br>                        ↓<br>                    return 409 Conflict</pre><p>The central decision table is:</p><p>SituationCorrect responseNew key and valid requestCreate one jobSame key and equivalent requestReturn the existing jobSame key and different requestReturn 409 ConflictTwo concurrent requests with the same keyDatabase allows only one creationRetry reaches another API instanceShared database returns the same mapping</p><h3>15. Idempotency Terminology</h3><h3>Idempotent operation</h3><p>An operation whose repeated execution does not create additional business effects.</p><h3>Idempotency key</h3><p>A client-provided identifier representing one logical operation.</p><h3>Idempotency record</h3><p>A durable server-side record connecting an idempotency key, request fingerprint and created business resource.</p><h3>Request fingerprint</h3><p>A stable identifier derived from the logical request, commonly created by hashing a canonical representation.</p><h3>Canonicalisation</h3><p>The process of transforming equivalent inputs into one consistent representation before comparison or hashing.</p><h3>Check-then-act race</h3><p>A race caused when code checks a condition and later acts on it without making the two steps atomic.</p><h3>Per-key synchronisation</h3><p>Serialising operations for the same key while allowing different keys to proceed concurrently.</p><h3>Atomic insert-if-absent</h3><p>An operation that claims a key only if no mapping currently exists.</p><p>ConcurrentHashMap.putIfAbsent() provides this inside one Java process.</p><p>A database unique constraint provides it across application processes.</p><h3>Unique constraint</h3><p>A database rule preventing multiple committed records from sharing the same constrained values.</p><h3>Conflict</h3><p>A request that cannot be accepted because it contradicts already-established state.</p><p>For idempotency, reusing one key for a different request is a meaningful 409 Conflict.</p><h3>Conclusion</h3><p>Idempotency is not implemented by merely detecting duplicate requests.</p><p>A complete idempotency design must answer:</p><ul><li>Which requests represent the same logical operation?</li><li>How is the key scoped?</li><li>How are equivalent requests compared?</li><li>What happens when two duplicate requests arrive concurrently?</li><li>What happens when those requests reach different application instances?</li><li>How does a retry recover the result of the original request?</li><li>What happens when a key is reused for a different payload?</li></ul><p>The most important design principles are:</p><ol><li>A retry may follow a successful operation whose response was lost.</li><li>A bare 409 Conflict does not recover the original result.</li><li>The key should map to the original business resource.</li><li>The server should store a fingerprint to detect conflicting key reuse.</li><li>Raw JSON hashes are unreliable when logically equivalent JSON can have different byte representations.</li><li>putIfAbsent() solves atomic insertion only inside one process.</li><li>Per-key locking also remains local unless backed by distributed coordination.</li><li>A database unique constraint coordinates all application instances.</li><li>The idempotency record and job must commit in the same transaction.</li><li>The same key and same request should return the same logical result.</li></ol><p>The central mental model is:</p><blockquote><em>An idempotency key is not merely a duplicate detector. It is a durable name for one logical operation and its resulting resource.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48ded6199548" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A free queue slot does not mean your system can safely accept another job]]></title>
            <link>https://medium.com/@deepanshuemblinux/a-free-queue-slot-does-not-mean-your-system-can-safely-accept-another-job-5ed13784be86?source=rss-240bf57904aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ed13784be86</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[site-reliability-engineer]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <dc:creator><![CDATA[Deepanshuemblinux]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 22:11:15 GMT</pubDate>
            <atom:updated>2026-07-23T22:11:15.242Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eVlUFD9yc-OwZq4sAEu1vg.png" /></figure><p>A free queue slot does not mean your system can safely accept another job</p><p>This distinction is easy to miss when designing asynchronous APIs.</p><p>A common design looks like this:</p><p>Request arrives<br>→ Create a job<br>→ Add it to a queue<br>→ Return 202 Accepted<br>→ Process it later</p><p>But what exactly did the server accept?</p><p>Inserting an object into a queue proves only one thing:</p><p><strong>There was space for another queue element.</strong></p><p>It does not prove that the system can safely retain and eventually process the job.</p><p>An accepted job may also require:</p><p>• Memory to retain its payload<br>• Temporary storage for uploaded data<br>• A tenant-specific outstanding-job slot<br>• An entry in a status store<br>• Staging capacity required while it waits</p><p>Therefore, proper admission control should answer a broader question:</p><p><strong>Can the system safely take responsibility for this job under the guarantees made by the API?</strong></p><p>A better submission flow is:</p><p>Request arrives<br>↓<br>Authenticate, authorize and validate<br>↓<br>Check whether the job is ever feasible<br>↓<br>Reserve resources consumed while the job waits<br>↓<br>Publish the job as PENDING<br>↓<br>Attempt admission into a bounded queue<br>↓<br>Return 202 Accepted</p><p>If any step fails, all previously created state and reservations must be rolled back.</p><p>The acceptance operation should appear all-or-nothing:</p><p><strong>Either the complete job is accepted, or nothing is accepted.</strong></p><p>There is another important distinction: not every resource should be reserved during submission.</p><p>Resources used only while the job is executing — such as worker threads, database connections, downstream connections, CPU capacity and processing memory — should usually be acquired just before execution.</p><p>Reserving them while a job waits can lead to:</p><p>• Low resource utilization<br>• Unnecessary request rejection<br>• Capacity fragmentation<br>• Resources sitting idle behind queued jobs</p><p>A useful design rule is:</p><p><strong>Reserve during admission only what acceptance immediately consumes or what the API contract explicitly guarantees.</strong></p><p>For execution-time resources:</p><ol><li>Validate during admission that the job is feasible.</li><li>Acquire the actual capacity when the scheduler is ready to run it.</li></ol><p>This also explains why bounded queues matter.</p><p>An unbounded queue does not remove overload. It hides it by converting immediate rejection into:</p><p>• Growing memory usage<br>• Increasing queueing latency<br>• Stale work<br>• Large backlogs<br>• Slow recovery<br>• Eventual process failure</p><p>Rejection is sometimes the correct system behaviour.</p><p>But rejection must be explicit.</p><p>The client should know:</p><p>• Whether the job was accepted<br>• Why it was rejected<br>• Whether retrying is appropriate<br>• When it should retry<br>• How the request can be traced</p><p>Temporary system-wide exhaustion may return 503 Service Unavailable.</p><p>A client exceeding its quota may receive 429 Too Many Requests.</p><p>Clients should then retry using exponential backoff, jitter and the server’s Retry-After guidance.</p><p>The central lesson:</p><p><strong>A reliable asynchronous API does not accept work merely because it can queue it. It accepts work only when it is prepared to take responsibility for it.</strong></p><p>#SystemDesign #DistributedSystems #BackendEngineering #SoftwareArchitecture #ReliabilityEngineering #SRE #APIDesign #Concurrency</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ed13784be86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Why the Second Read Is Always Faster: A Practical Proof of Linux Page Cache]]></title>
            <link>https://medium.com/@deepanshuemblinux/why-the-second-read-is-always-faster-a-practical-proof-of-linux-page-cache-5822b058ba83?source=rss-240bf57904aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/5822b058ba83</guid>
            <category><![CDATA[page-cache]]></category>
            <category><![CDATA[page-fault]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Deepanshuemblinux]]></dc:creator>
            <pubDate>Thu, 08 Jan 2026 17:33:59 GMT</pubDate>
            <atom:updated>2026-01-08T17:33:59.808Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iHO4FcG3tlQ_MXWGACwIbQ.png" /></figure><p>🚀 <strong>Why the Second Read Is Always Faster: A Practical Proof of Linux Page Cache</strong></p><p>When people say “Linux caches files in memory”, it often sounds abstract.<br> I wanted to prove it experimentally, not by theory, but by measuring page faults and access time.</p><p>This blog walks through a small, controlled experiment that demonstrates:</p><ul><li>How Linux page cache works</li><li>Why major page faults disappear on repeated reads</li><li>How Linux differentiates between cold cache and hot cache</li><li>Why multiple processes can read the same file without extra disk I/O</li></ul><h3>🎯 Aim of the Experiment</h3><p>The goal was to establish that:</p><p>Linux page cache avoids repeated disk I/O and major page faults when the same file is accessed multiple times — even by different processes.</p><p>Specifically, I wanted to observe:</p><ul><li>Disk-backed page faults on first access (cold cache)</li><li>Cache-backed accesses on subsequent runs (hot cache)</li><li>Reduction in both latency and major page faults</li></ul><h3>🧪 Experiment Setup</h3><h3>System actions</h3><p><strong>Drop page cache</strong></p><pre>echo 3 &gt; /proc/sys/vm/drop_cache</pre><p><strong>Run a Go program that:</strong></p><ul><li>mmap()s a file</li><li>Touches ~80 KB of data</li><li>Measures access time</li></ul><p><strong>Check major page faults for the process</strong></p><p><strong>Run the same program again (without dropping cache)</strong></p><h3>🧠 Why mmap() Was Used</h3><p>This experiment intentionally uses mmap() instead of read().</p><p>Why?</p><p>Because:</p><ul><li>mmap() forces user-space page faults</li><li>Each page accessed must be mapped via the MMU</li><li>Disk-backed pages cause major page faults</li><li>Cache-backed pages cause minor faults (or none)</li></ul><p>This makes page cache behavior visible and measurable.</p><h3>🧩 The Go Program Used</h3><pre>package main<br>import (<br>	&quot;fmt&quot;<br>	&quot;os&quot;<br>	&quot;syscall&quot;<br>	&quot;time&quot;<br>)</pre><pre>func main() {<br>	if len(os.Args) &lt; 2 {<br>		fmt.Println(&quot;Usage: go run mmap.go &lt;file-path&gt;&quot;)<br>		return<br>	}</pre><pre>	path := os.Args[1]</pre><pre>	file, err := os.Open(path)<br>	if err != nil {<br>		panic(err)<br>	}<br>	defer file.Close()</pre><pre>	info, err := file.Stat()<br>	if err != nil {<br>		panic(err)<br>	}</pre><pre>	size := info.Size()<br>	if size == 0 {<br>		fmt.Println(&quot;Empty file&quot;)<br>		return<br>	}</pre><pre>	// mmap entire file (read-only, private)<br>	data, err := syscall.Mmap(<br>		int(file.Fd()),<br>		0,<br>		int(size),<br>		syscall.PROT_READ,<br>		syscall.MAP_PRIVATE,<br>	)<br>	if err != nil {<br>		panic(err)<br>	}<br>	defer syscall.Munmap(data)</pre><pre>	// Touch only first 80 KB<br>	touchSize := 80 * 1024<br>	if touchSize &gt; len(data) {<br>		touchSize = len(data)<br>	}</pre><pre>	start := time.Now()</pre><pre>	var sum byte<br>	for i := 0; i &lt; touchSize; i++ {<br>		sum += data[i]<br>	}</pre><pre>	elapsed := time.Since(start)</pre><pre>	fmt.Printf(&quot;Touched %d bytes\n&quot;, touchSize)<br>	fmt.Printf(&quot;Checksum (to avoid optimization): %d\n&quot;, sum)<br>	fmt.Printf(&quot;Time to access mmaped data: %v\n&quot;, elapsed)</pre><pre>	fmt.Println(&quot;Sleeping for 10 minutes...&quot;)<br>	time.Sleep(10 * time.Minute)<br>}</pre><h3>Why the sum variable exists</h3><p>To prevent compiler optimizations from removing memory access.<br> Each byte is actually read, guaranteeing page faults occur.</p><h3>🔍 How Major Page Faults Were Measured</h3><p>Using:</p><pre>cat /proc/&lt;pid&gt;/stat</pre><p>From this file:</p><ul><li>Field 12 → majflt (major page faults)</li><li>Counts disk-backed page faults</li><li>Measured per process, since process start</li></ul><h3>📊 Observations</h3><h3>First Run (Cold Cache)</h3><p>After dropping cache:</p><ul><li>~22 major page faults</li><li>~1.3 ms access time</li></ul><p>What happened internally:</p><ul><li>File pages were not in RAM</li><li>Each page access triggered:</li><li>MMU page fault</li><li>Disk read</li><li>Page cache population</li><li>Kernel had to fetch data from disk</li></ul><h3>Second Run (Hot Cache)</h3><p>Without dropping cache:</p><ul><li>0 major page faults</li><li>~100 microseconds access time</li></ul><p>What changed:</p><ul><li>File pages were already in page cache</li><li>Kernel simply:</li><li>Updated page tables</li><li>Mapped existing pages</li><li>No disk I/O</li><li>No major faults</li></ul><h3>🔥 What This Proves About Linux Page Cache</h3><h3>1️⃣ Page cache is global</h3><ul><li>It is shared across processes</li><li>Once a file page is cached, any process can reuse it</li></ul><h3>2️⃣ Page cache eliminates disk I/O</h3><ul><li>Disk is accessed only on cache miss</li><li>Subsequent reads are RAM-only</li></ul><h3>3️⃣ Page cache eliminates major faults</h3><ul><li>Major faults occur only when disk I/O is required</li><li>Cached pages do not cause major faults</li></ul><h3>❄️ Cold Cache vs 🔥 Hot Cache (Theory)</h3><h3>Cold Cache</h3><ul><li>File pages not in RAM</li><li>Requires disk reads</li><li>Causes major page faults</li><li>High latency</li></ul><h3>Hot Cache</h3><ul><li>File pages already in RAM</li><li>No disk reads</li><li>No major faults</li><li>Very low latency</li></ul><p>Linux aggressively tries to keep hot data cached and evicts cold data under pressure.</p><h3>🧠 What Happens Internally (Simplified)</h3><h3>Cold cache access</h3><p>User access<br> → MMU page fault<br> → Kernel checks page cache<br> → Miss<br> → Read from disk<br> → Insert into page cache<br> → Update page table<br> → Resume process</p><h3>Hot cache access</h3><p>User access<br> → MMU page fault (or none)<br> → Page already in cache<br> → Map page<br> → Resume process</p><p>This difference is exactly what your measurements captured.</p><h3>⚠️ Why drop_caches Was Used (And Why It’s Dangerous)</h3><pre>echo 3 &gt; /proc/sys/vm/drop_caches</pre><p>This:</p><ul><li>Drops all clean page cache</li><li>Ignores hot vs cold distinction</li><li>Simulates a “cold boot” memory state</li></ul><p>⚠️ This is for experiments only, not production.</p><h3>🧠 Final Takeaway</h3><p>Linux page cache is the single most important reason file I/O is fast on a healthy system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5822b058ba83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Really Happens When Linux Reads and Writes Files: A Deep Dive into Page Cache]]></title>
            <link>https://medium.com/@deepanshuemblinux/what-really-happens-when-linux-reads-and-writes-files-a-deep-dive-into-page-cache-63fe56a067ab?source=rss-240bf57904aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/63fe56a067ab</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[file-io]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[page-cache]]></category>
            <dc:creator><![CDATA[Deepanshuemblinux]]></dc:creator>
            <pubDate>Wed, 07 Jan 2026 17:59:33 GMT</pubDate>
            <atom:updated>2026-01-07T17:59:33.333Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jfdmImtALCS1cykoLMsiWw.png" /></figure><p>Page cache contains <strong>file-backed pages</strong> — RAM pages that contain file data, indexed by <strong>(inode, offset)</strong>.</p><p>Linux knows a file page is already in RAM because it maintains a <strong>global page-cache index</strong> keyed by <strong>(file, offset)</strong>, and page faults first consult this cache before doing any disk I/O.</p><h3>The Three Things Linux Tracks (Crucial)</h3><p>For every file-backed page, Linux tracks:</p><ul><li>Virtual memory mappings (per process)</li><li>Page cache entries (global, system-wide)</li><li>Physical page frames</li></ul><p>Think of the page cache as a huge global hash table:</p><pre>(file_inode, page_offset) → struct page (physical frame)</pre><h3>Key Property</h3><ul><li>✔ Page cache is global</li><li>✔ Shared by all processes</li><li>✔ Managed by kernel</li><li>✔ File-backed (not anonymous)</li></ul><h3>What Page Cache Holds</h3><ul><li>File contents read from disk</li><li>Executable code pages</li><li>Shared libraries</li><li>mmap’d file regions</li><li>File metadata blocks (indirectly)</li></ul><h3>What Page Cache Does NOT Contain</h3><ul><li>Heap memory</li><li>Stack memory</li><li>Go slices</li><li>malloc’d buffers</li></ul><p>These are <strong>anonymous pages</strong>.</p><h3>What Happens When a Process Accesses a File Page</h3><p>Let’s take an mmap() example (cleanest case).</p><h3>Step-by-Step</h3><h4>① CPU Access</h4><p>Process touches a virtual address in an mmap’d region.</p><h4>② Page Table Check</h4><p>MMU sees:</p><ul><li>PTE not present</li><li>Triggers page fault</li></ul><h4>③ Kernel Enters Page Fault Handler</h4><p>Kernel sees:</p><ul><li>Address belongs to a file-backed VMA</li><li>Knows which file + offset this address maps to</li></ul><p>This information comes from:</p><ul><li>struct vm_area_struct</li></ul><h4>④ Kernel Checks the Page Cache (Key Step)</h4><p>Kernel computes:</p><pre>(inode, offset)</pre><p>Internally:</p><ul><li>Indexed by page offset</li></ul><h3>Two Possible Outcomes</h3><h3>Case A: Page Found in Page Cache → MINOR FAULT</h3><ul><li>Physical page already in RAM</li></ul><p>Kernel:</p><ul><li>Increments page refcount</li><li>Creates a PTE pointing to that page</li><li>Marks it present</li><li>Updates TLB</li></ul><p>📌 No disk I/O<br> ➡ <strong>Minor page fault</strong></p><h3>Case B: Page NOT in Page Cache → MAJOR FAULT</h3><p>Kernel must:</p><ul><li>Allocate a page frame</li><li>Read data from disk</li><li>Insert into page cache</li><li>Map into process page table</li></ul><p>➡ <strong>Major page fault</strong></p><h3>Same Logic for read() (Buffered I/O)</h3><p>Even without mmap():</p><pre>read(fd, buf, 4096);</pre><p>Internally:</p><ul><li>Kernel still uses page cache</li><li>Copies data from page cache → user buffer</li></ul><p>If page is cached:</p><ul><li>No disk read</li><li>Fast path</li></ul><pre>Process VA → PTE → ❌ (not present)<br>                 |<br>                 v<br>           Page fault<br>                 |<br>        VMA tells file + offset<br>                 |<br>        Page cache lookup<br>          /              \<br>        HIT              MISS<br>        |                  |<br>   Map existing page    Read from disk<br>        |                  |<br>     Minor fault        Major fault</pre><h3>When a Process Reads a File, Where Does the Data Go?</h3><p>This is the most misunderstood part.</p><p>Example:</p><pre>read(fd, user_buf, size)</pre><h3>What Actually Happens</h3><pre>Disk<br> ↓<br>Page Cache  (file-backed page)<br> ↓<br>Copy to user buffer (anonymous page)</pre><pre>+---------+<br>|  Disk   |<br>+---------+<br>     |<br>     v<br>+-------------------+<br>|   Page Cache      |  ← file-backed<br>+-------------------+<br>     |<br>     v<br>+-------------------+<br>| Process heap/stack|  ← anonymous<br>+-------------------+</pre><h3>Important Consequences</h3><ul><li>Yes, data ends up in process memory</li><li>But the page cache page remains separate</li><li>The process buffer is a copy</li><li>Cache exists to allow reuse</li></ul><h3>Step-by-Step Breakdown of read()</h3><ol><li>Process calls read()</li><li>Kernel checks</li><li>Is (inode, offset) already in page cache?</li><li>If NOT present:Allocate a page cache page</li><li>Read disk → page cache</li><li>Then: copy_to_user() copies bytes</li><li>Destination is anonymous memory (heap/stack)</li></ol><h3>Why NOT Read Directly Into Process Buffer?</h3><p>This is the core confusion.</p><h3>Reason #1: Page Cache Enables Sharing</h3><p>Imagine: 10 processes read the same file</p><p>Without page cache:</p><ul><li>Disk read happens 10 times</li><li>10 separate RAM copies</li></ul><p>With page cache:</p><ul><li>Disk read happens once</li><li>All processes reuse same page</li></ul><p>Critical for:</p><ul><li>Binaries</li><li>Shared libs</li><li>Logs</li><li>Databases</li><li>Containers</li></ul><h3>Reason #2: Page Cache Enables Readahead</h3><p>You read 4 KB<br> Kernel reads 128 KB</p><p>Why?</p><ul><li>Sequential access optimization</li><li>Avoid future disk I/O</li></ul><p>This logic <strong>must live in kernel-managed cache</strong>, not process memory.</p><h3>Reason #3: Page Cache Enables Memory Pressure Control</h3><p>Linux can:</p><ul><li>Drop clean page cache pages anytime</li><li>Reclaim without swap</li><li>Re-read from disk later</li></ul><p>Anonymous memory:</p><ul><li>Must be swapped or killed</li></ul><p>If file data lived directly in anonymous pages:</p><ul><li>Kernel would lose this advantage</li></ul><h3>Reason #4: mmap() Fundamentally REQUIRES Page Cache</h3><pre>char *p = mmap(fd, ...);</pre><p>What actually happens:</p><ul><li>Kernel creates virtual mappings</li><li>No disk read yet</li><li>Pages faulted lazily</li></ul><p>On first access:</p><pre>Page fault<br> ↓<br>Check page cache<br> ↓<br>Disk → page cache<br> ↓<br>Map page cache page into process</pre><p>❗ No anonymous memory<br> ❗ No copying</p><p>Multiple processes mmap same file:</p><ul><li>✔ Same page cache pages</li><li>✔ Same physical memory</li><li>✔ Different virtual addresses</li></ul><h3>Executables &amp; Shared Libraries</h3><p>When you run /bin/bash:</p><ul><li>ELF segments are mapped via mmap()</li><li>NOT read via read()</li></ul><p>Code sections:</p><ul><li>File-backed</li><li>Live in page cache</li></ul><p>Result:</p><ul><li>Single physical copy</li><li>Shared across all users</li></ul><p>Verify:</p><pre>cat /proc/&lt;pid&gt;/maps</pre><p>You’ll see:</p><pre>r-xp /usr/bin/bash</pre><h3>mmap(): Anonymous or Page Cache?</h3><p><strong>Rule:</strong><br> mmap’d files are <strong>page-cache backed</strong>, not anonymous.</p><pre>Disk<br> ↓<br>Page Cache  ← shared<br> ↓<br>Process address mapping</pre><p>📌 No copy is made</p><p>This is why:</p><ul><li>mmap is faster</li><li>Pages are shared</li><li>Memory usage is lower</li></ul><h3>Why mmap Pages Are Reclaimable</h3><ul><li>File-backed</li><li>Kernel can discard them anytime</li><li>Reload from disk</li></ul><p>Anonymous memory:</p><ul><li>No disk backing</li><li>Must go to swap</li></ul><p>This is why Linux reclaims <strong>file cache first</strong>.</p><h3>All File Writes Go Through Page Cache</h3><p>All file writes go to <strong>page cache first</strong>, not disk.<br> Disk write happens later, asynchronously.</p><p>This is <strong>write-back caching</strong>.</p><h3>What Happens on write(fd, buf, size)?</h3><p>High-level flow:</p><pre>Process buffer (anonymous)<br> ↓ copy_from_user()<br>Page cache (file-backed)<br> ↓ (later)<br>Disk</pre><p>Yes — the reverse of read.</p><h3>Step-by-Step (Very Important)</h3><h4>Step 1: System Call</h4><ul><li>buf is anonymous memory</li><li>Kernel must copy data safely</li></ul><h4>Step 2: Copy into Page Cache</h4><p>Kernel:</p><ul><li>Finds file (inode, offset)</li><li>Locates or allocates page cache pages</li><li>Copies user buffer → page cache</li></ul><p>Pages are now:</p><ul><li>Dirty</li><li>File-backed</li><li>In RAM</li></ul><h4>Step 3: Return to User</h4><ul><li>write() returns before disk write</li><li>Program thinks data is written</li><li>Reality: data is only in RAM</li></ul><h3>Dirty Pages — The Key Concept</h3><p>Once written:</p><ul><li>Page is marked <strong>Dirty</strong></li></ul><p>Tracked via:</p><ul><li>xarray / radix tree</li><li>per-inode dirty accounting</li></ul><p>Check:</p><pre>cat /proc/meminfo<br>Dirty:<br>Writeback:</pre><h3>When Does Data Go to Disk?</h3><p>Via background writeback:</p><ul><li>Periodic flushing</li><li>Memory pressure</li><li>Thresholds</li></ul><p>Handled by:</p><ul><li>flush-* threads</li><li>kworker</li><li>Writeback subsystem</li></ul><h3>Tunables</h3><pre>cat /proc/sys/vm/dirty_ratio<br>cat /proc/sys/vm/dirty_background_ratio</pre><p>Example:</p><ul><li>dirty_background_ratio = 10%</li><li>dirty_ratio = 20%</li></ul><p>Meaning:</p><ul><li>10% → start background flushing</li><li>20% → writers get throttled</li></ul><h3>Heavy Writes and Performance Collapse</h3><p>Scenario:</p><ul><li>Fast writer</li><li>Slow disk</li></ul><p>Result:</p><ul><li>Page cache fills with dirty pages</li><li>Kernel blocks writers</li><li>write() slows down</li></ul><p>This is <strong>write throttling</strong>.</p><p>Observe via:</p><pre>vmstat 1</pre><ul><li>b → blocked</li><li>wa → IO wait</li></ul><h3>What About fsync()?</h3><p>fsync() changes everything.</p><p>Without fsync():</p><ul><li>Data can sit in RAM for seconds</li><li>Crash = data loss</li></ul><p>With fsync():</p><pre>Page cache<br> ↓<br>Disk<br> ↓<br>Wait</pre><p>The call blocks until:</p><ul><li>Data is on disk</li><li>Metadata is consistent</li></ul><p>Used by:</p><ul><li>Databases</li><li>Journaling systems</li><li>Durable queues</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63fe56a067ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>