<?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 Chintan Suryawanshi on Medium]]></title>
        <description><![CDATA[Stories by Chintan Suryawanshi on Medium]]></description>
        <link>https://medium.com/@chintansuryawanshi1?source=rss-74b7a704c704------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YeLOm-th1HJufeH0</url>
            <title>Stories by Chintan Suryawanshi on Medium</title>
            <link>https://medium.com/@chintansuryawanshi1?source=rss-74b7a704c704------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:42:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chintansuryawanshi1/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[Can two guests book the same room? A PostgreSQL concurrency test]]></title>
            <link>https://medium.com/@chintansuryawanshi1/can-two-guests-book-the-same-room-a-postgresql-concurrency-test-712b5ef80a8c?source=rss-74b7a704c704------2</link>
            <guid isPermaLink="false">https://medium.com/p/712b5ef80a8c</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Chintan Suryawanshi]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 05:41:01 GMT</pubDate>
            <atom:updated>2026-12-01T05:41:01.664Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Open two SQL sessions, put one night of room 204 in contention, and watch what decides which guest gets a confirmation.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ScN0c0FujFiLlX9NFEWFAw.png" /><figcaption>PostgreSQL Concurrency Test for Double-Booked Hotel Rooms</figcaption></figure><p>At 9:41, Mira picks room 204 for Friday and Saturday night. Dev picks the same room for Saturday and Sunday night. Their arrival dates differ. Their departure dates differ. An ordinary unique constraint on the room and those two dates would happily accept both reservations. On Saturday evening, someone would need another room.</p><p>That single shared night is the case worth putting in a PostgreSQL concurrency test. It catches two mistakes that a happy-path booking test can miss. An availability check can go stale between reading and writing, and comparing whole date ranges for equality can miss a partial overlap.</p><h3>Give the database a night to compare</h3><p>For this example, the hotel assigns a specific physical room when the guest books. Each row represents a confirmed stay. Use the hotel’s local arrival and departure dates. A guest arriving December 4 and departing December 6 occupies the nights of the 4th and 5th. The next guest can arrive on the 6th.</p><p>PostgreSQL can express that directly. The range constructor below includes the lower bound and excludes the upper bound. The &amp;&amp; operator asks whether two ranges share any date. Try these two expressions side by side. <a href="https://www.postgresql.org/docs/current/rangetypes.html">PostgreSQL range types</a></p><pre>SELECT<br>  daterange(&#39;2026-12-04&#39;, &#39;2026-12-06&#39;, &#39;[)&#39;) &amp;&amp;<br>  daterange(&#39;2026-12-05&#39;, &#39;2026-12-07&#39;, &#39;[)&#39;) AS shared_night,<br>  daterange(&#39;2026-12-04&#39;, &#39;2026-12-06&#39;, &#39;[)&#39;) &amp;&amp;<br>  daterange(&#39;2026-12-06&#39;, &#39;2026-12-08&#39;, &#39;[)&#39;) AS same_day_turnover;</pre><p>Expected values are true and false, respectively. The second value matters as much as the first. If you fix the Saturday conflict by counting departure day as an occupied night, you accidentally take a sellable night out of inventory.</p><h3>Let both guests see the room</h3><p>Open two independent psql connections to the same fresh test database. Run setup once in session A with autocommit enabled.</p><pre>CREATE TABLE booking_demo (<br>    room_id integer NOT NULL,<br>    guest text NOT NULL,<br>    arrival date NOT NULL,<br>    departure date NOT NULL,<br>    CHECK (arrival &lt; departure)<br>);</pre><p>In <strong>both</strong> sessions, run the following before either session inserts a row. Saturday, December 5, is the night both people want.</p><pre>BEGIN ISOLATION LEVEL READ COMMITTED;<br><br>SELECT count(*) AS occupied<br>FROM booking_demo<br>WHERE room_id = 204<br>  AND daterange(arrival, departure, &#39;[)&#39;) @&gt; DATE &#39;2026-12-05&#39;;</pre><p>Both readers should get zero. Now run the first insert in A and leave the transaction open. Run the second insert in B. Then execute COMMIT; in each session.</p><pre>-- Session A<br>INSERT INTO booking_demo VALUES (204, &#39;Mira&#39;, &#39;2026-12-04&#39;, &#39;2026-12-06&#39;);<br><br>-- Session B<br>INSERT INTO booking_demo VALUES (204, &#39;Dev&#39;, &#39;2026-12-05&#39;, &#39;2026-12-07&#39;);</pre><p>Rerun the count. Expect <strong>two bookings for one room on Saturday</strong>. No dirty read was involved. Each availability query accurately described the committed data it could see. Neither query gave its caller an exclusive claim on a future insert. Wrapping each pair of statements in a transaction still leaves room for that sequence at Read Committed. <a href="https://www.postgresql.org/docs/current/transaction-iso.html#XACT-READ-COMMITTED">PostgreSQL transaction isolation</a></p><h3>Put the overlap rule on the table</h3><p>For the second experiment, create an empty sibling table. Keeping the first table makes the before-and-after results easy to compare. Setup requires permission to install the supplied btree_gist extension or a database where it is already available.</p><pre>CREATE EXTENSION IF NOT EXISTS btree_gist;<br><br>CREATE TABLE booking_guarded (<br>    LIKE booking_demo INCLUDING CONSTRAINTS,<br>    CONSTRAINT one_stay_per_room_night<br>        EXCLUDE USING gist (<br>            room_id WITH =,<br>            daterange(arrival, departure, &#39;[)&#39;) WITH &amp;&amp;<br>        )<br>);</pre><p>Read those two comparisons together. PostgreSQL rejects a pair of rows when both describe the same room <strong>and</strong> their stays overlap. Two rooms can be occupied on Saturday. One room can host two consecutive stays. The positive-length check inherited from the first table also rules out a zero-night booking, which would otherwise cover an empty range. <a href="https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-CONSTRAINT">PostgreSQL constraints on ranges</a></p><h3>Pause before the first commit</h3><p>In <strong>session A</strong>, insert Mira’s stay and leave the transaction open.</p><pre>BEGIN;<br>INSERT INTO booking_guarded VALUES (204, &#39;Mira&#39;, &#39;2026-12-04&#39;, &#39;2026-12-06&#39;);</pre><p>In <strong>session B</strong>, run the competing insert.</p><pre>BEGIN;<br>INSERT INTO booking_guarded VALUES (204, &#39;Dev&#39;, &#39;2026-12-05&#39;, &#39;2026-12-07&#39;);</pre><p>B should wait because A still controls the outcome. Switch back to <strong>A</strong> and run COMMIT;. B should now report an exclusion violation. In B, run \echo :SQLSTATE immediately after the error to see 23P01, then run ROLLBACK; to clear B&#39;s failed transaction. <a href="https://doxygen.postgresql.org/execIndexing_8c_source.html">PostgreSQL executor implementation</a> · <a href="https://www.postgresql.org/docs/current/errcodes-appendix.html">PostgreSQL error codes</a></p><p>Now rerun the Saturday count against booking_guarded. Expect <strong>one</strong>. That assertion deserves a place in an integration test. A client timing out or crashing can also give you one failed request. Checking the specific constraint error and the committed row count proves more about the booking rule than checking for an HTTP error alone.</p><p>For the other branch, repeat the same two inserts using a fresh room number in both sessions. This time, issue ROLLBACK; in A while B is waiting. B&#39;s insert should succeed, and B can commit. This catches an implementation that rejects every competing request as soon as someone else starts checkout, even when the first guest abandons it.</p><h3>Give the losing guest a useful answer</h3><p>Suppose the losing request came from a React checkout page. The guest can do something about a sold-out room. They can pick a different room, shorten the stay, or search again. A generic server-error toast gives them none of those choices.</p><p>In a Node.js handler, inspect both the database error code and the constraint name. After rolling back any failed explicit transaction, translate 23P01 from one_stay_per_room_night into an HTTP 409 Conflict with a stable application code such as ROOM_UNAVAILABLE. Keep unrelated database failures on their own error path. On success, send the guest a confirmation only after the database commits.</p><p>A booking conflict also differs from a repeated submission. If the first request committed and the guest retried after a lost response, reporting “sold out” might hide their own successful booking. An idempotency key tied to the booking request lets the API return the original confirmation in that case. The exclusion constraint decides whether two stays can coexist.</p><h3>Choose tests that match the inventory you sell</h3><p>Alongside the two-session test, keep a few inexpensive cases with explicit expected outcomes.</p><pre>|Existing reservation |New request      |Expected outcome|<br>|---------------------|-----------------|----------------|<br>|Room 204, Dec 4–6    |Room 204, Dec 5–7|Reject the overlapping stay|<br>|Room 204, Dec 4–6    |Room 204, Dec 6–8|Accept same-day turnover|<br>|Room 204, Dec 4–6    |Room 205, Dec 5–7|Accept a different room|<br>|Empty inventory      |Room 204, Dec 6–6|Reject the zero-night stay|</pre><p>One assumption runs through every row in this article. The guest books an identified physical room. A hotel selling “any king room” with assignment at check-in has a different inventory rule. Two overlapping king bookings may be perfectly valid if two king rooms exist. Applying this constraint to a room <em>type</em> would quietly cap sales at one.</p><p>When reviewing a booking change, open the two connections and stop just before the first commit. Ask what the second guest should see if the first guest confirms, then ask what should happen if the first guest walks away. Those two outcomes turn “we handle concurrency” into a test a teammate can repeat.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=712b5ef80a8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why a small Next.js card can download a viewport-sized image]]></title>
            <link>https://medium.com/@chintansuryawanshi1/why-a-small-next-js-card-can-download-a-viewport-sized-image-0a745f62dc0d?source=rss-74b7a704c704------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a745f62dc0d</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Chintan Suryawanshi]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 05:46:01 GMT</pubDate>
            <atom:updated>2026-11-30T05:46:01.809Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Follow one image from its CSS slot to its network request, and use </em><em>sizes to tell the browser how wide the card will actually be.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VQ2Y4tIvm89IbMiTpcs-yw.png" /><figcaption>A small browser card displays the same mountain lake as an oversized print hanging behind it, illustrating the difference between display size and downloaded image size.</figcaption></figure><p>Picture a hotel listing on a 1440-pixel-wide desktop. The photo at the top of each card is 360 CSS pixels wide. It looks sharp, the crop is right, and the page uses next/image. Then you open the Network panel and find a request for an image wider than the entire row of cards.</p><p>How do you tell whether that request is wasteful? A 720-pixel image can be a sensible choice for a 360-pixel card on a 2× display. The interesting question is <strong>what width the browser thought the card would occupy when it chose the file</strong>. The rendered page gives you one half of that answer. The &lt;img&gt; element gives you the other. <a href="https://nextjs.org/docs/app/api-reference/components/image?utm_source=chatgpt.com">nextjs.org</a></p><h3>Start with the card that looks correct</h3><p>Here’s a small example. Assume the card sits in a full-width listing area, with 16 pixels of space on either side on narrow screens. The photo grows with the viewport until it reaches 360 pixels.</p><pre>.hotel-card {<br>  width: min(360px, calc(100vw - 32px));<br>}<br>.hotel-card__photo {<br>  position: relative;<br>  aspect-ratio: 3 / 2;<br>}</pre><pre>import Image from &quot;next/image&quot;;<br><br>export function HotelCard() {<br>  return (<br>    &lt;article className=&quot;hotel-card&quot;&gt;<br>      &lt;div className=&quot;hotel-card__photo&quot;&gt;<br>        &lt;Image<br>          src=&quot;/hotel-courtyard.jpg&quot;<br>          alt=&quot;A shaded courtyard with tables beside the pool&quot;<br>          fill<br>          style={{ objectFit: &quot;cover&quot; }}<br>        /&gt;<br>      &lt;/div&gt;<br>      &lt;h2&gt;Courtyard Hotel&lt;/h2&gt;<br>    &lt;/article&gt;<br>  );<br>}</pre><p>The wrapper reserves space. fill lets the image occupy that space. objectFit: &quot;cover&quot; controls the crop. You can adjust all three, refresh the page, and see exactly what changed. The subtle omission is sizes. With a responsive fill image and no explicit slot width, the browser can work from a full-viewport assumption. The layout still looks right after the larger file arrives. <a href="https://nextjs.org/docs/app/api-reference/components/image?utm_source=chatgpt.com">nextjs.org</a></p><h3>Read the layout as a sentence</h3><p>For this card, the rule is simple enough to say aloud: <em>Give the image the viewport width minus 32 pixels, up to a maximum of 360 pixels.</em> The card reaches that cap at a viewport width of <strong>392 pixels</strong>. That gives us the sizes value directly.</p><pre>&lt;Image<br>  src=&quot;/hotel-courtyard.jpg&quot;<br>  alt=&quot;A shaded courtyard with tables beside the pool&quot;<br>  fill<br>  sizes=&quot;(max-width: 392px) calc(100vw - 32px), 360px&quot;<br>  style={{ objectFit: &quot;cover&quot; }}<br>/&gt;</pre><p>The first matching condition wins. At 375 pixels, the declared slot is 343 pixels wide. At 1440 pixels, it’s 360. The CSS still owns the layout. The new attribute gives the browser the same information when choosing among the image widths in srcset. <a href="https://nextjs.org/docs/app/api-reference/components/image?utm_source=chatgpt.com">nextjs.org</a></p><h3>Put numbers on the difference</h3><p>Here’s what those two descriptions imply on a 2× display. These are calculated targets. The browser chooses from the candidates actually available, so the requested file can have a different width. <a href="https://nextjs.org/docs/app/api-reference/components/image?utm_source=chatgpt.com">nextjs.org</a></p><pre>| Viewport     | Rendered card | Target from a full-viewport hint | Target from the card’s `sizes` |<br>|--------------|---------------|----------------------------------|--------------------------------|<br>| 375 CSS px   | 343 CSS px    | 750 image px                     | 686 image px                   |<br>| 768 CSS px   | 360 CSS px    | 1,536 image px                   | 720 image px                   |<br>| 1,440 CSS px | 360 CSS px    | 2,880 image px                   | 720 image px                   |</pre><p>That first row explains why the bug is easy to miss on a phone. The estimates are close. On desktop, the card stopped growing hundreds of pixels ago, but the full-viewport estimate kept climbing. At 1440 pixels, the two descriptions differ by a factor of four in width. You need the actual transfers to say how many bytes that costs.</p><h3>Check which candidate the browser chose</h3><p>Open DevTools, select the card’s actual &lt;img&gt; in Elements, and run this in the Console. In Chromium DevTools, $0 refers to the selected element. currentSrc gives you the URL the browser selected from the available candidates. <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/currentSrc?utm_source=chatgpt.com">MDN</a></p><pre>const img = $0;<br><br>console.table({<br>  renderedWidth: img.getBoundingClientRect().width,<br>  declaredSizes: img.sizes,<br>  devicePixelRatio: window.devicePixelRatio,<br>  selectedURL: img.currentSrc,<br>});</pre><p>Run the comparison twice at the <strong>same viewport width and device pixel ratio</strong>. Keep DevTools open, disable the cache in Network, and reload for each version. If the card starts below the fold, scroll it into view. Find the request matching selectedURL and record its transferred bytes. With the default Next.js optimizer, the URL’s w parameter also makes the requested candidate width easy to spot. <a href="https://nextjs.org/docs/app/api-reference/components/image?utm_source=chatgpt.com">nextjs.org</a></p><p>There are two useful results here. If the selected width falls and the photo still looks sharp, you can report the byte difference you actually observed. If both versions select the same file, check the viewport, display density, and available srcset widths. Two different slot estimates can lead to the same available candidate. <a href="https://nextjs.org/docs/app/api-reference/components/image?utm_source=chatgpt.com">nextjs.org</a></p><h3>Let the placement supply sizes</h3><p>The easiest way to reintroduce this bug is to reuse the corrected image component somewhere else. A hotel photo might appear in a capped listing card, a narrow recommendations rail, and a full-width detail page. Hardcoding 360px inside HotelPhoto would fix the listing and give the detail page a misleading hint. <a href="https://nextjs.org/docs/app/api-reference/components/image?utm_source=chatgpt.com">nextjs.org</a></p><p>I’d keep the shared component responsible for the image and let each placement pass sizes. The listing knows its cap. The detail page knows whether the hero spans the viewport. And when a designer changes the grid, the developer editing that layout can update the corresponding hint in the same review.</p><p>For your next image-performance check, pick one repeated card and collect three values: <strong>rendered width, selected candidate, transferred bytes</strong>. Those give you a concrete answer to a better question than “Are we using optimized images?” You can tell whether this particular card downloaded a sensible file for the space it occupied.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a745f62dc0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Hotel Analytics Platform That Gets Occupancy, ADR and RevPAR Right]]></title>
            <link>https://medium.com/@chintansuryawanshi1/designing-a-hotel-analytics-platform-that-gets-occupancy-adr-and-revpar-right-029291d6005a?source=rss-74b7a704c704------2</link>
            <guid isPermaLink="false">https://medium.com/p/029291d6005a</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[hospitality-industry]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Chintan Suryawanshi]]></dc:creator>
            <pubDate>Sat, 28 Nov 2026 05:41:02 GMT</pubDate>
            <atom:updated>2026-11-28T05:41:02.030Z</atom:updated>
            <content:encoded><![CDATA[<p><em>An engineering approach to building reliable hospitality analytics with React, Node.js and PostgreSQL.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NkDT70rV8A74QAR3ZB4f9Q.png" /><figcaption>Hotel analytics platform architecture</figcaption></figure><p>A hotel analytics dashboard can have beautiful charts, responsive tables and advanced filters — and still produce misleading business insights.</p><p>The problem often starts beneath the frontend: incorrectly defined metrics, inconsistent data aggregation and unreliable reporting pipelines.</p><p>Let’s design an architecture that addresses these problems.</p><h3>1. Understand the core hospitality metrics</h3><p>Three fundamental indicators measure hotel revenue performance.</p><pre>| Metric       | Formula                            | Purpose |<br>|--------------|------------------------------------|---------|<br>| Occupancy    | Rooms sold ÷ available rooms × 100 | Room utilization |<br>| ADR          | Room revenue ÷ rooms sold          | Average selling rate |<br>| RevPAR       | Room revenue ÷ available rooms     | Revenue performance |</pre><p>RevPAR combines the effects of occupancy and pricing. <a href="https://www.costar.com/products/str-benchmark/resources/glossary?utm_source=chatgpt.com">CoStar</a></p><p>Consider a hotel with:</p><ul><li>Available rooms: 100</li><li>Rooms sold: 75</li><li>Room revenue: ₹4,50,000</li></ul><p>The results are:</p><p>KPIResultOccupancy75%ADR₹6,000RevPAR₹4,500</p><p>These calculations are simple. Maintaining their accuracy across millions of reservation records is the engineering challenge.</p><h3>2. Design the data pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*gC0u32TWmdxrYPQE7PXIBw.png" /></figure><p>The ingestion pipeline should normalize reservations, room inventory, cancellations and revenue information before calculating business metrics.</p><p>A useful starting point is to maintain separate datasets for:</p><ul><li>Daily inventory.</li><li>Reservation room nights.</li><li>Room revenue.</li><li>Historical booking snapshots.</li></ul><p>This prevents the reporting layer from becoming tightly coupled to external reservation formats.</p><h3>3. Never average averages blindly</h3><p>Consider two days of hotel performance.</p><pre>| Day     | Rooms sold | Available | Revenue   | ADR    |<br>|---------|------------|-----------|-----------|--------|<br>| Monday  | 20         | 100       | ₹1,00,000 | ₹5,000 |<br>| Tuesday | 80         | 100       | ₹2,40,000 | ₹3,000 |</pre><p>A simple average produces an ADR of ₹4,000.</p><p>But the correct combined ADR is:</p><p>ADR =340000/100 =₹3,400</p><p>The difference comes from weighting each day’s result by the number of rooms sold.</p><p>Always aggregate underlying values before calculating ratios.</p><h3>4. Centralize KPI calculation</h3><p>PostgreSQL can calculate these metrics consistently at the reporting layer.</p><pre>SELECT<br>    property_id,<br>    SUM(rooms_sold) * 100.0 /<br>    NULLIF(SUM(available_rooms), 0)<br>        AS occupancy,<br>    SUM(room_revenue) /<br>    NULLIF(SUM(rooms_sold), 0)<br>        AS adr,<br>    SUM(room_revenue) /<br>    NULLIF(SUM(available_rooms), 0)<br>        AS revpar<br>FROM daily_hotel_metrics<br>GROUP BY property_id;<br></pre><p>This approach assumes validated daily records with a consistent reporting grain.</p><p>Using NULLIF prevents division-by-zero errors while preserving the distinction between undefined metrics and zero revenue.</p><h3>5. Handle historical and future performance</h3><p>Hotel revenue managers need more than historical reports.</p><p>An analytics platform should distinguish:</p><pre>| Metric   | Meaning |<br>|----------|---------|<br>| TY       | This Year |<br>| LY       | Last Year |<br>| STLY     | Same Time Last Year |<br>| OTB      | On The Books |<br>| Pickup   | Booking changes between snapshots |<br>| Forecast | Expected future performance |</pre><p>For example, seven-day pickup measures the net change in bookings or revenue between two snapshots taken seven days apart for the same stay period.</p><p>Historical snapshots are essential. Current reservation data alone cannot reliably reconstruct what the hotel knew at an earlier date.</p><h3>6. Design the React dashboard</h3><p>The frontend should support several reporting dimensions:</p><ul><li>Property and location.</li><li>Room type.</li><li>Rate plan.</li><li>Distribution channel.</li><li>Stay date.</li><li>Arrival date.</li><li>Day of week.</li><li>Market segment.</li></ul><p>Use shared filter state across KPI cards, charts, tables and CSV exports.</p><p>Most importantly, all components should consume the same metric definitions from the backend.</p><p>Otherwise, the occupancy percentage displayed in a KPI card might disagree with the exported report.</p><h3>7. Build for production reliability</h3><pre>| Challenge              | Recommended approach |<br>|------------------------|----------------------|<br>| Large datasets         | Pre-aggregation and pagination |<br>| Slow reports           | Indexed queries and caching |<br>| Duplicate reservations | Idempotent ingestion |<br>| Late data updates      | Reconciliation jobs |<br>| Incorrect calculations | Automated metric tests |<br>| Multiple hotels        | Tenant isolation |<br>| Different currencies   | Consistent currency conversion policy |</pre><p>Document inventory exclusions, complimentary rooms and revenue recognition rules before implementing the calculations. These definitions affect comparability across properties and periods.</p><h3>Conclusion</h3><p>The success of a hospitality analytics platform is not determined by how many charts it displays.</p><p>It depends on whether revenue managers can trust the numbers behind those charts.</p><p>Reliable metrics, consistent data pipelines and well-designed aggregation logic should come before sophisticated visualizations.</p><p><strong>Your dashboard is only as good as the data model underneath it.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=029291d6005a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Reliable Web3 Transaction States with React and Ethers.js]]></title>
            <link>https://medium.com/@chintansuryawanshi1/building-reliable-web3-transaction-states-with-react-and-ethers-js-b048c0839ff9?source=rss-74b7a704c704------2</link>
            <guid isPermaLink="false">https://medium.com/p/b048c0839ff9</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Chintan Suryawanshi]]></dc:creator>
            <pubDate>Fri, 27 Nov 2026 06:00:07 GMT</pubDate>
            <atom:updated>2026-11-27T06:00:07.897Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Design predictable transaction experiences beyond loading, success and error.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NT-thu82_cSTQN83vNJlfw.png" /><figcaption>Web3 Transaction States</figcaption></figure><h3>The problem with traditional loading states</h3><p>A Web3 transaction isn’t a normal API request.</p><p>When a user initiates a blockchain transaction, several independently changing events can occur: wallet approval, network submission, block inclusion, confirmations and transaction replacement.</p><p>Managing everything with a single isLoading boolean creates an unreliable user experience.</p><h3>1. Model the transaction lifecycle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*eb-82WtHwv9loMN_FjD3bg.png" /></figure><p>Each state represents a different condition requiring different UI behavior.</p><pre>| State              | UI behavior |<br>|--------------------|-------------|<br>| Awaiting signature | Check your wallet |<br>| Pending            | Display transaction hash |<br>| Confirmed          | Show successful confirmation |<br>| Rejected           | User declined the request |<br>| Reverted           | Explain execution failure |<br>| Replaced           | Track the replacement |<br>| Unknown            | Reconcile transaction status |</pre><h3>2. Define explicit TypeScript states</h3><pre>type TransactionState =<br>  | { status: &quot;idle&quot; }<br>  | { status: &quot;awaiting_signature&quot; }<br>  | { status: &quot;pending&quot;; hash: string }<br>  | { status: &quot;confirmed&quot;; hash: string }<br>  | { status: &quot;rejected&quot; }<br>  | { status: &quot;reverted&quot;; hash: string }<br>  | { status: &quot;replaced&quot;; hash: string }<br>  | { status: &quot;unknown&quot;; hash?: string };</pre><p>Discriminated unions prevent contradictory UI states and make transaction handling more predictable.</p><h3>3. Handle blockchain confirmations</h3><p>With Ethers.js v6:</p><pre>const tx = await contract.someMethod();<br><br>dispatch({<br>  status: &quot;pending&quot;,<br>  hash: tx.hash,<br>});<br>const receipt = await tx.wait(2);<br>if (receipt?.status === 1) {<br>  dispatch({<br>    status: &quot;confirmed&quot;,<br>    hash: tx.hash,<br>  });<br>}</pre><p>Receiving a transaction hash does not mean execution succeeded. The confirmation policy should depend on the network and application requirements.</p><h3>4. Handle replacement and failure scenarios</h3><p>A robust transaction manager must distinguish between:</p><ul><li>Wallet rejection.</li><li>Smart contract reversion.</li><li>Insufficient funds.</li><li>Network interruption.</li><li>Transaction replacement.</li><li>Confirmation timeout.</li></ul><p>Ethers.js v6 provides structured error codes, including TRANSACTION_REPLACED, to help classify these situations.</p><p>A timeout should not automatically be interpreted as a failed transaction. It may still be processed by the network.</p><h3>5. Separate transaction logic from UI components</h3><p>A production-oriented application can use the following architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*8ycyuwOVkkgxg5w5b6llaw.png" /></figure><p>This separation makes transaction handling reusable, testable and easier to maintain.</p><p>React’s useReducer is a useful option for managing more complex state transitions.</p><h3>6. Production readiness checklist</h3><ul><li>Prevent duplicate submissions.</li><li>Validate wallet account and network.</li><li>Persist pending transaction hashes.</li><li>Support transaction replacement.</li><li>Reconcile status after page reload.</li><li>Monitor confirmation requirements and reorganizations.</li><li>Test failure paths alongside successful transactions.</li></ul><h3>Conclusion</h3><p>Reliable Web3 applications require more than successful smart contract interactions.</p><p>They require frontend architecture that accurately represents the asynchronous and sometimes uncertain nature of blockchain transactions.</p><p>Treat transactions as a lifecycle, not a loading spinner.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b048c0839ff9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build an LLM Regression Testing Pipeline with TypeScript and GitHub Actions]]></title>
            <link>https://medium.com/@chintansuryawanshi1/how-to-build-an-llm-regression-testing-pipeline-with-typescript-and-github-actions-f94404c51678?source=rss-74b7a704c704------2</link>
            <guid isPermaLink="false">https://medium.com/p/f94404c51678</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Chintan Suryawanshi]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 05:41:01 GMT</pubDate>
            <atom:updated>2026-11-26T05:41:01.508Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XftfpF_2rcejOxksI992iQ.png" /><figcaption>An LLM regression testing pipeline connecting an evaluation dataset, language model, validation checks, and a continuous integration quality gate.</figcaption></figure><p><em>Stop relying on manual prompt testing. Build an automated evaluation pipeline that detects AI quality regressions before deployment.</em></p><h3>Introduction</h3><p>Traditional software testing is relatively predictable.</p><p>Given a particular input, we generally expect a particular output.</p><p>LLM-powered applications introduce another challenge: their responses can vary even when the application code and input remain unchanged.</p><p>A small modification to a system prompt, model configuration, retrieval mechanism, or application context can silently reduce output quality.</p><p>Successful HTTP responses don’t prove that your AI application is working correctly.</p><p>We need a testing strategy that evaluates actual behaviour.</p><p>In this article, we’ll build a lightweight LLM regression testing pipeline using:</p><ul><li>TypeScript</li><li>Node.js</li><li>OpenAI SDK</li><li>Zod</li><li>GitHub Actions</li><li>Version-controlled evaluation datasets</li></ul><h3>1. What should we test?</h3><p>Traditional unit tests remain essential, but LLM evaluations introduce additional quality checks.</p><p>EvaluationPurposeJSON validityConfirm the response can be parsedSchema validationVerify the expected structureSemantic accuracyCheck whether the response is correctDomain validationEnforce business constraintsLatencyMonitor response performanceRegression detectionCompare quality against an approved baseline</p><p>Task-specific, continuous evaluation is particularly useful because generative AI outputs are variable. <a href="https://developers.openai.com/api/docs/guides/evaluation-best-practices?trk=public_post_comment-text&amp;utm_source=chatgpt.com">OpenAI API</a></p><p>For our example, we’ll evaluate an AI-powered customer-support ticket classifier.</p><h3>2. Design the evaluation pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*dviIxXrWZEnU-ev8TKJEEg.png" /></figure><p>The important architectural decision is separating the application from the evaluation runner.</p><p>This allows us to test different prompts and models without rewriting our test cases.</p><h3>3. Project setup</h3><p>Create a new Node.js project.</p><pre>mkdir llm-regression-testing<br>cd llm-regression-testing<br><br>npm init -y<br>npm install openai zod<br>npm install -D typescript tsx @types/node<br><br>npx tsc --init</pre><p>Project structure:</p><pre>llm-regression-testing/<br>├── src/<br>│   ├── classifier.ts<br>│   └── schema.ts<br>├── evals/<br>│   ├── dataset.ts<br>│   ├── baseline.json<br>│   └── runner.ts<br>├── reports/<br>├── .github/<br>│   └── workflows/<br>│       └── llm-evals.yml<br>├── package.json<br>├── package-lock.json<br>└── tsconfig.json</pre><h3>4. Create the application and evaluation dataset</h3><p>Start by defining the expected response structure.</p><h3>src/schema.ts</h3><pre>import { z } from &quot;zod&quot;;<br><br>export const TicketSchema = z.object({<br>  category: z.enum([<br>    &quot;billing&quot;,<br>    &quot;technical&quot;,<br>    &quot;general&quot;,<br>  ]),<br>  priority: z.enum([<br>    &quot;low&quot;,<br>    &quot;medium&quot;,<br>    &quot;high&quot;,<br>  ]),<br>}).strict();<br><br>export type Ticket = z.infer&lt;typeof TicketSchema&gt;;</pre><p>Zod provides runtime validation in addition to TypeScript’s compile-time type system. <a href="https://zod.dev/basics?utm_source=chatgpt.com">Zod</a></p><p>Next, implement the classifier.</p><h3>src/classifier.ts</h3><pre>import OpenAI from &quot;openai&quot;;<br>import { TicketSchema } from &quot;./schema&quot;;<br><br>const client = new OpenAI();<br><br>export async function classifyTicket(message: string) {<br>  const model = process.env.LLM_MODEL;<br><br>  if (!model) {<br>    throw new Error(&quot;LLM_MODEL is required&quot;);<br>  }<br><br>  const response = await client.responses.create({<br>    model,<br>    instructions: `<br>      Classify customer support messages.<br>      Categories: billing, technical, general.<br>      Priorities: low, medium, high.<br>      Duplicate charges and service outages<br>      must receive high priority.<br>      General feature inquiries receive<br>      low priority.<br>      Return only a JSON object containing<br>      category and priority.<br>    `,<br>    input: message,<br>  });<br><br>  return TicketSchema.parse(<br>    JSON.parse(response.output_text)<br>  );<br>}</pre><p>For compatible models, production implementations should also consider native Structured Outputs instead of relying solely on prompt-based formatting.</p><h3>evals/dataset.ts</h3><pre>import type { Ticket } from &quot;../src/schema&quot;;<br><br>type EvalCase = {<br>  id: string;<br>  input: string;<br>  expected: Ticket;<br>  critical: boolean;<br>};<br><br>export const dataset: EvalCase[] = [<br>  {<br>    id: &quot;billing-001&quot;,<br>    input: &quot;I was charged twice.&quot;,<br>    expected: {<br>      category: &quot;billing&quot;,<br>      priority: &quot;high&quot;,<br>    },<br>    critical: true,<br>  },<br>  {<br>    id: &quot;technical-001&quot;,<br>    input: &quot;The application is completely unavailable.&quot;,<br>    expected: {<br>      category: &quot;technical&quot;,<br>      priority: &quot;high&quot;,<br>    },<br>    critical: true,<br>  },<br>  {<br>    id: &quot;general-001&quot;,<br>    input: &quot;Where can I find information about features?&quot;,<br>    expected: {<br>      category: &quot;general&quot;,<br>      priority: &quot;low&quot;,<br>    },<br>    critical: false,<br>  },<br>];</pre><p>These are illustrative evaluation cases. A production dataset should also include ambiguous inputs, edge cases, anonymized historical failures, and realistic customer messages.</p><h3>5. Build the regression evaluation runner</h3><p>The runner executes each test case and compares the model’s output with the expected result.</p><p>It also checks whether critical business cases pass.</p><h3>evals/runner.ts</h3><pre>import { mkdir, readFile, writeFile } from &quot;node:fs/promises&quot;;<br>import { classifyTicket } from &quot;../src/classifier&quot;;<br>import { dataset } from &quot;./dataset&quot;;<br><br>async function runEvaluations() {<br>  const baseline = JSON.parse(<br>    await readFile(&quot;evals/baseline.json&quot;, &quot;utf8&quot;)<br>  );<br>  const results = [];<br>  for (const test of dataset) {<br>    const start = Date.now();<br>    try {<br>      const actual = await classifyTicket(test.input);<br>      const passed =<br>        actual.category === test.expected.category &amp;&amp;<br>        actual.priority === test.expected.priority;<br>      results.push({<br>        id: test.id,<br>        expected: test.expected,<br>        actual,<br>        critical: test.critical,<br>        passed,<br>        latencyMs: Date.now() - start,<br>      });<br>    } catch {<br>      results.push({<br>        id: test.id,<br>        critical: test.critical,<br>        passed: false,<br>        error: &quot;Classification or validation failed&quot;,<br>        latencyMs: Date.now() - start,<br>      });<br>    }<br>  }<br>  const passedCount = results.filter(<br>    result =&gt; result.passed<br>  ).length;<br>  const passRate = passedCount / results.length;<br>  const criticalFailures = results.filter(<br>    result =&gt; result.critical &amp;&amp; !result.passed<br>  );<br>  const report = {<br>    model: process.env.LLM_MODEL,<br>    total: results.length,<br>    passRate,<br>    baselinePassRate: baseline.passRate,<br>    criticalFailures: criticalFailures.length,<br>    results,<br>  };<br>  await mkdir(&quot;reports&quot;, { recursive: true });<br>  await writeFile(<br>    &quot;reports/evaluation.json&quot;,<br>    JSON.stringify(report, null, 2)<br>  );<br>  console.log(JSON.stringify(report, null, 2));<br>  if (<br>    passRate &lt; baseline.passRate ||<br>    passRate &lt; 0.95 ||<br>    criticalFailures.length &gt; 0<br>  ) {<br>    process.exitCode = 1;<br>  }<br>}<br>runEvaluations().catch(error =&gt; {<br>  console.error(error.message);<br>  process.exitCode = 1;<br>});</pre><p>Create an initial baseline after evaluating and approving a known application version.</p><h3>evals/baseline.json</h3><pre>{<br>  &quot;passRate&quot;: 1<br>}</pre><p>The value above is illustrative, not a measured benchmark.</p><p>The evaluation runner now fails if:</p><ul><li>Quality decreases below the approved baseline.</li><li>The overall pass rate drops below 95%.</li><li>Any critical evaluation case fails.</li></ul><p>The thresholds should ultimately reflect the application’s business risk and dataset characteristics.</p><h3>6. Automate regression tests with GitHub Actions</h3><p>Add the following script to package.json:</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;eval&quot;: &quot;tsx evals/runner.ts&quot;<br>  }<br>}</pre><p>Configure an OPENAI_API_KEY repository secret and an LLM_MODEL repository variable containing your chosen compatible model identifier.</p><h3>.github/workflows/llm-evals.yml</h3><pre>name: LLM Regression Tests<br><br>on:<br>  workflow_dispatch:<br>  push:<br>    branches: [main]<br>  schedule:<br>    - cron: &quot;0 2 * * *&quot;<br>permissions:<br>  contents: read<br>jobs:<br>  evaluate:<br>    runs-on: ubuntu-latest<br>    timeout-minutes: 15<br>    steps:<br>      - name: Checkout repository<br>        uses: actions/checkout@v6<br>      - name: Setup Node.js<br>        uses: actions/setup-node@v7<br>        with:<br>          node-version: &quot;24&quot;<br>          cache: npm<br>      - name: Install dependencies<br>        run: npm ci<br>      - name: Run evaluations<br>        run: npm run eval<br>        env:<br>          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}<br>          LLM_MODEL: ${{ vars.LLM_MODEL }}<br>      - name: Save evaluation report<br>        if: always()<br>        uses: actions/upload-artifact@v4<br>        with:<br>          name: llm-evaluation-report<br>          path: reports/</pre><p>Commit your package-lock.json so CI installs the locked dependency versions with npm ci. <a href="https://docs.github.com/en/actions/tutorials/build-and-test-code/nodejs?learn=continuous_integration&amp;learnProduct=actions&amp;utm_source=chatgpt.com">GitHub Docs</a></p><p>This workflow runs evaluations whenever changes reach the main branch, on demand, and once daily.</p><p>For pre-merge release gating, configure a trusted evaluation workflow and required status checks. Avoid exposing API credentials to untrusted pull-request code.</p><h3>7. Moving towards production-grade LLM testing</h3><p>This pipeline provides a starting point, not a complete evaluation platform.</p><p>As the application grows, introduce additional capabilities.</p><pre>| Capability                 | Benefit |<br>| Repeated evaluations       | Account for model variability |<br>| Prompt versioning          | Identify behavioural changes |<br>| Model snapshot tracking    | Improve reproducibility |<br>| Human-reviewed datasets    | Improve evaluation quality |<br>| Token and cost monitoring  | Track operational expenses |<br>| Baseline history           | Identify long-term quality trends |<br>| Human-calibrated scoring   | Evaluate subjective responses |</pre><p>Exact comparisons work well for classification and constrained extraction tasks. Open-ended generation may instead require rubric-based evaluation and human review.</p><p>Avoid automatically updating baselines simply because a new model performs differently. Baseline changes should be reviewed and explicitly approved.</p><h3>Conclusion</h3><p>LLM integration is becoming a software engineering discipline of its own.</p><p>Writing prompts is only one part of building reliable AI applications.</p><p>The more important challenge is establishing measurable behaviour, continuously evaluating it, and preventing quality regressions from reaching users.</p><p><strong>If your application has automated deployment but no automated AI evaluation, you are monitoring code deployment — not necessarily application quality.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f94404c51678" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL Indexes: Why Column Order Matters More Than You Think]]></title>
            <link>https://medium.com/@chintansuryawanshi1/postgresql-indexes-why-column-order-matters-more-than-you-think-07ff60f6f69a?source=rss-74b7a704c704------2</link>
            <guid isPermaLink="false">https://medium.com/p/07ff60f6f69a</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database-optimization]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[performance-engineering]]></category>
            <dc:creator><![CDATA[Chintan Suryawanshi]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 13:46:01 GMT</pubDate>
            <atom:updated>2026-11-24T13:46:01.695Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1g_9_Ho7Agpi-_sQ0G3BVg.png" /><figcaption>A stylized B-tree illustration introducing PostgreSQL composite index column ordering.</figcaption></figure><p><em>Understanding composite B-tree indexes, query patterns, selectivity, and execution plans to design faster database queries.</em></p><p>Adding an index is easy.</p><p>Designing the right index for your application’s workload is where database engineering becomes interesting.</p><p>Consider these two PostgreSQL indexes:</p><pre>CREATE INDEX idx_orders_customer_status<br>ON orders (customer_id, status);</pre><pre>CREATE INDEX idx_orders_status_customer<br>ON orders (status, customer_id);</pre><p>Both contain exactly the same columns. But they are organized differently and can produce very different query execution plans.</p><p>Let’s understand why.</p><h3>1. How composite B-tree indexes work</h3><p>A composite B-tree index organizes entries according to multiple column values.</p><p>Consider an index on:</p><pre>CREATE INDEX idx_customer_created<br>ON orders (customer_id, created_at);s</pre><p>Its logical ordering resembles:</p><pre>| customer_id | created_at |<br>| 101         | 2026-01-01 |<br>| 101         | 2026-02-15 |<br>| 102         | 2026-01-10 |<br>| 102         | 2026-03-20 |<br>| 103         | 2026-02-05 |</pre><p>Entries are ordered primarily by customer_id and subsequently by created_at within each customer group.</p><p>PostgreSQL can exploit this organization to locate a customer’s orders and efficiently narrow the search by date.</p><p>Reversing the columns changes that organization entirely.</p><h3>2. Understanding the leading-column principle</h3><p>Consider this index:</p><pre>CREATE INDEX idx_orders_composite<br>ON orders (customer_id, status, created_at);</pre><p>Different queries can benefit from it differently.</p><pre>| Query filter                      | Typical index suitability |<br>| `customer_id`                     | Excellent |<br>| `customer_id, status`             | Excellent |<br>| `customer_id, status, created_at` | Excellent |<br>| `customer_id, created_at`         | Depends on data distribution |<br>| `status`                          | Often less efficient |<br>| `created_at`                      | Often less efficient |</pre><p>In general, restrictions on the leading columns allow PostgreSQL to narrow the relevant B-tree search range more effectively. <a href="https://www.postgresql.org/docs/18/indexes-multicolumn.html?utm_source=chatgpt.com">postgresql.org</a></p><p>However, the absence of a leading-column filter does <strong>not</strong> mean the index is automatically unusable.</p><p>We’ll revisit that distinction shortly.</p><h3>3. Equality conditions versus range conditions</h3><p>Consider a SaaS application that frequently executes this query:</p><pre>SELECT *<br>FROM orders<br>WHERE customer_id = 101<br>  AND status = &#39;completed&#39;<br>  AND created_at &gt;= &#39;2026-01-01&#39;;</pre><p>A suitable candidate index is:</p><pre>CREATE INDEX idx_orders_lookup<br>ON orders (customer_id, status, created_at);</pre><p>Why?</p><ul><li>customer_id uses an equality condition.</li><li>status uses an equality condition.</li><li>created_at uses a range condition.</li></ul><p>The index can narrow down the customer and status before scanning the relevant date range.</p><p>Now compare it with:</p><pre>CREATE INDEX idx_orders_alternative<br>ON orders (created_at, customer_id, status);</pre><p>Depending on the data distribution, PostgreSQL may need to examine a broader date range before identifying matching customers and statuses.</p><p>A useful starting heuristic is:</p><p><strong>Design around leading equality conditions, followed by range conditions, while accounting for sorting requirements and the wider workload.</strong></p><p>It is a heuristic, not a universal rule.</p><h3>4. Why selectivity isn’t everything</h3><p>A common recommendation is to always put the most selective column first.</p><p>That advice is incomplete.</p><p>Consider these two columns:</p><p>ColumnDistinct valuescustomer_id100,000status4</p><p>You might immediately conclude that customer_id must come first.</p><p>But imagine your application’s primary query is:</p><pre>SELECT *<br>FROM orders<br>WHERE status = &#39;pending&#39;<br>ORDER BY created_at DESC<br>LIMIT 20;</pre><p>An index beginning with customer_id is unlikely to be the best fit for this query.</p><p>A better candidate would be:</p><pre>CREATE INDEX idx_pending_orders<br>ON orders (status, created_at DESC);</pre><p>The important lesson is that index design starts with query patterns, not isolated column statistics.</p><p>High cardinality alone doesn’t determine the ideal column order.</p><h3>5. Using indexes to optimize sorting</h3><p>Indexes aren’t only useful for filtering.</p><p>B-tree indexes can also provide rows in the required order, potentially avoiding an explicit sort.</p><p>Consider:</p><pre>SELECT id, status, created_at<br>FROM orders<br>WHERE customer_id = 101<br>ORDER BY created_at DESC<br>LIMIT 20;</pre><p>A suitable index is:</p><pre>CREATE INDEX idx_recent_customer_orders<br>ON orders (customer_id, created_at DESC);</pre><p>PostgreSQL may use the index to locate the customer and retrieve the most recent matching orders without a separate sorting operation.</p><p>This is especially valuable for:</p><ul><li>Appointment calendars</li><li>Transaction histories</li><li>Customer dashboards</li><li>Activity feeds</li><li>Order management systems</li></ul><p>Whether PostgreSQL chooses that plan depends on estimated execution costs, available statistics, and the query itself.</p><p>B-tree indexes support forward and backward scanning, with column direction becoming particularly important for mixed-direction ordering. <a href="https://www.postgresql.org/docs/16/indexes-ordering.html?utm_source=chatgpt.com">postgresql.org</a></p><h3>6. The PostgreSQL 18 skip-scan exception</h3><p>Traditionally, developers were taught that a composite index was ineffective without a condition on its first column.</p><p>PostgreSQL 18 makes that explanation particularly outdated.</p><p>Consider:</p><pre>CREATE INDEX idx_orders_status_customer<br>ON orders (status, customer_id);</pre><p>And this query:</p><pre>SELECT *<br>FROM orders<br>WHERE customer_id = 101;</pre><p>PostgreSQL can consider a technique called <strong>B-tree skip scan</strong>.</p><p>Because status might have only a few distinct values, the database can perform targeted searches across those groups rather than scanning the entire index.</p><p>Conceptually:</p><pre>Search pending orders for customer 101<br>Search completed orders for customer 101<br>Search cancelled orders for customer 101<br>Search refunded orders for customer 101</pre><p>This can be beneficial when the leading column has sufficiently few distinct values and the later condition is selective.</p><p>But skip scan does not eliminate the need for good index design. PostgreSQL still chooses a plan based on its estimated costs. <a href="https://www.postgresql.org/about/featurematrix/detail/skip-scan-on-multicolumn-b-tree-indexes/?utm_source=chatgpt.com">postgresql.org</a></p><h3>7. Covering indexes and INCLUDE columns</h3><p>Sometimes columns are required in the query results but aren’t needed for searching or sorting.</p><p>Consider:</p><pre>SELECT customer_id, created_at, total_amount<br>FROM orders<br>WHERE customer_id = 101<br>ORDER BY created_at DESC;</pre><p>We could create:</p><pre>CREATE INDEX idx_orders_covering<br>ON orders (customer_id, created_at DESC)<br>INCLUDE (total_amount);</pre><p>Here:</p><ul><li>customer_id and created_at are index keys.</li><li>total_amount is stored as additional payload.</li><li>PostgreSQL may perform an index-only scan when the required visibility conditions are satisfied.</li></ul><p>This approach can reduce heap access, but additional stored columns also increase index size and maintenance costs.</p><h3>8. Verify everything with EXPLAIN ANALYZE</h3><p>Never assume an index improves performance simply because PostgreSQL uses it.</p><p>Measure the actual query.</p><pre>EXPLAIN (ANALYZE, BUFFERS)<br>SELECT *<br>FROM orders<br>WHERE customer_id = 101<br>  AND status = &#39;completed&#39;<br>  AND created_at &gt;= &#39;2026-01-01&#39;;</pre><p>Pay attention to:</p><pre>| Metric                   | What it reveals |<br>| Execution Time           | Actual execution duration |<br>| Index Cond               | Conditions evaluated through the index |<br>| Filter                   | Additional filtering applied |<br>| Rows Removed by Filter   | Unnecessary rows processed |<br>| Buffers                  | Page access and cache activity |<br>| Sort                     | Whether explicit sorting occurs |<br>| Estimated vs Actual Rows | Quality of planner estimates |</pre><p>Remember that a sequential scan can legitimately outperform an index scan when a query retrieves a large portion of the table.</p><p>The goal is efficient query execution, not forcing every query to use an index.</p><h3>9. The cost of excessive indexing</h3><p>Indexes are not free.</p><p>Every additional index introduces potential costs:</p><ul><li>Increased storage consumption</li><li>Additional write overhead</li><li>More maintenance work</li><li>Greater memory pressure</li><li>Potentially slower inserts, updates, and deletes</li></ul><p>Before adding another composite index, examine whether an existing one already supports the workload.</p><p>For example, an index on (customer_id, status) may make another index on (customer_id) redundant for some workloads, although the smaller index can still have advantages.</p><p>Measure before removing either.</p><h3>Conclusion</h3><p>The best PostgreSQL index isn’t necessarily the one with the most columns or the most selective column first.</p><p>It’s the one designed around how your application actually accesses data.</p><p>Before creating a composite index:</p><ol><li>Identify frequently executed queries.</li><li>Study equality and range predicates.</li><li>Consider sorting and pagination.</li><li>Examine column cardinality and data distribution.</li><li>Compare execution plans.</li><li>Evaluate read improvements against write costs.</li></ol><p><strong>An index isn’t just a performance feature. It’s a data access design decision.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07ff60f6f69a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Next.js Dashboard That Loads in Layers]]></title>
            <link>https://medium.com/@chintansuryawanshi1/building-a-next-js-dashboard-that-loads-in-layers-debe715cbd23?source=rss-74b7a704c704------2</link>
            <guid isPermaLink="false">https://medium.com/p/debe715cbd23</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Chintan Suryawanshi]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 17:01:13 GMT</pubDate>
            <atom:updated>2026-11-23T17:01:13.565Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mn44RNtttSZMMwQnVMRRWw.png" /><figcaption>Design scalable SaaS dashboards using Server Components, Suspense and parallel data fetching.</figcaption></figure><p>Modern SaaS dashboards often combine multiple independent data sources: revenue metrics, appointment records, activity feeds, charts and notifications.</p><p>The architectural challenge isn’t necessarily fetching all this information. It’s deciding when each piece of information should become visible.</p><p>If one slow API prevents an entire dashboard from rendering, users wait even when most of the information is already available.</p><p>Next.js provides a different approach. By combining Server Components, parallel data fetching and React Suspense boundaries, developers can progressively reveal content rather than treating the entire page as one loading operation.</p><p>Let’s explore this through an illustrative SaaS analytics dashboard.</p><h3>1. The problem: blocking the entire dashboard</h3><p>Consider a dashboard containing three sections:</p><ul><li>Revenue summary</li><li>Recent transactions</li><li>Performance analytics</li></ul><p>A typical implementation might look like this:</p><pre>export default async function DashboardPage() {<br>  const revenue = await getRevenue();<br>  const transactions = await getTransactions();<br>  const analytics = await getAnalytics();<br><br>return (<br>    &lt;&gt;<br>      &lt;RevenueSummary data={revenue} /&gt;<br>      &lt;TransactionsTable data={transactions} /&gt;<br>      &lt;AnalyticsChart data={analytics} /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>This introduces two limitations:</p><ul><li>Independent requests execute sequentially.</li><li>The dashboard waits for every request before returning its content.</li></ul><p>Even when two sections are ready, the remaining request can delay the entire page.</p><h3>2. Parallel data fetching</h3><p>The first improvement is to initiate independent requests concurrently.</p><pre>const [revenue, transactions, analytics] =<br>  await Promise.all([<br>    getRevenue(),<br>    getTransactions(),<br>    getAnalytics(),<br>  ]);</pre><p>This removes unnecessary sequential waiting.</p><p>However, Promise.all() still waits for every promise to resolve successfully before continuing.</p><p>Parallel data fetching addresses unnecessary dependencies between requests. Streaming addresses unnecessary dependencies in rendering.</p><p>Both matter.</p><h3>3. Establish Server and Client Component boundaries</h3><p>Next.js App Router pages and layouts are Server Components by default.</p><p>Keep data retrieval and non-interactive presentation on the server where appropriate. Introduce Client Components only where browser APIs, state or user interaction are required.</p><p>A possible project structure:</p><pre>app/<br>  dashboard/<br>    page.tsx<br>    components/<br>      RevenuePanel.tsx<br>      TransactionsPanel.tsx<br>      AnalyticsPanel.tsx<br>      ChartControls.tsx<br>    lib/<br>      data.ts</pre><p>An interactive chart control could use a Client Component:</p><pre>&#39;use client&#39;;<br><br>import { useState } from &#39;react&#39;;<br><br>export default function ChartControls() {<br>  const [expanded, setExpanded] = useState(false);<br>  <br>return (<br>    &lt;button<br>      onClick={() =&gt; setExpanded(!expanded)}<br>      aria-expanded={expanded}<br>    &gt;<br>      {expanded ? &#39;Show less&#39; : &#39;Show more&#39;}<br>    &lt;/button&gt;<br>  );<br>}</pre><p>There is no need to turn the whole dashboard into a Client Component just because one section needs interactivity.</p><h3>4. Introduce independent Suspense boundaries</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Ub7-B0IkkbgcXrXKie8Fw.png" /></figure><p>Each section can reveal its content independently when ready.</p><pre>import { Suspense } from &#39;react&#39;;<br><br>export default function DashboardPage() {<br>  const revenue = getRevenue();<br>  const transactions = getTransactions();<br>  const analytics = getAnalytics();<br><br>return (<br>    &lt;main&gt;<br>      &lt;h1&gt;Analytics Dashboard&lt;/h1&gt;<br>      &lt;Suspense fallback={&lt;RevenueSkeleton /&gt;}&gt;<br>        &lt;RevenuePanel data={revenue} /&gt;<br>      &lt;/Suspense&gt;<br>      &lt;Suspense fallback={&lt;TransactionsSkeleton /&gt;}&gt;<br>        &lt;TransactionsPanel data={transactions} /&gt;<br>      &lt;/Suspense&gt;<br>      &lt;Suspense fallback={&lt;AnalyticsSkeleton /&gt;}&gt;<br>        &lt;AnalyticsPanel data={analytics} /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><p>Each Server Component awaits only its required data.</p><pre>type Revenue = {<br>  amount: number;<br>  currency: string;<br>};<br><br>export default async function RevenuePanel({<br>  data,<br>}: {<br>  data: Promise&lt;Revenue&gt;;<br>}) {<br>  const revenue = await data;<br>  return (<br>    &lt;section&gt;<br>      &lt;h2&gt;Revenue&lt;/h2&gt;<br>      &lt;p&gt;<br>        {new Intl.NumberFormat(&#39;en-US&#39;, {<br>          style: &#39;currency&#39;,<br>          currency: revenue.currency,<br>        }).format(revenue.amount)}<br>      &lt;/p&gt;<br>    &lt;/section&gt;<br>  );<br>}</pre><p>The remaining panels follow the same pattern with their appropriate data types.</p><p>The data-access functions represent illustrative application services. Their actual implementation depends on your API or database.</p><h3>5. Design loading and error states deliberately</h3><p>For each dashboard section, ask:</p><ul><li>Does the user need this information immediately?</li><li>Can the information be fetched independently?</li><li>Would loading it separately create an inconsistent experience?</li></ul><p>Use appropriately sized skeletons to reduce layout shifts.</p><p>Remember that Suspense is not a complete error-handling strategy. Implement appropriate error boundaries and meaningful unavailable states.</p><p>For critical financial and business information, explicitly displaying unavailable data is preferable to displaying a misleading zero.</p><h3>6. Consider production trade-offs</h3><p>Concern — — — — — — — — — — — Engineering decision</p><p>JavaScript — — — — — —— — — — Keep client boundaries small</p><p>Backend load — — — — — — — — Avoid unnecessary concurrent requests</p><p>Data consistency — — — — — — Group dependent data appropriately</p><p>Caching — — — — — — — — — — Define suitable freshness requirements</p><p>User experience — — — — — — Use meaningful loading boundaries</p><p>Deployment — — — — — — — — Verify streaming support</p><p>Streaming can help useful sections become visible earlier, but it does not make database queries inherently faster.</p><p>Measure actual performance using browser recordings, server timings and network behavior.</p><h3>Conclusion</h3><p>A responsive Next.js dashboard is not simply a page with faster APIs.</p><p>It is a collection of carefully designed rendering and data boundaries.</p><ul><li>Start independent requests concurrently.</li><li>Keep appropriate functionality on the server.</li><li>Use Suspense around meaningful sections.</li><li>Handle loading and errors deliberately.</li><li>Measure actual performance.</li></ul><p>Design around the information your users need first.</p><p>That is the difference between waiting for a complete dashboard and progressively delivering a useful one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=debe715cbd23" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>