<?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 Gabor Koos on Medium]]></title>
        <description><![CDATA[Stories by Gabor Koos on Medium]]></description>
        <link>https://medium.com/@gabor.koos?source=rss-e13802f71817------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*I0wF5ZGpdDd6aKtMtP0Z_Q.jpeg</url>
            <title>Stories by Gabor Koos on Medium</title>
            <link>https://medium.com/@gabor.koos?source=rss-e13802f71817------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 02:40:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gabor.koos/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[Your JS Date Is Lying to You]]></title>
            <link>https://levelup.gitconnected.com/your-js-date-is-lying-to-you-54c54f040cee?source=rss-e13802f71817------2</link>
            <guid isPermaLink="false">https://medium.com/p/54c54f040cee</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webdev]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Gabor Koos]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 15:01:54 GMT</pubDate>
            <atom:updated>2026-07-24T15:01:54.883Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EOYZIGRSVWbAFSsaiGT3Nw.jpeg" /></figure><p>Run this in your browser console:</p><pre>const d1 = new Date(&#39;2026-07-21&#39;)<br>console.log(d1.getDate())</pre><p>If you are in a timezone west of UTC, you will see 20, not 21. The string looks unambiguous, but Date parsed it as UTC midnight, then getDate() converted to your local time and moved the clock back. You asked for July 21st, but got July 20th.</p><p>Or try the constructor directly:</p><pre>const d2 = new Date(2026, 7, 21)<br>console.log(d2.toDateString()) // &quot;Fri Aug 21 2026&quot;</pre><p>Months are 0-indexed, so 7 is August, not July. You probably asked for July 21st and got August 21st.</p><p>And if you needed a reminder that Date objects are mutable:</p><pre>const deadline = new Date(&#39;2026-07-21&#39;)<br>deadline.setDate(32)<br>console.log(deadline) // 2026-08-01</pre><p>No error, just silent rollover.</p><p>These are default behavior of the most-used date API in the world, quietly corrupting date logic in production applications for thirty years. Date was written in ten days in 1995, modeled closely on the Java java.util.Date class (which Java later deprecated). The web grew around it, frameworks worked around it, and the traps became invisible because everyone assumed the API made sense.</p><p>This post works through the main ways Date misleads you - parsing, mutation, timezones, arithmetic, and serialization - and shows how the Temporal API, now available in most modern runtimes, fixes each one. Along the way, it also covers safe patterns for code that is still stuck on Date and cannot migrate yet.</p><h3>Parsing Is Unreliable</h3><p>The <a href="https://tc39.es/ecma262/#sec-date-time-string-format">ECMAScript spec</a> says new Date(string) must support one format: ISO 8601 date-time strings like &quot;2026-07-21T12:00:00Z&quot;, everything else is implementation-defined. In practice every engine accepts a wide range of informal strings — &quot;July 21, 2026&quot;, &quot;21/07/2026&quot;, &quot;07-21-2026&quot;, but they don&#39;t agree on all of them, and the spec does not require them to.</p><p>That sounds like an edge case until you hit the most common one: a plain date string.</p><pre>console.log(new Date(&#39;2026-07-21&#39;))   // parsed as UTC midnight<br>console.log(new Date(&#39;2026/07/21&#39;))   // parsed as local midnight (or Invalid Date in some engines)<br>console.log(new Date(&#39;July 21 2026&#39;)) // parsed as local midnight</pre><p>The ISO date-only format YYYY-MM-DD is treated as UTC by the spec. All other date strings are treated as local time, if they parse at all. So two strings that look functionally identical to a human can produce timestamps twelve hours apart depending on which separator you happened to use. The first one will shift dates when you call getDate(), getMonth(), or any other local-time method while the user is outside UTC. The second may throw Invalid Date in one runtime and succeed in another.</p><p>Another footgun: Date() and new Date() do not do the same thing.</p><pre>console.log(Date(&#39;2026-07-21&#39;))      // current date-time string, input ignored<br>console.log(new Date(&#39;2026-07-21&#39;))  // parsed Date object: eg. Tue Jul 21 2026 01:00:00 GMT+0100 (British Summer Time)</pre><p>Forgetting new changes the operation from parsing to formatting &quot;now&quot;, which can quietly invalidate tests and debugging output.</p><p>Invalid Date is its own problem. Date does not throw on a bad string:</p><pre>const d = new Date(&#39;not a date&#39;)<br>console.log(d)           // Invalid Date<br>console.log(isNaN(d))    // true</pre><p>The object is constructed. It breaks later, silently, when you try to use the value — typically as a NaN that propagates through arithmetic, or as the string &quot;Invalid Date&quot; that ends up stored in a database or sent to an API.</p><p>This is why nearly every production codebase that deals seriously with dates ends up reaching for a library. <a href="https://date-fns.org/">date-fns</a>, <a href="https://day.js.org/">dayjs</a>, and <a href="https://moment.github.io/luxon/">luxon</a> all provide strict parsing functions that throw explicitly when a string does not match the expected format. That behavior is what Date should have had from the start.</p><p><a href="https://tc39.es/proposal-temporal/">Temporal</a> is JavaScript&#39;s next-generation built-in date and time API (Temporal.*), designed to replace the sharp edges of Date. At the time of writing, its normative text is still maintained in the proposal repository while final ECMA-262 publication catches up, but engines and polyfills can still implement it because the Stage 4 semantics are already fixed. Temporal.PlainDate.from(&#39;2026-07-21&#39;) parses one format and always means a calendar date with no timezone involved. Temporal.Instant.from(&#39;2026-07-21T00:00:00Z&#39;) requires an explicit UTC offset. Ambiguous input becomes a parse error instead of a silent timezone shift.</p><p>For the next sections, we stay on Date because most existing codebases still run on it, and these bugs are where production incidents usually happen. Temporal appears as a reference model for safer semantics, not as an assumption that every project can migrate immediately.</p><h3>0-Based Months and Mutation Break Assumptions</h3><p>Even when you construct a Date correctly, month indexing and mutation rules still create production bugs.</p><p>As shown in the intro example (new Date(2026, 7, 21)), constructor month values are 0-based, so 7 means August, creating round-trip errors:</p><pre>function toApiDateParts(d) {<br>    return {<br>        year: d.getFullYear(),<br>        month: d.getMonth(), // returns 0..11<br>        day: d.getDate()<br>    }<br>}<br><br>console.log(toApiDateParts(new Date(&#39;2026-12-15T00:00:00Z&#39;)))<br>// { year: 2026, month: 11, day: 15 }</pre><p>If another service expects month: 12, your December data is now November data.</p><p>Mutation makes this worse because helper functions can modify caller-owned values without signaling it:</p><pre>function addBusinessDays(date, days) {<br>    // Mutates input object<br>    date.setDate(date.getDate() + days)<br>    return date<br>}<br><br>const invoiceDate = new Date(&#39;2026-07-21T00:00:00Z&#39;)<br>const dueDate = addBusinessDays(invoiceDate, 14)<br><br>console.log(invoiceDate.toISOString()) // 2026-08-04T00:00:00.000Z<br>console.log(dueDate.toISOString())     // 2026-08-04T00:00:00.000Z</pre><p>Many teams discover this only after seeing audit fields or cache keys “randomly” drift.</p><p>Overflow normalization adds another hidden branch to your logic:</p><pre>const renewal = new Date(&#39;2026-01-31T00:00:00Z&#39;)<br>renewal.setMonth(renewal.getMonth() + 1)<br><br>console.log(renewal.toISOString())<br>// 2026-03-03T00:00:00.000Z</pre><p>Your intent was “next month”. The runtime result was “plus a month, then normalize invalid day.” That can be acceptable for some domains and disastrous for billing, compliance, or reporting.</p><p>Normalization also applies to constructor parts, including negative and zero values:</p><pre>console.log(new Date(2026, -1, 1).toISOString()) // 2025-12-01T00:00:00.000Z<br>console.log(new Date(2026, 1, 0).toISOString())  // 2026-01-31T00:00:00.000Z</pre><p>This behavior is sometimes useful for date arithmetic, but dangerous when accidental.</p><p>Temporal addresses all three pain points directly: clearer type boundaries, one-based calendar fields in PlainDate, and immutable operations that return new values.</p><pre>const invoiceDate = Temporal.PlainDate.from(&#39;2026-07-21&#39;)<br>const dueDate = invoiceDate.add({ days: 14 })<br><br>console.log(invoiceDate.toString()) // 2026-07-21<br>console.log(dueDate.toString())     // 2026-08-04</pre><p>The original value stays unchanged, and the intent is visible in the code.</p><h3>Timezones and DST Turn Simple Logic Into Incidents</h3><p>Date stores an instant (milliseconds since Unix epoch, UTC), but most everyday methods (getHours, getDate, toString) project that instant into the host machine&#39;s local timezone. Bugs appear when code mixes UTC and local operations without noticing.</p><pre>const d = new Date(&#39;2026-07-21T00:30:00Z&#39;)<br><br>console.log(d.toISOString()) // 2026-07-21T00:30:00.000Z<br>console.log(d.getUTCDate())  // 21<br>console.log(d.getDate())     // may be 20 in timezones west of UTC</pre><p>Same instant, different calendar day, depending on which getter you call. This is a common source of “off by one day” bugs in reports and date filters.</p><p>DST adds another layer. In DST-observing timezones, some local days are 23 hours and some are 25.</p><pre>// Example outcome in America/New_York around spring-forward transition<br>const start = new Date(&#39;2026-03-08T00:00:00-05:00&#39;)<br>const end = new Date(&#39;2026-03-09T00:00:00-04:00&#39;)<br><br>console.log((end - start) / (1000 * 60 * 60))<br>// 23</pre><p>If billing, rate limits, retention windows, or SLAs assume every local day is 24 hours, these transitions produce subtle data drift.</p><p>Serialization makes the confusion travel between systems:</p><pre>const d = new Date(&#39;2026-07-21T15:00:00-04:00&#39;)<br><br>console.log(d.toString())     // local representation<br>console.log(d.toISOString())  // UTC representation<br>console.log(JSON.stringify(d)) // same as ISO string</pre><p>JSON.stringify always emits UTC ISO strings. If another service later interprets that value as a local wall-clock time, the original timezone intent is gone.</p><p>This is why Date cannot preserve input timezone intent. It stores an instant, not a &quot;timezoneful&quot; local timestamp. For example:</p><pre>const d = new Date(&#39;2000-01-01T00:00:00+20:00&#39;)<br>console.log(d.getTimezoneOffset())<br>// your machine&#39;s local offset, not +20:00</pre><p>The +20:00 changed how the input was interpreted into an instant, but that offset is not retained as date object metadata.</p><p>Form controls add another sharp edge. When valueAsDate is supported and populated for &lt;input type=&quot;date&quot;&gt; and &lt;input type=&quot;time&quot;&gt;, it follows UTC-oriented semantics, which often surprises teams expecting local wall-clock behavior.</p><p>Safe Date rule for distributed systems: persist and transmit instants in UTC (toISOString()), then attach an explicit IANA timezone (America/New_York, Europe/Berlin) when you need calendar semantics.</p><p>Temporal splits these concepts into different types so mistakes are harder to make:</p><ul><li>Temporal.Instant for machine time points</li><li>Temporal.ZonedDateTime for timezone-aware calendar math</li><li>Temporal.PlainDate for date-only values with no timezone</li></ul><p>That type separation removes a large class of local-vs-UTC mix-ups that Date makes easy.</p><h3>Arithmetic and Duration Logic Are Fragile by Default</h3><p>Date has no first-class duration type, so most code falls back to raw millisecond math:</p><pre>const msPerDay = 24 * 60 * 60 * 1000<br>const expiresAt = new Date(start.getTime() + 30 * msPerDay)</pre><p>That looks harmless, but it bakes in assumptions that are often false in local-time workflows (DST days are not always 24 hours) and hard to audit in business logic.</p><p>Calendar arithmetic is where these shortcuts break fastest. “Add one month” is not equivalent to “add 30 days” and can diverge by several days around month boundaries.</p><pre>const jan31 = new Date(&#39;2026-01-31T00:00:00Z&#39;)<br><br>const plus30Days = new Date(jan31.getTime() + 30 * 24 * 60 * 60 * 1000)<br>const plus1Month = new Date(jan31)<br>plus1Month.setUTCMonth(plus1Month.getUTCMonth() + 1)<br><br>console.log(plus30Days.toISOString()) // 2026-03-02T00:00:00.000Z<br>console.log(plus1Month.toISOString()) // 2026-03-03T00:00:00.000Z</pre><p>Both are “reasonable” operations. Neither means the same thing. If your domain says “next billing month”, milliseconds are the wrong unit.</p><p>Even simple comparisons can blur intent when everything is expressed as numbers:</p><pre>const ageMs = Date.now() - createdAt.getTime()<br>if (ageMs &gt; 90 * 24 * 60 * 60 * 1000) {<br>    archive(record)<br>}</pre><p>This mixes machine-time thresholds with calendar expectations. Around DST and timezone conversions, teams start seeing records archived earlier or later than product owners expect.</p><p>Safe Date pattern when migration is not possible:</p><ul><li>use UTC for machine-time durations (timeouts, TTLs, retry backoff)</li><li>use explicit calendar logic for date-based rules (monthly renewals, “same day next month”)</li><li>centralize date math helpers and test them against DST and month-end cases</li></ul><p>Temporal makes this separation explicit by giving you dedicated types for both instants and durations:</p><pre>const start = Temporal.ZonedDateTime.from(&#39;2026-01-31T00:00:00+00:00[UTC]&#39;)<br><br>const nextMonth = start.add({ months: 1 })<br>const plus30Days = start.add({ days: 30 })<br><br>console.log(nextMonth.toString()) // 2026-02-28T00:00:00+00:00[UTC]<br>console.log(plus30Days.toString()) // 2026-03-02T00:00:00+00:00[UTC]</pre><p>The code now states intent directly: calendar month arithmetic versus day-count arithmetic.</p><h3>Serialization and Storage Quietly Drop Intent</h3><p>By the time a date leaves your process, the hardest problem is no longer parsing but preserving meaning across boundaries. With Date, the value carries an instant, but many business workflows care about local calendar intent: &quot;run at 9:00 in Berlin,&quot; &quot;invoice date is July 21 in tenant timezone,&quot; or &quot;daily reset at local midnight.&quot;</p><p>A plain JSON round-trip often erases that intent:</p><pre>const payload = {<br>    scheduledAt: new Date(&#39;2026-07-21T09:00:00-04:00&#39;)<br>}<br><br>const json = JSON.stringify(payload)<br>console.log(json)<br>// {&quot;scheduledAt&quot;:&quot;2026-07-21T13:00:00.000Z&quot;}</pre><p>The offset -04:00 is gone. You still have the same instant, but not the original wall-clock context.</p><p>The same issue shows up in storage layers:</p><pre>localStorage.setItem(&#39;dueDate&#39;, JSON.stringify(new Date(&#39;2026-07-21&#39;)))<br><br>const raw = localStorage.getItem(&#39;dueDate&#39;)<br>const loaded = new Date(JSON.parse(raw))<br><br>console.log(loaded.toString())<br>// rendered in current machine timezone, which may differ from where it was created</pre><p>Move the data between regions, or open it on a laptop with a different timezone, and “same date” features start drifting by hours or even by a day.</p><p>API contracts can amplify this drift when they mix ambiguous field names and inconsistent semantics:</p><ul><li>createdAt: instant in UTC</li><li>businessDate: calendar date in tenant timezone</li><li>runAt: local wall-clock time tied to a specific IANA zone</li></ul><p>If all three are serialized as plain ISO strings without explicit schema rules, bugs are guaranteed.</p><p>Safe transport pattern with Date:</p><ul><li>for instants, send UTC ISO strings (toISOString())</li><li>for calendar dates, send date-only strings (YYYY-MM-DD) as plain data, not Date objects</li><li>for local-time schedules, send both local time and timezone id (Europe/Berlin)</li><li>validate and normalize at service boundaries, not deep inside business logic</li></ul><p>Temporal maps cleanly to this contract style:</p><ul><li>Temporal.Instant for UTC machine timestamps</li><li>Temporal.PlainDate for date-only business fields</li><li>Temporal.ZonedDateTime when timezone and wall-clock semantics must survive round-trips</li></ul><p>Serialization stops being a guessing game once the type matches the meaning.</p><h3>Temporal in Real Projects: Adoption Without a Big-Bang Rewrite</h3><p>As Temporal seems to address many of the shortcomings of Date, at this point the natural question is: should you replace every Date right now?</p><p>Usually, no.</p><p>Most teams need a mixed model for a while:</p><ul><li>keep Date at interop edges that require it (legacy APIs, third-party SDKs, older libraries)</li><li>use Temporal for new domain logic where correctness matters</li><li>convert explicitly at boundaries instead of letting values drift implicitly</li></ul><p>That incremental approach avoids the riskiest migration pattern: touching every timestamp in the codebase at once.</p><p>A practical rollout plan:</p><ol><li>Identify high-cost date paths first: billing cycles, reporting windows, retention policies, scheduling.</li><li>Introduce small date utilities that expose intent (toBusinessDate, toUtcInstant, nextBillingDate).</li><li>Implement those utilities with Temporal internally.</li><li>Keep adapters for Date at API/database boundaries until dependent systems are updated.</li><li>Add tests for DST transitions, month-end rollover, and timezone conversion invariants.</li></ol><p>Interop is straightforward when done explicitly:</p><pre>const sourceDate = new Date(&#39;2026-07-21T00:00:00.000Z&#39;)<br><br>// Date -&gt; Temporal<br>const instant = Temporal.Instant.fromEpochMilliseconds(sourceDate.getTime())<br><br>// Temporal -&gt; Date<br>const roundTripDate = new Date(instant.epochMilliseconds)<br><br>console.log(instant.toString())<br>console.log(roundTripDate.toISOString())</pre><p>For environments that do not yet provide native Temporal, use one of the <a href="https://www.npmjs.com/package/@js-temporal/polyfill">polyfills</a> and keep the same API surface. That lets you standardize semantics now and remove polyfill wiring later. If bundle size is a concern, evaluate lighter alternatives and only ship the parts you need. In many apps this cost is still preferable to recurring production date bugs.</p><p>Choose the model that matches the boundary and the risk profile:</p><ul><li>Date remains a compatibility type.</li><li>Temporal becomes your correctness type.</li></ul><p>Defining those roles explicitly makes date logic simpler, safer, and easier to review.</p><h3>Practical Rules for Date Code You Still Have to Maintain</h3><p>Many teams cannot switch everything to Temporal in one quarter. If your codebase still uses Date heavily, enforce a few hard rules and date bugs drop quickly.</p><ol><li>Ban ambiguous parsing.<br>Only accept strict input formats. Parse YYYY-MM-DD as a calendar date value, and parse instants with full ISO date-time plus explicit offsets (Z or +/-HH:mm). Reject everything else.</li><li>Separate instant fields from calendar fields in your schema.<br>Use names that encode semantics, such as createdAtUtc, businessDate, localRunTime, and timeZoneId.</li><li>Keep UTC for transport and storage.<br>Persist instants as ISO UTC strings, and store timezone identifiers separately when wall-clock behavior matters.</li><li>Never mutate a shared Date instance.<br>Clone before modification in helper functions:</li></ol><pre>function addDaysImmutable(date, days) {<br>    const next = new Date(date)<br>    next.setUTCDate(next.getUTCDate() + days)<br>    return next<br>}</pre><p>5. Centralize date math.<br>Put all date arithmetic in one module with tests for DST boundaries, month-end rollover, leap years, and timezone conversions.</p><p>6. Test with multiple timezones in CI.<br>Run the same test suite at least in UTC and one DST-observing timezone. Many bugs only appear outside your local developer setup.</p><p>7. Log both machine and calendar context in critical flows.<br>When debugging production incidents, log the instant, timezone id, and derived local date/time used in business decisions.</p><p>These rules are boring by design. Boring date handling is what prevents expensive production surprises.</p><h3>Conclusion</h3><p>Date survives because it is everywhere, not because it is safe (or even correct) by default. It mixes parsing ambiguity, mutable state, timezone projection, and normalization rules into one API, then asks application code to keep all of that straight under production load. Temporal fixes most of the pain by separating concerns, enforcing immutability, and providing explicit types for instants, calendar dates, and timezone-aware schedules. So the latter is the right choice for new code, and the former is a compatibility type that should be isolated behind adapters, and eventually retired.</p><p>You do not need a full rewrite tomorrow, you need explicit semantics today.</p><ul><li>treat instants, calendar dates, and timezone-aware schedules as different data types</li><li>enforce strict parsing and boundary validation</li><li>isolate legacy Date usage behind adapters</li><li>move high-risk business logic to Temporal as you touch it</li></ul><p>That approach works in real teams, with real constraints. It reduces incident risk immediately and creates a clear path away from the sharp edges of Date.</p><p>If you think you have mastered Date, try the excellent (unaffiliated) quiz at <a href="https://jsdate.wtf/">https://jsdate.wtf/</a>. You might be in for a surprise 😄</p><p>Dates are not the only things lying to you in JavaScript. Other posts in the series:</p><ul><li><a href="https://blog.gaborkoos.com//posts/2026-03-28-Your-Debounce-Is-Lying-to-You/">Your Debounce Is Lying to You</a></li><li><a href="https://blog.gaborkoos.com//posts/2026-03-31-Your-Throttling-Is-Lying-to-You/">Your Throttling Is Lying to You</a></li><li><a href="https://blog.gaborkoos.com//posts/2026-04-19-Your-HTTP-Client-Is-Lying-to-You/">Your HTTP Client Is Lying to You</a></li><li><a href="https://blog.gaborkoos.com//posts/2026-05-09-Your-Recursion-Is-Lying-to-You/">Your Recursion Is Lying to You</a></li><li><a href="https://blog.gaborkoos.com//posts/2026-06-11-Your-Package-Manager-Is-Lying-to-You/">Your Package Manager Is Lying to You</a></li><li><a href="https://blog.gaborkoos.com//posts/2026-06-28-Your-Console-Is-Lying-to_You/">Your console.log Is Lying to You</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54c54f040cee" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/your-js-date-is-lying-to-you-54c54f040cee">Your JS Date Is Lying to You</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your console.log Is Lying to You]]></title>
            <link>https://levelup.gitconnected.com/your-console-log-is-lying-to-you-4726f01d1b08?source=rss-e13802f71817------2</link>
            <guid isPermaLink="false">https://medium.com/p/4726f01d1b08</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Gabor Koos]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 19:45:01 GMT</pubDate>
            <atom:updated>2026-06-29T19:45:01.840Z</atom:updated>
            <content:encoded><![CDATA[<p>Open your browser DevTools and run this:</p><pre>const user = { name: &quot;Bob&quot; }<br>console.log(user)<br>user.name = &quot;Alice&quot;</pre><p>You would expect the log to show { name: &quot;Bob&quot; }, the value at the time of the console.log call. The collapsed line is what you expect:</p><pre>▶ Object { name: &quot;Bob&quot; }</pre><p>But expand it, and you will see:</p><pre>name: &quot;Alice&quot;</pre><p>Oops. So what’s going on? console.log() is the most-used debugging tool in JavaScript, but it can be subtly unreliable. Not because it is broken, but because <strong>it optimizes for speed and interactivity rather than for accuracy</strong>. It was built for fast exploration in a live, interactive environment, and those priorities come with tradeoffs that can genuinely mislead you during debugging. Over the next sections, we&#39;ll look at a few ways the console can mislead you - and, more importantly, why each one exists.</p><h3>Objects Aren’t Snapshots</h3><p>When you pass an object to console.log() in browser DevTools, the browser does not immediately serialize it into a string. Instead, it stores a <strong>live reference</strong> to that object and defers the actual rendering until you expand the entry. This is called lazy evaluation, and it is what caused the surprise.</p><p>The collapsed ▶ Object you see is essentially a placeholder: the properties shown inside it are evaluated at the moment you click the arrow, not at the moment you called console.log(). By then, your code has already continued running. That means what you&#39;re seeing is not a frozen record of the object at the time of logging, but a live view into whatever the object happens to look like when DevTools renders it. In the example:</p><ol><li>You log { name: &quot;Bob&quot; }</li><li>DevTools stores a reference to the user object</li><li>The code continues executing</li><li>user.name is mutated to &quot;Alice&quot;</li><li>You expand the logged object later and see the current state</li></ol><p>This behavior can feel unintuitive at first, because most developers mentally model console.log() as &quot;print this value right now&quot;, but in browser DevTools, it is closer to &quot;show me this object as it exists when I look at it&quot;.</p><p>This design is intentional: if DevTools were to eagerly serialize every object at log time, it would have to deeply traverse and copy potentially large object graphs on every log call. In complex applications, especially ones with frequent logging inside loops or render cycles, that overhead would be expensive in both memory and performance. By deferring evaluation, DevTools stays fast and interactive, even when working with large or constantly changing state.</p><p>But that optimization comes with a tradeoff: <strong>what you see in the console is not always what existed at the moment you logged it</strong>. Once you internalize that distinction (log time vs view time), a whole class of “weird bugs” starts making sense.</p><h3>Promises and Async Timing</h3><p>Promises change state over time, so a promise that was pending when you logged it may appear fulfilled when you inspect it later. This is related to a deeper async distinction: promises represent future results, not ownership of the work producing those results, which is why <a href="https://blog.gaborkoos.com/posts/2025-12-23-Cancellation-In-JavaScript-Why-Its-Harder-Than-It-Looks/">cancellation in JavaScript is harder than it looks</a>.</p><pre>const promise = fetch(&#39;https://jsonplaceholder.typicode.com/posts/1&#39;)<br>console.log(promise)</pre><p>You see:</p><pre>▶ Promise { &lt;state&gt;: &quot;pending&quot; }</pre><p>Expand it after the network resolves:</p><pre>&lt;state&gt;: &quot;fulfilled&quot;<br>&lt;value&gt;: Response { type: &quot;cors&quot;, url: &quot;https://jsonplaceholder.typicode.com/posts/1&quot;, redirected: false, … }<br>&lt;prototype&gt;: Promise.prototype { … }</pre><p>The promise resolved after you logged it, but the console shows both the pending and resolved states depending on when you inspect it. The mechanism differs from the mutable object earlier: the promise genuinely settled from pending to fulfilled once, rather than being mutated repeatedly. The symptom, though, is the same: what you read depends on when you look, not on when you logged.</p><p>Unlike objects, DevTools isn’t showing a live mutable object here: the promise really did transition from pending to fulfilled exactly once. But the experience is similar: <strong>what you learn from the console depends on when you inspect it, not merely when you logged it</strong>.</p><h3>The <a href="https://en.wikipedia.org/wiki/Heisenbug">Heisenbug</a> Effect: Logging Changes Reality</h3><p>At some point, every JavaScript developer hits this: you have a bug, add one console.log to debug, rerun the flow, and the bug disappears. This may sound unbelievable at first, but <strong>logging can change timing enough to hide races and ordering bugs</strong>.</p><p>console.log is not free. It does formatting work, sends data to DevTools, and can trigger object inspection overhead. In hot paths, that extra work shifts scheduling just enough to change outcomes.</p><p>Common places where this matters:</p><ul><li>Tight loops where tiny delays change interleaving</li><li>UI rendering paths where extra work affects frame timing</li><li>Event handlers where ordering between <a href="https://blog.gaborkoos.com/posts/2025-10-25-Modern-Javascript-Concurrency/">microtasks and macrotasks</a> is fragile</li><li><a href="https://blog.gaborkoos.com/posts/2026-03-29-One-Cache-to-Rule-Them-All-Handling-Responses-and-In-Flight-Requests-with-Durable-Objects/">Request dedupe and cache races</a> where “first winner” behavior is timing-sensitive</li></ul><p>This concept is not easy to demonstrate in a small snippet, and the result is deliberately engine-dependent, so you may see different outcomes in Chrome and Firefox. That variability is itself the point. Try this in a browser console:</p><pre>function run(label, withDebugWork) {<br>  let done = false;</pre><pre>  // Producer: flips done, but not immediately<br>  setTimeout(() =&gt; {<br>    done = true;<br>  }, 5);</pre><pre>  // Consumer: checks quickly<br>  const check = () =&gt; {<br>    console.log(label, done ? &quot;OK&quot; : &quot;FAILED&quot;);<br>  };</pre><pre>  if (withDebugWork) {<br>    console.log(&quot;debug path&quot;);<br>    // simulate instrumentation overhead<br>    const t = performance.now();<br>    while (performance.now() - t &lt; 8) {}<br>  }</pre><pre>  setTimeout(check, 0);<br>}</pre><pre>run(&quot;no-debug&quot;, false);<br>run(&quot;with-debug&quot;, true);</pre><p>The results are not reproducible, and that is exactly the point. Depending on the engine, your machine, and how busy it is, you might see both runs report FAILED, both report OK, or a split between them, and rerunning can change the answer. Sometimes the busy-wait in the debug path delays the consumer long enough for the producer&#39;s timer to fire first; sometimes it does not. The takeaway is not &quot;the debug run passes.&quot; It is that the timing here is fragile enough that adding work in one path can flip the outcome at all. When a result depends on margins this thin, anything you add to observe it, including a single log, can change what you see.</p><p>I once debugged a duplicate-request bug where two click handlers could fire before a shared inFlight flag was set. With no logs, both requests escaped. With a console.log(&#39;click&#39;) at the top of the handler, the second request consistently vanished: the log delayed execution enough that the first handler set inFlight before the second one checked it.</p><p>How to debug without masking it? When you suspect a timing bug, prefer lower-impact techniques:</p><ol><li>Log less frequently and at boundaries, not inside hot loops.</li><li>Log primitives (id, timestamp, state) instead of large objects.</li><li>Use performance.now() markers to trace ordering explicitly.</li><li>Reproduce with and without logs to confirm observer effect.</li><li>Use breakpoints and the debugger timeline when possible.</li></ol><p>Most importantly: if one extra log changes behavior, you are not looking at a stable system, you are looking at a race.</p><h3>React State Lies</h3><p>React adds another trap: the state value you log right after an update call is not the updated one.</p><pre>const [count, setCount] = useState(0)</pre><pre>function handleClick() {<br>  setCount(count + 1)<br>  console.log(&#39;after setCount:&#39;, count) // stale value<br>}</pre><p>setCount schedules an update, but that is only half the reason. The other half is closure capture: count is a const bound to this particular render, so nothing that happens later in the same handler can change it. Even without batching, the count you log here is the value from the render that created the handler.</p><p>If you want to log the updated value, log from an effect tied to that state:</p><pre>useEffect(() =&gt; {<br>  console.log(&#39;count changed:&#39;, count)<br>}, [count])</pre><p>The takeaway: the value you logged was never live to begin with. It was frozen into the handler when the render created it, so reading it after setCount tells you about that render, not your current state.</p><p>The same stale-observation problem shows up in request-driven UI too: <a href="https://blog.gaborkoos.com/posts/2026-03-28-Your-Debounce-Is-Lying-to-You/">Your Debounce Is Lying to You</a> covers stale responses and request lifecycle bugs, while <a href="https://blog.gaborkoos.com/posts/2026-03-31-Your-Throttling-Is-Lying-to-You/">Your Throttling Is Lying to You</a> covers event timing bugs where the final observed state matters.</p><h3>The Line Number Can Lie Too</h3><p>Sometimes the misleading part is not the value, but where DevTools says it came from.</p><p>In modern JavaScript apps, the code running in the browser is often not the code you wrote. It may have passed through TypeScript, Babel, minification, bundling, code splitting, JSX transforms, or framework compilers. Source maps try to connect the generated code back to your original files, but that mapping is only as good as the build pipeline that produced it.</p><p>When source maps are stale, missing, incorrectly uploaded, or generated with low fidelity, console stack traces can point at the wrong file, the wrong line, or a line that only roughly corresponds to the generated code. This is especially confusing when debugging production builds, where minification and bundling can collapse many original modules into a small number of generated files.</p><p>This does not mean DevTools is broken. It means it is doing a reverse lookup through a translation table.</p><p>Common causes:</p><ul><li>The browser is using an old cached bundle or source map.</li><li>The deployed JavaScript and deployed source maps are from different builds.</li><li>Minification collapsed or reordered code in ways the map only approximates.</li><li>Framework or compiler transforms moved your logic away from the line you wrote.</li><li>Production source maps were stripped, hidden, or uploaded only to an error tracker.</li></ul><p>When the line number looks suspicious, verify the build artifact. Check whether the logged code exists in the compiled bundle, hard refresh or disable cache, compare build hashes, and reproduce in a development build with high-quality source maps.</p><p>The console may be showing the right event, but the wrong address.</p><h3>When You Actually Need a Snapshot</h3><p>Most of the time, live inspection is useful. But sometimes you need one hard guarantee: “show me exactly what this value looked like at this moment.” That is when you take a snapshot explicitly.</p><h3>Option 1: structuredClone (best default)</h3><pre>const snap = structuredClone(obj)<br>console.log(snap)</pre><p>Pros:</p><ul><li>Deep clone</li><li>Preserves more built-in types than JSON methods</li><li>Great default in modern runtimes</li></ul><p>Caveats:</p><ul><li>Cannot clone functions</li><li>Cannot clone DOM nodes</li><li>Can throw on unsupported values</li></ul><h3>Option 2: JSON.parse(JSON.stringify(obj)) (legacy fallback)</h3><pre>const snap = JSON.parse(JSON.stringify(obj))<br>console.log(snap)</pre><p>Pros:</p><ul><li>Works almost everywhere</li><li>Easy to remember</li></ul><p>Caveats:</p><ul><li>Drops undefined, functions, symbols</li><li>Converts Date to string</li><li>Breaks on circular references</li><li>Loses prototype/class information</li></ul><h3>Option 3: lodash.cloneDeep (library route)</h3><pre>import cloneDeep from &#39;lodash/cloneDeep&#39;</pre><pre>const snap = cloneDeep(obj)<br>console.log(snap)</pre><p>Pros:</p><ul><li>Mature, predictable deep clone behavior</li><li>Useful in older environments without structuredClone</li></ul><p>Caveats:</p><ul><li>Extra dependency</li><li>Heavier than native options</li><li>Still not a perfect clone of every possible runtime value</li></ul><h3>Practical guidance</h3><p>Use snapshots surgically, not everywhere:</p><ol><li>Snapshot only at boundaries you care about (before mutation, before retry, before enqueue).</li><li>Prefer structuredClone first.</li><li>Fall back to JSON method only when you know the data shape is JSON-safe.</li><li>If cloning cost is too high, log narrow primitives (id, status, version) instead of whole objects.</li></ol><h3>Choose the Right Tool: A Quick Decision Tree</h3><p>console.log is still useful, but it should be your first pass, not your final instrument. Use the tool that matches the question you are actually asking.</p><h3>“What was the exact value at this moment?”</h3><p>Use a snapshot.</p><pre>console.log(structuredClone(state))</pre><p>This avoids live-reference surprises and gives you evidence you can trust later. Cloning can be expensive for large objects, so reserve it for the values you actually need to freeze.</p><h3>“How does this value evolve over time?”</h3><p>Use breakpoints and step-through debugging.</p><pre>debugger</pre><p>Then inspect call stack, scope, and update order directly instead of inferring from scattered logs. The art of debugging is a vast topic itself, but the key is to <strong>observe the program’s execution in a controlled way</strong>.</p><h3>“Why is framework state stale here?”</h3><p>Use framework DevTools (React/Vue/Svelte), not raw logs after update calls. They show lifecycle timing, render phases, and batched updates, which is exactly the scheduling that ad-hoc logging gets wrong.</p><h3>“Why does this stack trace point to the wrong line?”</h3><p>Check your source maps and build artifacts.</p><p>Make sure the JavaScript bundle and source map came from the same build, disable cache while debugging, and reproduce in a development build when possible. In production, treat source-mapped line numbers as clues, not absolute proof.</p><h3>“What happened in production?”</h3><p>Use structured logging with stable fields.</p><pre>logger.info(&#39;request_finished&#39;, {<br>  requestId,<br>  userId,<br>  status,<br>  durationMs,<br>})</pre><p>Production debugging needs queryable logs, correlation IDs, and timestamped events, not console snapshots. Tracing requests across services and time belongs in observability tooling, not the console.</p><h3>Conclusion</h3><p>Remember, console.log() is not broken. It is optimized for speed, interactivity, and convenience, not for preserving exact truth at every point in time. That tradeoff is why you may see confusing behavior around live references, async timing, scheduler boundaries, and framework updates. The logs are often technically correct, but easy to misinterpret. Use the console as a fast exploration tool, then upgrade your approach when the question gets precise:</p><ul><li>Need exact point-in-time evidence? Snapshot.</li><li>Need ordering and causality? Debugger and timeline tools.</li><li>Need production truth? Structured logs with stable fields and correlation IDs.</li></ul><p>Do not stop using the console, stop trusting it blindly.</p><p>This is part of the same hidden-assumption pattern as <a href="https://blog.gaborkoos.com/posts/2026-04-19-Your-HTTP-Client-Is-Lying-to-You/">Your HTTP Client Is Lying to You</a>, <a href="https://blog.gaborkoos.com/posts/2026-05-09-Your-Recursion-Is-Lying-to-You/">Your Recursion Is Lying to You</a>, and <a href="https://blog.gaborkoos.com/posts/2026-06-11-Your-Package-Manager-Is-Lying-to-You/">Your Package Manager Is Lying to You</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4726f01d1b08" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/your-console-log-is-lying-to-you-4726f01d1b08">Your console.log Is Lying to You</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Evaluate an npm Package — 2026 Edition]]></title>
            <link>https://levelup.gitconnected.com/how-to-evaluate-an-npm-package-2026-edition-666a8165d0f9?source=rss-e13802f71817------2</link>
            <guid isPermaLink="false">https://medium.com/p/666a8165d0f9</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Gabor Koos]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 03:41:30 GMT</pubDate>
            <atom:updated>2026-06-15T03:41:30.785Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VjiDrN0xUX9lyrkEh9oKPw.jpeg" /></figure><p>Every time you run npm install, you are adding code that will execute in your production environment: code written by someone you have never met, with access to whatever your process can reach. It might touch your filesystem, make outbound network requests, read environment variables, or quietly exfiltrate data. You are, in effect, trusting a stranger with your infrastructure.</p><p>Most developers manage this risk by checking two numbers: weekly downloads and GitHub stars. Neither tells you anything meaningful about whether a package is safe, maintained, or honest about what it does. (Most npm packages use GitHub. If a project is hosted elsewhere, apply the same principles.)</p><p>Supply chain attacks have made this worse. Event-stream, ua-parser-js, node-ipc, xz utils — the pattern is consistent: a legitimate, widely used package gets compromised, either through a maintainer being social-engineered, a typosquat, or a dependency buried three levels deep. The npm ecosystem, with its culture of small composable packages and deep transitive dependency trees, is a particularly attractive target. You can do everything right and still get hit through something you never directly installed.</p><p>There is a newer variation worth knowing about. AI coding assistants hallucinate package names. They confidently suggest npm install some-plausible-sounding-package for packages that do not exist. Attackers monitor those hallucinations and register the names - a technique now called <strong>slopsquatting</strong> - so that when a developer follows the suggestion without checking, they install something malicious. If an LLM suggests a package you have never heard of, verify that it exists, has a real history, and has provenance before you run the install.</p><p>This risk increases when you run LLMs in agent mode. In many setups, package selection and installation happen back-to-back without a human checkpoint. If you are doing that, rely on enforcement in the toolchain (for example, a wrapper or install hook that blocks unknown or unverified packages), not on “remember to check first” prompt text.</p><p>None of the above means you should stop using open source packages — that would make you less productive without making you meaningfully safer. What it means is that picking a package deserves more than a five-second glance at the star count.</p><p>This guide gives you a repeatable process for evaluating an npm package before you add it. It takes 5 to 10 minutes. It won’t guarantee safety — nothing will — but it will help you make an informed decision rather than an optimistic one.</p><h3>0. Do you actually need this package?</h3><p>Before you audit anything, ask the simplest question first: should this dependency exist in your project at all?</p><p>Many npm incidents become severe not because one package is inherently catastrophic, but because a tiny convenience package gets copied across dozens of services and frontend apps until it is everywhere. If that package is compromised, abandoned, or suddenly unpublished, your blast radius is no longer small.</p><h3>What to check:</h3><p>Do a <strong>removal test</strong> in your head: if this package disappeared tomorrow, how hard would it be to replace? If the answer is “we would have to refactor half the codebase,” treat it as high-risk and apply stricter scrutiny.</p><p>If it is a tiny utility, ask whether you can implement the same thing in a few lines in your own codebase. Pulling a dependency for one helper function is often not worth the long-term risk.</p><p>Check the package dependency footprint. A package with zero runtime dependencies is not automatically safe, but fewer dependencies generally means a smaller attack surface and fewer transitive surprises. On npm, inspect the dependency count and scan what those dependencies actually are.</p><p>Then check where you plan to use it. A package used in one isolated internal tool has a different risk profile from one that will be imported across every service.</p><h3>1. Is it actively maintained?</h3><p>An unmaintained package is a liability that compounds over time. Security vulnerabilities go unpatched. Compatibility with newer Node versions breaks silently. The API freezes while the ecosystem moves on, and eventually you are pinned to an old version of something because updating it would require replacing a package nobody is touching anymore.</p><p>The obvious signal is recent commits, but commit frequency alone is misleading. A package can have a commit last week that does nothing but update a CI action. What you are looking for is whether the author is still engaged with the actual software.</p><h3>What to check:</h3><p>On the GitHub repository, go to the <strong>Issues</strong> tab. Look at the oldest open issues. Are they acknowledged? If someone reported a bug 18 months ago and the author has never replied, that tells you something about what the maintenance relationship looks like when things go wrong.</p><p>Look at the <strong>Commits</strong> tab. Filter out bot commits and CI noise. When was the last time a human made a meaningful change to the source code, not just a dependency bump or a workflow tweak?</p><p>Look at who is doing the work. If almost every meaningful commit, release, and issue reply comes from one person, you have <strong>maintainer concentration risk</strong> (the “bus factor” — the number of people who would need to be hit by a bus before the project is in trouble). That is not automatically bad — many excellent packages are run by one maintainer — but it means your operational risk is tied to one human’s availability and energy.</p><p>On the <strong>npm page</strong>, go to the Versions tab. Is there a recognizable release cadence — monthly, quarterly, whatever — or a 2-year gap followed by a burst of activity? Long gaps followed by sudden updates are sometimes a red flag in themselves: accounts do get taken over.</p><p>Check the <strong>CHANGELOG</strong>. If it just lists commit hashes, it is nearly useless. A changelog that says “Fixed: deduplication plugin now clones responses per waiter to prevent body-already-used errors” is a changelog written by someone who cares whether you understand what changed and why. The quality of the changelog is a proxy for how the author thinks about the people using their software.</p><p>Finally, if the package exposes a public API that has changed over time, look for a migration guide. An author who documents breaking changes and provides an upgrade path is an author who thinks about the downstream cost of their decisions.</p><h3>2. Can you trust what’s actually published to npm?</h3><p>Maintenance is about the future. This section is about something more immediate: whether what is on the npm registry right now is actually what the author intended to publish.</p><p>The npm registry has no verification by default. When you install a package, you are trusting that the bytes you receive match the source code you can read on GitHub. For most packages, most of the time, that is true. But the mechanism that links source to publish — an NPM_TOKEN stored as a CI secret, or sometimes just on a developer&#39;s laptop - is exactly the kind of credential that attackers target.</p><p>The event-stream attack in 2018 is the clearest example: a maintainer handed over control of a popular package to a stranger. The stranger published a version with a malicious dependency. Millions of projects were affected before anyone noticed. No one hacked GitHub. No one broke npm’s infrastructure. They just got the credentials.</p><p><a href="https://docs.npmjs.com/cli/v9/commands/npm-publish#provenance"><strong>Provenance attestation</strong></a> is the modern answer to this. When a package is published with provenance, the npm registry receives a cryptographic attestation (signed by GitHub’s OIDC infrastructure) that ties the specific package tarball to a specific commit in a specific repository, built by a specific GitHub Actions workflow run. You can verify it. The attestation is public. If someone publishes a package claiming to be from a specific repository but the attestation does not match, that is detectable.</p><h3>What to check:</h3><p>Go to npmjs.com/package/&lt;package-name&gt;. Next to the version name, there should be a green &quot;Provenance&quot; badge if the package was published with provenance:</p><figure><img alt="Provenance badge" src="https://cdn-images-1.medium.com/max/366/1*6TUlF7VPZrMjnNI_-7Dnpg.png" /></figure><p>Click on it, then on the “View more details” link. It will take you to the bottom of the page:</p><figure><img alt="Provenance details" src="https://cdn-images-1.medium.com/max/799/1*5AVGa-p0pjDN5OZoN7NG0Q.png" /></figure><p>It shows the repository URL, the commit SHA, and the GitHub Actions workflow run that published the package. You can click through to all of those things to verify that they exist and make sense. If the badge is there and the details check out, you can be reasonably confident that the package you are installing is what the author intended to publish.</p><p>If it is not there, the package was published without provenance — which is not automatically suspicious (most packages predate the feature), but it means you cannot verify the source-to-publish chain.</p><p>You can also check from the command line. In any project that has the package installed, run:</p><pre>npm audit signatures</pre><p>This verifies the cryptographic signatures of all installed packages and reports which ones have valid provenance attestation.</p><p>If you want to look at how a package is published, find the .github/workflows/ directory in the repository and open the publish workflow. Look for three things:</p><ul><li>npm publish --provenance - this is what generates the attestation</li><li>id-token: write in the job permissions - this is what allows the OIDC token exchange with npm</li><li>The absence of NPM_TOKEN as a secret - if the workflow uses Trusted Publishing (OIDC), there is no long-lived token to steal</li></ul><p>Finally, look at how GitHub Actions are referenced in the workflow files. Actions referenced as uses: actions/checkout@v4 or uses: actions/setup-node@main are pinned to a mutable tag - the action author can change what that tag points to at any time, and your workflow will silently start running different code. Actions pinned to a full commit SHA (uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd) cannot be changed without updating the reference in the workflow file itself. It is a small thing, but it closes a real attack surface.</p><p>One more thing that runs code on your machine before you have reviewed any of it: install scripts. The preinstall, install, and postinstall hooks in package.json execute the moment you run npm install. Most legitimate packages do not need them - native addons that compile C++ bindings are the main genuine use case. If you see an install script in a package that has no obvious reason for one, that is worth understanding before you proceed.</p><h3>3. Is the CI pipeline real or decorative?</h3><p>A green badge in the README is easy to fake, or rather, easy to earn without it meaning much. A repository can have continuous integration that runs three tests on a single happy path and reports 100% pass rate. That badge is technically accurate and entirely useless.</p><p>What you want to know is whether the CI pipeline actually protects the codebase: whether it would catch a regression, a type error, or a broken edge case before it ships.</p><h3>What to check:</h3><p>Go to the <strong>Actions</strong> tab on GitHub. Look at the workflow runs. Do they trigger on pull_request events, not just on pushes to main? A pipeline that only runs after merging is not protecting anything, it&#39;s just producing a record of what already happened.</p><p>Open a recent merged pull request. Did CI run on it? Did anyone have to wait for it to pass before merging? If the PR was merged 30 seconds after it was opened with no CI run, the pipeline is decoration.</p><p>Find the test configuration file: vitest.config.js, jest.config.js, or equivalent. Look for coverage thresholds. Something like:</p><pre>thresholds: {<br>  lines: 90,<br>  functions: 90,<br>  branches: 90,<br>}</pre><p>If thresholds are configured, the CI pipeline will fail if coverage drops below them. If they are not configured, coverage might be reported but it is not enforced, an author can delete half the tests and the build will still pass.</p><p>Also look at what the tests actually cover. A test/ directory that mirrors the src/ structure, or unit tests co-located with the source files, is a good sign. A single index.test.ts file with a handful of smoke tests is a different thing entirely. You cannot audit the tests in detail, but you can get a sense of whether the author takes them seriously.</p><h3>4. Is the code quality visible?</h3><p>You are not going to audit the entire codebase of every package you consider. That is not realistic. But you can take a quick look at the signals that correlate with code quality, the things an author does or does not do that are visible at a glance and tend to predict whether the package is robust or fragile.</p><h3>What to check:</h3><p>Look at the linting configuration: eslint.config.js, .eslintrc, or equivalent. Does it exist? Is it non-trivial? A blank or near-empty linting config suggests the author is not enforcing consistency or catching obvious mistakes automatically. Linting is table stakes; its absence is a signal.</p><p>Check whether the package ships a well-formed bundle. Look at the exports field in package.json. A modern package should specify named export conditions: import and require if it supports both module systems, or just import if it is intentionally ESM-only, and ideally types if it ships TypeScript declarations. A package that only sets main with no exports field at all was written before this became standard practice. That is not disqualifying, but it tells you something about how current the author&#39;s practice is.</p><p>Look at the package.json for a prepublishOnly script:</p><pre>&quot;prepublishOnly&quot;: &quot;npm run build &amp;&amp; npm run test:ci&quot;</pre><p>This prevents an author from accidentally publishing a broken build or a build that skips tests. It does not protect against malicious publishes, but it does tell you the author has thought about accidental ones.</p><p><strong>For TypeScript packages specifically:</strong> open tsconfig.json and check whether strict: true is set. Strict mode enables null checks, strict function types, and no-implicit-any - a whole class of bugs caught at compile time rather than in production. An author who turns it off has decided some of those bugs are acceptable.</p><p>Also search the repository for any and @ts-ignore. A few uses in genuinely awkward interop situations is normal. Dozens of them scattered through the source code means the TypeScript types are largely cosmetic: the package has the .ts extension but not the type safety.</p><h3>5. What happens when something goes wrong?</h3><p>Every non-trivial package will eventually have a security vulnerability. The question is how the author handles it when it does. Do they respond quickly? Do they disclose responsibly — privately first, then publicly with a fix? Do they document what happened so you can assess whether your version is affected?</p><h3>What to check:</h3><p>Look for a SECURITY.md file in the repository root, or go to github.com/&lt;owner&gt;/&lt;repo&gt;/security/policy. This should tell you how to report a vulnerability privately, a contact method, a timeline for response, and some indication that the author takes disclosures seriously. Its absence does not mean the package is insecure, but it does mean that if you find something, you have no clear path to report it without accidentally disclosing it publicly.</p><p>Go to the <strong>Security</strong> tab on GitHub and look at the Advisories section. Has anything been published? If yes, how was it handled — was the disclosure coordinated, was a fix available when it went public, was the affected version range clearly documented? A well-handled historical advisory is actually a positive signal; it means the author knows what a responsible disclosure process looks like and has followed it.</p><p>Check osv.dev or snyk.io for known vulnerabilities in the package. These aggregate CVEs and GitHub Security Advisories. If the package has known unpatched vulnerabilities, that is something you need to know before installing it.</p><p><a href="https://socket.dev/">Socket.dev</a> goes further than CVE databases. Rather than waiting for a vulnerability to be reported and cataloged, it does behavioral analysis: does this package access the network? Does it touch the filesystem in unexpected ways? Does it contain obfuscated code? Does it have install scripts? It also has a GitHub app that runs this analysis on pull requests and flags new dependencies before they are merged. For packages you are seriously considering, it is worth a quick check.</p><p>If you operate in a high-assurance environment, <a href="https://socket.dev/features/firewall">Socket Firewall</a> is also worth knowing about. Instead of only warning at review time, it enforces package policy at install time and can block known-malicious packages from entering your environment at all. That is usually overkill for hobby projects, but for regulated or security-sensitive systems it can be a strong extra control.</p><p>Finally, look at how quickly past security issues were addressed. A critical vulnerability fixed within days is different from one that sat open for three months. Response time on security issues is one of the clearest signals of how seriously an author takes the responsibility of maintaining a public package.</p><h3>The Checklist</h3><p>Not all of these checks carry equal weight. If you only have time for three things:</p><ol><li><strong>Do you actually need it?</strong> If you can replace it quickly or avoid it entirely, you remove risk instead of managing it.</li><li><strong>Does it have provenance?</strong> This is the clearest signal that the published package is what the author intended to publish.</li><li><strong>Does it have unexplained install scripts?</strong> Code runs on your machine the moment you run npm install.</li></ol><p>If the package is production-critical, add a fourth check: <strong>is the maintainer responsive?</strong> If something goes wrong, you want to know that the person who can fix it will actually fix it.</p><p>Everything else is worth checking when the stakes are higher.</p><h3>Security-critical signals</h3><p>These affect whether the package is safe to install and whether what you are installing is what the author published.</p><p>Signal Where to check Green Red Provenance npmjs.com version page “Provenance” section present and matches repo No provenance, or version published from unknown source Trusted publishing .github/workflows/publish.yml OIDC + --provenance, no NPM_TOKEN NPM_TOKEN secret, manual publish steps Install scripts package.json scripts field None present, or obvious native-addon reason preinstall/postinstall with no clear justification Pinned CI actions .github/workflows/*.yml SHA-pinned third-party actions @v3, @latest, @main</p><h3>Operational maturity signals</h3><p>These tell you how seriously the author takes maintenance, quality, and the long-term cost of depending on their package.</p><p>Signal Where to check Green Red Active maintenance GitHub commits + open issues Commits in last 3 months, issues acknowledged Last commit 2+ years ago, stale issues ignored Dependency footprint npm package page + lockfile tree Few dependencies for package scope, no surprising transitive tree Large transitive tree for a trivial utility Maintainer concentration Commits, releases, issue/PR responses Work distributed across multiple active maintainers One maintainer handles nearly all code, releases, and support Coverage enforced vitest/jest config Thresholds configured at 80%+ No thresholds, or coverage badge that never changes Security policy SECURITY.md or Security tab Clear disclosure process, contact method Missing, or just a generic template with no contact</p><p>A package that is clean on security-critical signals but weak on operational maturity is a calculated risk. A package that fails the security-critical signals is a different category of problem.</p><h3>Risk is not binary</h3><p>None of this is a pass/fail test. It is a risk assessment, and risk depends on context.</p><p>A utility that formats dates in a UI has a different risk profile than an HTTP client sitting between your service and a government API. A dependency that receives 50 million weekly downloads has more eyes on it than one that receives 500. A package from an organization with a dedicated security team is different from one maintained by a single developer in their spare time. None of these are disqualifying conditions on their own — some of the most reliable packages in the ecosystem are maintained by individuals — but they affect how much scrutiny you should apply.</p><p>The goal is not to find a package with a perfect score on every dimension. The goal is to understand what you are accepting when you add it to your project, and to make that decision deliberately rather than by default.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=666a8165d0f9" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-evaluate-an-npm-package-2026-edition-666a8165d0f9">How to Evaluate an npm Package — 2026 Edition</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built a Confluence Crawler]]></title>
            <link>https://levelup.gitconnected.com/how-i-built-a-confluence-crawler-2cf4349ff0b5?source=rss-e13802f71817------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cf4349ff0b5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-tools]]></category>
            <dc:creator><![CDATA[Gabor Koos]]></dc:creator>
            <pubDate>Tue, 26 May 2026 15:17:02 GMT</pubDate>
            <atom:updated>2026-05-26T15:17:02.373Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>TLDR: If you are not interested in the story and just want the tool, go straight to the repository: </em><a href="https://github.com/gkoos/confluence2md"><em>github.com/gkoos/confluence2md</em></a><em>. It is a CLI that crawls Confluence and mirrors it into local Markdown files, including links, comments, and attachments, with support for incremental updates.</em></blockquote><p>This started with a small problem that slowly became expensive: finding things in our company Confluence was harder than it should have been.</p><p>The first issue was human. Search results were noisy; useful pages existed, but they were buried under stale docs, half-duplicated runbooks, and pages whose titles made sense only to the person who wrote them three years ago. When you are in the middle of an incident or trying to understand a legacy service, that’s not ideal.</p><p>The second issue was machine. I was building workflows with LLMs, and Confluence turned out to be a difficult source to work with directly. The content model is not designed around LLM retrieval quality. You can pull pages through APIs, but you still need to normalize structure, preserve context, handle references, and keep updates in sync. If the source layer is messy, everything downstream in your AI pipeline inherits the mess.</p><p>At some point the idea clicked: Markdown is a format that both humans and machines handle well. Humans can read it in any editor, Git can diff it, indexers can process it, LLM pipelines can chunk it. So instead of fighting Confluence at query time, why not mirror the space locally into clean Markdown and treat that mirror as the canonical retrieval layer?</p><p>That was the origin of confluence2md.</p><h3>The First Attempt</h3><p>The first design looked almost too clean: at heart, this is a two-phase crawling problem.</p><p>Phase one: start from one or more seed pages, crawl linked pages to a configurable depth, and convert each page into Markdown.</p><p>Phase two: once you know the complete set of crawled pages, rewrite internal Confluence links into local relative links.</p><p>On paper, this gives you exactly what you want. You avoid guessing link targets while crawling, because rewrite decisions happen only after the graph is known. You keep the logic separable: fetching and conversion in phase one, graph-aware link correction in phase two.</p><p>I expected most of the effort to be around traversal performance and retry logic. Instead, the hardest work appeared in the conversion layer and update model. The crawling algorithm was the easy part.</p><h3>The Pain of Converting Confluence to Markdown</h3><p>Confluence content is not “almost Markdown”: it is stored in a custom storage format that is XML-heavy, macro-heavy, and full of edge cases that are perfectly valid in Confluence but awkward outside of it.</p><p>The first surprise: two pages that look visually similar in Confluence can serialize very differently in storage format. Tables, rich text blocks, code snippets, callouts, and macro output can appear in patterns that are not trivial to flatten into readable Markdown.</p><p>The second surprise was links: “a link to another Confluence page” is not a single thing. You encounter multiple URL shapes, embedded references, path-based forms, query-based forms, and links whose targets are obvious to Confluence but not obvious to your converter. If link extraction fails silently, your local mirror is technically present but functionally broken.</p><p>The third surprise was macros. Macros are one of Confluence’s superpowers, but also one of the biggest export headaches. Some macros map cleanly to Markdown — like constructs. Others are effectively mini-apps embedded in page content. You need a strategy for graceful degradation, not perfect one-to-one fidelity. Your realistic goal is utility, not pixel-perfect cloning.</p><p>The key lesson was that conversion is not just a renderer problem. You are trying to preserve meaning and navigability under a different representation model. Once I accepted that, the implementation got better: normalize aggressively, preserve critical references, and be explicit about what gets transformed versus passed through. And I most likely missed lots of edge cases too. The best I could do was to cover the most common patterns I encountered and make sure the system is resilient to weird content rather than brittle.</p><h3>The Pain of Comments and Attachments</h3><p>After getting page conversion to a usable state, comments and attachments became the next wall.</p><p>Comments matter more than people think. In many organizations, the real decision history lives in comments: caveats, corrections, “do not do this anymore”, and contextual notes that never made it into the page body. Exporting pages without comments creates a technically complete mirror that is practically incomplete.</p><p>Attachments are similar. A runbook that references scripts, screenshots, or PDFs is only useful if those references survive locally. Broken attachment links are almost worse than missing files, because they create false confidence.</p><p>In Confluence APIs, comments and attachments often come through different endpoints and different response shapes. They do not naturally slot into a naive page conversion pass. I had to treat them as first-class parts of the model: fetch, normalize, persist, and rewrite references so local files resolve correctly.</p><p>For comments, the practical choice was to append them into a clear section in each generated Markdown page. That keeps context colocated with the source page while staying machine-readable. For attachments, the rule was simple: if a page references a file and that file is in scope, download it and rewrite the reference to local path. If not, fail visibly.</p><p>Once those rules were in place, the mirror stopped feeling like an “export artifact” and started feeling like a usable documentation corpus.</p><h3>The Pain of Updates</h3><p>Then came the real operational problem.</p><p>A corporate Confluence space can have thousands of pages. Most runs happen because a small subset changed. Full recrawls are wasteful, slow, and expensive in API quota terms. If every update cycle requires reprocessing everything, people stop running updates, and your mirror becomes stale.</p><p>Initially, <a href="https://developer.atlassian.com/cloud/confluence/advanced-searching-using-cql/">CQL</a> looked like the obvious solution. Query pages by modification window, fetch only changed content, done. In theory, elegant. In practice, not sufficient.</p><p>Why it did not hold up in production:</p><p>CQL can tell you what changed according to indexed metadata, but does not magically solve all dependency and consistency issues for a local mirror. Link graphs can shift. Referenced pages may become relevant without being directly changed in a way your query catches at the right time. Some operational edge cases appear around indexing lag and query behavior that are tolerable in UI search but painful for deterministic synchronization.</p><p>I needed a model that prioritized reliable convergence over clever query shortcuts.</p><p>The solution became an incremental strategy backed by checkpoints and deterministic traversal behavior. In short: keep the crawl model stable, detect what is dirty versus reusable, and make update decisions based on explicit processing state rather than optimistic assumptions.</p><p>This is where the dual-checkpoint idea paid off:</p><ul><li>A completed checkpoint tracks what finished processing.</li><li>A successful checkpoint tracks what finished with zero errors.</li></ul><p>That split avoids a common failure mode where partial runs accidentally look “healthy” and poison future incrementals. You can advance progress while still preserving correctness signals.</p><p>The result is that updates mode can reuse clean artifacts aggressively while still rerendering genuinely dirty pages. It is fast enough to run frequently, and predictable enough to trust.</p><h3>Technical Choices</h3><p>Go was a deliberate choice, not just personal preference.</p><p>For CLI tools, Go gives you a very practical package: fast startup, straightforward concurrency, solid standard library, and simple deployment through static binaries. That matters when your users might run the tool in local shells, CI jobs, or mixed developer environments across operating systems.</p><p>The crawling workload itself also maps well to Go’s model. You can manage concurrency and rate limiting cleanly without pulling in heavyweight runtime dependencies. The codebase stays compact and maintainable, which matters for a tool that has to evolve with API quirks.</p><p>On distribution, Go keeps friction low. Cross-platform release artifacts for Linux, macOS, and Windows are easy to automate, and users can download, extract, and run without installing language runtimes. For internal tooling adoption, that is a huge win.</p><h3>From Chaos to a Working Mirror</h3><p>At this point, the major blockers were resolved: conversion fidelity, link rewriting, comments and attachments, and incremental update correctness.</p><p>What emerged is not a one-off exporter but a repeatable mirror process. You can point it at seeds, run a full sync, then run updates regularly and keep a local Markdown representation of your Confluence knowledge that stays useful over time.</p><p>That sounds simple now, but it took several iterations to make “works once” become “works repeatedly under real constraints”.</p><h3>What Is It Good For</h3><p>The first obvious use case is a personal or team second brain. Once content is local Markdown, people can search and browse with tools they already trust instead of relying entirely on Confluence UI behavior.</p><p>The second is offline and operational resilience. If network access is limited, if Confluence is degraded, or if you simply want a local snapshot for incident work, the mirror is immediately useful.</p><p>The third is versioned knowledge management. Putting mirrored docs in Git gives you history, diffs, and visibility into how operational knowledge evolves. That is valuable for onboarding, audits, and postmortems.</p><p>The fourth is machine workflows. Clean local Markdown plus metadata is a far better substrate for indexing and retrieval than trying to resolve everything live against Confluence APIs at query time.</p><p>In practice, this means one mirror can serve multiple audiences: humans browsing docs, engineers diffing changes, and AI systems consuming structured text.</p><h3>Next Steps</h3><p>The obvious next step is to feed the mirror into a <a href="https://en.wikipedia.org/wiki/Retrieval-augmented_generation">RAG pipeline</a>, but that should not mean “one page equals one chunk”. That naive approach throws away structural signals and often hurts retrieval quality.</p><p>A stronger pipeline should chunk by semantic boundaries: headings, sections, and content blocks that correspond to coherent ideas. It should preserve metadata such as page ID, title, source URL, section path, and update timestamp. It should also account for duplicated content, stale snapshots, and link context that may improve answer grounding.</p><p>Another important step is retrieval strategy. Hybrid retrieval often works better than pure vector search for operational docs, because exact keywords (service names, env vars, incident IDs) matter. A good pipeline can combine lexical and semantic retrieval, then rerank with contextual scoring.</p><p>There is also room for change-aware indexing: when the mirror updates, only re-embed affected chunks and keep stable identifiers so downstream stores do not churn unnecessarily.</p><p>In other words, mirroring Confluence to Markdown is not the final destination. It is the foundation. Once that foundation is reliable, higher-level knowledge workflows become much easier to build correctly.</p><h3>Conclusion</h3><p>This project began as frustration with documentation discoverability and ended as a practical data pipeline for both humans and machines.</p><p>The core idea is simple: convert an operationally messy knowledge source into a local, readable, versionable, machine-friendly representation. The implementation was not simple at all, especially around conversion fidelity and incremental correctness, but the payoff is real: a Confluence space you can actually work with.</p><p>If this sounds useful for your team, the tool is open source and ready to run:<br><a href="https://github.com/gkoos/confluence2md">github.com/gkoos/confluence2md</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cf4349ff0b5" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-i-built-a-confluence-crawler-2cf4349ff0b5">How I Built a Confluence Crawler</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Recursion Is Lying to You]]></title>
            <link>https://levelup.gitconnected.com/your-recursion-is-lying-to-you-d2ae5a1177f8?source=rss-e13802f71817------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2ae5a1177f8</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[tail-recursion]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Gabor Koos]]></dc:creator>
            <pubDate>Mon, 18 May 2026 15:41:06 GMT</pubDate>
            <atom:updated>2026-05-18T15:41:06.295Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jc5ucJT-N8EW9g56TLI90A.jpeg" /></figure><p><a href="https://developer.mozilla.org/en-US/docs/Glossary/Recursion">Recursion</a> is one of those ideas developers learn early and trust for years. If the recursive step is simple and the base case is correct, the code feels clean and safe.</p><p>It is elegant for a reason: many problems are naturally recursive, and the code often mirrors how we explain the logic out loud. For tree walks, nested structures, and divide-and-conquer patterns, recursion can be easier to read than explicit loops.</p><p>The catch is physical limits. Even with a correct base case and sound logic, each recursive call still consumes stack space. At some depth, you crash with stack overflow.</p><p>If you read <a href="https://blog.gaborkoos.com/posts/2026-03-28-Your-Debounce-Is-Lying-to-You/">Your Debounce Is Lying to You</a> and <a href="https://blog.gaborkoos.com/posts/2026-03-31-Your-Throttling-Is-Lying-to-You/">Your Throttling Is Lying to You</a>, this is the recursion version of the same pattern: elegant abstraction, hidden operational edge.</p><h3>Problem Setup: Recursion Hits The Wall</h3><p>You can run everything below directly in a browser console. Let’s start simple: a recursive sum of all integers from 1 to n.</p><pre>function sum(n) {<br>  if (n === 0) return 0;<br>  return n + sum(n - 1);<br>}</pre><pre>sum(10); // 55</pre><p>Now push a big input:</p><pre>sum(100000); // RangeError or InternalError: too much recursion in most JS runtimes</pre><p>What just happened? The function is logically correct, but each call to sum stays on the stack until the one below it returns. At depth 100,000 the runtime runs out of stack space and throws. It has nothing to do with the result being wrong, it is purely a physical limit on how many nested frames the runtime can hold at once.</p><h3>The Tail Recursion Rescue Story</h3><p>The usual next step is <a href="https://en.wikipedia.org/wiki/Tail_call">tail call optimization</a>. The idea is simple: make the recursive call the last thing the function does, so the runtime can reuse the same frame instead of pushing a new one.</p><p>Note that sum is <strong>not</strong> tail-recursive, even though the recursive call appears on the last line. After sum(n - 1) returns, there is still pending work: the result must be added to n. <strong>A call is only in tail position when its return value is forwarded immediately, with no pending computation afterward</strong>.</p><p>The tail-recursive version moves that pending state into an accumulator:</p><pre>function sumTR(n, acc = 0) {<br>  if (n === 0) return acc;<br>  return sumTR(n - 1, acc + n);<br>}</pre><pre>sumTR(10); // 55</pre><p>Here sumTR(...) is the very last thing that happens — no pending +, no pending anything. The running total lives in acc, not in waiting stack frames. In theory, a runtime that implements TCO can execute this in constant stack space regardless of depth.</p><p>Now repeat the same stress input:</p><pre>sumTR(100000); // may still throw RangeError!</pre><p>Even with correct tail-recursive structure, many JavaScript runtimes still allocate a new stack frame per call and throw at large depth. This surprises developers who expect TCO to be a universal guarantee. <a href="https://262.ecma-international.org/6.0/#sec-tail-position-calls">ECMAScript 2015</a> formally specified proper tail calls in strict mode, but most engines never adopted the feature consistently. Some shipped it and then walked it back due to performance regressions. Others never implemented it at all. The result is that you cannot assume tail recursion is stack-safe in production JavaScript, even if the code is correctly structured for TCO.</p><h3>A Note on Fibonacci</h3><p><a href="https://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci</a> is the go-to recursion textbook example and it does run into stack limits too, but it carries a second problem that makes it even worse: <strong>exponential time complexity</strong>.</p><pre>function fib(n) {<br>  if (n &lt;= 1) return n;<br>  return fib(n - 1) + fib(n - 2);<br>}</pre><p>Each call branches into two more calls, so the total number of calls grows as O(2ⁿ). fib(30) already makes over a million calls; fib(50) is in the tens of billions. In a browser this freezes the tab long before any stack limit is reached, which makes the failure mode look identical to a stack overflow but have a completely different root cause.</p><p>The tail-recursive version of Fibonacci:</p><pre>function fibTR(n, a = 0, b = 1) {<br>  if (n === 0) return a;<br>  if (n === 1) return b;<br>  return fibTR(n - 1, b, a + b);<br>}</pre><p>This version runs in linear time, but it still risks stack overflow at large n due to the same TCO uncertainty. The exponential version is a red herring for this discussion because it fails for a completely different reason: stack overflow and exponential blowup are two separate problems. They look the same from the outside (the page hangs or crashes) but require completely different fixes.</p><h3>Runtime Reality (At The Time Of Writing)</h3><p>At the time of writing (May 2026), proper tail-call optimization support is not something you can count on across JavaScript runtimes.</p><p>Runtime Engine Proper Tail Calls You Can Rely On? Practical Take Chrome V8 No Do not expect stack-safe tail recursion. Node.js V8 No Tail-recursive code can still overflow. Deno V8 No Same operational expectation as Node/Chrome. Firefox SpiderMonkey No Do not treat tail recursion as a safety guarantee. Safari JavaScriptCore Inconsistent — JSC has shipped and walked back TCO across versions Do not rely on it; behavior has varied enough across releases that it is not a stable guarantee. Bun JavaScriptCore-based Engine-dependent, not a cross-runtime guarantee Verify on exact version; do not assume universal behavior.</p><p>The key point is portability. Tail recursion is a property of function structure, while stack reuse is a property of runtime implementation. Even if one engine behaves better in one version, production JavaScript usually spans multiple targets, and correctness should not depend on optimizer-specific behavior. A function can be perfectly tail-recursive in shape and still consume stack per call in the environments your users actually run.</p><h3>Better Patterns for Production Code</h3><p>Every recursive function can be rewritten iteratively, and that is usually the safest choice in production when input depth can grow. Iteration does not rely on runtime optimizations for stack safety, because it does not consume stack frames per step. This does not mean giving up the recursive mental model. You can still write code that is conceptually recursive but uses an explicit stack or a <em>trampoline</em> to manage control flow without hitting physical limits.</p><pre>function sumIter(n) {<br>  let acc = 0;<br>  for (let i = n; i &gt; 0; i--) acc += i;<br>  return acc;<br>}</pre><pre>sumIter(1000000); // no recursive stack growth</pre><h3>The Trampoline Pattern</h3><p>If you want to keep the recursive structure for readability but need to avoid stack growth, you can use a trampoline: a loop that repeatedly calls a function that returns either a final result or another function to call.</p><pre>function trampoline(fn) {<br>  let result = fn;<br>  while (typeof result === &#39;function&#39;) {<br>    result = result();<br>  }<br>  return result;<br>}</pre><pre>function sumTrampoline(n, acc = 0) {<br>  if (n === 0) return acc;<br>  return () =&gt; sumTrampoline(n - 1, acc + n);<br>}</pre><pre>trampoline(() =&gt; sumTrampoline(100000)); // no stack overflow, still tail-recursive in spirit</pre><p>Trampolines trade stack safety for additional function allocations and dispatch overhead, so they are most useful when preserving recursive structure matters more than raw performance.</p><p>This approach scales in a way that does not depend on runtime tail-call behavior, which is exactly what you want when input depth can grow. If recursive structure improves readability for a particular problem, these techniques let you keep that mental model with explicit tradeoffs instead of implicit runtime assumptions.</p><p>A useful rule of thumb is to keep recursion for small, bounded depths that you control, and <strong>switch to iterative control flow as soon as depth is user-driven, data-driven, or operationally uncertain</strong>. For hot paths, benchmark both styles, but do not base correctness on assumed TCO.</p><h3>Practical Checklist</h3><ul><li>Never assume TCO in JavaScript for production-critical paths.</li><li>Test with realistic upper bounds, not toy input sizes.</li><li>Favor iterative implementations when depth can grow.</li><li>Treat recursion as a readability tool, not a stack-safety guarantee.</li></ul><h3>Conclusion</h3><p>Recursion itself is not the enemy, unverified runtime assumptions are. Tail-recursive shape does not automatically make JavaScript stack-safe, and that gap is where many “works on my machine” surprises come from in production.</p><p>Use recursion where it improves clarity and depth is genuinely bounded. When depth can grow or input is outside your control, prefer iterative designs that make stack behavior explicit and portable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2ae5a1177f8" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/your-recursion-is-lying-to-you-d2ae5a1177f8">Your Recursion Is Lying to You</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decorating Promises Without Breaking Them]]></title>
            <link>https://levelup.gitconnected.com/decorating-promises-without-breaking-them-435bebc1670e?source=rss-e13802f71817------2</link>
            <guid isPermaLink="false">https://medium.com/p/435bebc1670e</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Gabor Koos]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 15:59:35 GMT</pubDate>
            <atom:updated>2026-04-20T15:59:35.284Z</atom:updated>
            <content:encoded><![CDATA[<p>I wanted .get().json().</p><p>This came up while building convenience plugins for <a href="https://github.com/fetch-kit/ffetch">ffetch</a>, a lightweight fetch wrapper focused on keeping native semantics intact. Libraries like <a href="https://github.com/sindresorhus/ky">ky</a> solve the ergonomics problem by introducing a custom Response-like object, which works great until something outside the library expects a plain Response. I wanted a different path.</p><p>Not because I needed it, strictly speaking. await fetch(&#39;/api/todos/1&#39;) followed by await response.json() works perfectly fine. But after the hundredth time writing that two-step dance across a codebase, you start reaching for something cleaner.</p><p>The usual answer is a wrapper class or a custom Promise subclass. Both work, but both carry a hidden cost: you are now responsible for whatever happens when you swap out the native Response for your own abstraction. instanceof checks break. Framework integrations that inspect the response directly can behave unexpectedly. And the moment someone passes your custom object into something that expected a plain Response, you have a problem.</p><p>I wanted a different answer. This is about that.</p><h3>The Goal</h3><p>The cleaner call site I was after looks like this:</p><pre>const todo = await client.get(&#39;/api/todos/1&#39;).json()</pre><p>Two requirements in tension. On one hand, .json() should be reachable without a separate await and variable assignment. On the other hand, await client.get(&#39;/api/todos/1&#39;) should still resolve to a genuine, unmodified Response — not a wrapper, not a subclass, not a Proxy.</p><p>Most approaches collapse this tension by picking one side. Either you get ergonomics and lose native semantics, or you keep native semantics and write the two-liner. The question is whether you can actually have both.</p><h3>The Mechanism</h3><p>A Promise in JavaScript is an object. Like any object, you can assign properties to it at runtime.</p><p>That is the whole trick. Instead of wrapping the Promise or replacing it with something else, you decorate it in place: attach the convenience methods directly as properties on the Promise instance returned by the fetch call.</p><p>Here is what that looks like in practice:</p><pre>function attachResponseShortcuts(promise: Promise&lt;Response&gt;) {<br>  const descriptor = (fn: (r: Response) =&gt; unknown) =&gt; ({<br>    value: function (this: Promise&lt;Response&gt;) {<br>      return this.then(fn)<br>    },<br>    enumerable: false,<br>    writable: false,<br>    configurable: false,<br>  })<br><br>  Object.defineProperties(promise, {<br>    json:        descriptor((r) =&gt; r.json()),<br>    text:        descriptor((r) =&gt; r.text()),<br>    blob:        descriptor((r) =&gt; r.blob()),<br>    arrayBuffer: descriptor((r) =&gt; r.arrayBuffer()),<br>    formData:    descriptor((r) =&gt; r.formData()),<br>  })<br><br>  return promise<br>}</pre><p>A few things are happening here that are worth unpacking.</p><p><strong>Property descriptors, not assignment.</strong> Using Object.defineProperties instead of promise.json = fn gives explicit control over the property attributes. Each method is enumerable: false which means it stays invisible to for...in loops, Object.keys, and JSON serialization. (They will still show up in browser DevTools when you expand the object and in Object.getOwnPropertyDescriptors(), but that is useful for debugging anyway — the point is they do not pollute standard iteration or JSON output.) It is writable: false and configurable: false, so it cannot be accidentally overwritten or deleted at runtime. This is intentional: without these locks, a careless reassignment (promise.json = myMock) would silently break the convenience layer for everyone holding that promise. The tradeoff is that it also prevents <em>intentional</em> overrides — if you need to mock .json() in a test, you cannot. This is a deliberate choice favoring safety over flexibility.</p><p><strong>Forwarding, not reimplementing.</strong> Each method is a one-liner that calls .then() on the Promise itself (via this) and delegates immediately to the native Response method. The parsing behavior, error handling, and body consumption rules all come from the browser or runtime. We are not reimplementing anything. The methods are thin pass-throughs.</p><p><strong>The Promise remains a Promise.</strong> await client.get(&#39;/api/todos/1&#39;) still resolves to the same native Response it always did. The added methods live on the instance itself, not on the prototype chain like native methods do — they are invisible properties on the Promise object. They do not affect the resolution value, the prototype chain, or any standard Promise behavior. (This is a meaningful difference: calls to promise.constructor or Object.getPrototypeOf(promise) see an untouched Promise, not a subclass or wrapper.)</p><h3>Idempotency</h3><p>If multiple plugins or hooks might touch the same promise — which is the case in a plugin-based architecture — you need to guard against decorating the same object twice. Object.defineProperties will throw if you try to redefine a non-configurable property.</p><p>A marker handles this, and this is one of the rare cases where a Symbol is genuinely useful: it provides collision-free identity that no other code can accidentally claim.</p><pre>const DECORATED = Symbol(&#39;ffetch.responseShortcutsDecorated&#39;)<br><br>function attachResponseShortcuts(promise: Promise&lt;Response&gt;) {<br>  if ((promise as any)[DECORATED]) return promise<br>  // ... defineProperties ...<br>  Object.defineProperty(promise, DECORATED, { value: true, enumerable: false })<br>  return promise<br>}</pre><p>The marker is invisible to Object.keys, Object.getOwnPropertyNames, and iteration — only findable via Object.getOwnPropertySymbols if you explicitly look for it. Decoration becomes a safe, idempotent operation regardless of call order, with zero risk of collision with any third-party code or browser internals.</p><h3>Typing It</h3><p>TypeScript does not know about properties you attach at runtime, so you have to tell it. The cleanest model here is an intersection type: the call site return type is Promise&lt;Response&gt; intersected with the shortcut interface.</p><pre>interface ResponseShortcuts {<br>  json&lt;T = unknown&gt;(): Promise&lt;T&gt;<br>  text(): Promise&lt;string&gt;<br>  blob(): Promise&lt;Blob&gt;<br>  arrayBuffer(): Promise&lt;ArrayBuffer&gt;<br>  formData(): Promise&lt;FormData&gt;<br>}<br><br>type DecoratedPromise = Promise&lt;Response&gt; &amp; ResponseShortcuts</pre><p>This is honest. DecoratedPromise really is both things simultaneously: a standard Promise that resolves to Response, and an object that happens to have five extra methods. The intersection expresses both without hiding either.</p><p>When the library does not have the plugin installed, the return type is Promise&lt;Response&gt; with no extras. When it does, it is Promise&lt;Response&gt; &amp; ResponseShortcuts. TypeScript catches you if you try to call .json() without the plugin, and it autocompletes when you have it. No runtime cost either way.</p><h3>Tradeoffs Worth Naming</h3><p>This technique is additive, not transformative. That is its strength and its limit.</p><p>It cannot change what Response contains. If you call .json() on a response that came back with a text/html body, you get the same parse error you would have got with the two-liner. The shortcut is a convenience, not a type-safe schema layer.</p><p>Body consumption rules are also unchanged. Response bodies can only be read once — calling .json() and then separately awaiting the response and calling .json() again will fail, exactly as native fetch would. Decoration does not change the underlying object.</p><p>The TypeScript types also do not capture body consumption state. If the response body was already read (e.g., by an upstream handler or middleware), calling .json() will throw at runtime. TypeScript will not catch this — the types express the structural shape of the methods, not the preconditions for their success. This is a general limitation of modeling Response state in TypeScript, not specific to this technique, but it is worth knowing: the intersection type Promise&lt;Response&gt; &amp; ResponseShortcuts is a shape guarantee, not a behavioral one.</p><p>And if you or your team prefer strict explicitness — no augmented promise objects, all parsing explicit — then this pattern is probably not the right call. It is a style choice. The native two-liner is perfectly readable, just longer.</p><p>Where this genuinely shines is in a plugin or middleware architecture where you want to offer ergonomics as opt-in behavior. The baseline remains untouched, native fetch-compatible, and requires zero knowledge of the convenience layer to work with.</p><h3>The Broader Point</h3><p>What I find interesting about this technique is that it demonstrates a property of JavaScript that is easy to forget: objects are open. A Promise is not a sealed system. You can extend it in flight without wrapping or subclassing, and without disturbing the contract anyone else has with it.</p><p>Preserve native behavior first. Layer ergonomics second, explicitly, and as close to invisibly as possible.</p><p>If the shortcut is there and you use it, you gain a line. If the shortcut is there and you do not use it, nothing changes. That is the shape of a good opt-in.</p><p>The full implementation lives in <a href="https://github.com/fetch-kit/ffetch">ffetch</a> if you want to see it in context. But the technique itself applies anywhere you need to decorate promises with convenience methods.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=435bebc1670e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/decorating-promises-without-breaking-them-435bebc1670e">Decorating Promises Without Breaking Them</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Debounce Is Lying to You]]></title>
            <link>https://javascript.plainenglish.io/your-debounce-is-lying-to-you-0afd64b0d44f?source=rss-e13802f71817------2</link>
            <guid isPermaLink="false">https://medium.com/p/0afd64b0d44f</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Gabor Koos]]></dc:creator>
            <pubDate>Sun, 29 Mar 2026 18:04:58 GMT</pubDate>
            <atom:updated>2026-03-29T18:04:58.333Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.geeksforgeeks.org/javascript/debouncing-in-javascript/">Debounce</a> is one of those patterns every frontend developer learns early and keeps using forever.</p><p>At its core, debouncing does one thing well: it coalesces a burst of calls into one invocation after a quiet window. That is a great fit for noisy UI signals.</p><p>Its most familiar use case is autocomplete, but the same pattern applies to resize handlers, scroll listeners, live validation, filter controls, and telemetry hooks.</p><p>A typical implementation looks like this:</p><pre>function debounce(fn, delay) {<br>    let timer;<br>    return (...args) =&gt; {<br>        clearTimeout(timer);<br>        timer = setTimeout(() =&gt; fn(...args), delay);<br>    };<br>}<br><br>const search = debounce(async (q) =&gt; {<br>    const res = await fetch(`/api/search?q=${q}`);<br>    const data = await res.json();<br>    render(data);<br>}, 300);</pre><p>It looks disciplined. It feels efficient. It ships fast.</p><p>And this is where the title comes from.</p><p>The issue is not debounce itself. The issue is this vanilla debounce + fetch pattern once real network behavior enters the picture.</p><p>It gives the feeling that requests are “under control,” but it does not control request lifecycle: response ordering, cancellation of stale work, or failure behavior.</p><p>That is why it feels like debounce is “lying” in production: the UI looks smoothed, while the network layer is still fragile.</p><p>In this article, we will keep debounce for what it is good at (UI smoothing), then harden the request path with cancellation, retries, and better error handling.</p><h3>The Illusion of “Fixed” Behavior</h3><p>Debounce is convincing: you type quickly, the UI triggers fewer calls, and the network tab looks quieter. It <em>feels</em> like the system is now stable. But in production, under real network conditions, many things can go wrong. You will experience stale data, wasted requests, silent failures and other unexpected behaviors.</p><p>This is true for any network request, but debounce adds another layer of complexity: it makes the UI look smooth while the network can still be unpredictable. This mismatch can create a false sense of security.</p><p>Debounce itself only guarantees one thing:</p><blockquote><em>“I won’t call this function too often.”</em></blockquote><p>Debounce smooths input frequency, not request lifecycle. It does <strong>not</strong> guarantee:</p><ul><li>Responses arrive in order.</li><li>Stale requests stop running.</li><li>Failures are handled consistently.</li></ul><p>In other words: it is <strong>a UI pattern, not a network pattern</strong>. So you have to make sure the underlying network layer is robust enough to handle real-world conditions. Before we examine what can go wrong, let’s set the stage!</p><h3>The Companion Code</h3><p>To make these problems visible, we have a companion demo app with a single text input where every keystroke triggers a debounced request to /api/echo?q=&lt;input&gt;. The backend is an Express server that returns { query, timestamp }, and the frontend appends each response to a div as query@timestamp. The stack is minimal: Node.js + Express on the backend, and plain HTML/CSS/JavaScript in the browser.</p><p>Clone the repo and install dependencies:</p><pre>git clone https://github.com/gkoos/article-debouncing.git<br>cd article-debouncing<br>npm install</pre><p>Then start the app:</p><pre>npm start</pre><p>And navigate to <a href="http://localhost:3000/">http://localhost:3000</a> in your browser. You will see something like this:</p><p>Now, as you type in the input field, you will see the responses coming back in the list below:</p><p>The UI also shows toast notifications for request success and failure, which will become relevant in later sections.</p><p>This is our baseline setup, it demonstrates the basic pattern. There is a 300ms debounce on the input, and the backend immediately responds with the query and a timestamp. The UI appends each response to the list.</p><h3>Problem 1: Race Conditions (aka Stale UI)</h3><p>On your local machine, everything is fast and smooth. But in production, network conditions are unpredictable. Requests can take varying amounts of time to complete, so there is no guarantee that responses will arrive in the same order they were sent. Let’s see what happens if we add random delays to the server response to simulate real network conditions.</p><p>Check out the 01-stale-requests branch and restart the server:</p><pre>git checkout 01-stale-requests<br>npm start</pre><p>We added a middleware that introduces a random delay of 0–1000ms for each request. Now, when you type quickly, you might see responses arriving out of order:</p><p>We typed 12345678, but the UI shows 1234567! The response for 7 came back <em>after</em> 8, so the UI is now stale. This is a classic race condition, and debounce itself does not prevent it. The UI is showing results for an older query, which can lead to confusion and errors in a real application.</p><p>How to fix this? We need to ensure that only the latest request’s response is processed, and any previous requests are either cancelled or ignored. We could implement a simple version of this by keeping track of the latest query and ignoring responses that don’t match it. But that would still allow all requests to run, which is inefficient. A better approach is to use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/AbortController">AbortController</a> API to cancel stale requests, so they don&#39;t consume resources or trigger side effects when they complete.</p><p>AbortController is a browser-native API. You create a controller, pass its signal to fetch, and call abort() whenever you want to cancel the request. The fetch will throw an AbortError, which you can catch and ignore since it&#39;s expected.</p><p>Here is the updated debounce callback with cancellation:</p><pre>let controller;<br><br>const debouncedFetch = debounce(async (q) =&gt; {<br>  if (!q) return;<br>  if (controller) controller.abort();<br>  controller = new AbortController();<br>  try {<br>    const response = await fetch(`/api/echo?q=${encodeURIComponent(q)}`, {<br>      signal: controller.signal<br>    });<br>    const data = await response.json();<br>    // render data...<br>  } catch (err) {<br>    if (err.name === &#39;AbortError&#39;) return;<br>    // handle real errors...<br>  }<br>}, 300);</pre><p>Two things changed:</p><ul><li>Before each request, we abort any in-flight request from the previous call and create a fresh controller.</li><li>After catching an error, we check if it’s an AbortError and return early: these are expected and not real failures.</li></ul><p>The result: in normal flow, only the last request in a typing burst ever completes. Previous ones are cancelled at the network level, not just ignored after the fact. (For absolute safety, you can also guard the render step with a request ID check. This covers the tiny edge window where a response resolves right before a newer request aborts the previous one.)</p><h3>Problem 2: Network Failures</h3><p>The network is not only unpredictable in terms of latency, but also in terms of reliability. Sometimes a request can fail that would have succeeded if retried. This can be due to transient server issues like network congestion, temporary spikes in load, or database timeouts. If we want a more robust user experience, we need to handle these failures gracefully.</p><p>Let’s simulate random failures in our backend. Check out the 02-failures branch and restart the server:</p><pre>git checkout 02-failures<br>npm start</pre><p>This version of the server adds a random failure mechanism: each request has a 40% chance to fail with a 500 error. Now this may be too aggressive, but it will help us see the problem clearly. When you type in the input field, you will see some requests fail:</p><p>Well, that’s not good. First, our UI shows undefined@undefined when a request fails. That happens because the server returns { error: &#39;Internal Server Error&#39; } on a 500, so data.query and data.timestamp are both undefined. Vanilla fetch doesn&#39;t throw on HTTP error status codes: it only rejects on network failures. So we need to check response.ok ourselves:</p><pre>const response = await fetch(`/api/echo?q=${encodeURIComponent(q)}`, {<br>  signal: controller.signal<br>});<br>if (!response.ok) throw new Error(`HTTP ${response.status}`);<br>const data = await response.json();</pre><p>Now a 500 throws before we ever touch the body, the catch handles it, and the error toast shows instead of broken output.</p><p>But that’s just the start. In a real app, you would want to implement some retry logic for transient failures. For example, you could automatically retry a failed request up to 3 times with exponential backoff. This way, if a request fails due to a temporary issue, it has a chance to succeed without the user having to do anything.</p><p>To implement this manually you’d need to write retry loops, track attempt counts, implement backoff timing, and make sure none of it fires after a cancellation. That’s not trivial, and it’s not the interesting part of your app, so let’s use a library for that.</p><p>@fetchkit/ffetch is a thin wrapper around fetch that handles exactly this. We&#39;ll use it for the retry behavior in our demo.</p><p>There are good alternatives in this space (for example ky, axios, or a custom wrapper). I chose ffetch here because it keeps a fetch-compatible API surface and handles abort-aware retries cleanly.</p><p>Since this is a minimal demo with no build step, we load it directly from a CDN rather than installing it. In a real project you’d npm install @fetchkit/ffetch and import it normally, but here a single import line is enough:</p><pre>import { createClient } from &#39;https://esm.sh/@fetchkit/ffetch&#39;;<br><br>const api = createClient({<br>  retries: 3, // retry up to 3 times on failure<br>  shouldRetry: (ctx) =&gt; ctx.response?.status &gt;= 500, // only retry on 5xx errors<br>});</pre><p>api has the exact same call signature as fetch: same arguments, same return type. You drop it in as a replacement:</p><pre>const response = await api(`/api/echo?q=${encodeURIComponent(q)}`, {<br>  signal: controller.signal<br>});</pre><p>What this buys us in this specific scenario:</p><ul><li><strong>retries: 3</strong> — if the server returns a 500, ffetch retries up to 3 more times before giving up</li><li><strong>shouldRetry</strong> — we only retry on 5xx; anything else (network error, abort) propagates immediately</li><li><strong>abort-aware backoff</strong> — if controller.abort() fires during the delay between retries, the wait exits immediately and the abort propagates; no stale work keeps running in the background</li></ul><p>That last point is quite convenient here. Without it, aborting a request mid-retry would cut the active fetch but leave the backoff timer running, which would then fire another fetch attempt that instantly aborts. Now we handle this correctly.</p><p>There’s one more thing we can clean up. Because the native fetch does not throw on HTTP error status codes (one of the pain points of the API), we had to add a manual check:</p><pre>if (!response.ok) throw new Error(`HTTP ${response.status}`);</pre><p>ffetch can handle this too. With the throwOnHttpError: true config option, any HTTP error response throws automatically, no manual check needed.</p><pre>const api = createClient({<br>  retries: 3,<br>  shouldRetry: (ctx) =&gt; ctx.response?.status &gt;= 500,<br>  throwOnHttpError: true,<br>});</pre><p>Now the fetch call is just:</p><pre>const response = await api(`/api/echo?q=${encodeURIComponent(q)}`, {<br>  signal: controller.signal<br>});<br>const data = await response.json();</pre><p>The catch block still handles everything - HTTP errors, network failures, real errors - without any extra branching in the happy path.</p><p>The final implementation can be found in the 03-fixed branch:</p><pre>git checkout 03-fixed<br>npm start</pre><p>For reference, the full code for the debounce callback with ffetch can be found <a href="https://github.com/gkoos/article-debouncing/blob/03-fixed/src/public/index.html">here</a>.</p><h3>Conclusion</h3><p>Debounce is not the problem. The problem is treating it as a complete solution for network control when it only handles one dimension of it: call frequency. It is a very useful pattern for smoothing out noisy UI signals, but it does not handle the complexities of real network behavior. To build a robust application, you need to complement debounce with proper request lifecycle management: cancellation of stale requests, retries with backoff for transient failures, and consistent error handling. This way, you can ensure that your UI remains not only responsive but also accurate even under unpredictable network conditions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0afd64b0d44f" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/your-debounce-is-lying-to-you-0afd64b0d44f">Your Debounce Is Lying to You</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Pagination to Improve GraphQL Performance]]></title>
            <link>https://levelup.gitconnected.com/using-pagination-to-improve-graphql-performance-615ce1944c4f?source=rss-e13802f71817------2</link>
            <guid isPermaLink="false">https://medium.com/p/615ce1944c4f</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Gabor Koos]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 16:19:35 GMT</pubDate>
            <atom:updated>2026-03-23T16:19:35.780Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2sIY1TVge8ueWZSx5LNlWg.jpeg" /></figure><p>GraphQL makes it easy to request exactly the data you need, but that flexibility can quickly turn into a performance problem when queries return large result sets. A single field that returns “all items” may work fine during development, yet silently degrade into slow responses, high memory usage, or even process crashes as data volume grows.</p><p>This is especially relevant in <strong>Node.js</strong> backends, where resolvers often materialize entire result sets in memory before returning a response. Fetching a large number of records in a single GraphQL query doesn’t just increase response time, it can put sustained pressure on the event loop, garbage collector, and overall process stability.</p><p>Pagination is the standard solution to this problem, but not all pagination strategies behave the same under load.</p><p>In this article, we’ll look at three common approaches to pagination in a Node.js GraphQL API: fetching everything at once, <em>offset-based pagination</em>, and <em>cursor-based pagination</em>. Rather than treating pagination as a purely theoretical concern, we’ll instrument each approach and observe how it affects response times and memory usage.</p><p>We’ll build a minimal GraphQL API using <strong>Express</strong> and <strong>Apollo Server</strong>, backed by a SQLite database seeded with 500,000 products. You’ll see how naive queries show up as slow requests and memory spikes, how offset-based pagination improves things but still has hidden costs, and why cursor-based pagination is — spoiler alert! — the recommended pattern for stable, scalable GraphQL APIs.</p><h3>Setting Up the Project</h3><p>To keep things simple, the article is accompanied by a runnable demo repository. The project is a small Node.js GraphQL API, with a SQLite backend populated with 500,000 products.</p><h3>Prerequisites</h3><p>To follow along, you’ll only need:</p><ul><li>Node.js 18+</li><li>npm</li><li>A basic understanding of GraphQL and Node.js development</li></ul><h3>Installation</h3><p>Start by cloning the repository and installing dependencies:</p><pre>git clone https://github.com/gkoos/article-graphql-pagination<br>cd article-graphql-pagination<br>npm install</pre><p>The project uses Prisma with SQLite and includes a seed script that creates 500,000 product records to demonstrate performance differences between pagination strategies.</p><p>Run the following commands to initialize and seed the database:</p><pre>npx prisma generate<br>npm run prisma:migrate<br>npm run prisma:seed</pre><p>This will create the database schema and populate it with realistic-looking product data.</p><h3>Running the Server</h3><p>Once setup is complete, start the server:</p><pre>npm start</pre><p>The GraphQL API will be available at http://localhost:4000, where you can explore the schema and run queries using the Apollo Sandbox.</p><h3>The Problem: Fetching All Data at Once</h3><p>Before introducing pagination, let’s start with the simplest approach: returning <em>all</em> records from a GraphQL field in a single request.</p><p>In our app, the allProducts query does exactly that. It loads all 500,000 products from the database and returns them as a single response. This kind of query is easy to write, easy to understand, and surprisingly common in early GraphQL schemas.</p><p>Here’s the resolver behind it:</p><pre>// src/resolvers.js<br>...<br>allProducts: async () =&gt; {<br>    console.time(&#39;allProducts&#39;);<br>    const products = await prisma.product.findMany({<br>    orderBy: { id: &#39;asc&#39; }<br>    });<br>    console.timeEnd(&#39;allProducts&#39;);<br>    console.log(`Fetched ${products.length} products (ALL)`);<br>    return products;<br>},</pre><p>There’s nothing technically wrong with this resolver. It does exactly what it promises. The problem is <em>scale</em>.</p><h3>Running the Fetch-All Query</h3><p>Open the GraphQL Sandbox at http://localhost:4000 and run the following query:</p><pre>query allProducts {<br>  allProducts {<br>    id<br>    name<br>    price<br>    category<br>  }<br>}</pre><p>Depending on your machine, the query may take several seconds to complete. You’ll also notice that the response payload is very large: hundreds of thousands of objects serialized into JSON and sent over the wire in one go.</p><p>In your terminal, you should see a log message like this:</p><pre>allProducts: 2.817s<br>Fetched 500000 products (ALL)</pre><p>A single request:</p><ul><li>Executes a large database query</li><li>Allocates memory for all 500,000 rows</li><li>Serializes the entire result set before responding</li></ul><p>In a real production API, this kind of request can quickly become problematic under concurrent load.</p><h3>Why This Pattern Breaks Down</h3><p>Even in this local setup, you can observe:</p><ul><li>High response times (often several seconds)</li><li>Significant memory usage spikes during request processing</li></ul><p>Because the resolver loads the entire dataset eagerly, the cost of this query <strong>scales linearly with the number of rows in the table</strong>. As the dataset grows, so does response time, memory pressure, and GC activity in the Node.js process.</p><p>This is one of those things that often goes unnoticed during development, but becomes very visible once real data and real traffic hit the system.</p><p>Fetching all data at once has a few fundamental problems:</p><ul><li><strong>Unbounded results</strong>: There’s no upper limit on how much data a client can request.</li><li><strong>Poor memory characteristics</strong>: Large result sets must be held in memory until the response is sent.</li><li><strong>Unpredictable performance</strong>: Response time grows with dataset size, not request intent.</li><li><strong>Easy to abuse</strong>: A single client can unintentionally (or intentionally) stress the backend.</li></ul><p><strong>Pagination</strong> exists to put boundaries around this behavior.</p><h3>Naive Offset-Based Pagination</h3><p>A natural first step after realizing that fetching everything at once doesn’t scale is to introduce <em>offset-based pagination</em>. This approach limits the number of records returned per request and allows clients to “page through” results using a combination of limit and offset.</p><p>Offset-based pagination is simple to implement and easy to reason about, which makes it a common choice in REST APIs and an equally common first attempt in GraphQL.</p><h3>Implementing Offset Pagination</h3><p>In our demo project, the productsOffset query exposes this pattern:</p><pre>// src/resolvers.js<br>...<br>productsOffset: async (_, { limit, offset }) =&gt; {<br>    console.time(&#39;productsOffset&#39;);<br>    if (limit &gt; 100) {<br>        limit = 100; // enforce a maximum limit to prevent abuse<br>    }<br>    const products = await prisma.product.findMany({<br>    take: limit,<br>    skip: offset,<br>    orderBy: { id: &#39;asc&#39; }<br>    });<br>    console.timeEnd(&#39;productsOffset&#39;);<br>    console.log(`Fetched ${products.length} products (offset: ${offset}, limit: ${limit})`);<br>    return products;<br>},</pre><p>One thing that’s important to note here is if we don’t limit the number of records returned, we could still end up fetching everything at once. <strong>Always implement a server-side maximum limit to prevent abuse</strong>.</p><p>The resolver uses Prisma’s take and skip options to implement limit and offset behavior. Clients can specify how many records they want (limit) and where to start (offset).</p><p>The corresponding GraphQL query looks like this:</p><pre>query productsOffset {<br>  productsOffset(limit: 20, offset: 0) {<br>    id<br>    name<br>    price<br>    category<br>  }<br>}</pre><p>Instead of returning all 500,000 products, this query fetches just a small window of results. Clients can request subsequent pages by increasing the offset value.</p><h3>Observing the Improvement</h3><p>Run the offset-based query a few times from the GraphQL Sandbox, changing the offset to simulate paging through the dataset.</p><p>In your terminal, you should see logs like this:</p><pre>productsOffset: 17.44ms<br>Fetched 20 products (offset: 0, limit: 20)</pre><p>Compared to the fetch-all approach, you should immediately notice:</p><ul><li>Much faster response times</li><li>Shorter database query time</li><li>Lower overall memory usage per request</li></ul><p>By limiting how many records are loaded and serialized, offset-based pagination dramatically reduces the per-request cost. Even under load, this approach is far more stable than returning everything at once.</p><h3>The Hidden Cost of Offsets</h3><p>While offset-based pagination is a clear improvement, it comes with a less obvious downside.</p><p>As the offset value increases, <strong>the database still needs to scan past the skipped rows to reach the requested page</strong>. For small offsets this isn’t a problem, but deeper pages can become increasingly expensive, especially on large tables.</p><p>Let’s query the last page of products:</p><pre>query productsOffset {<br>  productsOffset(limit: 20, offset: 499980) {<br>    id<br>    name<br>    price<br>    category<br>  }<br>}</pre><p>Run this query and observe the terminal logs:</p><pre>productsOffset: 1.055s<br>Fetched 20 products (offset: 499980, limit: 20)</pre><p>In this particular case, the first query took 17ms, while the last page took more than a second!</p><p>From the client’s perspective, this query looks almost identical to fetching the first page, but from the database’s perspective, it may involve scanning hundreds of thousands of rows before returning just 20.</p><h3>Why This Matters in GraphQL APIs</h3><p>Offset-based pagination also has semantic issues in GraphQL:</p><ul><li><strong>Unstable pagination</strong>: Inserts or deletes can shift offsets, causing clients to skip or duplicate items.</li><li><strong>No natural continuation</strong>: Clients must manage offsets manually.</li><li><strong>Poor fit for infinite scrolling</strong>: Large offsets become increasingly inefficient.</li></ul><p>These limitations are why offset-based pagination is generally considered a transitional solution in GraphQL APIs.</p><h3>Cursor-Based Pagination</h3><p>Offset-based pagination improves performance by limiting result size, but it still becomes less efficient as clients paginate deeper into a dataset. In GraphQL APIs, the recommended alternative is <strong>cursor-based pagination</strong>, where each page starts from a known position instead of skipping an arbitrary number of rows.</p><p>Cursor-based pagination is a better fit for large datasets because its <strong>performance depends on page size, not page number</strong>.</p><h3>Implementing Cursor-Based Pagination</h3><p>In this project, cursor-based pagination is implemented using Prisma’s native cursor support. Each product’s id is encoded into an opaque cursor, which the client passes back when requesting the next page.</p><p>At a high level, the resolver:</p><ol><li>Decodes the after cursor (if present)</li><li>Uses it as a database cursor</li><li>Fetches first + 1 records to determine if another page exists</li><li>Builds a connection-style response with edges and pageInfo</li></ol><p>Here is the resolver implementation:</p><pre>// src/resolvers.js<br>// Helper function to encode cursor<br>function encodeCursor(id) {<br>  return Buffer.from(id.toString()).toString(&#39;base64&#39;);<br>}<br><br>// Helper function to decode cursor<br>function decodeCursor(cursor) {<br>  return parseInt(Buffer.from(cursor, &#39;base64&#39;).toString(&#39;ascii&#39;));<br>}<br>...<br>productsCursor: async (_, { first = 20, after }) =&gt; {<br>    console.time(&#39;productsCursor&#39;);<br>    <br>    const cursor = after ? { id: decodeCursor(after) } : undefined;<br>    <br>    // Fetch one extra to determine if there&#39;s a next page<br>    const products = await prisma.product.findMany({<br>    take: first + 1,<br>    ...(cursor &amp;&amp; {<br>        skip: 1, // Skip the cursor itself<br>        cursor: cursor<br>    }),<br>    orderBy: { id: &#39;asc&#39; }<br>    });<br>    const hasNextPage = products.length &gt; first;<br>    const edges = products.slice(0, first).map(product =&gt; ({<br>    cursor: encodeCursor(product.id),<br>    node: product<br>    }));<br>    const pageInfo = {<br>    hasNextPage,<br>    hasPreviousPage: !!after,<br>    startCursor: edges.length &gt; 0 ? edges[0].cursor : null,<br>    endCursor: edges.length &gt; 0 ? edges[edges.length - 1].cursor : null<br>    };<br>    const totalCount = await prisma.product.count();<br>    console.timeEnd(&#39;productsCursor&#39;);<br>    console.log(`Fetched ${edges.length} products (cursor-based, after: ${after || &#39;start&#39;})`);<br>    return {<br>    edges,<br>    pageInfo,<br>    totalCount<br>    };<br>},</pre><p>This approach ensures that each query resumes from a precise position in the dataset rather than scanning past thousands of rows.</p><h3>Querying with Cursors</h3><p>To fetch the first page of products:</p><pre>query cursorProductsFirst {<br>  productsCursor(first: 20) {<br>    edges {<br>      cursor<br>      node {<br>        id<br>        name<br>        price<br>        category<br>      }<br>    }<br>    pageInfo {<br>      hasNextPage<br>      hasPreviousPage<br>      startCursor<br>      endCursor<br>    }<br>    totalCount<br>  }<br>}</pre><p>In the terminal, you’ll see something like:</p><pre>productsCursor: 39.993ms<br>Fetched 20 products (cursor-based, after: start)</pre><p>And the response will be:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;productsCursor&quot;: {<br>      &quot;edges&quot;: [<br>        {<br>          &quot;cursor&quot;: &quot;MQ==&quot;,<br>          &quot;node&quot;: {<br>            &quot;id&quot;: 1,<br>            &quot;name&quot;: &quot;Product 1&quot;,<br>            &quot;price&quot;: 581.7240166646505,<br>            &quot;category&quot;: &quot;Clothing&quot;<br>          }<br>        },<br>        ...<br>        {<br>          &quot;cursor&quot;: &quot;MjA=&quot;,<br>          &quot;node&quot;: {<br>            &quot;id&quot;: 20,<br>            &quot;name&quot;: &quot;Product 20&quot;,<br>            &quot;price&quot;: 979.7302196981608,<br>            &quot;category&quot;: &quot;Sports&quot;<br>          }<br>        }<br>      ],<br>      &quot;pageInfo&quot;: {<br>        &quot;hasNextPage&quot;: true,<br>        &quot;hasPreviousPage&quot;: false,<br>        &quot;startCursor&quot;: &quot;MQ==&quot;,<br>        &quot;endCursor&quot;: &quot;MjA=&quot;<br>      },<br>      &quot;totalCount&quot;: 500000<br>    }<br>  }<br>}</pre><p>The format is slightly different from our offset-based implementation, but all 20 products are returned as expected, plus some useful pagination metadata. To fetch the next page, the client simply uses the endCursor from the previous response:</p><pre>query cursorProductsNext {<br>  productsCursor(first: 20, after: &quot;MjA=&quot;) {<br>    edges {<br>      cursor<br>      node {<br>        id<br>        name<br>        price<br>        category<br>      }<br>    }<br>    pageInfo {<br>      hasNextPage<br>      endCursor<br>    }<br>  }<br>}</pre><p>And the response will contain products 21–40:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;productsCursor&quot;: {<br>      &quot;edges&quot;: [<br>        {<br>          &quot;cursor&quot;: &quot;MjE=&quot;,<br>          &quot;node&quot;: {<br>            &quot;id&quot;: 21,<br>            &quot;name&quot;: &quot;Product 21&quot;,<br>            &quot;price&quot;: 194.5758511706771,<br>            &quot;category&quot;: &quot;Toys&quot;<br>          }<br>        },<br>        ...<br>        {<br>          &quot;cursor&quot;: &quot;NDA=&quot;,<br>          &quot;node&quot;: {<br>            &quot;id&quot;: 40,<br>            &quot;name&quot;: &quot;Product 40&quot;,<br>            &quot;price&quot;: 527.7330156641641,<br>            &quot;category&quot;: &quot;Electronics&quot;<br>          }<br>        }<br>      ],<br>      &quot;pageInfo&quot;: {<br>        &quot;hasNextPage&quot;: true,<br>        &quot;hasPreviousPage&quot;: true,<br>        &quot;startCursor&quot;: &quot;MjE=&quot;,<br>        &quot;endCursor&quot;: &quot;NDA=&quot;<br>      },<br>      &quot;totalCount&quot;: 500000<br>    }<br>  }<br>}</pre><p>And for the next page, we would use the new endCursor value of &quot;NDA=&quot; and so on.</p><p>The cursor itself is opaque to the client and should be treated as an implementation detail. If the client can “guess” cursor values, it may lead to unintended behavior.</p><p>Now let’s try to fetch the last page using the cursor! To do this on the client-side, we should keep following the endCursor values until we reach the end. However, for demonstration purposes, we will cheat a little and directly encode the 499980th product&#39;s ID and create a cursor for it. In resolvers.js, the encodeCursor() function does this. What we need is Buffer.from(&quot;499980&quot;).toString(&quot;base64&quot;), which results in NDk5OTgw, therefore our query to fetch the last page looks like this:</p><pre>query cursorProductsNext {<br>  productsCursor(first: 20, after: &quot;NDk5OTgw&quot;) {<br>    edges {<br>      cursor<br>      node {<br>        id<br>        name<br>        price<br>        category<br>      }<br>    }<br>    pageInfo {<br>      hasNextPage<br>      endCursor<br>    }<br>  }<br>}</pre><p>Check your terminal logs again:</p><pre>productsCursor: 35.197ms<br>Fetched 20 products (cursor-based, after: NDk5OTgw)</pre><p>As you can see, the response times remain consistent regardless of how deep we paginate into the dataset!</p><p>Compared to offset-based pagination, you should observe:</p><ul><li>Consistent database execution time, even for later pages</li><li>Uniform request duration across pages</li><li>Stable memory usage per request</li></ul><p>Because each query starts from a known position, the database does not need to scan past large numbers of rows.</p><h3>Why Cursor-Based Pagination Scales Better</h3><p>Cursor-based pagination avoids the main pitfalls of offset-based pagination:</p><ul><li>Performance does not degrade as clients paginate deeper</li><li>Pagination remains stable when records are inserted or deleted</li><li>Works naturally with infinite scrolling or stream-like UIs</li><li>Produces predictable, easy-to-compare timings/measurements in observability tools</li></ul><p>Although cursor-based pagination requires slightly more setup than offset-based pagination, it provides far more reliable performance characteristics and is the preferred pattern for production GraphQL APIs.</p><h3>Conclusion</h3><p>Pagination is often treated as a schema design detail in GraphQL, but as shown earlier, it has a direct and measurable impact on performance, memory usage, and system stability.</p><p>Fetching all data at once may be convenient, but it quickly becomes a liability as datasets grow. Offset-based pagination improves the situation by limiting result size, yet still introduces hidden costs that surface as users paginate deeper. Cursor-based pagination, on the other hand, provides consistent performance characteristics regardless of dataset size, making it the most reliable choice for production GraphQL APIs.</p><p>More importantly, this article highlights the value of observability-driven decisions. Without instrumentation, all three approaches can appear to “work”. But with proper profiling in place, the differences become clear, allowing you to make informed choices about how to design your API for real-world usage patterns.</p><p>If you’re building or maintaining a GraphQL API in Node.js, <strong>cursor-based pagination should be your default</strong> (unless your dataset is small and unlikely to grow). And whatever approach you choose, instrument it early. Pagination is not just about shaping responses: it’s about shaping how your system behaves under real-world load.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=615ce1944c4f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/using-pagination-to-improve-graphql-performance-615ce1944c4f">Using Pagination to Improve GraphQL Performance</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing and Benchmarking the Same Feature in Node and Go]]></title>
            <link>https://levelup.gitconnected.com/developing-and-benchmarking-the-same-feature-in-node-and-go-fb06f07beb47?source=rss-e13802f71817------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb06f07beb47</guid>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Gabor Koos]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 16:18:52 GMT</pubDate>
            <atom:updated>2026-03-23T16:18:52.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*qeTUcQ7vHUhUqErlbKneMQ.png" /></figure><p>When I started building chaos-proxy, the initial goal was simple: make API chaos testing practical for JavaScript and TypeScript teams. I wanted something that could sit between an app and its upstream API and introduce realistic turbulence on demand: latency spikes, intermittent failures, and other behavior that makes integration tests feel closer to production.</p><p>Node.js was the obvious first runtime for that because the ecosystem, tooling, and middleware ergonomics are excellent for rapid iteration. It is hard to overstate how productive that setup is when the main audience is already living in npm, TypeScript, and JavaScript test runners.</p><p>Later, I rewrote the same proxy in Go to push raw proxy performance further and support higher throughput under load. The intent was not to replace one with the other philosophically, but to explore a different optimization frontier with the same product idea.</p><p>This post documents what happened when I implemented the same non-trivial feature in both runtimes: hot config reload. Then I reran the benchmark from my previous article to see how the newer versions compare.</p><p>The interesting part is not only the final numbers. It is also how two mature runtimes guide you toward different internal designs, even when you are enforcing the same external behavior contract.</p><p>Old benchmark post:<br><a href="https://blog.gaborkoos.com/posts/2025-10-11-Nodejs-vs-Go-in_Practice-Performance-Comparison-of-chaos-proxy-And-chaos-proxy-go/">https://blog.gaborkoos.com/posts/2025-10-11-Nodejs-vs-Go-in_Practice-Performance-Comparison-of-chaos-proxy-And-chaos-proxy-go/</a></p><p>Repositories:</p><ul><li>Node implementation: <a href="https://github.com/fetch-kit/chaos-proxy">https://github.com/fetch-kit/chaos-proxy</a></li><li>Go implementation: <a href="https://github.com/fetch-kit/chaos-proxy-go">https://github.com/fetch-kit/chaos-proxy-go</a></li></ul><h3>Implementing Hot Config Reload in Two Runtimes</h3><p>The goal of hot config reload was to allow users to update the proxy’s behavior without downtime. This means that when a new config is posted to the /reload endpoint, the proxy should parse, validate, and apply the new configuration atomically, without interrupting in-flight requests. This enables advanced testing scenarios where you can change the chaos behavior on the fly to model dynamic production conditions like feature rollouts, traffic shifts, or evolving failure modes.</p><p>Both implementations follow the same external contract:</p><ul><li>POST /reload accepts a full config snapshot</li><li>Parse -&gt; validate -&gt; build -&gt; swap, all-or-nothing</li><li>Deterministic in-flight behavior (request-start snapshot semantics)</li><li>Reject concurrent reload requests</li><li>Consistent status model (400, 409, 415, success returns version and reload duration)</li></ul><p>So the user-facing behavior is aligned. Clients see the same API and guarantees. The internal shape is where Node and Go felt very different.</p><h3>Runtime model</h3><p><strong>Node</strong> leaned toward a dynamic runtime object: rebuild middleware/router chain, then swap the active runtime. That style maps naturally to the way Node applications are often composed. Rebuilds are straightforward to express, and the overall control flow stays compact.</p><p><strong>Go</strong> leaned toward immutable runtime snapshots: config + router + version behind an atomic pointer. In practice, this makes the runtime feel more explicit. You can point to exactly what a request observed and exactly when a new version became active.</p><h3>Concurrency model</h3><p>In <strong>Node</strong>, most complexity is around making reload writes serialized and safe while requests continue flowing.</p><p>In <strong>Go</strong>, the read/write split is explicit: request path loads one snapshot at request start, reload path builds fresh state under lock, then atomically swaps.</p><p>Behaviorally both approaches are equivalent from a user perspective. The difference is mostly in how obvious the invariants are when you revisit the code weeks later.</p><h3>In-flight guarantees</h3><p>Both versions guarantee request-start snapshot semantics.</p><p>In <strong>Node</strong>, this is easier to accidentally violate if mutable shared state leaks into request handling.</p><p>In <strong>Go</strong>, the pointer-load-at-entry pattern makes this guarantee structurally harder to violate.</p><p>That was one of the strongest practical contrasts for me: same requirement, different default safety profile.</p><h3>Router lifecycle and rebuild mechanics</h3><p><strong>Node</strong> composition is lightweight and ergonomic for rebuilds.</p><p><strong>Go</strong> rebuilds a fresh router and re-registers middleware/routes on each reload. Behavior is explicit and predictable at the snapshot level, with middleware execution order deterministic only when config uses ordered list elements (not multiple keys in one map). It can look verbose at first, but this explicitness pays off when debugging edge cases around reload timing.</p><h3>Validation and rollback boundaries</h3><p>Both use the same pipeline: parse -&gt; validate -&gt; build -&gt; swap.</p><p><strong>Node</strong> gives more dynamic flexibility but needs stricter guard discipline.</p><p><strong>Go</strong>’s type-driven pipeline made failure paths and rollback behavior cleaner to reason about.</p><p>In both runtimes, treating build and swap as separate phases was the key to keeping rollback semantics simple.</p><h3>Stateful middleware behavior</h3><p>Both implementations rebuild middleware instances on reload. That means in-memory middleware state (for example counters or local token buckets) resets by design after a successful reload. This is intentional and worth calling out to users because it is product behavior, not an implementation accident.</p><h3>Benchmark Rerun</h3><p>After adding hot config reload support, I reran the old benchmark setup.</p><p>The goal here was not to produce an absolute, universal number for every environment. The goal was to keep methodology stable enough to compare the old and new versions and see whether the relative shape changed.</p><h3>System and Test Environment (Same Machine as the Old Article)</h3><p>This rerun was executed on the same machine as the benchmark in the previous article, with the same local topology (Caddy backend on localhost, proxy on localhost, load generated by hey on the same host).</p><p>Machine characteristics:</p><ul><li>CPU: AMD Ryzen 7 5800H with Radeon Graphics</li><li>Cores/Threads: 8 cores / 16 threads</li><li>Base clock: 3.2 GHz</li><li>RAM: 16 GB DDR4</li><li>OS: Windows 10 Home 22H2 64-bit</li></ul><p>Benchmark setup characteristics:</p><ul><li>Backend: Caddy serving /api/hello on localhost:8080</li><li>Proxy target: localhost:5000</li><li>Load generator: hey</li><li>Command pattern: hey -n 1000 -c 50 <a href="http://localhost/">http://localhost</a>:/api/hello</li><li>Runs per scenario: 3 (median reported)</li></ul><p>Reproducibility command block (same pattern used for this article):</p><pre># 1) Start Caddy backend<br>./caddy.exe run --config Caddyfile<br><br># 2) Baseline (direct Caddy)<br>for i in 1 2 3; do ./hey -n 1000 -c 50 http://localhost:8080/api/hello | tee -a baseline-caddy-runs.txt; done<br><br># 3) Node proxy benchmark (in another terminal, start proxy first)<br>npx chaos-proxy --config chaos.yaml<br>for i in 1 2 3; do ./hey -n 1000 -c 50 http://localhost:5000/api/hello | tee -a node-3.0.1-runs.txt; done<br><br># Stop the Node proxy process before running the Go proxy benchmark (both use port 5000)<br><br># 4) Go proxy benchmark (in another terminal, start proxy first)<br>./chaos-proxy-go.exe --config chaos.yaml<br>for i in 1 2 3; do ./hey -n 1000 -c 50 http://localhost:5000/api/hello | tee -a go-0.2.1-runs.txt; done</pre><p>Versions in this rerun:</p><ul><li>chaos-proxy (Node): 3.0.1</li><li>chaos-proxy-go (Go): 0.2.1</li></ul><p>I also verified response-size parity for fairness:</p><ul><li>Caddy: 94 bytes/request</li><li>Node 3.0.1: 94 bytes/request</li><li>Go 0.2.1: 94 bytes/request</li></ul><p>This check mattered because an earlier Node run returned compacted JSON (smaller payload), which could bias throughput. The final numbers below use matched response sizes.</p><h3>Current Rerun (Median of 3)</h3><ul><li><strong>Direct Caddy</strong>: 24,912.1845 requests/sec, 0.0018 s average latency, 0.0156 s p99 latency.</li><li><strong>chaos-proxy</strong> Node 3.0.1: 3,788.0065 requests/sec, 0.0129 s average latency, 0.0318 s p99 latency.</li><li><strong>chaos-proxy-go</strong> 0.2.1: 7,286.8293 requests/sec, 0.0062 s average latency, 0.0248 s p99 latency.</li></ul><h3>Old Benchmark Reference (from previous post)</h3><ul><li><strong>Direct Caddy</strong>: 28,383.8519 requests/sec, 0.0016 s average latency, 0.0116 s p99 latency.</li><li><strong>chaos-proxy</strong> Node 2.0.0: 4,262.3420 requests/sec, 0.0115 s average latency, 0.0417 s p99 latency.</li><li><strong>chaos-proxy-go</strong> 0.0.5: 8,828.0577 requests/sec, 0.0053 s average latency, 0.0140 s p99 latency.</li></ul><h3>What changed?</h3><ol><li>Go vs Node in current versions</li></ol><ul><li>Go is still clearly ahead.</li><li>Throughput: Go is about 1.92x higher than Node (7286.8 vs 3788.0 req/sec).</li><li>Average latency: Node is about 2.08x slower than Go (0.0129s vs 0.0062s).</li></ul><ol><li>Go old vs Go new</li></ol><ul><li>Throughput decreased from 8828.1 to 7286.8 req/sec (~17.5% lower).</li><li>Average latency increased from 0.0053s to 0.0062s (~17.0% higher).</li><li>P99 increased from 0.0140s to 0.0248s.</li></ul><ol><li>Node old vs Node new</li></ol><ul><li>Throughput decreased from 4262.3 to 3788.0 req/sec (~11.1% lower).</li><li>Average latency increased from 0.0115s to 0.0129s (~12.2% higher).</li><li>P99 improved from 0.0417s to 0.0318s.</li></ul><p>Adding hot-reload-safe runtime mechanics introduces measurable overhead even in steady-state forwarding paths, which is why both implementations are slower than their previous versions in this benchmark shape.</p><p>I did not trigger reloads during benchmark traffic, so this should be interpreted as structural overhead from the runtime architecture needed to guarantee safe reload semantics, not reload execution cost itself.</p><h3>Why There Is Overhead Even Without Calling /reload</h3><p>Even if reload is never triggered during the benchmark request stream, the hot reload feature still changes the steady-state architecture:</p><ul><li>Requests now run through runtime indirection designed for safe snapshot semantics.</li><li>Runtime objects and routing/middleware composition are organized around swap-ready boundaries.</li><li>Concurrency guards and state-boundary discipline are now part of the normal request path design.</li></ul><p>In other words, the cost is not from running /reload repeatedly during the test. The cost comes from maintaining reload-safe invariants all the time.</p><h3>Conclusion</h3><p>Implementing the same feature in Node and Go was one of the most useful engineering exercises I have done in a while.</p><p>The final behavior contract can be identical across runtimes, but the implementation pressure points are very different:</p><ul><li>Node emphasizes dynamic composition and careful mutation control.</li><li>Go emphasizes snapshot immutability and explicit concurrency boundaries.</li></ul><p>Performance-wise, the high-level outcome still holds: the Go proxy remains roughly 2x faster than the Node proxy in this benchmark shape. At the same time, both implementations are now better specified in terms of live reconfiguration semantics, which was the actual feature goal. The implementations are likely not fully performance-tuned yet. For now, that trade-off is acceptable for the feature guarantees we wanted.</p><p>And yes, it was genuinely fun to build.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb06f07beb47" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/developing-and-benchmarking-the-same-feature-in-node-and-go-fb06f07beb47">Developing and Benchmarking the Same Feature in Node and Go</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lessons Learned from Running a Privacy-First Disposable Email Service: Insights from nullmail.cc]]></title>
            <link>https://levelup.gitconnected.com/lessons-learned-from-running-a-privacy-first-disposable-email-service-insights-from-nullmail-cc-9bb6d25738b6?source=rss-e13802f71817------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bb6d25738b6</guid>
            <category><![CDATA[email-privacy]]></category>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[disposable-email-address]]></category>
            <dc:creator><![CDATA[Gabor Koos]]></dc:creator>
            <pubDate>Fri, 20 Feb 2026 15:32:06 GMT</pubDate>
            <atom:updated>2026-02-20T15:32:06.498Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t80R0ZBGTyJnGLX8bXgFYg.png" /></figure><p>A few days ago, I got an unexpected email from Cloudflare: my domain, maildock.store, had stopped using their nameservers and was at risk of being deleted. This was unexpected, as I hadn&#39;t made any changes to the DNS settings. After some investigation, I discovered that the domain had been flagged for abuse, likely due to its association with disposable email services.</p><p>For context, maildock.store powers <a href="https://nullmail.cc/">nullmail.cc</a>, a privacy-first disposable email service. Users can create addresses, receive emails, and have them automatically deleted after expiration - all without signing up, tracking, or sending any outgoing mail. The frontend is a <a href="https://kit.svelte.dev/">SvelteKit</a> app on <a href="https://vercel.com/">Vercel</a>, emails are forwarded via <a href="https://forwardemail.net/">forwardemail.net</a> into a <a href="https://supabase.com/">Supabase</a> database, and the system automatically cleans up expired content. It&#39;s minimal by design, but robust enough to provide a fully functional disposable inbox - mostly in free tiers of various services.</p><p>Despite this simplicity, domains like maildock.store can trigger automated abuse flags. What followed was a whirlwind of DNS checks, WHOIS lookups, blacklist verification, and conversations with the .store registry, <a href="https://radix.website/">Radix</a>. In this post, I&#39;ll walk through the story, how (I think) I resolved the issue, and the architectural choices that made it possible to recover safely, while keeping the service privacy-first.</p><h3>Design Philosophy</h3><p>At its core, Nullmail is built around <strong>privacy, simplicity, and minimalism</strong>. The goal is straightforward: users should be able to receive emails without giving away personal information, signing up for accounts, or being tracked. There’s no analytics, no logging beyond what’s necessary to deliver emails, and no outgoing SMTP — the service is strictly receive-only.</p><p>Every design choice reflects this philosophy. Addresses are ephemeral and automatically expire, keeping the system lean and reducing the risk of abuse. The database only stores what’s necessary: the address itself and the emails sent to it. No unnecessary metadata, no IP logs, no behavioral tracking. Even the UI is stripped down to essentials, giving users just enough functionality to check their inbox and manage addresses.</p><p>This minimal, privacy-first approach has a practical benefit as well: it reduces the attack surface and limits what can go wrong. There’s no complicated backend for sending mail, no rate-limiting infrastructure, and no analytics that could trigger false positives with anti-spam systems.</p><h3>Architecture Overview</h3><p>The simplicity of Nullmail’s design is mirrored in its architecture. The service combines a few lightweight, well-chosen components to deliver a fully functional disposable email system while staying mostly in free tiers:</p><ul><li><strong>Frontend</strong>: A SvelteKit app hosted on Vercel. It handles the user interface for reading emails and managing addresses, with minimal JavaScript and no tracking.</li><li><strong>Backend/API</strong>: The same SvelteKit app provides serverless API routes on Vercel for core operations: creating new addresses, listing inboxes, fetching email bodies, and extending expiry timestamps.</li><li><strong>Database</strong>: A Supabase Postgres instance stores addresses and emails. The database schema is minimal, consisting of:</li><li><strong>addresses table</strong>: stores the address and its expiry timestamp.</li><li><strong>emails table</strong>: stores sender, recipient, subject, body, and delivery timestamp. Each email references an address, and expired addresses (and their emails) are automatically deleted via a scheduled cron job every five minutes.</li><li><strong>Email ingestion</strong>: All incoming emails are routed through forwardemail.net. ForwardEmail posts inbound mail to a Vercel API endpoint, which inserts it into the Supabase database.</li><li><strong>Domains &amp; DNS</strong>: The service operates under the domains maildock.store and nullmail.cc. DNS is managed through <a href="https://www.cloudflare.com/">Cloudflare</a>, which provides:</li><li>Nameserver hosting</li><li>MX, SPF, DMARC, TLSRPT, and _security TXT records</li><li>Proxying for web traffic (though Nullmail is mostly static)</li><li>Protection against accidental misconfiguration or abuse flags</li><li><strong>Optional UX</strong>: Browser extensions for <a href="https://chromewebstore.google.com/detail/nullmail-extension/ogbnjlpdlihcbfmdffhkklhikjlmkfnm?pli=1">Chrome</a> and <a href="https://addons.mozilla.org/en-US/firefox/addon/nullmail-extension/">Firefox</a> open the site with a fromExtension=1 flag for minor interface tweaks.</li></ul><p>The codebase can be found on GitHub: <a href="https://github.com/gkoos/nullmail/">gkoos/nullmail</a>.</p><p>This architecture is lightweight but resilient, perfectly aligned with the privacy-first philosophy: no outgoing SMTP, minimal logging, and automated cleanup. It also meant that when the domain was flagged by Radix, most of the infrastructure was unaffected: the problem was isolated to DNS and registry-level issues.</p><h3>The Incident</h3><p>Even with a minimal, receive-only setup, disposable email domains can attract attention from automated abuse systems. As I mentioned earlier, I got an email from Cloudflare warning that maildock.store had stopped using their nameservers and was at risk of being deleted. At first, it felt like a false alarm — I hadn’t touched any DNS settings.</p><p>Digging deeper, I discovered that the domain had been placed on ServerHold by Radix, the registry that manages .store domains. ServerHold is usually reserved for domains flagged for abuse, spam, or other policy violations. In my case, the likely trigger was the domain&#39;s association with my disposable email service, even though Nullmail is strictly receive-only and doesn&#39;t send outbound mail.</p><p>To investigate, I ran WHOIS checks, TXT and MX lookups, and verified DNS settings through Cloudflare. I also checked common spam/blacklist sources like SURBL: initially, the domain appeared flagged, though later it was cleared. While the frontend and database remained fully functional, the suspension meant that any new email delivery could fail and the domain risked being removed entirely.</p><p>This incident highlighted the harsh reality: even a minimal, privacy-first service with just a few users can run into registry-level issues. Fortunately, the architecture — isolated frontend, serverless backend, and Cloudflare-managed DNS — meant that the problem was largely contained to the domain itself, and recovery would be possible with the right steps.</p><h3>The Resolution</h3><p>Once I confirmed that maildock.store was on ServerHold, the next step was to contact Radix directly via their <a href="https://abuse.radix.website/unsuspension">unsuspension form</a>. I explained the service, emphasized it&#39;s receive-only nature, and detailed the privacy-first safeguards in place.</p><p>Radix responded positively and removed the ServerHold, reinstating the domain. To further prevent future issues and provide a point of contact for abuse reports, I created a dedicated abuse mailbox (<a href="/service/mailto:abuse@maildock.store">abuse@maildock.store</a>). This mailbox is stored in the Supabase database, has no public access, and is checked only via the Supabase UI as needed.</p><p>Next, I verified and cleaned up the DNS records in Cloudflare:</p><ul><li>Removed old registrar NS entries that were no longer needed.</li><li>Deleted test or placeholder A records that could confuse DNS checks.</li><li>Confirmed MX records pointing to forwardemail.net were correct.</li><li>Ensured SPF, DMARC, TLSRPT, and _security TXT records were properly configured, with the abuse mailbox as the contact.</li></ul><p>After these steps, the domain was fully operational again: emails were being received reliably, and the system continued to enforce automatic cleanup of expired content.</p><p>This experience reinforced the importance of clear abuse contact channels, proper DNS hygiene, and documenting a simple, minimal architecture that isolates potential issues. Even a small, receive-only service can be flagged, but thoughtful design makes recovery straightforward.</p><p>Honestly, I should have anticipated this sooner. Luckily, the solution was simple, and the service is back up without any lasting damage. The incident also provided valuable insights into how registry-level abuse flags work and how to design a service that can recover gracefully from them.</p><h3>Lessons Learned</h3><p>The ServerHold incident with maildock.store offered several insights about running a minimal disposable email service:</p><ul><li>Despite being receive-only, with no outgoing mail, maildock.store was still flagged for potential abuse. utomated systems at the registry level tend to be cautious and sometimes overly conservative. Also, because no logs are kept, there’s no way to tell what triggered the flag, which is a risk of a privacy-first approach.</li><li>DNS and registry configurations matter more than expected.</li><li>Inconsistencies in nameservers or leftover records may trigger alerts. While the system itself was unaffected, the domain’s reachability depends on clear, correct DNS entries.</li><li>Direct communication with the registry is crucial — and they were responsive and helpful in resolving the issue once I provided context about the service and its safeguards.</li><li>Automated abuse flags are often resolvable with context. Having a clear explanation and a point of contact (<a href="/service/mailto:abuse@maildock.store">abuse@maildock.store</a>) allowed me to restore the domain quickly.</li><li>Minimalism has trade-offs: a simple architecture isolates most operations from failures like this, but no logging and lack of outbound monitoring means we rely on external feedback to detect issues.</li><li>The “why” remains uncertain: we still don’t know exactly what triggered the abuse flag. This leaves open questions about how disposable domains are evaluated, and whether additional safeguards could reduce false positives. And also makes me wonder if the domain was targeted by a malicious actor who reported it, or tried to exploit the service, or if it was just an automated flag based on the domain’s history or traffic patterns.</li></ul><p>Overall, the experience reinforced that running a privacy-first service comes with uncertainties and edge cases. While minimalism and privacy help in some areas, external systems (registries, DNS providers, abuse monitors) can still impact availability in ways that are outside the service’s direct control. In a larger context, this highlights the need to do your due diligence and understand the challenges of running a service that interacts with the broader internet ecosystem, even if it’s designed to be as simple and private as possible. Also, value your users, but don’t trust them to not try to abuse the service, and design with that in mind.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bb6d25738b6" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/lessons-learned-from-running-a-privacy-first-disposable-email-service-insights-from-nullmail-cc-9bb6d25738b6">Lessons Learned from Running a Privacy-First Disposable Email Service: Insights from nullmail.cc</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>