<?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 Vinay Kumar | System Architect (@thisvinaykumar) on Medium]]></title>
        <description><![CDATA[Stories by Vinay Kumar | System Architect (@thisvinaykumar) on Medium]]></description>
        <link>https://medium.com/@thisvinaykumar?source=rss-e184dbcd37f7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EIfIdqDQBBLillzdKgxigQ.jpeg</url>
            <title>Stories by Vinay Kumar | System Architect (@thisvinaykumar) on Medium</title>
            <link>https://medium.com/@thisvinaykumar?source=rss-e184dbcd37f7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 10:09:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thisvinaykumar/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[The Cache Answered Too Fast. Our Angular Dropdown Went Empty After the First Form.]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@thisvinaykumar/the-cache-answered-too-fast-our-angular-dropdown-went-empty-after-the-first-form-859b21f02c2f?source=rss-e184dbcd37f7------2"><img src="https://cdn-images-1.medium.com/max/1632/1*ng0OSWGZVEM_-X-YT1qeUg.png" width="1632"></a></p><p class="medium-feed-snippet">A warm shareReplay cache, a signal write during render, and zoneless Angular. The fix, the cleaner shape, and a test that catches it.</p><p class="medium-feed-link"><a href="https://medium.com/@thisvinaykumar/the-cache-answered-too-fast-our-angular-dropdown-went-empty-after-the-first-form-859b21f02c2f?source=rss-e184dbcd37f7------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@thisvinaykumar/the-cache-answered-too-fast-our-angular-dropdown-went-empty-after-the-first-form-859b21f02c2f?source=rss-e184dbcd37f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/859b21f02c2f</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Vinay Kumar | System Architect (@thisvinaykumar)]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 13:31:01 GMT</pubDate>
            <atom:updated>2026-11-14T13:31:01.705Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[“Use an Idempotency Key” Covers One of Three Ways a Payment Runs Twice]]></title>
            <link>https://medium.com/@thisvinaykumar/use-an-idempotency-key-covers-one-of-three-ways-a-payment-runs-twice-a299dbb21b47?source=rss-e184dbcd37f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a299dbb21b47</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Vinay Kumar | System Architect (@thisvinaykumar)]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 13:31:01 GMT</pubDate>
            <atom:updated>2026-11-12T20:06:25.499Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A 60-second interview answer with code: idempotency keys, atomic claims and balance checks, from real duplicate bugs in OpsX.</em></p><p><em>I am Vinay Kumar, a Senior Software Developer at Easyres Travel Technology, currently building enterprise ERP and logistics solutions like OpsX (IMS-SAAS).</em></p><p>“Your user presses Pay once. Their phone sends it three times. What do you build so the money moves once?”</p><p>I have been asked a version of this in SDE-2 rounds. The usual reply is four words, “add an idempotency key”, followed by silence while the panel expects more.</p><p>Here is the more. Duplicates come from three places. The client repeats itself. Two people change one record together. Or somebody sends a fresh, honest-looking request that the business should refuse. A key covers only the first source.</p><p>I shipped bugs of every kind in OpsX, the ERP we build in Bihar for gyms, shops and small factories, plus one that hid between two documents. For a gym owner, a fee cycle reduced twice is their rent, not a flaky test. Here is each bug and what closed it.</p><h3>How does an idempotency key actually stop a retried request?</h3><p><strong>The first insert wins, and a unique index decides who was first.</strong> No read-then-check step exists for a race to slip through.</p><p>The app makes a UUID when the button is tapped and puts it in the Idempotency-Key header. A retry carries that same UUID.</p><p>The server’s claim() inserts a claim row holding tenant, key, a payload hash and the state in_progress. A { tenantId: 1, key: 1 } unique index guards that collection. The first insert lands. Any copy arriving later bounces with Mongo error 11000, the duplicate-key error everyone has met in logs.</p><h3>What happens to the request that loses?</h3><p>It loads the winning row and chooses:</p><ul><li><strong>Hash differs:</strong> 422. Someone reused a key for another body, and replaying the old result would conceal a write the client believes happened.</li><li><strong>Row finished:</strong> return the saved response with Idempotent-Replay: true. Audit logs mark it a replay, so nobody sees a phantom second posting.</li><li><strong>Row still running:</strong> 409, retry shortly.</li><li><strong>Running past 120 seconds:</strong> assume the first worker died. One retry may adopt the row through findOneAndUpdate, filtered on the exact createdAt it loaded. Both that age check and the new timestamp run on the database clock, not the app’s.</li></ul><p>The hash is sha256 over method, path and body, with object keys sorted first. Without sorting, identical bodies written in different key order would look like separate requests.</p><pre>import { createHash } from &#39;node:crypto&#39;;</pre><pre>const STALE_MS = 120_000;</pre><pre>function stable(v: unknown): string {<br>  if (Array.isArray(v)) return `[${v.map(stable).join(&#39;,&#39;)}]`;<br>  if (v !== null &amp;&amp; typeof v === &#39;object&#39;) {<br>    const o = v as Record&lt;string, unknown&gt;;<br>    return `{${Object.keys(o).sort().map((k) =&gt; `${JSON.stringify(k)}:${stable(o[k])}`).join(&#39;,&#39;)}}`;<br>  }<br>  return JSON.stringify(v) ?? &#39;null&#39;;<br>}</pre><pre>export const fingerprint = (method: string, path: string, body: unknown) =&gt;<br>  createHash(&#39;sha256&#39;).update(`${method}\n${path}\n${stable(body)}`).digest(&#39;hex&#39;);</pre><pre>// IdemKey is a Mongoose model; ApiError(status, code) is a small HTTP error class.<br>export async function claim(tenantId: string, key: string, fp: string) {<br>  // Insert only if absent. createdAt comes from MongoDB&#39;s clock ($$NOW), not this pod&#39;s.<br>  const res = await IdemKey.updateOne(<br>    { tenantId, key },<br>    [{ $set: {<br>      fingerprint: { $ifNull: [&#39;$fingerprint&#39;, fp] },<br>      status: { $ifNull: [&#39;$status&#39;, &#39;in_progress&#39;] },<br>      createdAt: { $ifNull: [&#39;$createdAt&#39;, &#39;$$NOW&#39;] },<br>    } }],<br>    { upsert: true },<br>  ).catch((err) =&gt; {<br>    if ((err as { code?: number }).code !== 11000) throw err; // lost a simultaneous insert<br>    return null;<br>  });<br>  if (res?.upsertedCount === 1) return { kind: &#39;proceed&#39; as const }; // we won the insert<br>  const row = await IdemKey.findOne({ tenantId, key }).lean();<br>  if (!row) throw new ApiError(409, &#39;REQUEST_IDEMPOTENCY_KEY_PROGRESS_RETRY&#39;);<br>  if (row.fingerprint !== fp) throw new ApiError(422, &#39;IDEMPOTENCY_KEY_ALREADY_USED_DIFFERENT&#39;);<br>  if (row.status === &#39;completed&#39;) return { kind: &#39;replay&#39; as const, body: row.responseBody };</pre><pre>  // Staleness is judged on the database clock too, so no pod&#39;s clock decides.<br>  const taken = await IdemKey.findOneAndUpdate(<br>    { tenantId, key, status: &#39;in_progress&#39;, createdAt: row.createdAt, // only if unchanged<br>      $expr: { $gt: [{ $subtract: [&#39;$$NOW&#39;, &#39;$createdAt&#39;] }, STALE_MS] } },<br>    [{ $set: { createdAt: &#39;$$NOW&#39; } }],<br>  );<br>  if (taken) return { kind: &#39;proceed&#39; as const };<br>  throw new ApiError(409, &#39;REQUEST_IDEMPOTENCY_KEY_PROGRESS_RETRY&#39;);<br>}</pre><p>That createdAt filter is compare-and-set in one line. When several retries try to adopt a stuck row, the first update changes the timestamp and every later filter matches nothing.</p><p>Both timestamps come from MongoDB’s own clock ($$NOW). An earlier version of this snippet compared Date.now() on the retrying pod with a createdAt written by another pod, so clock skew between pods could quietly shift the 120-second window. Credit to Ferretmartin, who caught this in the responses.</p><p>Adoption is still a guess. A first request that was merely slow now runs alongside its adopter. Releasing the claim once a handler has written part of its work opens the same gap. That is why the handler carries its own guard, shown in the next section.</p><figure><img alt="Sequence diagram: a phone sends a payment with Idempotency-Key k1 and the API’s claim insert wins; a retry with the same key hits a duplicate-key error and gets 409 while the first is in progress; after the payment is saved and marked completed, a later retry gets the stored response with Idempotent-Replay: true." src="https://cdn-images-1.medium.com/max/1024/1*qs1U7bryCO292gq6kIoRfg.png" /><figcaption>One key, three requests: the first insert wins, a copy that arrives mid-flight gets 409, and a copy after completion gets the stored response replayed.</figcaption></figure><h3>Why save the response before replying?</h3><p>complete() writes the result into the claim. Put that inside rxjs tap and the phone may hear back first; an instant retry then receives 409 for a working payment. concatMap makes the write finish before anything leaves. Below, handler$ is what NestJS hands you as next.handle().</p><pre>return handler$.pipe(<br>  catchError(async (err) =&gt; {<br>    await release(tenantId, key);        // only handler failures land here<br>    throw err;<br>  }),<br>  concatMap(async (body) =&gt; {<br>    await complete(tenantId, key, body); // stored first...<br>    return body;                         // ...then sent<br>  }),<br>);</pre><p>Because catchError comes first, it catches only handler errors, and a failed handler frees its key: nobody wants an error replayed. When complete() itself throws, the payment already happened, so leave that row running and let adoption handle it. A TTL index clears rows after 24 hours.</p><h3>Why store claims in MongoDB rather than Redis?</h3><p>A replay must return the original response, so this store cannot forget. Redis forgets under an eviction policy, after a restart without persistence, or across a failover. Each turns a harmless retry into a second charge. Our keys sit beside the payments and are exactly as durable.</p><h3>Why can’t the key stop two approvers?</h3><p><strong>Two people send two keys.</strong> To the key layer both requests are new, and letting both through is correct.</p><p>We hit this in October 2026 with gym fees paid by UPI. Each payment waits for the front desk to approve it, and approval reduces the member’s outstanding cycle. A spec showed that approving one waiting payment twice reduced the cycle twice.</p><p>decidePayment loaded the payment, checked its state, then settled.</p><pre>// Before: read-then-write<br>const payment = await GymPayment.findById(id);<br>if (!payment || payment.paymentStatus !== &#39;Pending&#39;) throw new ApiError(409, &#39;GYM_PAYMENT_CHANGED&#39;);<br>await settleFeeCycle(payment);            // both requests get here<br>payment.paymentStatus = &#39;Approved&#39;;<br>await payment.save();</pre><p>Both callers load Pending, both pass, both settle.</p><p>The repair moves the decision into one conditional write that matches only while the row still looks as the approver saw it:</p><pre>// After: atomic claim, then act<br>const read = await GymPayment.findById(id).lean();<br>if (!read) throw new ApiError(404, &#39;Payment not found&#39;);<br>// the read only supplies what the approver saw; the update decides<br>const decidedAt = new Date();</pre><pre>const claimed = await GymPayment.findOneAndUpdate(<br>  { _id: id, paymentStatus: &#39;Pending&#39;, voided: { $ne: true },<br>    amountMinor: read.amountMinor, utr: read.utr ?? { $exists: false } },<br>  { $set: { paymentStatus: &#39;Approved&#39;, approvedBy: userId, approvedAt: decidedAt } },<br>  { new: true },<br>);<br>if (!claimed) throw new ApiError(409, &#39;GYM_PAYMENT_CHANGED&#39;);</pre><pre>try {<br>  await settleFeeCycle(claimed);<br>} catch (err) {<br>  // e.g. BALANCE_ORIGINAL_PAYMENT_CHANGED: put the payment back as it was read<br>  await GymPayment.updateOne(<br>    { _id: id, paymentStatus: &#39;Approved&#39;, approvedAt: decidedAt },   // only our own approval<br>    { $set: { paymentStatus: &#39;Pending&#39; } },<br>  );<br>  throw err;<br>}</pre><p>On one document, findOneAndUpdate is atomic. Fire two together and exactly one matches; the other gets null and a 409. Including amount and UTR also blocks approving something edited after the approver opened it, and voided rows never match.</p><p>Settling works the same way: a single updateOne with $inc, matching only while the cycle&#39;s due amount still covers the payment. If that moved, the error rolls the payment back to waiting, ready for another try.</p><p>Before the change, three of four new specs were red. Tests caught it while it still lived on its branch, so no customer saw it. The race spec runs on a real mongod and fires both approvals together with Promise.allSettled. Calling approve twice in sequence would have passed even on the broken code.</p><p>One hole remains open. If the process dies between claim and settle, the payment says Approved while the cycle never moves, and nothing in OpsX repairs that yet. I plan to put both steps in one transaction, as our goods receipts already do, before this ships.</p><h3>What stops a second request that looks completely valid?</h3><p><strong>Only the business rule.</strong> In OpsX, an order already received in full could be received again, and no key or lock had any reason to object.</p><p>Each extra receipt inflated stock, its valuation, the vendor’s spend total and the ledger payable, for goods nobody delivered. Every request was new, had its own key and raced with no one.</p><p>applyReceipt added the quantity without any cap and ignored the order&#39;s state. A missing order made it return quietly. The portal helped the mistake along by filling in the whole ordered amount whenever an order was linked.</p><p>Now one private validateReceipt() runs twice: from the read-only assertReceivable() before anything is written, and again inside applyReceipt(), because that method moves the number.</p><pre>const EPS = 1e-6;</pre><pre>function validateReceipt(po: PurchaseOrder | null, lines: ReceiptLine[]): void {<br>  if (!po) throw new ApiError(400, &#39;PURCHASE_ORDER_NO_LONGER&#39;);<br>  if (po.status === &#39;cancelled&#39;) throw new ApiError(400, &#39;PURCHASE_ORDER_CANCELLED_GOODS&#39;);<br>  if (po.status === &#39;draft&#39;) throw new ApiError(400, &#39;PURCHASE_ORDER_NOT_RELEASED&#39;);<br>  if (po.status === &#39;received&#39;) throw new ApiError(400, &#39;PURCHASE_ORDER_ALREADY_FULLY&#39;);</pre><pre>  const merged = new Map&lt;string, number&gt;();            // merge split lines first<br>  for (const l of lines) merged.set(l.materialId, (merged.get(l.materialId) ?? 0) + l.qty);</pre><pre>  for (const [materialId, qty] of merged) {<br>    const line = po.lines.find((p) =&gt; p.materialId === materialId);<br>    if (!line) throw new ApiError(400, &#39;Material is not on this purchase order&#39;);<br>    if (qty &gt; line.orderedQty - line.receivedQty + EPS)<br>      throw new ApiError(400, &#39;Quantity exceeds the open balance&#39;);<br>  }<br>}</pre><p>Merging per material shuts a quiet door. With 100 units still due, two 60-unit lines for one material each look fine separately yet take 120 together. We allow a tiny epsilon since steel goes by kilogram, oil by litre, and floating point cannot add tenths exactly.</p><p>The portal now shows just the orders that can still receive, and suggests what is left instead of the whole order.</p><p>Two receipts landing in the same instant? The whole receipt posts inside one MongoDB transaction: stock, value and the order update. Two transactions modifying one order document hit a write conflict, and Mongo aborts one. Its retry validates against the new balance and is refused.</p><h3>What if two documents both pay one salary month?</h3><p><strong>Make one document own it.</strong> In October 2026 we paid someone’s last month twice: once through the normal payslip, once more through their exit settlement.</p><p>Now, while that settlement is a draft, or approved or paid with final salary in it, the payroll run computes the last slip but holds it back. The settlement includes final pay only when the slip is held, and approval refuses if the figure moved since the draft.</p><h3>Which HTTP status should a duplicate get?</h3><p><strong>A 4xx with a clear reason, never 500.</strong> I learned it from a minor bug. A clerk saved a stock code that already existed, the database rejected it, and our API passed that on as 500. The dialog said something failed and to try again. They did, and failed identically.</p><pre>function toCodeConflict(err: unknown, message: string): never {<br>  if ((err as { code?: number })?.code === 11000) throw new ApiError(409, message);<br>  throw err;<br>}</pre><p>We check for the code before saving and keep this mapper as the safety net. My split: 409 when the request clashes with current state or its twin is running, 422 for a reused key with a new body, 500 only for genuine faults. A 500 invites retries, and for a duplicate no retry can succeed.</p><p>Our own order refusals above return 400 with a named code, not 422, and I would say so in an interview. The number matters less than the rule: the screen must be able to explain it.</p><h3>How do you answer this in an interview in 60 seconds?</h3><blockquote><em>“Duplicates come from three places, and I guard each separately.”</em></blockquote><blockquote><em>“One: the client repeats itself after a double tap or timeout. I take an idempotency header, insert a claim under a unique tenant-plus-key index, and treat that insert as the lock. I hash the body and release the claim if handling fails.”</em></blockquote><blockquote><em>“Two: different users change one record together, say two approvers. Different keys, so I turn the state change into one update conditioned on current status, with 409 when it no longer matches.”</em></blockquote><blockquote><em>“Three: a brand new request that passes every format check yet breaks a balance, like a second receipt on a finished order. Only the business rule catches it, so I check what is still open before writing. If two documents could pay for one thing, I pick a single owner.”</em></blockquote><p>The panel is not testing whether you know a header name. They want you to ask what produces the second request. Expect follow-ups on a slow first call (adoption after 120 seconds, then the handler’s own guard), on Redis (it can lose keys), and on 409 versus 422 (state clash versus reused key).</p><h3>Checklist before you ship a money or stock endpoint</h3><ol><li>Every POST that moves money or stock takes an idempotency header, locked by a unique index.</li><li>Each key is bound to a body hash; a changed body under an old key gets 422.</li><li>Save the response before replying; free the claim only on handler failure.</li><li>Pending records change state through one conditional update, never load-then-save.</li><li>Remaining quantity is checked, not just status, after merging lines per item.</li><li>If two documents could pay for one thing, one holds back and approval verifies it.</li><li>Duplicate-key errors become 409 plus a message telling users what to fix.</li><li>Races are proven with truly concurrent calls on a real database.</li></ol><p>Next time someone asks you this, first ask what produces that second request.</p><p><strong>Written by Vinay Kumar (</strong><strong>@thisvinaykumar)</strong> — Senior Software Engineer, System Architect &amp; Creator of <a href="https://opsx.in/">OpsX</a>. 🌐 <a href="https://thisvinaykumar.opsx.in/">Portfolio</a> | 💼 <a href="https://www.linkedin.com/in/thisvinaykumar/">LinkedIn</a> | 📸 <a href="https://www.instagram.com/thisvinaykumar">Instagram (@thisvinaykumar)</a> | 💻 <a href="https://github.com/thisvinaykumar">GitHub</a> | 🐦 <a href="https://x.com/thisvinaykumar">X (@thisvinaykumar)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a299dbb21b47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Interview: Share One fetch() Between Two Components, Let Each Cancel Alone]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://javascript.plainenglish.io/one-fetch-two-components-the-header-aborts-the-profile-card-goes-blank-4cff7f3611f0?source=rss-e184dbcd37f7------2"><img src="https://cdn-images-1.medium.com/max/1632/1*7IYFMiKftjDV0sMtf-SKOA.png" width="1632"></a></p><p class="medium-feed-snippet">Two weak answers, the Response-body trap, and the ref-counted AbortController fix SDE-2 interviewers want.</p><p class="medium-feed-link"><a href="https://javascript.plainenglish.io/one-fetch-two-components-the-header-aborts-the-profile-card-goes-blank-4cff7f3611f0?source=rss-e184dbcd37f7------2">Continue reading on JavaScript in Plain English »</a></p></div>]]></description>
            <link>https://javascript.plainenglish.io/one-fetch-two-components-the-header-aborts-the-profile-card-goes-blank-4cff7f3611f0?source=rss-e184dbcd37f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cff7f3611f0</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <dc:creator><![CDATA[Vinay Kumar | System Architect (@thisvinaykumar)]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 13:31:01 GMT</pubDate>
            <atom:updated>2026-11-11T05:20:11.232Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[My AI Coding Agent Said “All Green.” tsc Had Crashed: 3 TypeScript CI Traps]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://blog.devgenius.io/three-checks-said-green-one-built-nothing-one-crashed-one-ran-330-suites-b0006353352b?source=rss-e184dbcd37f7------2"><img src="https://cdn-images-1.medium.com/max/1632/1*7wM67HFAToXcd5Hh3De9uA.png" width="1632"></a></p><p class="medium-feed-snippet">Exit code 0, an empty grep and a Jest folder-name match fooled my agents. These are the shell checks I run now.</p><p class="medium-feed-link"><a href="https://blog.devgenius.io/three-checks-said-green-one-built-nothing-one-crashed-one-ran-330-suites-b0006353352b?source=rss-e184dbcd37f7------2">Continue reading on Dev Genius »</a></p></div>]]></description>
            <link>https://blog.devgenius.io/three-checks-said-green-one-built-nothing-one-crashed-one-ran-330-suites-b0006353352b?source=rss-e184dbcd37f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0006353352b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Vinay Kumar | System Architect (@thisvinaykumar)]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 13:31:01 GMT</pubDate>
            <atom:updated>2026-11-16T12:53:38.509Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How await Really Works in Node.js: A Mongoose Bug That Approved Overtime Twice]]></title>
            <link>https://blog.stackademic.com/store-undefined-the-await-interview-answer-a-mongoose-bug-taught-me-38cd778afc95?source=rss-e184dbcd37f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/38cd778afc95</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Vinay Kumar | System Architect (@thisvinaykumar)]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 13:31:01 GMT</pubDate>
            <atom:updated>2026-11-11T01:54:20.468Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Lazy thenables, a leaked AsyncLocalStorage scope, and the 60-second interview answer it taught me.</em></p><p><em>I am Vinay Kumar, a Senior Software Developer at Easyres Travel Technology, currently building enterprise ERP and logistics solutions like OpsX (IMS-SAAS).</em></p><p>An interviewer pastes a single line and leans back:</p><pre>const user = await User.findOne({ email });</pre><p>“Walk me through the await here.&quot;</p><p>Most candidates say it pauses until the promise resolves, then hands back the result.</p><p>Correct, and forgettable. This is the most common JavaScript await interview question, and that reply is the most common answer to it. It also leaves out two details. In October, each of them gave me an OpsX bug to fix.</p><p>At SDE-2, the person across the table wants to know if you can predict the timing of a line, and what sneaks in ahead of it. OpsX is the ERP and attendance product I build from Patna and Gaya, for small businesses in India. Both bugs came from getting that timing wrong.</p><h3>await calls then() and steps aside</h3><p>await hands its operand to the same logic Promise.resolve() uses. Give it something carrying a then function and that function gets invoked. Anything else is wrapped in a promise that is already resolved.</p><p>Meanwhile the async function pauses and control returns to the event loop. Nothing blocks. A database reply can take many loop turns, and other code runs in every one of them.</p><h3>A thenable does nothing until someone calls then()</h3><p>A thenable is just something with a then function on it. await never checks whether it is a genuine Promise.</p><pre>function makeLazy() {<br>  return {<br>    then(resolve) {<br>      console.log(&#39;then() called. Work starts now.&#39;);<br>      resolve(42);<br>    },<br>  };<br>}<br> <br>async function main() {<br>  const job = makeLazy();<br>  console.log(&#39;job built, nothing has run&#39;);<br>  const value = await job;<br>  console.log(&#39;value:&#39;, value);<br>}<br> <br>main();</pre><p>On Node.js 24.11.1:</p><pre>job built, nothing has run<br>then() called. Work starts now.<br>value: 42</pre><p>Creating the object ran no code. The work began at await job. Delete that line and the log after it, and the second message is never printed.</p><p>One finer point for senior rounds. The engine does not invoke then synchronously at the await. It schedules that invocation as its own microtask. With native promises V8 takes a shortcut and skips the visible then, but the rule holds for both: nothing settles until a subscriber shows up.</p><h3>Does a Mongoose query run when you build it?</h3><p>No. Mongoose’s own docs call a Query a thenable, and it executes when .then() is called.</p><pre>const q = Order.deleteMany({ status: &#39;draft&#39; }); // builds a query. No database call.<br>await q;                                         // now it runs</pre><p>deleteMany(filter) gives you an object holding the filter and options. MongoDB has heard nothing yet. Awaiting it sends the request. So does calling .exec(), and so does .then(). That gap is what lets you chain filters, projections and .lean() before anything runs.</p><p>There is a price. Execute one Query object twice and Mongoose 9.9.1 throws a MongooseError: Query was already executed: .... For an actual Promise, use .exec().</p><p>Laziness bites hardest when a query is built inside one context and executed inside another.</p><h3>Bug: a lazy delete escaped its AsyncLocalStorage scope</h3><p>The purge executed outside the scope meant to authorise it, so a guard rejected it. Every attendance record in OpsX has a revision trail. A plugin saves each change with a note saying why.</p><p>That note rides on AsyncLocalStorage (the one in node:async_hooks), so code several calls deep picks it up with no extra parameter. A wrapper, RevisionCtx.run(note, fn), sets the scope up. A Mongoose pre-hook on the revisions collection blocks deletes unless the store says purge.</p><p>Here is how the purge call looked:</p><pre>await RevisionCtx.run(note, () =&gt; Model.deleteMany(filter));</pre><p>It failed with:</p><pre>attendanceRevisions is append-only — deleteMany refused</pre><p>The arrow function handed back an unexecuted Query. run returned it upward and closed its scope on the way out. Only afterwards did the caller&#39;s await call .then(). So the delete reached the hook with an empty store.</p><p>Each piece was fine on its own. The sequence was wrong.</p><p>You can reproduce it with no database at all:</p><pre>// als-lazy.js  (run with: node als-lazy.js)<br>const { AsyncLocalStorage } = require(&#39;node:async_hooks&#39;);<br>const ctx = new AsyncLocalStorage();<br> <br>function lazyDelete() {<br>  return {<br>    then(resolve) {<br>      console.log(&#39;delete runs, store =&#39;, ctx.getStore());<br>      resolve(&#39;done&#39;);<br>    },<br>  };<br>}<br> <br>// Broken: returns the lazy object. It runs after the scope ends.<br>const runBroken = (store, fn) =&gt; ctx.run(store, fn);<br> <br>// Fixed: await inside the scope, so it runs while the store is set.<br>const runFixed = (store, fn) =&gt; ctx.run(store, async () =&gt; await fn());<br> <br>async function main() {<br>  await runBroken({ note: &#39;purge&#39; }, () =&gt; lazyDelete());<br>  await runFixed({ note: &#39;purge&#39; }, () =&gt; lazyDelete());<br>}<br> <br>main();</pre><p>On Node.js 24.11.1:</p><pre>delete runs, store = undefined<br>delete runs, store = { note: &#39;purge&#39; }</pre><figure><img alt="Terminal output on Node.js 24.11.1: an AsyncLocalStorage store is undefined when a lazy thenable is awaited outside ctx.run, and holds the note when it is awaited inside." src="https://cdn-images-1.medium.com/max/1024/1*ib82kFGufqu9gtCFL2Cbng.png" /><figcaption>Same lazy delete, two wrappers. Awaited outside the scope, the store is gone; awaited inside, the note is there. Real output.</figcaption></figure><p>Where the await lives is the whole difference. runFixed awaits inside ctx.run, so then() is queued with the note still in place.</p><p>The real wrapper now reads:</p><pre>return notes.run({ ...(notes.getStore() ?? {}), ...note }, async () =&gt; await fn());</pre><p>It merges any outer note, then awaits fn before the scope can close. Any lazy query fires in the right context. Call sites still say async () =&gt; await Model.deleteMany(filter). With the wrapper fixed, that is belt and braces, kept as a signal to the next reader.</p><h3>nextTick runs before promises, timers run last (in CommonJS)</h3><p>In a CommonJS file, Node prints the synchronous logs, then nextTick, then promise callbacks, then timers. This puzzle tends to follow the await question. Guess before reading on:</p><pre>// order.cjs  (CommonJS on purpose)<br>console.log(&#39;A: sync start&#39;);<br> <br>setTimeout(() =&gt; console.log(&#39;B: setTimeout 0&#39;), 0);<br> <br>Promise.resolve().then(() =&gt; console.log(&#39;C: promise then&#39;));<br> <br>queueMicrotask(() =&gt; console.log(&#39;D: queueMicrotask&#39;));<br> <br>process.nextTick(() =&gt; console.log(&#39;E: nextTick&#39;));<br> <br>console.log(&#39;F: sync end&#39;);</pre><p>On Node.js 24.11.1, as CommonJS:</p><pre>A: sync start<br>F: sync end<br>E: nextTick<br>C: promise then<br>D: queueMicrotask<br>B: setTimeout 0</pre><p>Why that order:</p><ul><li><strong>A, F:</strong> the synchronous script finishes before any callback gets a turn.</li><li><strong>E:</strong> once the current operation ends, Node empties its process.nextTick queue ahead of promise jobs.</li><li><strong>C, D:</strong> both land in the same microtask queue, first in, first out. C was queued earlier.</li><li><strong>B:</strong> a zero-delay setTimeout has to wait until the loop reaches timers, and that happens only once the microtasks are empty.</li></ul><p>Two extra points mark someone who has actually run this.</p><p>process.nextTick exists only in Node. A browser throws on that line. Strip it, and Chrome logs A, F, C, D, B.</p><p>Save the identical code as order.mjs, run it on Node.js 24.11.1, and the order becomes A, F, C, D, E, B. Module code runs as part of a promise job, which means the microtask queue empties before Node gets around to nextTick.</p><figure><img alt="Terminal output on Node.js 24.11.1: the same event loop puzzle run as order.cjs and order.mjs; process.nextTick runs third in CommonJS and fifth in an ES module." src="https://cdn-images-1.medium.com/max/1024/1*PsGPV27dhmy0DI9Cy_9kRQ.png" /><figcaption>One file, two module systems. In CommonJS nextTick runs third; as an ES module it runs fifth. Real output.</figcaption></figure><h3>Single-threaded Node still races at every await</h3><p>Yes, single-threaded Node can race. Your JavaScript runs on one thread, yet code sitting between one await and the next is not atomic. Each await lets the thread pick up another request.</p><p>The OpsX safety audit found exactly this in the punch code. A double-click, or a phone and a stale portal tab pressed at the same moment, could each raise an overtime approval for the same day.</p><p>The risky version, simplified:</p><pre>const day = await Attendance.findOne({ employeeCode, date });<br>if (day?.checkOutAt) return day;          // &quot;not yet checked out&quot;<br> <br>// another request can run here, and pass the same check<br> <br>await Attendance.updateOne(<br>  { employeeCode, date },<br>  { $set: { checkOutAt: now } },<br>  { upsert: true },<br>);<br>await openOvertimeApproval(employeeCode, date); // runs twice</pre><p>Both requests see an open day. Both write. Both raise an approval. Without the compare-and-set, the audit saw the same overtime land in the approvals inbox twice, and the clock moved to the later press. Neither real upsert, for arrival or departure, carried an $exists: false guard.</p><p>What closes it is compare-and-set. Move the condition into the write, and MongoDB tests and updates in a single step.</p><pre>try {<br>  const day = await Attendance.findOneAndUpdate(<br>    { employeeCode, date, checkOutAt: { $exists: false } }, // the guard<br>    { $set: { checkOutAt: now /* , ... */ } },<br>    { upsert: true, new: true },<br>  );<br>  await openOvertimeApproval(employeeCode, date); // only the winner gets here<br>  return day;<br>} catch (err: unknown) {<br>  if ((err as { code?: number })?.code === 11000) {<br>    // E11000 duplicate key error: the other request won. Re-read instead of failing.<br>    return await Attendance.findOne({ employeeCode, date }).lean();<br>  }<br>  throw err;<br>}</pre><p>Once checkOutAt exists, the filter matches no document, so the upsert attempts an insert. The pair (employeeCode, date) is unique-indexed on the collection, so that insert is refused with E11000 duplicate key error.</p><p>Here, that error just means the other press got there first. The code re-reads the day and returns it.</p><h3>How can a test make two requests collide on purpose?</h3><p>Put a barrier in a test stub of the last dependency awaited before the write, and run both calls against a real mongod. checkout-race.spec.ts does exactly that.</p><p>It calls Att.init() first, so the unique (employeeCode, date) index exists. The test&#39;s own comment says that index &quot;is the whole argument&quot;. A mock offers no index and no atomic filter. Nothing in it can collide.</p><p>Promise.all alone starts both calls but leaves the interleaving to whichever database reply lands first. That catches the bug on some runs, not all.</p><p>The service is built with stubbed dependencies. The last await before the write is the day-off settlement step, compOff.settleWorkedDay, so the barrier goes inside that stub. Production code gets no test hook.</p><pre>const barrier = (arrivals: number) =&gt; {<br>  let n = 0;<br>  let open!: () =&gt; void;<br>  const gate = new Promise&lt;void&gt;((r) =&gt; (open = r));<br>  return async () =&gt; {<br>    if (++n &gt;= arrivals) open();<br>    await gate;<br>  };<br>};<br> <br>let hold: () =&gt; Promise&lt;void&gt; = async () =&gt; undefined;<br> <br>// the stubbed compOff dependency (trimmed):<br>//   settleWorkedDay: async () =&gt; { await hold(); return { overtimeMin: null }; }<br> <br>hold = barrier(2);<br>await Promise.all([svc.checkOut(&#39;E1&#39;, {}), svc.checkOut(&#39;E1&#39;, {})]);<br>// assert: exactly one overtime approval was opened</pre><p>With two arrivals required, neither half writes until both have read “not closed yet”. The old code then writes twice, opens two approvals, and fails on every run.</p><p>With the fix in place, one guarded write wins. The other hits E11000, re-reads, and opens nothing.</p><h3>The 60-second answer that covers all of this</h3><p>Say it in your own words. Out loud it runs about a minute:</p><p>“await runs its operand through Promise.resolve rules: a thenable has its then called, and any other value is wrapped as already resolved. The async function pauses and gives control back. When that promise settles, what is left of the function goes onto the microtask queue, so it never jumps ahead of the synchronous code still running.</p><p>Node runs process.nextTick callbacks ahead of promise jobs, and timers after both.</p><p>This has real consequences. Mongoose queries are lazy thenables that execute only on await or .exec(). Build one in an AsyncLocalStorage.run callback, await it outside, and it runs with no context.</p><p>And since each await yields, a read followed by a write across one is not atomic, single thread or not. I close that gap by putting the condition inside the database write, and I prove it with a barrier test on a real mongod.&quot;</p><h3>A checklist you can use</h3><ol><li><strong>Keep Mongoose queries inside the scope that needs them.</strong> Inside AsyncLocalStorage.run, await or .exec() the query, and make the wrapper itself do ctx.run(store, async () =&gt; await fn()) rather than ctx.run(store, fn).</li><li><strong>Enable </strong><strong>@typescript-eslint/no-floating-promises.</strong> It requires type information and treats thenables the same as promises. So a query nobody awaits, one that will never run, gets flagged. It would have missed my bug, because my query was returned, not dropped.</li><li><strong>Never read, await, then write without a guard in the write itself.</strong> Put $exists: false, a version number or a status check in the filter.</li><li><strong>Back a guarded upsert with uniqueness on the fields that identify the row</strong>, like (employeeCode, date). No index means no E11000, and a second document slips in.</li><li><strong>When a guarded upsert throws E11000, the other request won.</strong> Fetch the row again and hand it back; do not surface it as an error.</li><li><strong>Race tests need a real database.</strong> Put the barrier in a stub of the last dependency awaited before the write.</li><li><strong>Memorise the sequence:</strong> synchronous code first, then nextTick, then promise jobs, then timers. At the top level of an ES module, nextTick and microtasks swap places.</li></ol><h3>Developer to developer</h3><p>No promise rejected in either bug. Both were about timing: when the code ran, and what slipped in before it.</p><p>Keep one line for the interview: await calls then, lets go of the thread, and picks up again as a microtask after the value settles.</p><p>If this kind of breakdown helps your prep, follow me for the next one from the OpsX codebase.</p><p><strong>Written by Vinay Kumar (</strong><strong>@thisvinaykumar)</strong> — Senior Software Engineer, System Architect &amp; Creator of <a href="https://opsx.in/">OpsX</a>. 🌐 <a href="https://thisvinaykumar.opsx.in/">Portfolio</a> | 💼 <a href="https://www.linkedin.com/in/thisvinaykumar/">LinkedIn</a> | 📸 <a href="https://www.instagram.com/thisvinaykumar">Instagram (@thisvinaykumar)</a> | 💻 <a href="https://github.com/thisvinaykumar">GitHub</a> | 🐦 <a href="https://x.com/thisvinaykumar">X (@thisvinaykumar)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38cd778afc95" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/store-undefined-the-await-interview-answer-a-mongoose-bug-taught-me-38cd778afc95">How await Really Works in Node.js: A Mongoose Bug That Approved Overtime Twice</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Architected OpsX (opsx.in): The Edge-First Attendance, Payroll & Workforce ERP]]></title>
            <link>https://medium.com/@thisvinaykumar/how-we-architected-opsx-opsx-in-the-edge-first-attendance-payroll-workforce-erp-bfd84d0d87c7?source=rss-e184dbcd37f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfd84d0d87c7</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[saas]]></category>
            <dc:creator><![CDATA[Vinay Kumar | System Architect (@thisvinaykumar)]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 13:31:02 GMT</pubDate>
            <atom:updated>2026-11-11T01:54:49.186Z</atom:updated>
            <content:encoded><![CDATA[<h3>System Design: An Offline-First Attendance &amp; Payroll SaaS in Node.js</h3><p><em>Kiosks that keep punching without internet, biometric ingestion, tenant isolation in MongoDB, and why the ledger lives in PostgreSQL.</em></p><p>At 09:00 a factory gate has forty people in a line and one tablet on the wall. The Wi-Fi drops twice a week. If every punch waits on a round trip to a server in another city, the line waits too, and the people at the back come in “late” for something that was never their fault.</p><p>That one scene shaped most of OpsX (<a href="https://opsx.in/">opsx.in</a>), the attendance, payroll and workforce ERP we build at Opsx Apex Private Limited. Inside our repo the project is still called ims-saas, because it started life as an Industrial Management System and grew outward from there. This post is the architecture as it is built today, including the parts we would do differently.</p><h3>What does “edge-first” mean for an attendance system?</h3><p><strong>The edge is wherever a person punches: the employee’s phone, the kiosk tablet at the gate, the biometric terminal on the wall.</strong> Edge-first means those devices capture, verify and queue the punch on their own, so the line keeps moving when the network does not. It does not mean the device is trusted. The server still owns the time of the punch, the rules of the shift and every rupee that comes out of payroll.</p><p>That split is the whole design in one sentence: the device decides fast, the server decides finally.</p><h3>What does the OpsX architecture look like?</h3><p>One backend codebase, three Node entrypoints, two web apps and two mobile apps.</p><ul><li><strong>apps/api</strong>: NestJS 11, REST under /api. Two instances behind nginx, restarted one at a time on deploy.</li><li><strong>apps/realtime</strong>: a Socket.IO gateway on a Redis adapter, for live notifications.</li><li><strong>apps/worker</strong>: BullMQ consumers and cron jobs. It has no HTTP listener at all.</li><li><strong>Control Center</strong>: an Angular 21 SPA for us, the platform owner. Tenants, plans, billing, form engine, feature flags.</li><li><strong>ERP Portal</strong>: an Angular 21 SPA for the customer. HR, attendance, payroll, inventory, procurement.</li><li><strong>OpsX Partner</strong> and <strong>OpsX Kiosk</strong>: two Expo / React Native apps, one for the employee’s own phone, one for a shared tablet at a site.</li></ul><p>The three backend apps import the same modules from libs/backend. They differ only in which providers they boot. Shared DTOs, enums and event names live in @ims/contracts, which both the Angular apps and the NestJS apps import, so a status string cannot drift between the screen and the database.</p><figure><img alt="OpsX architecture diagram: the employee phone app, kiosk tablet and biometric terminal at the edge, plus the Control Center and ERP Portal web apps, all reach nginx; nginx routes to the NestJS api and realtime apps; api, realtime and worker use MongoDB and Redis; the worker drains a finance outbox into the PostgreSQL general ledger once a minute." src="https://cdn-images-1.medium.com/max/1024/1*mUd8RrgszZQ8pTtrqw7yjQ.png" /><figcaption>OpsX at a glance: devices capture and queue at the edge; one NestJS codebase runs as api, realtime and worker; MongoDB holds operations, Postgres holds the books.</figcaption></figure><p>We also wrote down a GraphQL design at the start. It was never built. The API is REST only, and the old design pages are marked as such, because a blueprint that describes a system nobody built is worse than no blueprint.</p><h3>How does a kiosk keep punching when the internet drops?</h3><p><strong>A face punch is verified on the tablet, signed with the tablet’s secret, written to a local queue, and the person is greeted at once. The network catches up later.</strong></p><p>The pieces, in order:</p><ol><li>The camera frame goes through two ONNX models on the device: YuNet finds the face, a face embedder turns it into a vector. A head-turn check runs before the match, which makes a photo held up to the camera much harder to pass off as a person.</li><li>The vector is matched against the site’s face templates. Those templates live in their own SQLCipher database file on the tablet, and its 256-bit key sits in the Android keystore through SecureStore. A wall tablet is a device somebody can pick up; biometric data on it is encrypted at rest.</li><li>The punch claim is signed with the terminal’s secret and inserted into punch_queue with INSERT OR IGNORE. Its punchId is derived from the claim itself, so a retry collides with the original instead of creating a second punch.</li><li>Every 20 seconds the kiosk drains the queue, oldest first, in batches. The server answers per punch. A duplicate counts as success. A punch that keeps failing is quarantined after a fixed number of attempts, not retried forever.</li><li>Every 30 minutes the tablet pulls a delta of face templates. The roster cache is considered stale after 12 hours.</li></ol><figure><img alt="Sequence diagram of a kiosk face punch: the tablet matches the face on the device, writes a signed claim to its local punch queue and greets the employee at once; every 20 seconds it sends the queue to the OpsX API, which verifies the signature, sets the time from the punch’s age and answers per punch." src="https://cdn-images-1.medium.com/max/1024/1*UmTBCU711ZG3V5SAADHYAQ.png" /><figcaption>A face punch is matched and signed on the tablet and the person is greeted at once. The drain sends the queue every 20 seconds; the server answers per punch and owns the final time.</figcaption></figure><p>The interesting part is what is <em>not</em> queued. A PIN punch needs the network. The PIN is checked on the server, and the roster cached on the tablet deliberately leaves out every PIN hash. A tablet carrying every PIN hash of a site turns one stolen device into an offline cracking exercise against the whole workforce. So a PIN punch with no connection would be an identity nobody verified, and the kiosk does not pretend otherwise.</p><p>Face enrolment is also online only. The server runs a duplicate check across the whole tenant before it accepts a new face, and that check cannot run on one tablet.</p><h3>Can you trust the time a phone says a punch happened?</h3><p><strong>No. OpsX treats the punch time as an age, not a wall clock.</strong></p><p>A phone’s clock belongs to the employee. If the server took occurredAt at face value, changing the phone&#39;s time would turn a late arrival into an on-time one. So the app and the kiosk send two readings from the same device clock: occurredAt (when the punch happened) and sentAt (when the request left). The server computes sentAt − occurredAt, which is the punch&#39;s age, and subtracts it from its own clock. Any offset on the device cancels out, because both readings carry it.</p><p>The guards around that:</p><ul><li>An age above 12 hours is refused to server time. A day that old is a regularisation request with a reason, not a silent backfill.</li><li>A negative age is refused.</li><li>An old app build that sends no sentAt falls back to a 15-minute skew limit.</li><li>Biometric terminals are the one exception. The ingest drain sets a server-only clockTrusted flag; the request DTO cannot carry it and the whitelist strips it if a client tries.</li></ul><p>The kiosk’s face batch carries one sentAt for the whole request. Before we added that, a face punch that sat offline for more than 15 minutes was recorded at the time it reached the server, which after a long outage could land it after midnight, on the wrong day.</p><h3>Why is “faceVerified” stored as evidence and not as proof?</h3><p>On the employee’s own phone, the face match runs against an embedding cached on that phone. The server cannot check it. A modified client can send faceVerified: true and nothing on the server would catch it. That is the cost of matching on the device, and we chose it on purpose, because the alternative was sending daily face photos to a server.</p><p>So the punch row stores faceVerified and faceScore as evidence: a claim, a score, a gap between receivedAt and the punch time, a coordinate. Together they make a far better audit record than a bare timestamp, and a pattern of low scores shows up in aggregate. They never gate pay.</p><p>geofenceVerified goes the other way. The server holds the office coordinates and the radius, so it derives that field itself and never accepts it from the client. Taking the client&#39;s word for it would replace the check with a request to be trusted.</p><h3>How do biometric terminals send punches without flooding the API?</h3><p><strong>The ingest endpoint returns </strong><strong>202 Accepted and does the work later.</strong> The tenant comes from a device registry, never from the request body, so a terminal cannot claim to belong to someone else.</p><p>The handler only authenticates the terminal, deduplicates, and parks each record as a pending event. It looks at no roster and no shift. A terminal that comes back online after a weekend replays its whole buffer at once, and if that burst had to wait on the attendance rules it would time out and replay again into the same congestion. A separate drain turns pending events into punches, inside the tenant&#39;s context. We learned the hard way that the drain needs a caller: the first version existed, was tested, and nothing ever invoked it, so a whole day of punches could sit at pending while every dashboard looked fine.</p><p>Records that match no employee are kept with a quarantined status and purged 30 days after the punch happened, counted from the punch and not from arrival, so a terminal replaying an old buffer cannot keep a stranger&#39;s record alive.</p><h3>How does a punch become a payslip?</h3><p>Every later stage reads a <em>classified day</em>, never a raw punch:</p><pre>punch → day frame → classified day → payroll period → payslip → salary ledger<br>           ▲              ▲                  ▲<br>         shift       leave ledger      pay policy snapshot</pre><p>The day classifier turns dates into frames and runs pure stages over the whole array in a fixed order. Each stage records why it decided what it did. Our first classifier decided each date on its own, and it was structurally unable to express one rule customers asked for: the sandwich rule, where a holiday between two absences counts as an absence. That rule asks a question about a day’s neighbours. The new pipeline sits behind an engineVersion, 21 fixtures pin the new engine to the old one&#39;s answers, and a shadow comparator runs both and reports every day where they disagree.</p><p>Two smaller decisions from this part saved real money:</p><ul><li><strong>A punch outside the shift window is refused only when the shift was assigned.</strong> If the punch itself chose the roster (an inferred shift), measuring it against that roster asks whether the punch agrees with a guess made from itself.</li><li><strong>The idempotency check runs before the window check.</strong> A punch already recorded is a fact. A phone draining its offline queue at 22:00 must get “already recorded”, not see every punch of the day rejected.</li></ul><h3>How are tenants kept apart in one MongoDB?</h3><p><strong>The plan decides the physical layout.</strong> Starter and Professional tenants share one database, and every document carries a tenantId. Enterprise tenants get a dedicated database, opened lazily and pooled in an LRU of 50 connections with a 15-minute idle eviction, so the database&#39;s connection limit is not exhausted by tenants who are asleep.</p><p>A Mongoose plugin, tenantScopePlugin, injects the tenant predicate into every query. It also hard-blocks $lookup, $unionWith and $graphLookup inside aggregations, because a cross-collection stage escapes the scope without any error. The consequence for feature work is real: you cannot join inside a tenant aggregate. You run the aggregate, then enrich the page with a second scoped find({ _id: { $in: [...] } }).</p><p>The one path the plugin cannot see is the raw driver, db.collection(...). A repo guard, tools/check-raw-collection.mjs, fails the build on it. Our first version of that guard read code line by line and missed the second raw call in the same file. A guard that only catches the first occurrence teaches you to trust it too early.</p><h3>Why does the general ledger live in PostgreSQL when everything else is in MongoDB?</h3><p><strong>Books need things MongoDB does not give you cheaply: </strong><strong>NUMERIC, </strong><strong>CHECK constraints the database enforces when the application is wrong, row-level security per tenant, and an append-only table where the delete privilege is revoked, not merely unused.</strong></p><p>So all operational data (employees, attendance, stock, orders, documents) stays in MongoDB, where the form engine can write each tenant’s own fields. Only the double-entry general ledger is in Postgres.</p><p>The two are never joined by a distributed transaction. They are joined by a transactional outbox:</p><ol><li>The business write and a financeOutbox row commit in the same Mongo transaction.</li><li>The worker drains the outbox every minute, with a concurrency of one across the whole worker.</li><li>A unique index on source_event_id in Postgres makes a double post impossible.</li><li>A failure is written on the outbox row and shown on the finance screen. Whatever cannot be delivered goes to a dead-letter trail.</li></ol><p>The books are allowed to lag the business by up to a minute. That is the price of atomicity, and we pay it on purpose: a minute is short enough that nobody notices, and long enough that a Postgres restart passes between two drains without anyone knowing.</p><h3>When should an event go on the bus, and when in the outbox?</h3><p>We also have an in-process domain event bus. It is in memory and fire-and-forget: a handler that throws is logged and dropped, and a process that dies between commit and delivery loses the event without a trace.</p><p>The rule we wrote for it:</p><blockquote><em>Publish on the bus only when losing the event would be a nuisance. When losing it would be wrong, it belongs in the outbox.</em></blockquote><p>“Refresh a cached last purchase price” can be stale until the next receipt. “Add this receipt to the supplier’s running total” is permanently wrong if lost, and nothing would ever notice. A bus event fired in the middle of a transaction is less safe than the direct call it replaced, because the direct call at least rolls back with everything else.</p><h3>What did we get wrong along the way?</h3><ul><li><strong>A green build does not mean the worker boots.</strong> NestJS resolves dependency injection at runtime. Registering a job processor without its whole service chain passes typecheck, tests and every guard, and then crash-loops on deploy. We boot the worker locally before shipping any new processor.</li><li><strong>Zero downtime is near, not absolute.</strong> Two API instances are taken out of rotation and restarted one at a time. That covers a deploy. It does not cover a schema change that the old instance cannot read, so rollback is planned per layer: nginx, process, schema and data do not roll back together.</li><li><strong>The 09:00 slowdown was a caching problem, not a message-broker problem.</strong> Each punch used to cost six or seven Mongo reads. A version-stamped cache key, rotated by the eleven routes that change punch state, took it to one read, and the punch write went from three operations to one upsert that treats a duplicate-key error as success.</li></ul><h3>Checklist: building attendance that works at the edge</h3><ul><li>Decide which checks the device may run alone (face match) and which need the server (PIN, enrolment).</li><li>Derive the punch id from the punch itself, so a retry is a duplicate, and treat a duplicate as success.</li><li>Send sentAt with occurredAt and compute the age on the server. Never trust a device wall clock.</li><li>Encrypt biometric templates at rest on shared devices, and keep secrets like PIN hashes off them entirely.</li><li>Store on-device verification as evidence. Never let it gate pay.</li><li>Return 202 for device ingest, and resolve the tenant from the device registry.</li><li>Run payroll on classified days, not on raw punches, and record why each day was classified the way it was.</li><li>Put the ledger where constraints are enforced, and feed it through an outbox, not a bus.</li></ul><p>If you run a factory, a warehouse or a field team in India and want to see this in production, OpsX is at <a href="https://opsx.in/">opsx.in</a>. If you are building something similar, I am happy to compare notes in the comments, especially on the parts we are still unsure about.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfd84d0d87c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running TypeScript Directly in Node.js: A ₹500 Item Came Back as ₹50,090]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://javascript.plainenglish.io/i-ran-my-typescript-with-plain-node-a-500-item-came-back-as-50-090-5180ce9a2ad7?source=rss-e184dbcd37f7------2"><img src="https://cdn-images-1.medium.com/max/1850/1*d2QbuCK33XrmMTl1I_j-Fg.png" width="1850"></a></p><p class="medium-feed-snippet">Node strips types but never checks them. What it erases, the 4 TS features it rejects, and the check you can&#x2019;t skip.</p><p class="medium-feed-link"><a href="https://javascript.plainenglish.io/i-ran-my-typescript-with-plain-node-a-500-item-came-back-as-50-090-5180ce9a2ad7?source=rss-e184dbcd37f7------2">Continue reading on JavaScript in Plain English »</a></p></div>]]></description>
            <link>https://javascript.plainenglish.io/i-ran-my-typescript-with-plain-node-a-500-item-came-back-as-50-090-5180ce9a2ad7?source=rss-e184dbcd37f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5180ce9a2ad7</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Vinay Kumar | System Architect (@thisvinaykumar)]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 13:31:01 GMT</pubDate>
            <atom:updated>2026-11-11T05:15:24.028Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to Craft a Standout Resume as a College Student]]></title>
            <link>https://medium.com/@thisvinaykumar/how-to-craft-a-standout-resume-as-a-college-student-c3bcc4336921?source=rss-e184dbcd37f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3bcc4336921</guid>
            <category><![CDATA[internships]]></category>
            <category><![CDATA[job-search]]></category>
            <category><![CDATA[college]]></category>
            <category><![CDATA[career-advice]]></category>
            <category><![CDATA[resume]]></category>
            <dc:creator><![CDATA[Vinay Kumar | System Architect (@thisvinaykumar)]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 00:19:42 GMT</pubDate>
            <atom:updated>2026-10-29T00:19:42.154Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical guide to tailoring, structuring and polishing your first resume, even with little work experience</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSicG0Cp2F5rGmF4EWKAmQ.jpeg" /></figure><p>Let’s face it: building a resume as a college student can feel like trying to solve a Rubik’s cube blindfolded. You’ve got limited work experience, you’re up against candidates with years in the game, and the stakes feel sky-high. But here’s the good news — a standout resume can level the playing field. Let’s dive into how to craft one that screams “hire me!” without sounding like a robot wrote it.</p><h3>Know Your Audience</h3><p>First things first: your resume isn’t a one-size-fits-all deal. Sending the same generic doc to every job is like wearing flip-flops to a formal interview — yikes. Tailoring your resume to the job or internship you’re applying for is non-negotiable. Start by digging into the company and role. Check their website, stalk their LinkedIn (professionally, of course), and read the job description like it’s a treasure map. Look for keywords — skills, tools, or qualities they’re hyping up. If the job description mentions “team collaboration” or “Python proficiency,” make sure those words show up in your resume (if they apply to you, obviously).</p><p><strong>Quick tip</strong>: Copy the job description into a word cloud generator to spot repeated terms. Those are your golden tickets — sprinkle them in naturally. This shows recruiters you’re not just throwing darts blindfolded; you’ve done your homework.</p><h3>Structure and Format</h3><p>A messy resume is like a cluttered dorm room — nobody wants to deal with it. Keep it clean, professional, and one page long. (Yes, one page. You’re not writing a memoir.) Stick to readable fonts like Arial, Calibri, or Times New Roman, sized 10–12. Clear headings and consistent formatting are your friends.</p><p>Here’s the skeleton of a solid college student resume:</p><ul><li><strong>Contact Info</strong>: Name, phone, email (make it professional — no “partyking2003@gmail.com”), and maybe a LinkedIn or portfolio link.</li><li><strong>Objective/Summary</strong>: A short, punchy sentence or two about who you are and what you bring. Example: “Motivated computer science major eager to apply coding skills in a software development internship.”</li><li><strong>Education</strong>: Your college, major, GPA (if it’s 3.0 or higher), and expected graduation date.</li><li><strong>Skills</strong>: Hard skills (e.g., Java, Adobe Photoshop) and soft skills (e.g., communication, problem-solving).</li><li><strong>Experience</strong>: Paid or unpaid work, including part-time jobs or internships.</li><li><strong>Projects</strong>: Coursework, side hustles, or personal projects that show off your skills.</li><li><strong>Extracurriculars</strong>: Clubs, volunteer work, or leadership roles.</li></ul><p>If your work experience is thin (we’ve all been there), bump up sections like Projects or Skills to flex your strengths. For example, that group project where you built a website? That’s gold — put it front and center.</p><h3>Highlighting Your Strengths</h3><p>Here’s where you shine, even if your “professional experience” is just slinging lattes at Starbucks or tutoring high schoolers. The trick is to frame everything in a way that screams, “I’m ready for this job!” Focus on transferable skills — stuff like time management, teamwork, or problem-solving that you’ve picked up from school, jobs, or clubs.</p><p>Use strong action verbs to describe what you did. Instead of “was part of a team,” say “collaborated with a team of five to design a marketing campaign.” Quantify whenever possible — numbers make recruiters’ eyes light up. For example:</p><ul><li><strong>Weak</strong>: Helped run a club event.</li><li><strong>Strong</strong>: Organized a campus charity event, raising $500 and boosting attendance by 20%.</li></ul><p>No internships? No problem. That group project where you coded a game in Python? List it under Projects. That time you led a fundraiser for your sorority? That’s leadership experience. Even your part-time gig as a cashier shows you can handle customer service and think on your feet. Pro tip: If you’re stuck, ask yourself, “What did I learn, and how does it relate to the job I want?”</p><p>Here’s an example: if your only “experience” is babysitting, turn “watched kids” into “managed schedules, resolved conflicts, and ensured safety for three children under 10.” Those words show organization and responsibility, which is exactly what an admin assistant internship looks for. You’ve got more to offer than you think!</p><h3>Make It Shine</h3><p>A great resume isn’t just about content — it’s about polish. Typos or inconsistent fonts are like showing up to an interview with spinach in your teeth. Read it aloud, run it through a spell-checker, and then read it again. Consistency matters: if you bold one section heading, bold them all. Avoid fluff like “hardworking” or “passionate” unless you can back it up with examples.</p><p>Get a second pair of eyes on it. Your roommate, a professor, or your campus career center can catch things you missed. A spell-checker won’t flag “pubic relations” when you meant “public relations,” because both are real words. Don’t be that person.</p><p>If you’ve got a LinkedIn profile or an online portfolio (like a GitHub for coders or a Behance for designers), toss in a link. Just make sure your LinkedIn isn’t a ghost town — update it with a decent photo and some details.</p><h3>Common Mistakes to Avoid</h3><p>Let’s talk pitfalls. A generic resume that could apply to any job is a one-way ticket to the trash bin. Tailor, tailor, tailor. Typos are another dealbreaker — recruiters will assume you’re sloppy. Don’t list every club or job you’ve ever had; stick to what’s relevant. If you’re applying for a marketing gig, your high school lifeguard job probably doesn’t need a starring role.</p><p>And please, don’t lie. Exaggerating is tempting, but getting caught saying you’re “fluent in Spanish” when you only know “hola” is a vibe-killer. Be honest, but frame your skills confidently.</p><h3>Conclusion</h3><p>Crafting a standout resume as a college student isn’t about having a decade of experience — it’s about showcasing your potential. You’ve got skills, passion, and a unique perspective, and a well-crafted resume is your megaphone to shout it to the world. It might take a few drafts (and a few coffee runs), but every tweak gets you closer to that internship or job. Start drafting today, tweak it for every application, and don’t be afraid to let your personality shine. You’ve got this!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3bcc4336921" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Every Hindi Translation Existed. Users Still Saw “crud.rm.liter” on Screen.]]></title>
            <link>https://medium.com/@thisvinaykumar/every-hindi-translation-existed-users-still-saw-crud-rm-liter-on-screen-933b8e87abf2?source=rss-e184dbcd37f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/933b8e87abf2</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[local-seo]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-solution]]></category>
            <dc:creator><![CDATA[Vinay Kumar | System Architect (@thisvinaykumar)]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 12:31:01 GMT</pubDate>
            <atom:updated>2026-10-23T12:31:01.880Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I am Vinay Kumar, a Senior Software Developer at Easyres Travel Technology, currently building enterprise ERP and logistics solutions like OpsX (IMS-SAAS).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ddk2OS4GYPjmDkLl0dZAgw.png" /></figure><p>A screenshot came in. A dropdown for units of measure. The options read:</p><p><strong>Kg</strong><br><strong>crud.rm.liter</strong><br><strong>crud.rm.meter</strong><br><strong>crud.rm.pcs</strong></p><p>The report said: “Hindi translations are missing. Please add them.”</p><p>They were not missing. Every one of those words was already translated, in both English and Hindi. Adding them again would have changed nothing.</p><h3>Why Hindi is not optional for us</h3><p>We build OpsX from Patna and Gaya, for small Indian businesses. The person marking attendance, approving leave or adding stock is often more at home in Hindi than in English. For them, a Hindi screen is not a nice extra. It is the difference between using the software and calling someone to do it for them.</p><p>So we made the whole app work in both languages. Today it has 2,735 pieces of text, each in English and Hindi.</p><p>That number sounds like the job is done. This story is about why it was not.</p><h3>How translation works in most apps</h3><p>You do not write “Liter” in the screen. You write a key, like crud.rm.liter. A file holds what that key means in each language:</p><pre>en: { &#39;crud.rm.liter&#39;: &#39;Liter&#39; }<br>hi: { &#39;crud.rm.liter&#39;: &#39;लीटर&#39; }</pre><p>Then, on the screen, you pass the key through a small translate function, and it shows the right word for the user’s language.</p><p>That last step is the one that went wrong.</p><h3>The clue was the one word that worked</h3><p>Look at the screenshot again. <strong>Kg</strong> showed correctly. Three lines below it, <strong>crud.rm.liter</strong> did not. Same dropdown.</p><p>Why would one option work and the others fail?</p><p>Because “Kg” was the only option written as a plain word, not a key. The dropdown was translating <em>nothing</em>. “Kg” just looked fine because it never needed translating.</p><p>The real bug was not in the translation file. It was in the screen. The screen showed the key directly and forgot to pass it through the translate step.</p><h3>Why it was so hard to see</h3><p>Our translate function does something sensible. If it gets a key it does not know, it shows the key as it is. That way, a missing translation shows something you can search for, instead of a blank space.</p><p>But it has a side effect. On screen, these two cases look exactly the same:</p><ul><li>a key that has <strong>no translation</strong>, and</li><li>a key that was <strong>never sent to be translated</strong>.</li></ul><p>Both show crud.rm.liter. So everyone looks in the translation file, finds nothing wrong, and gets confused.</p><p>We had five automatic checks for translations. All five were green the whole time. Every one of them asked “is this text translated?” None of them asked “is the translation actually being used?”</p><h3>Where text hides in an app</h3><p>After this, we went looking for every place English could sneak onto a Hindi screen. It was not just the screens. We found text in seven kinds of places:</p><ol><li><strong>The screens themselves.</strong> The obvious one.</li><li><strong>Settings and lists in code.</strong> Like the units dropdown, where a field is called label but holds a key.</li><li><strong>Messages from the server.</strong> “Leave balance is too low” comes from the backend, not the screen.</li><li><strong>Small pop-up messages.</strong> “Attendance marked.” We found 76 of these written directly in English in the code. They are some of the most-read words in the whole app.</li><li><strong>Labels built inside other components.</strong> Page numbers, “Next”, “Previous” in a ready-made table.</li><li><strong>Default values.</strong> A button whose default label was “Export”, set once and forgotten.</li><li><strong>AI answers.</strong> Our in-app assistant has to answer in the user’s language too.</li></ol><p>If you only check the first one, you will ship a “Hindi” app that is half English.</p><h3>“X is required” does not translate word by word</h3><p>One validation message had two bugs on top of each other. In code, it was:</p><pre>`${field.label} is required`</pre><p>The label was a key, so the user saw crud.rm.sku is required. If we had only fixed the key, a Hindi user would have seen &quot;SKU is required&quot;. English, on a Hindi screen, and it would have looked fixed.</p><p>And Hindi puts words in a different order. “SKU is required” is “SKU ज़रूरी है”. You cannot glue a translated word in front of an English sentence. The whole sentence has to be a translation, with a space for the field name:</p><pre>en: { &#39;form.err.required&#39;: &#39;{field} is required&#39; }<br>hi: { &#39;form.err.required&#39;: &#39;{field} ज़रूरी है&#39; }</pre><h3>Hindi made the app too heavy, at first</h3><p>All 2,735 Hindi lines were loaded for every user, even those who only use English. One day the app grew past our size limit of 2.5 MB and the build refused to finish.</p><p>The fix was simple. Load Hindi only for people who choose Hindi. The first download went from 2.50 MB to 1.88 MB for everyone. Hindi users wait a moment once, and we show nothing until it is ready, so they never see an English flash first.</p><p>On a slow 3G connection in a small town, 600 KB less is a real difference.</p><h3>What we changed</h3><p>We added a new check that reads the code and fails the build if anything named label is shown without the translate step.</p><p>The neat part: translating a plain word is harmless. The translate function returns “Kg” as “Kg”. So there is never a case where adding the translate step is wrong. That removes the guesswork, and the rule can be strict.</p><p>There were 81 old places that broke the rule. We did not blindly change all 81 in one day. The check allows at most 81, and that number can only go down. New code must follow the rule from day one.</p><h3>A checklist you can use</h3><p>If you are adding Hindi (or any Indian language) to your app:</p><ol><li>Switch to the language and click through every screen. Do not trust a “100% translated” report.</li><li>Look for dotted words like page.title on screen. That is a key that never got translated.</li><li>Search your code for pop-up messages written in English.</li><li>Translate server error messages by a code, not by their English text.</li><li>Never build a sentence by gluing words. Translate the whole sentence, with blanks.</li><li>Check dropdowns, table headers, page numbers and default button labels.</li><li>Load each language only for people who use it.</li><li>Test on a phone screen too. Mobile layouts often show labels that a desktop screenshot never shows.</li></ol><h3>Developer to developer</h3><p>Our checks were not wrong. They were answering a different question from the one that mattered. “Is it translated?” and “does the user see it in their language?” sound the same. They are not.</p><p>The bug was found by a person looking at a screen, not by any of our tests. I think about that a lot.</p><p>When we built OpsX, I learned that for a small business owner in Bihar, one English word in the wrong place can make the whole screen feel like it is not meant for them. Hindi support is not a feature you switch on. It is something you check again every time you add a screen.</p><p><strong>Vinay Kumar</strong><br>Senior Software Developer, Easyres Travel Technology<br>Building OpsX: attendance, salary and field-staff tracking for Indian SMEs, from Bihar. <a href="https://opsx.in/">opsx.in</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=933b8e87abf2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[He Worked 11 Hours. The Software Paid Him for Half a Day.]]></title>
            <link>https://medium.com/@thisvinaykumar/he-worked-11-hours-the-software-paid-him-for-half-a-day-1dce19328201?source=rss-e184dbcd37f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dce19328201</guid>
            <category><![CDATA[payroll]]></category>
            <category><![CDATA[hr]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vinay Kumar | System Architect (@thisvinaykumar)]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 12:31:01 GMT</pubDate>
            <atom:updated>2026-10-17T12:31:01.646Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RVqdk7XtxLxlOD4SdbJgxw.png" /></figure><p><em>I am Vinay Kumar, a Senior Software Developer at Easyres Travel Technology, currently building enterprise ERP and logistics solutions like OpsX (IMS-SAAS).</em></p><p>The attendance screen showed one row for one day:</p><p><strong>In: 09:00. Out: 20:05. Worked: 11.1 hours. Overtime: +1.1 hours.</strong></p><p>And right next to it, a small badge: <strong>Half-day.</strong></p><p>The salary was calculated for half a day.</p><p>Nothing crashed. No error showed up. Every test passed. The code did exactly what it was written to do. That was the problem.</p><h3>Small businesses run on trust in the salary</h3><p>We build OpsX from Patna and Gaya for small Indian businesses: gyms, shops, small factories and teams with field staff. In these places, the owner often knows every worker by name. If the salary is wrong by even one day, the worker does not open a support ticket. He goes to the owner. And the owner stops trusting the software.</p><p>The bug above came from a real gym using our app. It taught me that payroll bugs are rarely “broken code.” They are <strong>wrong rules</strong>, and wrong rules pass every test.</p><h3>Bug 1: The software believed the label, not the clock</h3><p>Earlier that day, someone had marked the employee as “Half-day.” Maybe he had asked to leave early. Then he stayed and worked a full day, and more.</p><p>Our salary engine decided each day from its <strong>status</strong> alone. Status said half day, so it paid half a day.</p><p>When I went to fix it, I found something worse. The engine did not just ignore the hours worked. It never even <em>loaded</em> them from the database. The query fetched the status and a few other fields, and the hours were not on the list. No rule could ever look at hours that were never fetched.</p><p><strong>Lesson:</strong> before you design a fix, check what data your code actually reads. A rule cannot work on a field the query never asked for.</p><h3>The fix was not “always trust the clock”</h3><p>The easy fix is: if the hours say full day, pay full day. But that would be wrong too.</p><p>An earlier change had made sure that when an admin sets a status by hand, it is not overwritten when someone saves the record again. That is right. The admin’s decision matters. What was wrong was that the conflict was <em>silent</em>.</p><p>So we built it carefully:</p><ul><li><strong>Show the conflict.</strong> A warning badge now sits right next to the “Half-day” label, so anyone can see the label and the clock disagree.</li><li><strong>Fix it automatically only when it is very clear.</strong> Only if the person worked the whole shift. A 4 or 5 hour day is exactly where the admin who marked “half day” is probably right.</li><li><strong>Never trust a machine-made check-out.</strong> If a worker forgets to punch out, the system closes the day at shift end. That makes the day look exactly “full”. So those days are flagged, but never fixed automatically.</li><li><strong>Do not swallow overtime.</strong> Turning the day into “full day” must not delete the 1.1 hours of overtime. We wrote a test just for that.</li><li><strong>Let each business choose.</strong> By default, the actual hours win. A business can switch to “only flag it” or “the label wins” if that is how they work.</li></ul><h3>Bug 2: Working on a day of approved leave</h3><p>Next case. An employee takes approved leave. His leave balance goes from 5 to 4. Then he comes to work anyway and works the full shift.</p><p>The software paid him for a leave day, and kept his leave balance at 4. He worked, and still lost a day of leave.</p><p>The code already had a function that “revokes” a leave. It cleared the leave from the calendar, gave the balance back and cancelled the request. Exactly the three things we needed. It looked like a one-line fix.</p><p>I am glad I read how it worked before using it.</p><ul><li><strong>It was all or nothing.</strong> A Monday to Friday leave is stored as one entry in the leave record, not five. Revoking it clears all five days. Worked on Wednesday? Monday, Tuesday, Thursday and Friday would also be stripped of leave, and become unpaid absences.</li><li><strong>A day with punches but no status counts as absent.</strong> The salary engine decided “did he work?” from the status, not from the punches. So just removing “leave” from Wednesday would not turn it into a working day. It would turn it into an unpaid absence.</li></ul><p>The “perfect” function would have taken away four days of pay to fix one.</p><p>What we did instead: release only that one day, give back only that one day of balance, and set the day’s status from the actual punches. The leave request itself stays. It is an agreement between the worker and his manager, and the other four days are real.</p><h3>And then a bug in my own fix</h3><p>A few days later, a review found that my fix did not fully work.</p><p>I had removed the leave link from the day’s record. But the salary engine did not build its list of leave days from those records. It built it from the leave request’s own start and end dates. The request still covered Wednesday, so Wednesday still counted as leave.</p><p>On paid leave, this made no difference to the money. On <strong>unpaid</strong> leave, it meant zero pay for a full day of work.</p><p><strong>Lesson:</strong> changing a value in one place does not change a list that is built from somewhere else. Find where the engine actually gets its answer.</p><h3>Bug 3: The days that do not exist</h3><p>We added a feature: click a person in the monthly summary and see the whole month, day by day.</p><p>The simple way is to list that person’s attendance records for the month. But a weekly off has no record. A holiday has no record. An absence has no record. A day before he joined has no record. The records only store punches.</p><p>So a simple list would show 22 days, while the summary row above it was built from all 30. The detail would disagree with the total it came from.</p><p>The fix: the detail screen asks the <strong>same salary engine</strong> to explain each day, instead of reading the records. And the salary preview in that panel calls the exact same function that makes the real payslip. So the preview can never drift from the payslip.</p><p><strong>Lesson:</strong> any screen that says “here is the detail behind this number” must use the same logic that made the number.</p><h3>Why the tests did not catch any of this</h3><p>We had more than 1,000 tests passing. Here is why they missed it.</p><p>Tests check what you told them to check. If the rule itself is wrong, the test checks the wrong rule, and passes.</p><p>And there was one more trap. In one case, a test replaced a helper with a fake one that always returned the right answer. Nine tests passed, but the real code was calling that helper the wrong way. A fake helper proves what it returns. It never proves you called it correctly.</p><h3>A checklist for anyone writing salary or attendance logic</h3><ol><li>When a label and the actual hours disagree, does anyone <em>see</em> it?</li><li>Does your calculation actually load every field your rule needs?</li><li>Is overtime kept safe when a day’s status changes?</li><li>Can a system-made value (like an auto check-out) trigger an automatic money change? It should not.</li><li>Before you reuse a function, read what it does to <em>all</em> the records it touches, not just the one you care about.</li><li>Do your “detail” screens use the same logic as the totals?</li><li>Test with real cases: half day then stayed late, leave then came to work, forgot to punch out, joined mid-month.</li><li>Let each business choose the policy, but pick a default that never quietly underpays.</li></ol><h3>Developer to developer</h3><p>Salary software is not about adding numbers. Adding is easy. It is about deciding what a day <em>was</em>. Was it worked? Was it leave? Who decided, and what if the clock disagrees?</p><p>No test and no AI tool will tell you that a half-day worker stayed for 11 hours. That came from a real gym and a real screen.</p><p>When we built OpsX, I learned that for a small business owner in Bihar, the salary sheet is where trust is won or lost. A worker who is underpaid by one day remembers it longer than any feature you ship. So when the label and the clock disagree, show it. Never decide in silence.</p><p><strong>Vinay Kumar</strong><br>Senior Software Developer, Easyres Travel Technology<br>Building OpsX: attendance, salary and field-staff tracking for Indian SMEs, from Bihar. <a href="https://opsx.in/">opsx.in</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dce19328201" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>