<?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 Juan Andrés Leiva on Medium]]></title>
        <description><![CDATA[Stories by Juan Andrés Leiva on Medium]]></description>
        <link>https://medium.com/@andresleiva.4?source=rss-c76ca4406d24------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fWam1MQKHPD-nswd</url>
            <title>Stories by Juan Andrés Leiva on Medium</title>
            <link>https://medium.com/@andresleiva.4?source=rss-c76ca4406d24------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:00:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andresleiva.4/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[Scaling Out SignalR: In-Memory State Behind a Load Balancer]]></title>
            <link>https://levelup.gitconnected.com/scaling-out-signalr-in-memory-state-behind-a-load-balancer-926f6d995867?source=rss-c76ca4406d24------2</link>
            <guid isPermaLink="false">https://medium.com/p/926f6d995867</guid>
            <category><![CDATA[signalr]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Juan Andrés Leiva]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 00:00:31 GMT</pubDate>
            <atom:updated>2026-08-05T19:10:03.557Z</atom:updated>
            <content:encoded><![CDATA[<p>A few years ago, I was the architect on a live collaboration tool. Multiple users joined the same session, worked over shared mutable state for hours, and everything traveled through SignalR. The product grew, and we had over 10.000 simultaneous users, and we decided to put more instances behind the load balancer.</p><p>Then the tickets started. Users inside the same session could not see each other. In all the meetings, there were reports of users being isolated or in smaller groups than they should have been. Nothing crashed, and nothing logged an error. The system was healthy by every measure we had.</p><p>Put side by side, the reports had a shape: the groups users saw were always subsets of their real session, never wrong ones, and which subset you got depended on who you asked. That shape pointed at only one place: our presence tracking lived in an in-memory dictionary, and after the scale-out it got distributed into different servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*WA8ruOzE_7xQKTo8yn7spw.png" /></figure><h3>Every server had its own reality</h3><p>The design was reasonable when it was written. When we had only one server, having one dictionary mapping connections to users made sense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*M48PDSVHS3j8yq7g9VlI_g.png" /><figcaption>One server holding a single presence dictionary that contains every connected user</figcaption></figure><p>But scaling it out partitioned the state:</p><p><strong>The state partitioned.</strong> Each instance kept its own private dictionary. A user who landed on server two was written into server two’s memory and nowhere else. Asking “<em>who is in this session</em>” returned whoever happened to share your server. SignalR’s Clients.All means <em>all clients connected to this process</em>. Without a backplane, a presence update raised on server two never reached the browsers attached to the other servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*w6oEalmLMSSMgOV7HmIHhg.png" /><figcaption>A load balancer spreading three users across three servers, each with a private dictionary holding only its own user, so every user sees a different reality</figcaption></figure><p>A user did not get an incomplete list once and recover. The list stayed wrong in the same way for as long as the connection lived, and reconnecting did not help, because the balancer pinned you right back to the same server.</p><h3>Sticky sessions solve a different problem</h3><p>We did have sticky sessions. New connections were spread across the servers and then pinned, so each user stayed on one server for as long as they were connected. But affinity binds a client to a server, and the thing our state was about was not a client. It was a session: a group of people working together for hours. Nothing pinned the members of one session to the same server, so the balancer scattered them across the whole pool, and each dictionary held only the fragment of the group that happened to land on it. The affinity was real, and it was doing its job. It was doing it at the wrong granularity.</p><h3>Why the development environment did not catch the issue</h3><p>We did not catch this in development because it was not catchable there. We had one dev server. Every client in every test landed in the same process and shared the same dictionary. Staging was topologically identical to production: multiple instances behind the same balancer with the same affinity. It still could not catch this. One tester on one computer is one client for the balancer to pin, and therefore one server, so every simulated user in the test shared a process exactly as they had on the single-instance dev box. What staging was missing was never more servers. It was more clients. The test suite passed because the code was, on a single instance, genuinely correct, and we failed to produce the same conditions real users had in production. This was a serious point in our post-mortem, and out of it came a new checklist we used from then on to evaluate every infrastructure change before deploying it. The incident also became a lecture: I walked the whole engineering team through it as a distributed-systems teaching moment, so the lesson would not stay locked inside the people who debugged it.</p><p>The bug did not exist until the new instances came up in production. It was created by the deployment topology, retroactively, in code nobody had touched for months.</p><p>That is the part worth generalizing. Every piece of state you keep in process memory carries an invisible assumption: <em>all traffic sees this memory</em>. Nothing in the type system records that assumption, and tests do not necessarily fail when it stops holding. The change that broke us did not touch application code at all. It was capacity work, adding instances, the kind of change that reads as an ops ticket.</p><h3>The part that was on me</h3><p>I greenlighted that change. The dev tests passed, the rollout plan looked clean, and I did not ask the one question that mattered: <strong><em>how does the infrastructure change affect the code it is supporting?</em></strong></p><p>Reviewing the scale-out as a design change, not a capacity change, was exactly my job, and I treated it as routine instead. The developers had implemented the tracker correctly for the system it was born into, and the tests honestly reported that it worked. The process had no step where “<em>what does this code mean on N machines</em>” would ever be asked.</p><h3>Rebuilding the bug so you can run it</h3><p>I could not show you the original system, so I rebuilt the failure in miniature: <a href="https://github.com/jandresleiva/signalr-redis-backplane-demo">signalr-redis-backplane-demo</a>, a docker-compose stack with three ASP.NET Core instances behind round-robin nginx, a presence hub, and a page that shows two things — which instance your tab landed on, and who it thinks is online. The infrastructure has its own walkthroughs in the repo ( <a href="https://github.com/jandresleiva/signalr-redis-backplane-demo/blob/main/docs/nginx.md">the nginx configuration</a> and <a href="https://github.com/jandresleiva/signalr-redis-backplane-demo/blob/main/docs/docker-compose.md">the compose topology</a>), so this article can stay about the bug.</p><p>Two differences from production are deliberate, and both come from the same constraint. Production had affinity and thousands of separate clients for the balancer to scatter. A laptop has one client, and every tab of one browser looks the same to the balancer, so affinity in the repro would pin all of them to one instance and hide the bug. The repro therefore drops affinity, and must skip SignalR’s negotiate step as a consequence, since the default handshake is what needs the affinity in the first place; a tab is then one request that lands on one instance. It also collapses the collaborative session into one global room; the production fix stayed at the session’s granularity, with presence keyed per session and updates sent to that session’s group rather than to every connected client. The invariant it demonstrates is the same: the presence list lives inside one process, and there is more than one process.</p><p>The entire lesson lives in one interface with two implementations:</p><pre>public interface IPresenceTracker<br>{<br>    Task AddAsync(string connectionId, string name);<br>    Task RemoveAsync(string connectionId);<br>    Task&lt;IEnumerable&lt;string&gt;&gt; GetAllAsync();<br>}</pre><p>The broken implementation is the one we shipped, reduced to its essence:</p><pre>// THE BUG: this dictionary lives inside one process. On a single instance it is<br>// perfectly correct. Behind a round-robin load balancer each of the three<br>// instances keeps its own private copy, so a user only ever sees the users who<br>// happened to land on the same instance. Nothing crashes and nothing logs an<br>// error -- the app just quietly shows everyone a different reality.<br>public class InMemoryPresenceTracker : IPresenceTracker<br>{<br>    private readonly ConcurrentDictionary&lt;string, string&gt; _users = new();<br><br>    public Task AddAsync(string connectionId, string name)<br>    {<br>        _users[connectionId] = name;<br>        return Task.CompletedTask;<br>    }<br><br>    public Task RemoveAsync(string connectionId)<br>    {<br>        _users.TryRemove(connectionId, out _);<br>        return Task.CompletedTask;<br>    }<br><br>    public Task&lt;IEnumerable&lt;string&gt;&gt; GetAllAsync()<br>    {<br>        return Task.FromResult&lt;IEnumerable&lt;string&gt;&gt;(_users.Values.ToList());<br>    }<br>}</pre><p>Run the broken mode and open a few tabs:</p><pre>docker compose up --build<br># open http://localhost:8080 in six tabs, join with different names</pre><p>Each tab tells you which instance it landed on. Tabs on different instances show different user lists, live, with no errors anywhere. The tabs make the bug visible; the test/ directory in the repo makes it objective, connecting six scripted SignalR clients through nginx and reporting what each one saw. This is the output of a run:</p><pre>&quot;instanceSpread&quot;: {<br>  &quot;app2&quot;: [&quot;user1&quot;, &quot;user4&quot;],<br>  &quot;app3&quot;: [&quot;user2&quot;, &quot;user5&quot;],<br>  &quot;app1&quot;: [&quot;user3&quot;, &quot;user6&quot;]<br>},<br>&quot;distinctFinalLists&quot;: [<br>  [&quot;user1&quot;, &quot;user4&quot;],<br>  [&quot;user2&quot;, &quot;user5&quot;],<br>  [&quot;user3&quot;, &quot;user6&quot;]<br>],<br>&quot;allAgree&quot;: false</pre><p>Six users, three disjoint answers. This was what hit us in production, with over ten thousand concurrent users and no error logs. That afternoon was mayhem.</p><h3>The fix</h3><p>We resolved it by moving the state out of the process and into Redis. There are two separate problems, and each needs its own fix:</p><p><strong>The broadcasts need a backplane.</strong> AddStackExchangeRedis makes every instance relay its Clients.All sends through Redis pub/sub, so a presence update raised on one server reaches browsers attached to all of them.</p><p><strong>The state needs to move out.</strong> The backplane does nothing for the dictionary. If the data itself stays per-process, every instance still answers “who is online” from its private copy. It just broadcasts its wrong answer more widely. The tracker has to read and write shared storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*Ujcp0-lfwQKs1HrgADTZYw.png" /><figcaption>The same three servers now sharing one Redis instance that relays broadcasts between them and holds the single presence list every instance reads</figcaption></figure><p>In the repro, both fixes together are this:</p><pre>if (mode == &quot;redis&quot;)<br>{<br>    // With abortConnect=false the multiplexer starts even if Redis is not up<br>    // yet and connects in the background.<br>    IConnectionMultiplexer redis =<br>        await ConnectionMultiplexer.ConnectAsync(redisConnection + &quot;,abortConnect=false&quot;);<br>    builder.Services.AddSingleton(redis);<br><br>    // The backplane relays Clients.All broadcasts between instances...<br>    signalR.AddStackExchangeRedis(options =&gt; options.ConnectionFactory = _ =&gt; Task.FromResult(redis));<br>    // ...and the shared tracker makes every instance agree on who is online.<br>    builder.Services.AddSingleton&lt;IPresenceTracker, RedisPresenceTracker&gt;();<br>}</pre><pre>public class RedisPresenceTracker : IPresenceTracker<br>{<br>    private const string Key = &quot;presence&quot;;<br>    private readonly IDatabase _db;<br><br>    public RedisPresenceTracker(IConnectionMultiplexer redis)<br>    {<br>        _db = redis.GetDatabase();<br>    }<br><br>    public Task AddAsync(string connectionId, string name)<br>    {<br>        return _db.HashSetAsync(Key, connectionId, name);<br>    }<br><br>    public Task RemoveAsync(string connectionId)<br>    {<br>        return _db.HashDeleteAsync(Key, connectionId);<br>    }<br><br>    public async Task&lt;IEnumerable&lt;string&gt;&gt; GetAllAsync()<br>    {<br>        var entries = await _db.HashGetAllAsync(Key);<br>        return entries.Select(e =&gt; e.Value.ToString()).ToList();<br>    }<br>}</pre><p>Same stack, same nginx, same three instances:</p><pre>docker compose down<br>PRESENCE_MODE=redis docker compose up</pre><p>Open the same tabs again. Every tab now shows every user, no matter which instance it landed on.</p><h3>Where this leaves you</h3><p>The dictionary was the right call when we had only one server. The rule it broke only came into force later: a process can scale horizontally only while the state it holds is either a disposable copy of truth kept somewhere else, or data scoped to a single connection. Everything else makes the process the authority for that data. Our dictionary was the authority for “who is online”, so adding instances quietly created many authorities where the design assumed one, partitioned by server when the thing they were authoritative about was a session. Nothing in the system had ever been asked to notice the difference.</p><p>The fix has real costs, and it is worth naming them instead of presenting Redis as a happy ending. Every join and leave now pays a network round trip on what used to be a dictionary lookup. Redis becomes a dependency to size, monitor, and make redundant, because centralizing the truth also centralizes the failure domain. Broadcasts cross the network twice, once in to the backplane and once out to every instance. Shared presence entries outlive a hard-killed instance unless something sweeps them, which is why real systems pair this pattern with a TTL or a heartbeat. And the backplane itself is pub/sub with at-most-once delivery, so a dropped message leaves a client holding a stale list until the next event; the fix does not eliminate silent divergence so much as move it behind a dependency you can monitor. If you would rather buy than operate, that is what a managed service like Azure SignalR Service gives you for the connection and broadcast half. The state still has to live somewhere shared.</p><p>Sticky sessions are not the shortcut past any of this; we already had them and kept them afterwards. Every pin is also drawn again on the next deploy or failover, so even the per-client stability it gives you is only as durable as the topology.</p><p>I will leave you with one question. For every static, singleton, and cache in a system that runs on more than one instance: <strong><em>is this memory the authority for something, or a copy of it?</em></strong></p><p><em>Originally published at </em><a href="https://andresleiva.com/blog/scaling-out-signalr-in-memory-state/"><em>https://andresleiva.com</em></a><em> on August 3, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=926f6d995867" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/scaling-out-signalr-in-memory-state-behind-a-load-balancer-926f6d995867">Scaling Out SignalR: In-Memory State Behind a Load Balancer</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[Postgres Index Types Explained: B-tree, GIN, BRIN, and Operators]]></title>
            <link>https://levelup.gitconnected.com/postgres-index-types-explained-b-tree-gin-brin-and-operators-6d89177af2e2?source=rss-c76ca4406d24------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d89177af2e2</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Juan Andrés Leiva]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 00:00:54 GMT</pubDate>
            <atom:updated>2026-07-29T19:40:46.714Z</atom:updated>
            <content:encoded><![CDATA[<p>In my <a href="https://andresleiva.com/blog/postgres-json-vs-jsonb">post about JSON and JSONB</a> I told you to create a GIN index with jsonb_path_ops and moved on, because that post was about a column type and not about indexing. This one pays the debt. What a GIN index actually is, why Postgres ships five other index types.</p><p>Every example below runs as written on a stock Postgres 17. The plans and sizes are real output from my machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WjoUOlMmec5nFyyFHJAw8Q.jpeg" /></figure><h3>An index is a bet</h3><p>An index is a separate data structure that trades write speed and disk for read speed. Every insert and update has to maintain every index on the table, and every index occupies real space, which you will see measured at the end of this post. That framing matters because the question is never “should I index this table” but “which reads are worth taxing my writes for”. An index that no query uses is a pure tax.</p><h3>Indexes accelerate operators, not columns</h3><p>When the planner considers an index, it does not ask “is there an index on this column”. It asks “is there an index whose type knows how to answer this operator”. A B-tree knows how to answer =, &lt;, &lt;=, &gt;=, &gt; and BETWEEN, because it keeps values in sorted order. It has no idea what to do with the array containment operator @&gt;. A GIN index answers @&gt; natively and cannot help you with &lt;.</p><p>The glue between an index type and the operators it serves is called an operator class. Most of the time the default class is what you want and you never type its name. The moment it becomes practical is when one index type offers a choice, which is exactly the jsonb_ops versus jsonb_path_ops decision from the JSONB post: same GIN machinery, different set of supported operators, different size.</p><p>Keep that lens for the rest of the post. Each index type below is just a different answer to the question “which operators do you need to be fast”.</p><h3>The demo table</h3><p>One table, one million rows, shaped like an event log because that is where indexing decisions get interesting: a user id to look up, a status that is almost always ok, a tags array, and a timestamp that grows with insert order.</p><pre>CREATE TABLE events (<br>  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,<br>  user_id    int    NOT NULL,<br>  status     text   NOT NULL,<br>  tags       text[] NOT NULL,<br>  created_at timestamptz NOT NULL<br>);<br><br>INSERT INTO events (user_id, status, tags, created_at)<br>SELECT<br>  i % 50000,<br>  CASE WHEN i % 211 = 0 THEN &#39;failed&#39; ELSE &#39;ok&#39; END,<br>  ARRAY[&#39;app&#39; || i % 7, (ARRAY[&#39;auth&#39;, &#39;billing&#39;, &#39;search&#39;, &#39;export&#39;, &#39;sync&#39;])[1 + i % 5]]<br>    || CASE WHEN i % 397 = 0 THEN ARRAY[&#39;beta&#39;] ELSE &#39;{}&#39; END,<br>  timestamptz &#39;2026-01-01 00:00:00+00&#39; + i * interval &#39;2 seconds&#39;<br>FROM generate_series(0, 999999) AS i;<br><br>ANALYZE events;</pre><h3>Life without an index</h3><p>Ask for one user’s events with nothing but the primary key in place:</p><pre>EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)<br>SELECT * FROM events WHERE user_id = 12345;</pre><pre>Gather (actual rows=20 loops=1)<br>   Workers Planned: 2<br>   Workers Launched: 2<br>   -&gt;  Parallel Seq Scan on events (actual rows=7 loops=3)<br>         Filter: (user_id = 12345)<br>         Rows Removed by Filter: 333327<br> Planning Time: 0.083 ms<br> Execution Time: 15.696 ms</pre><p>Postgres read the entire table and threw two parallel workers at it to make that less painful. Twenty matching rows required inspecting a million. A sequential scan is the baseline, and on small tables it is often the genuinely fastest plan. On a million rows, for twenty matches, it is the thing indexes exist to avoid.</p><h3>B-tree, the default for a reason</h3><p>CREATE INDEX with no USING clause gives you a B-tree, a balanced tree of sorted values. Sorted order is why it covers the widest set of operators: equality, every comparison, BETWEEN, and it can feed ORDER BY without a sort step.</p><pre>CREATE INDEX events_user_id_idx ON events (user_id);<br><br>EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)<br>SELECT * FROM events WHERE user_id = 12345;</pre><pre>Bitmap Heap Scan on events (actual rows=20 loops=1)<br>   Recheck Cond: (user_id = 12345)<br>   Heap Blocks: exact=20<br>   -&gt;  Bitmap Index Scan on events_user_id_idx (actual rows=20 loops=1)<br>         Index Cond: (user_id = 12345)<br> Planning Time: 0.087 ms<br> Execution Time: 0.046 ms</pre><p>From 15.7 milliseconds to 0.046. Same query, same data, three hundred times faster.</p><blockquote>A bitmap scan is a two-phase strategy. The Bitmap Index Scan walks the index and collects the locations of every matching row into a bitmap in memory. The Bitmap Heap Scan then sorts those locations by page and visits each table page exactly once. When matches are scattered across the table, as they are here, this beats jumping back and forth between index and table row by row. You will meet this plan shape with every index type in this post, because GIN and BRIN produce their results as bitmaps by nature.</blockquote><p>The same B-tree serves range queries for free:</p><pre>EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)<br>SELECT * FROM events WHERE user_id BETWEEN 100 AND 199;</pre><pre>Bitmap Heap Scan on events (actual rows=2000 loops=1)<br>   Recheck Cond: ((user_id &gt;= 100) AND (user_id &lt;= 199))<br>   Heap Blocks: exact=41<br>   -&gt;  Bitmap Index Scan on events_user_id_idx (actual rows=2000 loops=1)<br>         Index Cond: ((user_id &gt;= 100) AND (user_id &lt;= 199))<br> Planning Time: 0.048 ms<br> Execution Time: 0.137 ms</pre><p>If your predicate is equality or ordering on a scalar, the B-tree is almost always the answer, which is why it is the default.</p><h3>GIN, the inverted index</h3><p>A B-tree stores one entry per row. That model collapses when a single value contains many searchable elements: an array of tags, the keys of a jsonb document, the words of a text document. You do not want an entry per row, you want an entry per element, pointing back at every row containing it. That structure is an inverted index, and in Postgres it is called GIN, for Generalized Inverted Index.</p><pre>CREATE INDEX events_tags_idx ON events USING gin (tags);<br><br>EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)<br>SELECT * FROM events WHERE tags @&gt; ARRAY[&#39;beta&#39;];</pre><pre>Bitmap Heap Scan on events (actual rows=2519 loops=1)<br>   Recheck Cond: (tags @&gt; &#39;{beta}&#39;::text[])<br>   Heap Blocks: exact=2519<br>   -&gt;  Bitmap Index Scan on events_tags_idx (actual rows=2519 loops=1)<br>         Index Cond: (tags @&gt; &#39;{beta}&#39;::text[])<br> Planning Time: 0.105 ms<br> Execution Time: 1.712 ms</pre><p>The @&gt; containment operator asks &quot;does this array contain these elements&quot;, the GIN index looks up beta in its element catalog, and 2,519 rows come back without touching the other 997,481. Swap the array for a jsonb column and this is exactly the index and operator pair from the JSONB post. Full-text search runs on the same machinery.</p><p>The cost side: GIN is the most expensive index here to maintain on writes, because one row insert may add many index entries. It earns that cost only when your queries genuinely ask containment-style questions.</p><h3>BRIN, the index that is barely there</h3><p>BRIN, Block Range Index, does not store row locations at all. It stores a summary per range of table pages, by default the minimum and maximum value found in each range of 128 pages. A query for a value range lets Postgres skip every block range whose summary cannot contain a match.</p><p>That only works when the physical layout correlates with the values, which is precisely the situation of a timestamp on an append-only table: rows arrive in time order, so each block range covers a narrow slice of time.</p><pre>CREATE INDEX events_created_brin ON events USING brin (created_at);<br><br>EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)<br>SELECT count(*) FROM events<br>WHERE created_at &gt;= &#39;2026-01-10&#39; AND created_at &lt; &#39;2026-01-11&#39;;</pre><pre>Aggregate (actual rows=1 loops=1)<br>   -&gt;  Bitmap Heap Scan on events (actual rows=43200 loops=1)<br>         Recheck Cond: ((created_at &gt;= &#39;2026-01-10 00:00:00+00&#39;...))<br>         Rows Removed by Index Recheck: 13120<br>         Heap Blocks: lossy=640<br>         -&gt;  Bitmap Index Scan on events_created_brin (actual rows=6400 loops=1)<br>               Index Cond: (...)<br> Planning Time: 0.093 ms<br> Execution Time: 3.755 ms</pre><p>Note lossy=640 and the recheck removing 13,120 rows. BRIN cannot say &quot;row 5 matches&quot;, only &quot;something in these pages might match&quot;, so Postgres visits the candidate pages and filters. That imprecision is the price of the headline number:</p><pre>CREATE INDEX events_created_btree ON events (created_at);<br><br>SELECT relname AS index_name, pg_size_pretty(pg_relation_size(oid)) AS size<br>FROM pg_class<br>WHERE relname IN (&#39;events_created_brin&#39;, &#39;events_created_btree&#39;);</pre><pre>index_name      | size<br>----------------------+-------<br> events_created_brin  | 24 kB<br> events_created_btree | 21 MB</pre><p>Twenty-four kilobytes against twenty-one megabytes for the same column, a factor of nearly a thousand. On logging, metrics, and event tables that only grow, <strong>BRIN buys you most of the benefit for a rounding error of disk and near-zero write overhead. On columns with no physical correlation it buys you nothing</strong>, which is the trade in one sentence.</p><h3>Partial and expression indexes</h3><p>These are not index types but modifiers that apply to any of the above, and they solve extremely common problems.</p><p>A partial index carries a WHERE clause and only indexes matching rows. My status column is failed in less than half a percent of rows, and failed rows are the only ones I ever look up by status:</p><pre>CREATE INDEX events_failed_idx ON events (created_at) WHERE status = &#39;failed&#39;;<br><br>EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)<br>SELECT * FROM events<br>WHERE status = &#39;failed&#39; AND created_at &gt;= &#39;2026-01-20&#39;;</pre><pre>Index Scan using events_failed_idx on events (actual rows=849 loops=1)<br>   Index Cond: (created_at &gt;= &#39;2026-01-20 00:00:00+00&#39;...)<br> Planning Time: 0.226 ms<br> Execution Time: 0.515 ms</pre><p>The index is 120 kB against 21 MB for its full-table equivalent, and every insert of an ok row skips it entirely. This plan is also a plain Index Scan rather than a bitmap: few enough rows, so Postgres walks the index and fetches rows directly.</p><p>An expression index indexes the result of an expression instead of a raw column, which is how you index lower(email), or a single hot key extracted from a jsonb document:</p><pre>CREATE INDEX chunks_source_type_idx ON chunks ((metadata -&gt;&gt; &#39;source_type&#39;));</pre><p>That line is lifted directly from the JSONB post, and it is worth restating what it does: it gives one JSON key an ordinary B-tree with ordinary statistics, no GIN involved.</p><h3>The bill</h3><p>Everything above, measured. This is the table and every index this post created on it:</p><pre>relname               |    size<br>----------------------+------------<br> events               | 89 MB<br> events_pkey          | 21 MB<br> events_created_btree | 21 MB<br> events_user_id_idx   | 7600 kB<br> events_tags_idx      | 2360 kB<br> events_failed_idx    | 120 kB<br> events_created_brin  | 24 kB</pre><p>The indexes together add up to more than half the size of the table itself, and every row written pays maintenance on all of them. This is why “just add an index” is not free advice, and why the sizes span three orders of magnitude for the same job on the same data.</p><h3>Let the operator choose</h3><p>After all of this, the decision procedure is short, because the operator in your WHERE clause has already made it. Equality and ranges on scalars want a B-tree. Containment questions against arrays, jsonb, or text search want GIN. Time ranges over huge append-only tables want BRIN. Then partial and expression modifiers narrow whichever one you picked to the rows and expressions you actually query.</p><p>When a plan surprises you, read it with the operator lens: EXPLAIN ANALYZE tells you which index answered which condition, and a sequential scan usually means no index on the table speaks the operator you used, or the table is small enough that speaking it does not matter.</p><p>If the GIN line in my JSONB post sent you here, you now have the whole picture: <a href="https://andresleiva.com/blog/postgres-json-vs-jsonb">the column type</a> decides which operators exist, and the operators decide which index earns its disk.</p><p><em>Originally published at </em><a href="https://andresleiva.com/blog/postgres-index-types/"><em>https://andresleiva.com</em></a><em> on July 28, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d89177af2e2" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/postgres-index-types-explained-b-tree-gin-brin-and-operators-6d89177af2e2">Postgres Index Types Explained: B-tree, GIN, BRIN, and Operators</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[Postgres JSON vs JSONB: Storing Data Chunks for AI Processing]]></title>
            <link>https://levelup.gitconnected.com/postgres-json-vs-jsonb-storing-data-chunks-for-ai-processing-2de178c396ab?source=rss-c76ca4406d24------2</link>
            <guid isPermaLink="false">https://medium.com/p/2de178c396ab</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Juan Andrés Leiva]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 00:00:11 GMT</pubDate>
            <atom:updated>2026-07-29T19:39:27.418Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently started storing chunks of documents for AI processing, and a decision I had been postponing for years finally caught up with me. Every chunk carries a bag of metadata; the metadata had to live somewhere, and Postgres offers two column types for it: json and jsonb. They accept exactly the same input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WaFfHX_ZMq_y0zkpXVuKEA.jpeg" /></figure><h3>They accept the same input and store different things</h3><p>The fastest way to see the difference is to feed both types the same slightly hostile payload: odd whitespace and a duplicated key.</p><pre>SELECT &#39;{&quot;b&quot;: 1,  &quot;a&quot;: 2, &quot;a&quot;: 3}&#39;::json  AS stored_as_json;<br>SELECT &#39;{&quot;b&quot;: 1,  &quot;a&quot;: 2, &quot;a&quot;: 3}&#39;::jsonb AS stored_as_jsonb;</pre><pre>stored_as_json<br>---------------------------<br> {&quot;b&quot;: 1,  &quot;a&quot;: 2, &quot;a&quot;: 3}<br><br> stored_as_jsonb<br>------------------<br> {&quot;a&quot;: 3, &quot;b&quot;: 1}</pre><p>The json column gave me back the exact bytes I sent, double space and duplicate key included. The jsonb column reordered the keys, collapsed the duplicate to the last value, and normalized the whitespace, because it did not store my text at all. It parsed the document once, on write, into a decomposed binary format, and what I get back is a rendering of that structure.</p><h3>Where the difference starts costing you</h3><ul><li><strong>Reads.</strong> Every operator you apply to a json value re-parses the whole document from text. jsonb navigates its binary structure directly.</li><li><strong>Writes.</strong> jsonb pays the parsing and conversion cost on insert.</li><li><strong>Indexing.</strong> jsonb supports GIN indexes over the whole document. If GIN is an unfamiliar word, I wrote <a href="https://andresleiva.com/blog/postgres-index-types">a primer on Postgres index types</a> that pairs with this post.</li><li><strong>Disk.</strong> jsonb tends to be slightly larger at rest. Both types participate in TOAST compression for large values. I will touch on what TOAST is below.</li></ul><h3>The table I built</h3><p>Chunking for AI processing has a specific shape. A document gets split into pieces, each piece gets embedded and retrieved later, and each piece drags metadata behind it: where it came from, its position, its token count, the heading trail above it. The problem is that every source type produces a different bag. A PDF has pages and maybe an OCR flag. An HTML page has a heading hierarchy. A transcript has timestamps and speakers.</p><p>That split, stable versus volatile, is the design rule. Fields I always filter or join on become real columns with real types and real constraints. The long tail goes into one jsonb column.</p><pre>CREATE EXTENSION IF NOT EXISTS vector;<br><br>CREATE TABLE documents (<br>  id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,<br>  title text NOT NULL<br>);<br><br>CREATE TABLE chunks (<br>  id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,<br>  document_id bigint NOT NULL REFERENCES documents (id),<br>  chunk_index int    NOT NULL,<br>  content     text   NOT NULL,<br>  embedding   vector(1536),<br>  metadata    jsonb  NOT NULL DEFAULT &#39;{}&#39;,<br>  created_at  timestamptz NOT NULL DEFAULT now(),<br>  UNIQUE (document_id, chunk_index)<br>);<br><br>CREATE INDEX chunks_metadata_idx ON chunks USING gin (metadata jsonb_path_ops);</pre><p>Two notes on that DDL. The embedding column and the extension line require <a href="https://github.com/pgvector/pgvector">pgvector</a>; it is where the retrieval side of this pipeline lives, it deserves its own post. If you want to run the examples without it, drop those two lines. The content itself is a plain text column on purpose, not a key inside the metadata, for reasons that will be obvious by the end.</p><p>To make the query plans below honest, here is a seed that produces a million chunks with the kind of varied metadata a real pipeline emits:</p><pre>INSERT INTO documents (title)<br>SELECT &#39;Document &#39; || i FROM generate_series(1, 50) AS i;<br><br>INSERT INTO chunks (document_id, chunk_index, content, metadata)<br>SELECT<br>  (i % 50) + 1,<br>  i / 50,<br>  &#39;Body of chunk &#39; || i,<br>  jsonb_build_object(<br>    &#39;source_type&#39;, (ARRAY[&#39;pdf&#39;, &#39;html&#39;, &#39;transcript&#39;])[1 + i % 3],<br>    &#39;page&#39;,        1 + i % 40,<br>    &#39;headings&#39;,    jsonb_build_array(&#39;Chapter &#39; || (i % 12)),<br>    &#39;token_count&#39;, 200 + i % 300<br>  ) || CASE WHEN i % 97 = 0 THEN &#39;{&quot;ocr&quot;: true}&#39; ELSE &#39;{}&#39; END::jsonb<br>FROM generate_series(0, 999999) AS i;<br><br>ANALYZE chunks;</pre><h3>Querying the bag</h3><p>The two operators you use constantly are -&gt;, which returns jsonb, and -&gt;&gt;, which returns text. The distinction bites people through quoting:</p><pre>SELECT metadata -&gt;&gt; &#39;source_type&#39;  AS source_type,<br>       metadata -&gt; &#39;headings&#39; -&gt; 0 AS first_heading<br>FROM chunks<br>WHERE id = 42;</pre><pre>source_type | first_heading<br>-------------+---------------<br> transcript  | &quot;Chapter 5&quot;</pre><p>The heading kept its quotes because -&gt; handed back a jsonb value, not a string. Chain with -&gt; while you navigate, finish with -&gt;&gt; when you want text.</p><p>The operator that justifies the GIN index is containment, @&gt;, which asks whether the document contains a given sub-document:</p><pre>EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF)<br>SELECT id, content<br>FROM chunks<br>WHERE metadata @&gt; &#39;{&quot;ocr&quot;: true}&#39;;</pre><pre>Bitmap Heap Scan on chunks (actual rows=10310 loops=1)<br>   Recheck Cond: (metadata @&gt; &#39;{&quot;ocr&quot;: true}&#39;::jsonb)<br>   Heap Blocks: exact=10310<br>   -&gt;  Bitmap Index Scan on chunks_metadata_idx (actual rows=10310 loops=1)<br>         Index Cond: (metadata @&gt; &#39;{&quot;ocr&quot;: true}&#39;::jsonb)<br> Planning Time: 0.090 ms<br> Execution Time: 30.110 ms</pre><p>Ten thousand OCR chunks out of a million, found through the index, in 30 milliseconds. Without the index this is a full scan of the table on every call.</p><p>The index used jsonb_path_ops, which is a deliberate choice over the default jsonb_ops. The path variant only accelerates containment, and in exchange the index is considerably smaller and faster for exactly that operator. The default variant additionally supports key-existence operators like ?. My filtering is all containment, so I take the smaller index. If you need &quot;does this key exist at all&quot; queries, you should use the default.</p><p>One more indexing tool matters in practice. When one scalar key is hot, a plain btree expression index beats GIN for it:</p><pre>CREATE INDEX chunks_source_type_idx ON chunks ((metadata -&gt;&gt; &#39;source_type&#39;));</pre><p>That gives equality filters on metadata -&gt;&gt; &#39;source_type&#39; an ordinary btree, with ordinary planner statistics, which GIN does not provide. It is also the only kind of index a plain json column could get, which tells you how much of the story indexing is.</p><p>For conditions that operators cannot express, jsonb speaks the SQL/JSON path language:</p><pre>SELECT count(*)<br>FROM chunks<br>WHERE metadata @? &#39;$.token_count ? (@ &gt; 450)&#39;;</pre><blockquote><em>The path string: ‘$.token_count ? (@ &gt; 450)’</em></blockquote><blockquote>- $ is the root of the JSON document, so for each row it means “this row’s metadata value”.</blockquote><blockquote>- $.token_count navigates to the token_count key, producing that value.</blockquote><blockquote>- ? (…) is a filter expression. It takes whatever the path produced so far and keeps only the items that satisfy the condition in parentheses.</blockquote><blockquote>- @ inside the filter means “the current item being tested”, the same role x plays in a lambda like x =&gt; x &gt; 450.</blockquote><blockquote><em>So the whole path reads: “go to token_count, and keep it only if its value is greater than 450.”</em></blockquote><p>And since Postgres 17 there is JSON_TABLE, which flattens documents into rows mid-query so the rest of your SQL can treat the bag like a table. Here it unnests the headings array and aggregates over it:</p><pre>SELECT jt.source_type, jt.heading, count(*) AS chunks<br>FROM chunks,<br>     JSON_TABLE(metadata, &#39;$&#39; COLUMNS (<br>       source_type text PATH &#39;$.source_type&#39;,<br>       NESTED PATH &#39;$.headings[*]&#39; COLUMNS (heading text PATH &#39;$&#39;)<br>     )) AS jt<br>GROUP BY jt.source_type, jt.heading<br>ORDER BY chunks DESC, jt.source_type, jt.heading<br>LIMIT 3;</pre><blockquote><em>FROM chunks, JSON_TABLE(metadata, …) is an implicit lateral join: for every row of chunks, Postgres feeds that row’s metadata into JSON_TABLE, which produces zero or more rows, and each produced row is stitched to the chunk row that generated it.</em></blockquote><blockquote><em>metadata is the document to consume, and ‘$’ is the row-generating path: “start from the root of the document”. With ‘$’ as the row pattern, each document initially produces one row.</em></blockquote><blockquote><em>The COLUMNS clause defines the schema of the virtual table, one entry per output column:</em></blockquote><blockquote>- source_type text PATH ‘$.source_type’ declares a column named source_type of SQL type text, filled by evaluating the path $.source_type against the current row’s document. The path is relative to the row pattern, so $ here means “the metadata object”.</blockquote><blockquote>- NESTED PATH ‘$.headings[]<em>’ COLUMNS (heading text PATH ‘$’) is the unnesting part. $.headings[]</em> means “every element of the headings array”, and the nested COLUMNS runs once per element. Inside it, the path ‘$’ now refers to the current array element itself, not the document root; the meaning of $ re-anchors at each nesting level. So a chunk whose metadata holds three headings produces three rows, each repeating the same source_type next to a different heading.</blockquote><pre>source_type |  heading  | chunks<br>-------------+-----------+--------<br> html        | Chapter 1 |  83334<br> pdf         | Chapter 0 |  83334<br> pdf         | Chapter 3 |  83334</pre><h3>The update trap</h3><p>This is the part I wish someone had put in front of me earlier. Postgres stores any column value larger than roughly two kilobytes through TOAST: compressed, sliced, and moved out of the main row. A fat jsonb document goes through exactly that machinery, and two consequences follow. <a href="https://www.postgresql.org/docs/current/storage-toast.html#STORAGE-TOAST-ONDISK">More about TOAST here</a></p><p>First, reading one key from a TOASTed document detoasts the whole document. Second, and worse, there is no such thing as a partial update. This looks surgical:</p><pre>UPDATE chunks<br>SET metadata = jsonb_set(metadata, &#39;{status}&#39;, &#39;&quot;embedded&quot;&#39;)<br>WHERE id = 42;</pre><p>It is not. jsonb_set builds a complete new document in memory and the UPDATE writes a complete new row version, TOAST and all. Flip one status flag on a chunk whose metadata weighs 50 KB and you have rewritten 50 KB, plus index maintenance.</p><p>The design rule: <strong>mutable state does not belong inside a large </strong><strong>jsonb document</strong>. Processing status, retry counts, timestamps that change, all of those are small scalars that update often, so they get their own columns where an update touches bytes instead of kilobytes. The same logic is why content is a text column in my table instead of a key in the metadata. The chunk body is the biggest thing in the row, and I refuse to drag it through a rewrite because a flag flipped. Cold data in the bag, hot data in columns.</p><h3>Is this not what document databases are for</h3><p>Fair question. A jsonb column inside a relational table is Postgres quietly absorbing the document-database use case: schemaless storage, indexed queries into arbitrary structure, and you keep transactions, joins, foreign keys, and SQL around it. For the chunk pipeline, that combination is the argument. The metadata is schemaless, but the chunks still need referential integrity to their documents and the embeddings sit in the same row. A separate document store or a dedicated vector database would give me two more systems to operate and a consistency problem I currently do not have. There are workloads where the dedicated systems genuinely win, mine was not the case.</p><h3>Where this leaves you</h3><p>The decision itself stays small. jsonb by default, json only when the original bytes are the point. What made the type earn its keep in my pipeline was everything around that choice: real columns for the fields I always touch, one GIN index matched to the operator I actually use, and mutable state kept out of the bag so TOAST never punishes a status flag.</p><p>The rule I have settled on is that columns hold what I know, jsonb holds what I cannot know yet, and keys get promoted to columns once they prove they are permanent.</p><p>If you are about to store chunks, payloads, or model outputs and were about to reach for a second database, try one jsonb column and a GIN index first.</p><p><em>Originally published at </em><a href="https://andresleiva.com/blog/postgres-json-vs-jsonb/"><em>https://andresleiva.com</em></a><em> on July 27, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2de178c396ab" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/postgres-json-vs-jsonb-storing-data-chunks-for-ai-processing-2de178c396ab">Postgres JSON vs JSONB: Storing Data Chunks for AI Processing</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[Claude Code as an Orchestrator: Using Cheaper Models to Ship Real Projects]]></title>
            <link>https://ai.plainenglish.io/claude-code-as-an-orchestrator-using-cheaper-models-to-ship-real-projects-9c33c7f99bec?source=rss-c76ca4406d24------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c33c7f99bec</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Juan Andrés Leiva]]></dc:creator>
            <pubDate>Mon, 13 Jul 2026 06:47:53 GMT</pubDate>
            <atom:updated>2026-07-13T06:47:53.585Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical guide to running Claude Code like a small team: a strong orchestrator model that delegates design, implementation, review, and testing to cheaper, faster subagents. With ready-to-copy .md files</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r2jNsGdJAxg3ZZXd6scBRQ.png" /></figure><p>Most people use Claude Code the same way they used a chat window: one powerful model, one long conversation, doing everything from reading the codebase to writing the code to running the tests. It works, but it is slow, it burns tokens on the expensive model for tasks a cheaper one could handle, and the context window fills up with noise from every file the agent grepped along the way.</p><p>There is a better mental model. Treat Claude Code like a small engineering team. One strong model acts as the orchestrator: it understands the goal, breaks it into pieces, and delegates. Cheaper, faster models act as the workers: they explore the codebase, run mechanical edits, and execute tests, then report back a short summary. The orchestrator never sees the 4,000 lines the worker read, only the two paragraphs that matter.</p><p>This article shows how to set that up for a real coding project, with copy-paste .md files, and a workflow that covers designing, implementing, reviewing, and testing.</p><h3>The Mental Model: Orchestrator and Workers</h3><p>The core idea rests on two features of Claude Code: <strong>subagents</strong> and <strong>per-agent model selection</strong>.</p><p>A subagent is a separate Claude instance with its own context window, its own system prompt, its own tool permissions, and its own model. When your main session delegates a task to a subagent, that subagent does the work in isolation and returns only its final answer. Your main conversation stays clean.</p><p>That isolation is what makes the cost savings possible. If a research task would read twenty files, you do not want those twenty files sitting in your expensive orchestrator’s context for the rest of the session. You want a cheap model to read them, distill them, and hand back a summary.</p><p>Here is the division of labor I use:</p><p><strong>Orchestrator (main session)</strong> — Model Opus 4.8 — Understands the goal, plans, delegates, synthesizes, makes judgment calls<br><strong>Explorer </strong>— Model Haiku 4.5 — Searches the codebase, finds files and patterns, reports locations<br><strong>Implementer</strong> — Model Sonnet 5 — Writes and edits code against a clear spec.<br><strong>Reviewer </strong>— Model Sonnet 5 — Reads a diff, flags bugs and style issues.<br><strong>Test Runner</strong> — Model Haiku 4.5 — Runs the test suite and build, reports pass or fail with the relevant output.</p><p>The rule of thumb: use the cheapest model that can do the job reliably. Searching and running commands are cheap tasks. Writing nuanced code and reviewing it are worth a mid-tier model. Only the coordination and the hard judgment calls need the top model.</p><h3>Step 1: Give the Project a Memory</h3><p>Before you define any agents, write a CLAUDE.md at the root of your project. This file is loaded automatically into every session and every subagent, so it is the right place for the facts that everyone on the “team” needs to know.</p><pre># Project: taskflow-api<br>REST API for a task management app.<br>## Stack<br>- Node.js with TypeScript<br>- Fastify for the HTTP layer<br>- PostgreSQL via Prisma<br>- npm as the package manager<br>## Conventions<br>- Routes live in `src/routes/`, one file per resource<br>- Business logic goes in `src/services/`, never in the route handlers<br>- All request input is validated with zod schemas in `src/schemas/`<br>- Errors are thrown as `AppError` and caught by the global error handler<br>## Commands<br>- `npm run dev` starts the dev server with hot reload<br>- `npm test` runs the vitest suite<br>- `npm run build` type-checks and compiles to `dist/`</pre><p>Keep it short. A CLAUDE.md that runs past two hundred lines starts costing you real context on every turn. Put the durable facts here (stack, conventions, commands) and leave the transient details to the conversation.</p><p>You can also place a CLAUDE.md inside a subdirectory. It loads only when the agent starts working with files in that directory, which keeps package-specific guidance out of the main context until it is needed.</p><h3>Step 2: Define the Workers</h3><p>Subagents live in .claude/agents/ as Markdown files. The YAML frontmatter configures the agent, and the body becomes its system prompt. The fields you will use most are name, description, model, and tools.</p><p>The description matters more than it looks. Claude reads it to decide when to delegate to this agent automatically, so write it as a trigger, not a title.</p><h3>The explorer (cheap and read-only)</h3><pre>---<br>name: explorer<br>description: Search the codebase to locate files, functions, and patterns. Use before any change that touches unfamiliar code. Returns locations and short summaries, never edits.<br>model: haiku<br>tools: Read, Glob, Grep, Bash<br>---<br>You are a fast codebase research agent. Your job is to find things and<br>report them concisely.<br>- Locate the relevant files, functions, and call sites for the task you are given.<br>- Report file paths with line numbers so they are easy to open.<br>- Summarize how the existing code works in a few sentences.<br>- Do not propose changes and do not edit anything. Finding and explaining is your whole job.</pre><p>Running this on Haiku is deliberate. Searching and reading is exactly the kind of high-volume, low-judgment work where the cheapest model earns its keep.</p><h3>The implementer (mid-tier, can edit)</h3><pre>---<br>name: implementer<br>description: Write and edit code against a clear, specific instruction. Use once the design is decided and you know exactly which files change.<br>model: sonnet<br>tools: Read, Edit, Write, Bash<br>---<br>You implement a well-defined change. You are given a spec: which files to<br>change and what the result should be.<br>- Follow the conventions in CLAUDE.md exactly.<br>- Match the style of the surrounding code: naming, imports, error handling.<br>- Make the change and nothing more. Do not refactor unrelated code.<br>- After editing, run the build or the relevant command to confirm it compiles.<br>- Report what you changed and any decision you had to make.</pre><h3>The reviewer (mid-tier, read-only)</h3><pre>---<br>name: reviewer<br>description: Review a diff or a set of recent changes for correctness bugs and convention violations. Use after implementation, before considering a task done.<br>model: sonnet<br>tools: Read, Grep, Bash<br>---<br>You review code the way a careful senior engineer reviews a pull request.<br>- Read the diff and the surrounding code for context.<br>- Flag correctness bugs first: off-by-one errors, missing awaits, unhandled<br>  errors, broken edge cases.<br>- Then flag convention violations against CLAUDE.md.<br>- Be specific: cite the file and line, explain the failure, suggest the fix.<br>- Do not rewrite the code yourself. Report findings and let the orchestrator decide.</pre><h3>The test runner (cheap, mechanical)</h3><pre>---<br>name: test-runner<br>description: Run the build and test suite, then report pass or fail with the relevant output. Use to verify a change works before moving on.<br>model: haiku<br>tools: Bash, Read<br>---<br>You run verification commands and report results plainly.<br>- Run the project&#39;s build and test commands (see CLAUDE.md).<br>- If everything passes, say so in one line.<br>- If something fails, quote the exact error and name the file it points to.<br>- Do not try to fix anything. Reporting accurately is the job.</pre><p>Notice the pattern across all four: each worker is narrow, each has a model matched to the difficulty of its task, and each is told to report back rather than sprawl. The orchestrator (your main session, running Opus) is what ties them together.</p><p>You set the main session’s model with /model opus inside a session, or by launching with claude --model opus. Everything below assumes the main session is your orchestrator.</p><h3>Step 3: The Workflow</h3><p>With the workers defined, a real feature moves through four phases. The orchestrator drives all of them and delegates the heavy lifting.</p><h3>Design</h3><p>Start in plan mode. Press Shift+Tab until Claude Code is in plan mode, which makes the session read-only, so the model explores and proposes without touching anything.</p><p>In this phase the orchestrator delegates exploration to the cheap explorer agent to map the territory, then does the actual thinking itself, because design is a judgment call worth the strong model.</p><pre>You: I want to add cursor-based pagination to the GET /tasks endpoint.<br>     Plan it. Use the explorer to find how that endpoint works today.<br><br>Orchestrator (Opus): [delegates to explorer on Haiku]<br>Explorer (Haiku): GET /tasks is handled in src/routes/tasks.ts, which calls<br>     listTasks() in src/services/taskService.ts. That service runs a Prisma<br>     findMany with no limit and no cursor. Query input is validated by a zod<br>     schema in src/schemas/tasks.ts.<br>Orchestrator: Here is the plan:<br>  1. Add `limit` and `cursor` query params to the tasks schema.<br>  2. Pass them into listTasks() and use Prisma&#39;s cursor pagination.<br>  3. Return a `nextCursor` alongside the results.<br>  No database migration needed. Approve?</pre><p>You review the plan as a human. This is the highest-leverage moment in the whole loop, because approving a good plan is cheap and catching a bad one here saves an hour of wrong implementation.</p><h3>Implement</h3><p>Once you approve, the orchestrator hands the spec to the implementer on Sonnet. The spec is concrete because the design phase made it concrete.</p><pre>Orchestrator: [delegates to implementer on Sonnet]<br>  &quot;In src/schemas/tasks.ts, add optional `limit` and `cursor` fields to the<br>   list query schema. In src/services/taskService.ts, update listTasks() to<br>   accept them and use Prisma&#39;s `take` and `cursor`, returning the rows and a<br>   `nextCursor`. Update the route in src/routes/tasks.ts to pass them through.<br>   Follow CLAUDE.md conventions.&quot;<br><br>Implementer (Sonnet): Updated the schema, service, and route. Type-check<br>   passes.</pre><p>The orchestrator did not spend Opus tokens writing a for-loop. It spent them deciding what the for-loop should do.</p><h3>Review</h3><p>Never let the model that wrote the code be the only one to judge it. Delegate a fresh review to the reviewer agent, which reads the diff with no attachment to the implementation.</p><pre>Orchestrator: [delegates to reviewer on Sonnet]<br>Reviewer (Sonnet): One issue. The `limit` field has no upper bound, so a<br>   client can request the entire table with ?limit=1000000 and exhaust the<br>   database. src/schemas/tasks.ts:12. Cap it, for example `.max(100)`.</pre><p>That is a real bug the implementer would happily have shipped. A separate reviewer with fresh context catches things the author is blind to. For a heavier review you can use the built-in /review for a pull request or the code-review skill for the working diff.</p><h3>Test</h3><p>Finally, the orchestrator asks the cheap test-runner to verify.</p><pre>Orchestrator: [delegates to test-runner on Haiku]<br>Test runner (Haiku): npm test passed, 47 tests green. npm run build type-checks<br>   clean. GET /tasks?limit=20 returns 20 rows and a nextCursor.</pre><p>Four phases, four different models pulling their weight, and the expensive one only touched the parts that needed judgment.</p><h3>Codify the Workflow with a Slash Command</h3><p>Once this loop feels natural, capture it as a custom command so you do not retype it. Slash commands are Markdown files in .claude/commands/. The filename becomes the command, and $ARGUMENTS is replaced with whatever you pass.</p><pre>---<br>description: Design, implement, review, and test a feature end to end<br>argument-hint: &lt;feature description&gt;<br>---<br>Deliver this feature using the full workflow: $ARGUMENTS<br>1. Use the explorer agent to map the relevant code. Do not skip this.<br>2. Propose a short plan and wait for my approval before editing.<br>3. Once approved, delegate the change to the implementer agent.<br>4. Delegate a review to the reviewer agent and address any real findings.<br>5. Delegate verification to the test-runner agent.<br>6. Summarize what changed in three lines.</pre><p>Save that as .claude/commands/feature.md and you can run /feature add cursor-based pagination to the tasks endpoint. The orchestrator follows the recipe every time, which means the cheap-worker delegation happens by default instead of only when you remember to ask for it.</p><h3>Automate the Boring Parts with Hooks</h3><p>Hooks let you run a shell command automatically when certain events happen, configured in .claude/settings.json. The most useful one for this workflow is running your type-checker or linter after every file edit, so mistakes surface immediately instead of at review time.</p><pre>{<br>  &quot;hooks&quot;: {<br>    &quot;PostToolUse&quot;: [<br>      {<br>        &quot;matcher&quot;: &quot;Edit|Write&quot;,<br>        &quot;hooks&quot;: [<br>          {<br>            &quot;type&quot;: &quot;command&quot;,<br>            &quot;command&quot;: &quot;npx tsc --noEmit 2&gt;&amp;1 | tail -10&quot;<br>          }<br>        ]<br>      }<br>    ]<br>  }<br>}</pre><p>Now every time any agent edits a file, the type-checker runs and its output goes back to the agent. If a change introduces a type error, the implementer sees it and fixes it on the spot, without waiting for the test phase. Hooks are deterministic, so this happens whether or not the model remembers to check.</p><p>A word of caution: a hook that runs a slow command on every edit will make the whole session drag. Keep hook commands fast, or scope the matcher so they only fire on the files that matter.</p><h3>Why This Is Cheaper and Better</h3><p>The obvious win is cost. Haiku is a fraction of the price of Opus, so pushing search and test execution down to it adds up quickly over a long session. But the more important win is quality, and it comes from context hygiene.</p><p>When one model does everything, its context fills with the raw output of every search, every file read, and every failed command. By the end of a long task it is reasoning over a haystack. When workers absorb that volume and return summaries, the orchestrator reasons over a clean, curated view of the project. It makes better decisions because it is not distracted.</p><p>The separation also creates natural checkpoints. A dedicated reviewer with fresh eyes catches what the author missed. A dedicated planner that you approve before any code is written catches wrong directions early. These are the same practices that make human teams effective, applied to a team of models.</p><h3>Practical Tips</h3><p>A few things I learned the hard way:</p><ul><li>Write descriptions as triggers. Claude decides when to delegate based on the agent’s description. “Use before any change that touches unfamiliar code” delegates reliably. “Codebase agent” does not.</li><li>Give workers the narrowest tools they need. An explorer that cannot write cannot accidentally edit. Constraint is a feature.</li><li>Do not over-delegate. A one-line typo fix does not need a five-agent pipeline. The orchestrator should just fix it. Reserve the full loop for real features.</li><li>Keep CLAUDE.md honest. Every agent trusts it. A stale command or a wrong convention in that file propagates to every worker at once.</li><li>Approve plans, not just diffs. The cheapest place to fix a mistake is in the plan, before a single line is written.</li></ul><p>Setting this up takes an afternoon. After that, every project you touch gets a small team of specialists instead of one overworked generalist, and you spend your own attention on the decisions that actually need a human.</p><p>If you found this useful, share it with someone who is still running every task through a single model.</p><p>Originally published on my blog: <a href="https://andresleiva.com/blog/claude-code-orchestrator-pattern/">https://andresleiva.com/blog/claude-code-orchestrator-pattern/</a><br>Find me on LinkedIn: <a href="https://www.linkedin.com/in/juan-andres-leiva/">https://www.linkedin.com/in/juan-andres-leiva/</a></p><h3>Before you go</h3><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c33c7f99bec" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/claude-code-as-an-orchestrator-using-cheaper-models-to-ship-real-projects-9c33c7f99bec">Claude Code as an Orchestrator: Using Cheaper Models to Ship Real Projects</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence 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[PostgreSQL Mistakes You’re Probably Making (And How to Fix Them)]]></title>
            <link>https://levelup.gitconnected.com/postgresql-mistakes-youre-probably-making-and-how-to-fix-them-544ade3ed69c?source=rss-c76ca4406d24------2</link>
            <guid isPermaLink="false">https://medium.com/p/544ade3ed69c</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Juan Andrés Leiva]]></dc:creator>
            <pubDate>Thu, 16 Oct 2025 20:24:26 GMT</pubDate>
            <atom:updated>2025-10-16T20:24:26.248Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A comprehensive guide to avoiding common PostgreSQL pitfalls that can compromise performance, data integrity, and maintainability</em></p><h3>Introduction</h3><p>PostgreSQL is one of the most powerful and flexible relational databases available, but with great power comes the potential for misuse. After years of building production systems, I’ve seen countless hours wasted debugging issues that could have been prevented by following established best practices. Over the years, the PostgreSQL community has identified numerous anti-patterns — practices that may seem reasonable at first but lead to problems down the road.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*58QOiR1bpuFM8nf43yakfA.png" /></figure><p>This guide compiles the most important things you should avoid when working with PostgreSQL, drawn from the collective wisdom of the community and hard-learned production lessons. Whether you’re designing a new schema or maintaining an existing system, these guidelines will help you avoid common traps.</p><h3>Key Takeaways</h3><p>Before we dive deep, here are the critical rules that will save you the most pain:</p><p><strong>For Data Types:</strong></p><ul><li>✅ Always use timestamptz for timestamps, never timestamp</li><li>✅ Use text instead of char(n) or arbitrary varchar(n) limits</li><li>✅ Use numeric for money, not the money type</li><li>✅ Use identity columns instead of serial (PostgreSQL 10+)</li></ul><p><strong>For Queries:</strong></p><ul><li>✅ Use NOT EXISTS instead of NOT IN with subqueries</li><li>✅ Avoid BETWEEN for timestamp ranges—use &gt;= and &lt; instead</li><li>✅ Use lowercase_with_underscores for all identifiers</li></ul><p><strong>For Schema Design:</strong></p><ul><li>✅ Use triggers instead of rules (always)</li><li>✅ Avoid table inheritance — use foreign keys or native partitioning</li></ul><p><strong>For Security:</strong></p><ul><li>✅ Never use trust authentication over TCP/IP</li><li>✅ Always use scram-sha-256 or better for password authentication</li></ul><p>If you remember nothing else, remember these. Now let’s explore why each matters.</p><h3>Database Encoding</h3><h4>Never Use SQL_ASCII</h4><p><strong>The Problem:</strong> SQL_ASCII is not actually ASCII. It means “no conversions” — the database performs no encoding validation or conversion whatsoever. When you use SQL_ASCII, PostgreSQL simply accepts whatever bytes you give it and treats them as belonging to whatever encoding you claim, without verification.</p><p>This creates a database that’s a ticking time bomb. You’ll end up with data in multiple encodings — UTF-8, Latin1, Windows-1252, and who knows what else — all mixed together with no way to reliably recover the original characters. When you try to retrieve data, you’ll get mojibake (garbled characters), and there’s no reliable way to fix it after the fact.</p><p><strong>The Exception:</strong> The only legitimate use case is when you’re dealing with data that’s already a hopeless mixture of unlabeled encodings, such as old IRC logs or non-MIME-compliant emails. Even then, consider using the bytea type instead or auto-detecting UTF-8 and assuming non-UTF-8 data is in a specific encoding like Windows-1252.</p><p><strong>What to Do Instead:</strong> Use UTF-8 (UTF8 encoding) for new databases. It supports all characters from all languages and is the internet standard.</p><h3>Tool Usage</h3><h4>Don’t Use psql -W or --password</h4><p><strong>The Problem:</strong> The -W or --password flags tell psql to prompt for a password <em>before</em> attempting to connect to the server. This means you&#39;ll be prompted even if the server doesn&#39;t require a password, which creates confusion when setting up authentication.</p><p>If your server is configured for peer authentication (common on local development machines), using -W makes it appear that password authentication is required when it isn&#39;t. Even worse, if you enter the wrong password or the user has no password set, you might still be logged in via peer authentication—making you think you have the correct password when you don&#39;t. This leads to confusion when trying to connect from other clients or systems.</p><p><strong>What to Do Instead:</strong> Just run psql without the flag. If the server requires a password, psql will prompt you automatically. You&#39;ll save a round trip to the server and avoid authentication confusion.</p><h3>Query Rewriting and Schema Design</h3><h4>Never Use Rules</h4><p><strong>The Problem:</strong> Rules look like conditional logic, but they’re actually a query rewriter. They don’t execute in the way you’d intuitively expect — they rewrite your query to modify it or add additional queries to it. This makes all non-trivial rules incorrect or at least surprising in their behavior.</p><p>Rules were a clever implementation detail for views, but exposing them directly to users has proven to be a mistake. They’re confusing, error-prone, and have been the source of countless bugs and misunderstandings.</p><p><strong>What to Do Instead:</strong> Use triggers. Triggers execute procedural code in response to events and behave exactly as you’d expect. If you think you need a rule, you almost certainly want a trigger instead.</p><h4>Avoid Table Inheritance</h4><p><strong>The Problem:</strong> Table inheritance was part of a fad in database design where the database structure was tightly coupled to object-oriented code. In practice, this tight coupling didn’t produce the desired results.</p><p>Table inheritance has several problems: constraints (particularly foreign keys and unique constraints) don’t work intuitively across the inheritance hierarchy, and you can end up with data integrity issues that are difficult to reason about.</p><p><strong>What to Do Instead:</strong> Use foreign keys to model relationships between tables. Since PostgreSQL 10, native table partitioning has replaced the one common legitimate use case for table inheritance (partitioning large tables).</p><p><strong>The Rare Exception:</strong> The temporal_tables extension for row versioning is one of the few remaining use cases where table inheritance might be acceptable if you&#39;re in a pinch and SQL:2011 temporal support isn&#39;t available. Even then, be aware of the caveats when working with parent tables.</p><h3>SQL Constructs</h3><h4>Don’t Use NOT IN with Subqueries</h4><p><strong>The Problem:</strong> NOT IN behaves unexpectedly when NULL values are present, and it has severe performance issues with subqueries.</p><p>Consider this query:</p><pre>SELECT * FROM foo WHERE col NOT IN (1, NULL);</pre><p>This always returns zero rows. Why? Because col IN (1, NULL) returns TRUE if col=1, and NULL otherwise (never FALSE). Since NOT(TRUE) is FALSE but NOT(NULL) is still NULL, there&#39;s no way for NOT IN (1, NULL) to return TRUE.</p><p>With subqueries, the situation is worse:</p><pre>SELECT * FROM foo WHERE foo.col NOT IN (SELECT bar.x FROM bar);</pre><p>If any value of bar.x is NULL, this returns zero rows—probably not what you intended.</p><p>Additionally, the query planner can’t optimize NOT IN (SELECT ...) into an anti-join, so it becomes either a hashed subplan (fast but only used for small result sets) or a plain subplan (horrifically slow with O(N²) complexity). Performance might look fine in testing but collapse by five orders of magnitude in production when the data grows.</p><p><strong>What to Do Instead:</strong> Use NOT EXISTS:</p><pre>SELECT * FROM foo <br>WHERE NOT EXISTS (SELECT FROM bar WHERE foo.col = bar.x);</pre><p><strong>The Exception:</strong> NOT IN (list, of, values) is safe when you&#39;re excluding specific constant values, as long as you&#39;re certain none of them are NULL.</p><h4>Don’t Use Upper Case Table or Column Names</h4><p><strong>The Problem:</strong> PostgreSQL folds all unquoted identifiers to lowercase. If you create a table with CREATE TABLE Foo(), it creates a table named foo. But if you use CREATE TABLE &quot;Bar&quot;(), it creates a table named Bar (with uppercase B).</p><p>This creates a quoting nightmare:</p><ul><li>SELECT * FROM Foo works (folded to foo)</li><li>SELECT * FROM foo works</li><li>SELECT * FROM &quot;Bar&quot; works</li><li>SELECT * FROM &quot;Foo&quot; fails (no table named Foo with capital F)</li><li>SELECT * FROM Bar fails (folded to bar, which doesn&#39;t exist)</li><li>SELECT * FROM bar fails</li></ul><p>Some tools always quote identifiers, others never do. When you mix tools, you’ll spend hours debugging why queries work in one tool but not another.</p><p><strong>What to Do Instead:</strong> Use lowercase names with underscores: user_profiles, order_items, created_at. You&#39;ll never need to quote them, and everything will just work.</p><p><strong>The Exception:</strong> If you need “pretty” names in report output, use column aliases: SELECT user_name AS &quot;User Name&quot; FROM users.</p><h4>Be Careful with BETWEEN (Especially for Timestamps)</h4><p><strong>The Problem:</strong> BETWEEN uses closed-interval comparison—both endpoints are included. This is particularly problematic with timestamps:</p><pre>SELECT * FROM events <br>WHERE event_time BETWEEN &#39;2018-06-01&#39; AND &#39;2018-06-08&#39;;</pre><p>This includes events at exactly 2018-06-08 00:00:00.000000 but excludes events later on that same day. You&#39;ll appear to have complete data for June 8th, but you&#39;re actually missing everything after midnight. When you get an event at exactly midnight, you might double-count it in overlapping queries.</p><p><strong>What to Do Instead:</strong> Use explicit comparisons:</p><pre>SELECT * FROM events <br>WHERE event_time &gt;= &#39;2018-06-01&#39; <br>  AND event_time &lt; &#39;2018-06-08&#39;;</pre><p><strong>The Exception:</strong> BETWEEN is safe for discrete quantities like integers or dates (not timestamps), as long as you remember that both endpoints are included.</p><h3>Date and Time Storage</h3><h4>Use timestamptz, Not timestamp</h4><p><strong>The Problem:</strong> Despite its name, timestamptz (also known as timestamp with time zone) doesn&#39;t store a timezone. It stores a point in time as microseconds since January 1, 2000 UTC. You can insert values in any timezone, and PostgreSQL converts them to UTC for storage.</p><p>The timestamp type (also known as timestamp without time zone) stores only the date and time you give it—like a photograph of a calendar and clock. Without knowing the timezone, you don&#39;t actually know what moment in time it represents. Arithmetic between timestamps from different locations or across daylight saving time changes will give wrong answers.</p><p><strong>What to Do Instead:</strong> Use timestamptz to store points in time. PostgreSQL will handle all timezone conversions for you, and arithmetic will work correctly across daylight saving time boundaries and between different timezones.</p><p><strong>The Exception:</strong> If you’re storing timestamps abstractly — like “the meeting happens at 2:00 PM” without caring what timezone — then timestamp might be appropriate. But if you&#39;re recording when something actually happened, use timestamptz.</p><h4>Don’t Store UTC in timestamp Columns</h4><p><strong>The Problem:</strong> Some developers coming from databases with poor timezone support use timestamp without time zone to store UTC values. This forces you to manually track that these are UTC values, and the database can&#39;t help you.</p><p>Simple time calculations become nightmarish. To get “last midnight in the user’s timezone,” you need:</p><pre>date_trunc(&#39;day&#39;, now() AT TIME ZONE u.timezone) <br>  AT TIME ZONE u.timezone AT TIME ZONE &#39;UTC&#39;</pre><p>With timestamptz, this would just be:</p><pre>date_trunc(&#39;day&#39;, now() AT TIME ZONE u.timezone)</pre><p><strong>What to Do Instead:</strong> Use timestamptz and let PostgreSQL handle the timezone conversions.</p><h4>Never Use timetz</h4><p><strong>The Problem:</strong> Even the PostgreSQL manual warns you about this type, saying it’s “only implemented for SQL compliance” and that its “definition exhibits properties which lead to questionable usefulness.”</p><p>A time with a timezone but no date is almost never what you actually need. What does “3:00 PM EST” mean without a date? It means different things on different sides of a daylight saving time change.</p><p><strong>What to Do Instead:</strong> Use timestamptz for timestamps, time for times of day (when the timezone doesn&#39;t matter), and date for dates.</p><h4>Don’t Use CURRENT_TIME</h4><p><strong>The Problem:</strong> CURRENT_TIME returns a value of type timetz, which as we just discussed, is problematic.</p><p><strong>What to Do Instead:</strong></p><ul><li>Use CURRENT_TIMESTAMP or now() for timestamptz</li><li>Use LOCALTIMESTAMP for timestamp without time zone</li><li>Use CURRENT_DATE for date</li><li>Use LOCALTIME for time</li></ul><h4>Don’t Use timestamp(0) or timestamptz(0)</h4><p><strong>The Problem:</strong> Precision specifications on timestamps <em>round</em> rather than truncate. If you store now() into a timestamp(0) column, you might be storing a value up to half a second in the <em>future</em>. This can cause subtle bugs with time-based logic.</p><p><strong>What to Do Instead:</strong> Use date_trunc(&#39;second&#39;, timestamp_value) to explicitly truncate to the second.</p><h4>Don’t Use +/-HH:mm as Text Timezone Names</h4><p><strong>The Problem:</strong> PostgreSQL doesn’t accept fixed timezone offsets like +05:00 in place of timezone names. If you provide such a string, it&#39;s interpreted as a POSIX timezone specification with the unfortunate property that positive values shift west while negative values shift east—the opposite of the ISO convention.</p><p><strong>What to Do Instead:</strong> For fixed offsets, use an interval:</p><pre>timestamp_value AT TIME ZONE INTERVAL &#39;04:00&#39;</pre><p><strong>The Exception:</strong> String timestamptz literals in ISO format can use signed offsets with standard ISO interpretation:</p><pre>SELECT &#39;2024-01-31 17:16:25+04&#39;::timestamptz; -- yields 1pm UTC</pre><h3>Text Storage</h3><h4>Never Use char(n)</h4><p><strong>The Problem:</strong> The char(n) type pads values with spaces to the specified width. This almost certainly isn&#39;t what you want. Those spaces are included in storage (so it doesn&#39;t save space), they&#39;re ignored in comparisons (which can cause unexpected behavior), and they need to be stripped in many contexts (which hurts performance).</p><p>Worse, char(n) isn&#39;t even a fixed-width type from a storage perspective. Since characters can take multiple bytes in UTF-8, the actual storage is variable-length anyway.</p><p>The manual specifically warns about this behavior with collations:</p><pre>SELECT &#39;a &#39;::CHAR(2) COLLATE &quot;C&quot; &lt; E&#39;a\n&#39;::CHAR(2)<br>-- returns true, even though C locale considers <br>-- space greater than newline</pre><p><strong>What to Do Instead:</strong> Use text. Always.</p><p><strong>The Exception:</strong> When porting ancient software that requires fixed-width fields. Or when you read the manual’s description and think “yes, that’s exactly what I need” rather than running away screaming.</p><h4>Don’t Use char(n) Even for Fixed-Length Identifiers</h4><p><strong>The Problem:</strong> A common response to “don’t use char(n)&quot; is &quot;but my values must always be exactly N characters&quot; (like country codes or hashes). Even in these cases, char(n) is wrong.</p><p>Why? Because char(n) doesn&#39;t reject values that are too short—it silently pads them with spaces. So it provides no validation benefit. Worse, comparing a char(n) column against a parameter typed as text or varchar can prevent index usage, and this is hard to debug because manual queries work fine.</p><p><strong>What to Do Instead:</strong> Use text with a CHECK constraint:</p><pre>CREATE TABLE countries (<br>    code text CHECK (code ~ &#39;^[A-Z]{3}$&#39;),<br>    ...<br>);</pre><p>Or create a domain:</p><pre>CREATE DOMAIN country_code AS text<br>    CHECK (VALUE ~ &#39;^[A-Z]{3}$&#39;);</pre><h4>Think Before Using varchar(n)</h4><p><strong>The Problem:</strong> varchar(n) throws an error if you try to insert a string longer than N characters. This is useful when you genuinely need a length limit, but it&#39;s often used thoughtlessly as a default.</p><p>If you arbitrarily choose varchar(20) for a surname field, you&#39;re setting yourself up for a production error when Hubert Blaine Wolfeschlegelsteinhausenbergerdorff signs up for your service. Many developers use varchar(255) by habit, carried over from databases where unlimited text storage wasn&#39;t efficient.</p><p>From a storage and performance perspective, varchar(20), varchar, and text are identical when storing the same string. The only difference is that varchar(n) enforces a maximum length.</p><p><strong>What to Do Instead:</strong> Use text as your default. If you need constraints on the value—minimum length, maximum length, character set restrictions—use a CHECK constraint, which can enforce all of these at once:</p><pre>CREATE TABLE users (<br>    username text CHECK (<br>        length(username) BETWEEN 3 AND 20 AND<br>        username ~ &#39;^[a-z0-9_]+$&#39;<br>    ),<br>    ...<br>);</pre><p><strong>The Exception:</strong> If you specifically want a maximum length and don’t need other validation, varchar(n) is perfectly fine. Also, varchar is in the SQL standard while text is not, so it might be better for maximum portability (though all major databases support text-like types).</p><h3>Other Data Types</h3><h4>Don’t Use money</h4><p><strong>The Problem:</strong> The money type is a fixed-point type implemented as a machine integer. While arithmetic is fast, it has several serious problems:</p><ol><li>It doesn’t handle fractions of a cent</li><li>Its rounding behavior is probably not what you want for financial calculations</li><li>It doesn’t store a currency — it assumes all money columns use the currency specified by the database&#39;s lc_monetary locale setting</li><li>If you change lc_monetary, all your values become wrong. Insert $10.00 with lc_monetary=&#39;en_US.UTF-8&#39;, change the setting, and you might retrieve ¥1,000 or 10,00 Lei</li></ol><p><strong>What to Do Instead:</strong> Use numeric for monetary values, possibly with an adjacent column storing the currency code:</p><pre>CREATE TABLE transactions (<br>    amount numeric(19,4) NOT NULL,<br>    currency char(3) NOT NULL CHECK (currency ~ &#39;^[A-Z]{3}$&#39;),<br>    ...<br>);</pre><p><strong>The Exception:</strong> If you’re working in a single currency forever, don’t need fractional cents, and only do addition and subtraction, money might work. But those are big ifs.</p><h4>Use Identity Columns Instead of serial</h4><p><strong>The Problem:</strong> The serial types (serial, bigserial, smallserial) have weird behaviors that make schema, dependency, and permission management unnecessarily cumbersome. They&#39;re implemented as a sequence with special dependency tracking, but that tracking doesn&#39;t work quite right in all scenarios.</p><p><strong>What to Do Instead:</strong> For PostgreSQL 10 and later, use identity columns</p><pre>CREATE TABLE users (<br>    id integer GENERATED ALWAYS AS IDENTITY,<br>    ...<br>);</pre><p>Or if you want to allow manual ID insertion:</p><pre>CREATE TABLE users (<br>    id integer GENERATED BY DEFAULT AS IDENTITY,<br>    ...<br>);</pre><p><strong>The Exception:</strong> If you need compatibility with PostgreSQL 9.6 or earlier, or if you’re using table inheritance (but see the warning about that), you might need serial.</p><h3>Authentication</h3><h4>Never Use trust Authentication Over TCP/IP</h4><p><strong>The Problem:</strong> The trust authentication method allows anyone to connect as any user without providing a password. With a line like this in your pg_hba.conf:</p><pre>host all all 0.0.0.0/0 trust</pre><p>You’re allowing anyone on the internet to authenticate as any PostgreSQL user, including the superuser. They can claim to be postgres, and PostgreSQL will believe them.</p><p>Even on your local development machine, trust over TCP/IP is dangerous. Anyone with access to your machine can connect as any user.</p><p><strong>What to Do Instead:</strong> Use proper authentication:</p><ul><li>For local development over TCP/IP: scram-sha-256 authentication with passwords, or restrict to localhost and use peer authentication over Unix sockets</li><li>For production: Always use strong authentication like scram-sha-256 (PostgreSQL 10+), combined with SSL/TLS for the connection</li><li>For CI/CD: Use a dedicated test database on an isolated network with restricted authentication</li></ul><p><strong>The Exception:</strong> There really isn’t one. Even for local development, peer authentication over Unix sockets is better than trust over TCP/IP.</p><h3>Wrap up</h3><p>PostgreSQL is extraordinarily powerful, but like any sophisticated tool, it rewards careful use and punishes carelessness. These anti-patterns have been identified through years of collective experience — each one represents real production issues that have bitten real developers.</p><p>The good news is that most of these pitfalls are easy to avoid once you know about them. Use text instead of varchar(n), use timestamptz instead of timestamp, use NOT EXISTS instead of NOT IN with subqueries, and always use proper authentication. Follow these guidelines, and you&#39;ll avoid the most common PostgreSQL mistakes.</p><p>Remember: when PostgreSQL seems to be behaving strangely, it’s often because we’re using a feature in a way that seemed reasonable but doesn’t match how PostgreSQL actually works. The answer usually isn’t to fight the database — it’s to learn the PostgreSQL way of doing things.</p><p>For more information and updates to these recommendations, visit the <a href="https://wiki.postgresql.org/wiki/Don&#39;t_Do_This">PostgreSQL Wiki’s “Don’t Do This” page</a> and consult the <a href="https://www.postgresql.org/docs/">official PostgreSQL documentation</a>. You can also use tools like <a href="https://github.com/kristiandupont/schemalint">schemalint</a> to automatically verify your database schema against these recommendations.</p><p><em>This article is based on the PostgreSQL community wiki’s collective wisdom. Special thanks to all the PostgreSQL developers and community members who have contributed to documenting these anti-patterns over the years.</em></p><p><strong>Juan Andrés Leiva</strong><br>I write about .NET architecture, DevOps, and modern development practices.<br>👉 Follow for deep technical dives and production-ready strategies.<br>💬 Share your thoughts or questions in the comments — I reply to all messages.<br><a href="https://github.com/jandresleiva">GitHub</a> · <a href="https://www.linkedin.com/in/juan-andres-leiva">LinkedIn</a> · <a href="https://medium.com/@andresleiva.4">Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=544ade3ed69c" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/postgresql-mistakes-youre-probably-making-and-how-to-fix-them-544ade3ed69c">PostgreSQL Mistakes You’re Probably Making (And How to Fix 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 npm Tokens Will Stop Working: GitHub’s New Security Rules and the Migration Playbook]]></title>
            <link>https://levelup.gitconnected.com/your-npm-tokens-will-stop-working-githubs-new-security-rules-and-the-migration-playbook-70385bee91ce?source=rss-c76ca4406d24------2</link>
            <guid isPermaLink="false">https://medium.com/p/70385bee91ce</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Juan Andrés Leiva]]></dc:creator>
            <pubDate>Wed, 15 Oct 2025 16:13:20 GMT</pubDate>
            <atom:updated>2025-10-16T20:00:49.609Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In late September 2025, GitHub announced the first phase of major security improvements to npm’s authentication and token system — part of a broader security roadmap for the npm ecosystem.<br>This move follows one of the most severe <strong>supply-chain security incidents</strong> the JavaScript ecosystem has ever seen, involving popular libraries like chalk, debug, and strip-ansi.</p><p>If you maintain or publish npm packages, this affects you.<br>And if your CI/CD pipelines rely on long-lived tokens or outdated auth flows, they will <strong>stop working by November 2025</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*rx60NetbH2eUReevsILiDw.png" /></figure><h3>Why GitHub Is Locking Down npm</h3><p>Over the past year, the npm ecosystem has faced escalating supply-chain attacks targeting maintainers through phishing and token theft. These incidents have demonstrated the urgent need for stronger security controls. Once inside, attackers pushed malicious versions of widely used packages, infecting downstream applications automatically.</p><p><strong>Key incidents:</strong></p><ul><li>A phishing campaign tricked high-profile maintainers into giving up npm tokens.<br> <a href="https://thehackernews.com/2025/09/20-popular-npm-packages-with-2-billion.html">The Hacker News report</a></li><li>The malware-laced versions exfiltrated developer secrets and crypto wallets.<br><a href="https://vercel.com/blog/critical-npm-supply-chain-attack-response-september-8-2025"> Vercel’s security postmortem</a></li><li>Researchers found a <strong>self-propagating worm</strong> (“Shai-Hulud”) capable of stealing GitHub and npm tokens to republish tainted packages.<br><a href="https://unit42.paloaltonetworks.com/npm-supply-chain-attack"> Palo Alto’s Unit42 analysis</a></li><li>Within a week, over 180 npm packages were compromised.<br><a href="https://www.sonatype.com/blog/ongoing-npm-software-supply-chain-attack-exposes-new-risks"> Sonatype report</a></li></ul><p>GitHub’s conclusion was clear:</p><blockquote>“Classic npm tokens and legacy 2FA flows are not enough to defend against modern supply-chain threats.”</blockquote><p>These attacks underscore a broader pattern of sophisticated supply-chain threats that prompted GitHub to accelerate its security roadmap.</p><h3>Who’s Affected</h3><p>This change impacts <strong>everyone</strong> who publishes or automates npm packages:</p><ul><li><strong>📦 Individual maintainers:</strong> <br>Must migrate to stronger 2FA (WebAuthn/FIDO) and granular tokens with expiration limits.</li><li><strong>👥 Teams and organizations:</strong> <br>CI/CD workflows using classic tokens must rotate credentials and refactor jobs before mid-November.</li><li><strong>🏢 Companies with automated releases:</strong> <br>Need to create scoped, short-lived automation tokens and protect them in secure environments — or better yet, migrate to Trusted Publishers (OIDC).</li><li><strong>👨‍💻 Consumers:</strong> <br>Indirectly affected — you depend on the ecosystem’s integrity, and these changes protect the packages you rely on.</li></ul><h3>The Timeline You Can’t Miss</h3><p>GitHub is rolling out these changes in phases over five weeks, completing by mid-November 2025. Here’s the official timeline from the GitHub changelog:<br><a href="https://github.blog/changelog/2025-09-29-strengthening-npm-security-important-changes-to-authentication-and-token-management">Strengthening npm security: Important changes to authentication and token management</a></p><ul><li><strong>Now (Late September — Early October):</strong> <br>npm CLI and website show deprecation warnings for classic tokens <br>→ <em>Action required:</em> Audit where you use NPM_TOKEN and classic tokens</li><li><strong>Early October 2025:</strong> <br>TOTP 2FA setup permanently disabled for new configurations <br>→ <em>Action required:</em> New 2FA setups must use WebAuthn/passkeys</li><li><strong>Mid-October 2025: <br></strong>New token lifetime limits enforced: 7-day default, 90-day maximum for newly created write-enabled granular tokens <br>→ <em>Action required:</em> Plan token rotation strategy or migrate to Trusted Publishers</li><li><strong>Mid-November 2025:</strong> <br>All classic tokens revoked; generation permanently disabled <br>→ <em>Action required:</em> All publishing must use granular tokens or Trusted Publishers (OIDC)</li></ul><p><strong>Critical:</strong> This is a phased rollout designed to give you time to adapt. Existing granular tokens continue working with their current expiration dates, but all classic tokens will stop working by mid-November.</p><h3>The Migration Checklist</h3><p>Here’s a production-grade plan to migrate safely and align with the new npm security model.</p><ol><li><strong>Inventory &amp; Audit</strong><br> • Locate all usage of npm tokens (classic and granular) in automation, CI pipelines, local scripts. <br> • Document which packages / scopes each token can publish to.</li><li><strong>Upgrade 2FA / Authentication</strong> <br>• <strong>For new 2FA setups:</strong> You must use WebAuthn/passkeys — TOTP setup is permanently disabled for new configurations.<br>• <strong>Existing TOTP 2FA:</strong> Continues to work for now but will be phased out in the coming months. Plan your migration to WebAuthn when feasible.<br>• WebAuthn provides phishing-resistant authentication that’s significantly more secure.</li><li><strong>Migrate Tokens<br></strong>• <strong>Generate granular access tokens</strong> with write/publish permissions, scoped to the minimal packages/orgs needed.<br>• <strong>Starting mid-October:</strong> New granular write tokens will default to 7-day expiration with a maximum of 90 days (down from unlimited).<br>• <strong>Existing granular tokens</strong> remain valid until their current expiration date — you have time to transition.<br>• <strong>Classic tokens are being sunset:</strong> Do not rely on classic/legacy npm tokens — all existing ones will be revoked and creation permanently disabled by mid-November.</li><li><strong>Update Automation / CI/CD</strong><br>• <strong>Immediate:</strong> Replace any use of classic tokens in CI/CD or scripted publish flows.<br>• <strong>Strongly recommended:</strong> Adopt <strong>Trusted Publishers (OIDC)</strong> — GitHub’s preferred approach for automation that eliminates tokens entirely.<br>• Trusted Publishers use temporary, job-specific credentials from GitHub Actions or GitLab CI/CD (more platforms coming soon).<br>• <strong>If you must use tokens:</strong> Use the new granular tokens and implement rotation strategies.</li><li><strong>Consider Trusted Publishers</strong> (Recommended Migration Path)<br>• <strong>Why this matters:</strong> Trusted publishing eliminates long-lived tokens entirely, removing the rotation burden.<br>• <strong>Benefits:</strong> No tokens to leak or rotate, automatic provenance attestation, simplified security model, better audit trails.<br>• <strong>Current support:</strong> GitHub Actions and GitLab CI/CD (Azure Pipelines, CircleCI coming soon).<br>• <strong>Documentation:</strong> <a href="https://docs.npmjs.com/trusted-publishers">https://docs.npmjs.com/trusted-publishers</a></li><li><strong>Test &amp; Monitor</strong><br>• Enable warnings and test token expiration behavior in staging before November.<br>• Monitor failures or permission issues in your pipelines.<br>• Set alerts or reminders for token expiry rotation.</li></ol><h3>Final Thoughts</h3><p>After years of escalating supply-chain threats, this update makes authentication more modern, enforceable, and safer by default.</p><p>This phased rollout is the first step in GitHub’s broader security roadmap for npm. The five-week timeline balances security improvements with giving the community time to adapt workflows. While these changes require effort, they’re essential for protecting the ecosystem from increasingly sophisticated attacks.</p><p>If you maintain or automate npm publishing:</p><ul><li>Audit your tokens now.</li><li>Switch to granular, expiring ones.</li><li>Refactor your pipelines for provenance and traceability.</li><li>Set up token rotation and monitoring before the mid-November deadline.</li></ul><p><strong>Juan Andrés Leiva</strong><br>I write about .NET architecture, DevOps, and modern development practices.<br>👉 Follow for deep technical dives and production-ready strategies.<br>💬 Share your thoughts or questions in the comments — I reply to all messages.<br><a href="https://github.com/jandresleiva">GitHub</a> · <a href="https://www.linkedin.com/in/juan-andres-leiva">LinkedIn</a> · <a href="https://medium.com/@andresleiva.4">Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70385bee91ce" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/your-npm-tokens-will-stop-working-githubs-new-security-rules-and-the-migration-playbook-70385bee91ce">Your npm Tokens Will Stop Working: GitHub’s New Security Rules and the Migration Playbook</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 Implement API Versioning in .NET Core Web APIs: Best Practices and Migration Guide]]></title>
            <link>https://levelup.gitconnected.com/how-to-implement-api-versioning-in-net-core-web-apis-best-practices-and-migration-guide-1e0d2131270b?source=rss-c76ca4406d24------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e0d2131270b</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Juan Andrés Leiva]]></dc:creator>
            <pubDate>Sun, 28 Sep 2025 19:49:39 GMT</pubDate>
            <atom:updated>2025-09-28T19:49:39.553Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Implement API Versioning in .NET Core Web APIs: Best Practices and Migration Guide</h3><h3>Introduction</h3><p>When building a Web API in .NET Core, breaking changes are inevitable. As your application grows, you’ll need to evolve endpoints, payloads, or behaviors in ways that risk breaking existing clients. The only safe way forward is to introduce <strong>API versioning</strong>.</p><p>In this article, we’ll cover <strong>what API versioning is, why it matters, the strategies you can use, how to implement it in .NET Core with the </strong><strong>Asp.Versioning packages, and how to migrate an existing API</strong>. We’ll also look at <strong>real-world practices from companies like GitHub, Stripe, and Microsoft Graph</strong> to show how versioning works at scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*93UW2Cuqad914bdl" /></figure><h3>What Is API Versioning?</h3><p>API versioning means publishing multiple versions of your API side by side. It allows you to:</p><ul><li>Maintain <strong>backward compatibility</strong> so existing clients don’t break.</li><li>Evolve APIs with <strong>parallel versions</strong> when introducing breaking changes.</li><li>Provide a <strong>clear migration path</strong> for clients.</li></ul><p>Some of the most well-known versioned APIs include:</p><ul><li><strong>GitHub REST API v3</strong> — URL path versioning.</li><li><strong>Stripe API</strong> — date-based header versioning.</li><li><strong>Google Maps API v3</strong> — URL path versioning.</li><li><strong>Microsoft Graph API</strong> — URL path versioning with v1.0 and beta.</li></ul><h3>Common API Versioning Strategies</h3><p>There are four primary ways to version a Web API, each with trade-offs:</p><h4>1. URL Path Versioning (most common)</h4><pre>/api/v1/orders<br>/api/v2/orders</pre><p>✅ Easy to understand and document<br> ❌ Can clutter endpoints as versions grow</p><h4>2. Query String Versioning</h4><pre>/api/orders?api-version=2.0</pre><p>✅ Keeps routes stable<br> ❌ May confuse caches or proxies</p><h4>3. Header Versioning</h4><pre>GET /api/orders<br>Header: api-version: 2.0</pre><p>✅ Clean URLs<br> ❌ Hidden unless you inspect headers</p><h4>4. Media Type Negotiation</h4><pre>Accept: application/json;v=1.0</pre><p>✅ Very expressive<br> ❌ Heavier for clients and tooling</p><h3>Setting Up API Versioning in .NET Core</h3><p>Microsoft provides an official package for API versioning:</p><pre>dotnet add package Asp.Versioning.Mvc</pre><h4>Configure in Program.cs</h4><pre>using Asp.Versioning;<br><br>builder.Services.AddApiVersioning(options =&gt;<br>{<br>    options.DefaultApiVersion = new ApiVersion(1, 0);<br>    options.AssumeDefaultVersionWhenUnspecified = true;<br>    options.ReportApiVersions = true;<br>});<br><br>builder.Services.AddVersionedApiExplorer(options =&gt;<br>{<br>    options.GroupNameFormat = &quot;&#39;v&#39;VVV&quot;; // v1, v2, etc.<br>    options.SubstituteApiVersionInUrl = true;<br>});</pre><p>This sets a default version, ensures requests without a version still work, and exposes supported/deprecated versions via headers.</p><h4>Versioning Controllers</h4><pre>using Asp.Versioning;<br><br>[ApiController]<br>[Route(&quot;api/v{version:apiVersion}/[controller]&quot;)]<br>[ApiVersion(1.0)]<br>[ApiVersion(2.0)]<br>public class OrdersController : ControllerBase<br>{<br>    [HttpGet]<br>    [MapToApiVersion(1.0)]<br>    public IActionResult GetV1() =&gt; Ok(&quot;Orders v1&quot;);<br><br>    [HttpGet]<br>    [MapToApiVersion(2.0)]<br>    public IActionResult GetV2() =&gt; Ok(&quot;Orders v2&quot;);<br>}</pre><p>Both versions run side by side, and the runtime picks the action based on the requested version.</p><h4>Query String or Header Versioning</h4><pre>using Asp.Versioning;<br><br>builder.Services.AddApiVersioning(options =&gt;<br>{<br>    options.ApiVersionReader = new QueryStringApiVersionReader(&quot;api-version&quot;);<br>    // or<br>    // options.ApiVersionReader = new HeaderApiVersionReader(&quot;x-api-version&quot;);<br>});</pre><h3>Migrating an Existing API to a Versioned Solution</h3><p>If you already have a live API, migration needs careful planning.</p><h4>Step 1: Define Breaking vs Non-Breaking</h4><ul><li><strong>Breaking:</strong> removing/renaming fields, changing types, narrowing enums, altering semantics.</li><li><strong>Non-breaking:</strong> adding optional fields, new enum values, new endpoints.</li></ul><h4>Step 2: Introduce a Default Version</h4><pre>options.DefaultApiVersion = new ApiVersion(1, 0);<br>options.AssumeDefaultVersionWhenUnspecified = true;</pre><h4>Step 3: Annotate Controllers</h4><pre>[ApiVersion(&quot;1.0&quot;)]</pre><h4>Step 4: Add New Versions for Breaking Changes</h4><pre>[ApiVersion(&quot;1.0&quot;, Deprecated = true)]<br>[ApiVersion(&quot;2.0&quot;)]</pre><h4>Step 5: Automate Contract Testing</h4><p>Run smoke tests across all supported versions in CI/CD pipelines to catch unintended breaking changes.</p><h4>Step 6: Document and Communicate</h4><ul><li>Publish separate Swagger/OpenAPI specs: /swagger/v1/swagger.json, /swagger/v2/swagger.json.</li><li>Add a <strong>version switcher</strong> in your docs.</li><li>Show <strong>deprecation banners</strong> in v1 docs linking to v2 equivalents.</li><li>Keep examples executable per version.</li></ul><blockquote><em>Good documentation is often the real client interface — invest in it as much as the code.</em></blockquote><h4>Step 7: Cap the Number of Live Versions</h4><p>Support <strong>at most two versions</strong> at once (current + previous). Sunsetting older ones reduces maintenance cost and complexity.</p><h3>Real-World Applications of API Versioning</h3><ul><li><strong>Enterprise SaaS</strong>: Let mobile apps lag behind without breaking.</li><li><strong>B2B APIs</strong>: Allow third-party clients to migrate at their own pace.</li><li><strong>Microservices</strong>: Decouple evolution of service-to-service contracts.</li></ul><p>Most organizations settle on supporting <strong>two versions simultaneously</strong>.</p><h3>How the Asp.Versioning Package Works Under the Hood</h3><p>The Asp.Versioning libraries integrate into ASP.NET Core’s request pipeline:</p><ol><li><strong>Readers</strong> extract version info from path, query, headers, or media type.</li><li><strong>Action selection</strong> matches only controller actions tagged with compatible [ApiVersion].</li><li><strong>Fallbacks</strong> apply defaults when no version is specified.</li><li><strong>Reporting</strong> adds response headers (api-supported-versions, api-deprecated-versions).</li><li><strong>Conventions</strong> allow applying versions globally without repeating attributes.</li></ol><p>It filters eligible actions based on the requested version.</p><h3>Conclusion</h3><p>API versioning is essential for any production Web API. In .NET Core, the Asp.Versioning packages provide first-class support to evolve your services safely.</p><p>By defining breaking rules, automating contract testing, investing in version-aware documentation, and capping the number of active versions, you set your API up for long-term stability and client trust.</p><p>This is exactly how large platforms like GitHub, Stripe, and Microsoft Graph manage their APIs, and your .NET Core projects can follow the same path.</p><p><strong>Juan Andrés Leiva</strong><br>I write about .NET architecture, API design, and DevOps.<br>👉 Follow for deep technical dives and production-ready strategies.<br>💬 Share your thoughts or questions in the comments — I reply to all messages.<br><a href="https://github.com/jandresleiva">GitHub</a> · <a href="https://www.linkedin.com/in/juan-andres-leiva">LinkedIn</a> · <a href="https://medium.com/@andresleiva.4">Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e0d2131270b" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-implement-api-versioning-in-net-core-web-apis-best-practices-and-migration-guide-1e0d2131270b">How to Implement API Versioning in .NET Core Web APIs: Best Practices and Migration Guide</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[Vector Databases Explained: Technology, AI Use Cases, and a Hands-On Example]]></title>
            <link>https://ai.plainenglish.io/vector-databases-explained-technology-ai-use-cases-and-a-hands-on-example-16ac909e8600?source=rss-c76ca4406d24------2</link>
            <guid isPermaLink="false">https://medium.com/p/16ac909e8600</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Juan Andrés Leiva]]></dc:creator>
            <pubDate>Wed, 24 Sep 2025 07:47:00 GMT</pubDate>
            <atom:updated>2025-09-24T07:47:00.507Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In my <a href="https://ai.plainenglish.io/cosine-difference-in-multidimensional-spaces-the-math-behind-vector-databases-6c3dd9a3bce5">previous article</a>, I broke down the math behind cosine difference and why it matters for vector search.<br> This time, let’s move from <strong>theory</strong> to <strong>practice</strong>: how vector databases actually work, where they fit in modern AI systems, and how you can start using one today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6toAsBiobu3mwW56" /></figure><h3>What Is a Vector Database?</h3><p>A <strong>vector database</strong> is a specialized system designed to store and query high-dimensional vectors efficiently.<br> Unlike relational databases, which optimize for joins and structured queries, vector databases are optimized for <strong>similarity search</strong> — answering questions like:</p><ul><li><em>Which items in my dataset are most similar to this one?</em></li><li><em>What documents are semantically close to this query?</em></li><li><em>Which images are visually related to this picture?</em></li></ul><p>They achieve this by implementing <strong>Approximate Nearest Neighbor (ANN)</strong> algorithms on top of scalable storage and indexing structures. Common techniques include HNSW (Hierarchical Navigable Small World graphs), IVF (Inverted File Index), and PQ (Product Quantization).</p><h3>Why Do AI Systems Need Vector Databases?</h3><p>AI models — especially large language models (LLMs) and multimodal models — produce embeddings: <strong>dense vector representations of text, images, or audio</strong>.<br> Storing these embeddings in a vector database enables a range of practical use cases:</p><h4>Semantic Search</h4><p>Search results ranked by meaning instead of keywords. For example:</p><ul><li>Query: <em>“What is the capital of France?”</em></li><li>Result: <em>“Paris is the capital city of France.”</em><br> Even if the exact word “capital” isn’t present, the embedding encodes semantic closeness.</li></ul><h4>Retrieval-Augmented Generation (RAG)</h4><p>Vector databases feed relevant context into LLMs.<br> Instead of asking ChatGPT to “hallucinate,” you can fetch relevant documents and pass them as grounding context.</p><h4>Image &amp; Multimedia Search</h4><p>Embedding models can transform images into vectors. Vector databases then allow queries like <em>“find pictures similar to this one”</em>.</p><h4>Recommendation Systems</h4><p>User behaviors are encoded into vectors, and similarity queries recommend items that “feel” alike in embedding space.</p><h3>Popular Vector Database Options</h3><p>When selecting a vector database for your project, consider these key factors:</p><p><strong>Scale and Performance</strong></p><ul><li><strong>FAISS</strong>: Best for prototyping and small-to-medium datasets (&lt; 1M vectors). Runs in-memory, no server management needed.</li><li><strong>Pinecone</strong>: Handles billions of vectors with sub-100ms latency. Managed service means no infrastructure overhead.</li><li><strong>Milvus</strong>: Open-source scalability with fine-grained control. Better for large enterprises with specific compliance needs.</li></ul><p><strong>Algorithm Trade-offs</strong></p><ul><li><strong>HNSW</strong>: Excellent query speed and accuracy, but higher memory usage. Ideal for real-time applications.</li><li><strong>IVF</strong>: Lower memory footprint, good for write-heavy workloads, slightly slower queries.</li><li><strong>PQ (Product Quantization)</strong>: Dramatically reduces storage (10–100x compression), with some accuracy trade-off.</li></ul><p><strong>Hybrid Search Capabilities</strong> Some databases like Weaviate combine vector search with traditional keyword search, enabling queries like: “Find AI articles published after 2023” + semantic similarity. This hybrid approach often produces better results than pure vector search alone.</p><p><strong>Cost Considerations</strong> Vector storage can become expensive at scale. A million 1536-dimensional vectors requires ~6GB of storage, plus index overhead. Factor in both storage and compute costs when planning your architecture.</p><h3>Scale and Use Case Context</h3><h4><strong>Dataset Size Thresholds</strong></h4><p>Vector databases shine when you cross certain complexity thresholds:</p><ul><li><strong>&lt; 10,000 vectors</strong>: Simple in-memory solutions or basic libraries often suffice</li><li><strong>10K — 1M vectors</strong>: Dedicated vector databases become beneficial for performance</li><li><strong>&gt; 1M vectors</strong>: Vector databases become essential — traditional approaches fail</li></ul><h4><strong>Real-World Scale Examples</strong></h4><ul><li><strong>E-commerce recommendation</strong>: Amazon likely stores billions of product embeddings</li><li><strong>Enterprise knowledge base</strong>: A company with 100K documents might generate 10M+ chunk embeddings for RAG</li><li><strong>Image search</strong>: Pinterest or Unsplash manage hundreds of millions of image embeddings</li></ul><h4><strong>When NOT to Use Vector Databases</strong></h4><p>Don’t reach for vector databases when:</p><ul><li>You have structured data with clear relationships (use SQL databases)</li><li>Your search requirements are purely keyword-based (use Elasticsearch)</li><li>Your dataset is small and changes frequently (simple caching might suffice)</li><li>You need ACID transactions or complex business logic (stick with traditional databases)</li></ul><p><strong>The AI Context</strong> In 2024–2025, vector databases have become infrastructure, not luxury. With embedding models becoming commoditized and RAG architectures standard, the question isn’t “Should I use a vector database?” but rather “Which one fits my specific needs?”</p><p>As multimodal models advance, expect to store not just text embeddings, but image, audio, and video vectors in the same systems — making vector databases even more central to AI application architecture.</p><h3>Hands-On Example: Using Pinecone for Semantic Search</h3><p>Let’s walk through a minimal example: store text embeddings and query them for similarity.</p><h4>1. Install dependencies</h4><pre>pip install &quot;pinecone-client&gt;=3&quot; &quot;openai&gt;=1.40&quot;</pre><h4>2. Initialize Pinecone</h4><pre>import os<br>import time<br>from pinecone import Pinecone, ServerlessSpec<br>from openai import OpenAI<br><br>INDEX_NAME = &quot;example-index&quot;<br>MODEL = &quot;text-embedding-3-small&quot;  # 1536 dims<br>DIM = 1536<br><br># Use env vars instead of hardcoding keys:<br># export PINECONE_API_KEY=...<br># export OPENAI_API_KEY=...<br>pc = Pinecone(api_key=os.environ[&quot;PINECONE_API_KEY&quot;])<br>client = OpenAI(api_key=os.environ[&quot;OPENAI_API_KEY&quot;])<br><br># Create (serverless) index if it doesn&#39;t exist<br>if INDEX_NAME not in [idx.name for idx in pc.list_indexes()]:<br>    pc.create_index(<br>        name=INDEX_NAME,<br>        dimension=DIM,<br>        metric=&quot;cosine&quot;,<br>        spec=ServerlessSpec(cloud=&quot;aws&quot;, region=&quot;us-east-1&quot;),<br>    )<br>    # Wait for index to be ready<br>    while not pc.describe_index(INDEX_NAME).status[&quot;ready&quot;]:<br>        time.sleep(1)<br><br>index = pc.Index(INDEX_NAME)</pre><h4>3. Generate embeddings with OpenAI</h4><pre>texts = [<br>    &quot;The Eiffel Tower is in Paris&quot;,<br>    &quot;The Colosseum is in Rome&quot;,<br>    &quot;The Statue of Liberty is in New York&quot;,<br>]<br>emb_data = client.embeddings.create(model=MODEL, input=texts).data<br>vectors = [<br>    {&quot;id&quot;: str(i), &quot;values&quot;: d.embedding, &quot;metadata&quot;: {&quot;text&quot;: t}}<br>    for i, (t, d) in enumerate(zip(texts, emb_data))<br>]</pre><h4>4. Upsert vectors into Pinecone</h4><pre>index.upsert(vectors=vectors)</pre><h4>5. Run a similarity query</h4><pre>query = &quot;What city is the Eiffel Tower located in?&quot;<br>q_vec = client.embeddings.create(model=MODEL, input=query).data[0].embedding<br>results = index.query(vector=q_vec, top_k=2, include_metadata=True)<br>print(results)</pre><p>You’ll see Pinecone return the closest matches, ranked by <strong>cosine similarity</strong>.</p><h3>Why This Matters</h3><p>The workflow above is the backbone of many production AI systems today. From chatbots with grounded answers to enterprise knowledge retrieval, vector databases solve the problem of <strong>fast and scalable similarity search in high dimensions</strong>.</p><p>As models grow larger and multimodal embeddings become standard, vector databases will only become more central.</p><h3>Wrap-Up</h3><p>In the last article, we explored <strong>cosine difference mathematically</strong>.</p><p>Now you’ve seen how that concept scales into real infrastructure: <strong>vector databases</strong> powering semantic search, RAG, recommendations, and beyond.</p><p>If you’re building AI systems in 2025, you’ll likely end up using one — and now you know where to start.</p><p>✍️ <strong>Juan Andrés Leiva</strong><br> I write about AI, .NET architecture, and production-ready DevOps.<br> 👉 Follow for deep technical dives and practical guides.<br> 💬 Share your thoughts in the comments — I reply to all.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16ac909e8600" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/vector-databases-explained-technology-ai-use-cases-and-a-hands-on-example-16ac909e8600">Vector Databases Explained: Technology, AI Use Cases, and a Hands-On Example</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence 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[React useState Anti-Patterns Every Reviewer Should Flag]]></title>
            <link>https://javascript.plainenglish.io/react-usestate-anti-patterns-every-reviewer-should-flag-52f41742cd16?source=rss-c76ca4406d24------2</link>
            <guid isPermaLink="false">https://medium.com/p/52f41742cd16</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Juan Andrés Leiva]]></dc:creator>
            <pubDate>Wed, 24 Sep 2025 01:11:27 GMT</pubDate>
            <atom:updated>2025-10-16T01:31:18.240Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>React’s useState hook looks simple. But in real projects, most bugs I review come from developers <strong>using it in the wrong situations</strong>.</p><p>If you’re doing code reviews, you need to know how to <strong>spot </strong><strong>useState anti-patterns fast</strong>, why they’re problematic, and what the correct solution looks like. This article is your guide.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zSBK_EJvMdundl1m" /></figure><h3>1. Storing Derived Data</h3><p><strong>Bad code</strong></p><pre>const [fullName, setFullName] = useState(`${user.first} ${user.last}`);<br>useEffect(() =&gt; setFullName(`${user.first} ${user.last}`), [user]);</pre><p>🔍 <strong>What to flag in review</strong><br>Effects that <em>only</em> update state from props. That’s a red flag for duplicated state.</p><blockquote><strong>Derived data</strong> means a value you can <strong>calculate from existing props or state</strong> instead of storing it separately in useState</blockquote><p>✅ <strong>Better code<br></strong>Don’t store derived data. Compute directly or memoize if expensive.</p><pre>const fullName = `${user.first} ${user.last}`;</pre><h3>2. Mirroring Props Into Local State</h3><p><strong>Bad code</strong></p><pre>function Input({ value }) {<br>  const [localValue, setLocalValue] = useState(value);<br>}</pre><p>🔍 <strong>What to flag</strong><br>useState initialized from props without a clear reason. This desyncs when the parent updates.</p><p>✅ <strong>Better code<br></strong>Use props directly, lift state up, or resync only on identity change.</p><ul><li>Use value directly (controlled).</li><li>Lift state up if the child should not own it.</li><li>Only sync on <em>record identity change</em>, not every prop update.</li></ul><h3>3. Mutating Objects or Arrays</h3><p><strong>Bad code</strong></p><pre>items.push(newItem);<br>setItems(items);ty</pre><p>🔍 <strong>What to flag</strong><br>Look for push, splice, or direct property assignment.</p><p>✅ <strong>Better code<br></strong>Use immutable updates ([...prev, newItem], {...prev, key: value}).</p><pre>setItems(prev =&gt; [...prev, newItem]);</pre><h3>4. Using State for Values That Don’t Drive UI</h3><p><strong>Bad code</strong></p><pre>const [timeoutId, setTimeoutId] = useState&lt;number&gt;();</pre><p>🔍 <strong>What to flag<br></strong>Values like timers, refs, or DOM handles in state. They don’t trigger renders.</p><p>✅ <strong>Better code<br></strong>Use useRef for mutable values that don’t affect rendering.</p><pre>const timeoutId = useRef&lt;number&gt;();</pre><h3>5. Setting State During Render</h3><p><strong>Bad code</strong></p><pre>if (!ready &amp;&amp; expensiveCheck()) setReady(true);</pre><p>🔍 <strong>What to flag</strong><br>Any setState call inside render logic → infinite re-renders.</p><p>✅ <strong>Better code<br></strong>Move side-effects into useEffect.</p><pre>useEffect(() =&gt; {<br>  if (expensiveCheck()) setReady(true);<br>}, []);</pre><h3>6. Forgetting Functional Updates</h3><p><strong>Bad code</strong></p><pre>setCount(count + 1);</pre><p>🔍 <strong>What to flag</strong><br>Counters, pagination, or increments that rely on count directly.</p><p>✅ <strong>Better code<br></strong>Use functional form.</p><pre>setCount(c =&gt; c + 1);</pre><h3>7. State Explosion (Too Many Booleans)</h3><p><strong>Bad code</strong></p><pre>const [isSaving, setIsSaving] = useState(false);<br>const [hasError, setHasError] = useState(false);<br>const [step, setStep] = useState(0);</pre><p>🔍 <strong>What to flag</strong><br>Multiple booleans tracking workflow → “boolean soup”.</p><p>✅ <strong>Better code</strong></p><pre>type State = { status: &#39;idle&#39;|&#39;saving&#39;|&#39;error&#39;; step: number };</pre><p>Use useReducer for workflows.</p><pre>type State = { step: number; status: &#39;idle&#39;|&#39;saving&#39;|&#39;error&#39;|&#39;complete&#39; };<br>type Action =<br>  | { type: &#39;NEXT&#39; }<br>  | { type: &#39;SAVE&#39; }<br>  | { type: &#39;ERROR&#39; }<br>  | { type: &#39;DONE&#39; };<br><br>function reducer(state: State, action: Action): State {<br>  switch (action.type) {<br>    case &#39;SAVE&#39;: return { ...state, status: &#39;saving&#39; };<br>    case &#39;ERROR&#39;: return { ...state, status: &#39;error&#39; };<br>    case &#39;DONE&#39;: return { ...state, status: &#39;complete&#39; };<br>    case &#39;NEXT&#39;: return { ...state, step: state.step + 1 };<br>  }<br>}<br><br>const [state, dispatch] = useReducer(reducer, { step: 0, status: &#39;idle&#39; });</pre><h3>8. Overusing State for Async Data</h3><p><strong>Bad code</strong></p><pre>const [user, setUser] = useState&lt;User | null&gt;(null);<br>useEffect(() =&gt; { fetch(&#39;/api/user&#39;).then(setUser); }, []);</pre><p>🔍 <strong>What to flag</strong><br>Every component writing its own fetch + isLoading + error.</p><p>✅ <strong>Better code</strong><br>Encapsulate in a custom hook (useUser) or use React Query/SWR.</p><h3>9. Conditional Hook Declarations</h3><p><strong>Bad code</strong></p><pre>if (enabled) {<br>  const [flag, setFlag] = useState(false);<br>}</pre><p>🔍 <strong>What to flag<br></strong>Hooks declared inside if, for, or after returns. Violates Rules of Hooks.</p><p>✅ <strong>Better code</strong><br>Hooks must always be top-level and unconditional.</p><h3>10. Redundant State Instead of Memo</h3><p><strong>Bad code</strong></p><pre>const [filtered, setFiltered] = useState(() =&gt; heavyFilter(data, q));<br>useEffect(() =&gt; setFiltered(heavyFilter(data, q)), [data, q]);</pre><p>🔍 <strong>What to flag</strong><br>Effects that recalcuate and storUse useMemo for expensive derivations.e values derived from other state.</p><p>✅ <strong>Better code<br></strong>Use useMemo for expensive derivations.</p><pre>const filtered = useMemo(() =&gt; heavyFilter(data, q), [data, q]);</pre><h3>11. Duplicating a Source of Truth</h3><p><strong>Bad code</strong></p><pre>const [cartCount, setCartCount] = useState(cart.items.length);</pre><p>🔍 <strong>What to flag<br></strong>When state equals something.length or a calculated prop. Duplication = desync risk.</p><p>✅ <strong>Better code<br></strong>Compute directly from the source array or object.</p><pre>const cartCount = cart.items.length;</pre><h3>12. Multiple Interdependent setState Calls</h3><p><strong>Bad code</strong></p><pre>setStart(v);<br>setEnd(v + 10);</pre><p>🔍 <strong>What to flag</strong><br>Several states updated together in sequence.</p><p>✅ <strong>Better code<br></strong>Consolidate into one state object or useReducer.</p><pre>setRange({ start: v, end: v + 10 });</pre><p>Or consolidate with useReducer.</p><h3>13. Debouncing/Throttling With Raw State</h3><p><strong>Bad code</strong></p><pre>useEffect(() =&gt; {<br>  const id = setTimeout(() =&gt; search(query), 300);<br>  return () =&gt; clearTimeout(id);<br>}, [query]);</pre><p>🔍 <strong>What to flag</strong><br>Search inputs with manual timeouts everywhere.</p><p>✅ <strong>Better code</strong><br>Extract into a useDebounce hook or use React’s useDeferredValue.<br><a href="https://react.dev/reference/react/useDeferredValue">https://react.dev/reference/react/useDeferredValue</a></p><h3>14. State Colocation Errors</h3><p><strong>Red flag scenarios</strong></p><ul><li>State lifted “just in case” at the top → excessive re-renders.</li><li>Same state duplicated across siblings.</li></ul><p>🔍 <strong>What to flag</strong><br>PRs where reviewers see state in the wrong place. Ask: <em>“who actually owns this state?”</em></p><p>✅ <strong>Better code</strong><br>Colocate state where it’s used. Lift only when multiple consumers need the same source.</p><h3>Review Checklist for useState</h3><p>This list is similar to the one we used in a consultancy I worked for. It became our standard checklist during React code reviews, helping us catch problems early and keep large codebases consistent.</p><p>When you see useState in a pull request, ask:</p><ul><li><strong>Is this derived from props/state?</strong> If yes → don’t store it.</li><li><strong>Does it affect rendering?</strong> If no → use useRef.</li><li><strong>Does it depend on previous state?</strong> If yes → functional update.</li><li><strong>Are there multiple booleans for workflow?</strong> If yes → useReducer.</li><li><strong>Is state being set in render or hooks declared conditionally?</strong> Reject.</li></ul><p>This list is similar to the one we used in a consultancy I worked for. It was standard for code reviews on React codebases.</p><h3>Wrap up</h3><p>Most useState bugs are <strong>predictable mistakes</strong> that show up in code reviews again and again.</p><p>As a reviewer, flagging these patterns early saves your team hours of debugging and prevents subtle desync issues. Use this guide as your <strong>mental checklist</strong> whenever you see useState in a PR.</p><p><strong>Juan Andrés Leiva</strong><br>I write about .NET, React, and cloud architecture.<br>👉 Follow me for deep dives and production-ready strategies.<br>💬 Share your thoughts in the comments — I reply to all.<br><a href="https://github.com/jandresleiva">GitHub</a> · <a href="https://www.linkedin.com/in/juan-andres-leiva">LinkedIn</a> · <a href="https://medium.com/@andresleiva.4">Medium</a></p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52f41742cd16" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/react-usestate-anti-patterns-every-reviewer-should-flag-52f41742cd16">React useState Anti-Patterns Every Reviewer Should Flag</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[React Canary <Activity />: Hide UI Without Unmounting and Preserve State Instantly]]></title>
            <link>https://javascript.plainenglish.io/react-canary-introduces-activity-a-new-primitive-for-async-state-ce879d1ee063?source=rss-c76ca4406d24------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce879d1ee063</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Juan Andrés Leiva]]></dc:creator>
            <pubDate>Mon, 22 Sep 2025 19:53:37 GMT</pubDate>
            <atom:updated>2025-09-23T01:31:01.883Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bj79WC9VGs7yOdnT" /></figure><h3>What is &lt;Activity /&gt;?</h3><p>React has introduced a new component, <strong>&lt;Activity /&gt;</strong>, in the <strong>Canary release channel</strong>. It provides a way to <strong>hide parts of your UI</strong> without unmounting them. Unlike conditional rendering or CSS hacks, &lt;Activity /&gt; preserves the <strong>DOM and state</strong> while <strong>cleaning up side effects</strong> (Effects) when hidden, and then restores them instantly when made visible again.</p><p>👉 Official docs: <a href="https://react.dev/reference/react/Activity">React </a><a href="https://react.dev/reference/react/Activity">&lt;Activity /&gt; reference</a><br>👉 Canary background: <a href="https://react.dev/blog/2023/05/03/react-canaries">React Canaries release notes</a><br>👉 Implementation details: <a href="https://github.com/facebook/react/pull/34374">PR #34374 on GitHub</a></p><h3>What is changing?</h3><p>Most React apps hide UI with conditional rendering:</p><pre>{isOpen &amp;&amp; &lt;Sidebar /&gt;}</pre><p>This works, but it <strong>unmounts</strong> the component and discards local state. Switching back means rebuilding everything from scratch.</p><p>Others rely on CSS:</p><pre>.sidebar {<br>  display: none;<br>}</pre><p>This preserves DOM and state but leaves <strong>Effects running</strong>, which can cause memory leaks and stale work.</p><p>&lt;Activity /&gt; combines the best of both:</p><ul><li><strong>Hides via </strong><strong>display: none</strong>.</li><li><strong>Preserves DOM and state</strong>.</li><li><strong>Cleans up Effects</strong> while hidden.</li><li><strong>Restores instantly</strong> when shown again.</li></ul><h3>How It Works</h3><pre>import { unstable_Activity as Activity } from &quot;react&quot;;<br><br>&lt;Activity mode={isOpen ? &quot;visible&quot; : &quot;hidden&quot;}&gt;<br>  &lt;Sidebar /&gt;<br>&lt;/Activity&gt;</pre><ul><li><strong>mode=&quot;visible&quot; or </strong><strong>&quot;hidden&quot;</strong> toggles visibility.</li><li>Hidden trees are still in the DOM but not visible.</li><li><strong>State is preserved</strong>, Effects are paused, and restored on show.</li><li>React schedules hidden updates at <strong>lower priority</strong>, so your app stays responsive.</li></ul><h3>Use Cases</h3><ol><li><strong>Tabs, drawers, and sidebars</strong> — Keep scroll, inputs, and local state intact when toggling views.</li><li><strong>Pre-render hidden UI</strong> — Background-render likely next screens for instant reveal.</li><li><strong>Performance during load</strong> — Render non-critical panels hidden, ready for use later.</li><li><strong>Draft restoration</strong> — Users won’t lose input when flipping between sections.</li></ol><h3>How It Compares</h3><ul><li><strong>Conditional rendering:</strong> Unmounts → <strong>state lost</strong>.</li><li><strong>CSS </strong><strong>display: none:</strong> Keeps DOM/state but <strong>Effects still run</strong>.</li><li><strong>Suspense / Transitions:</strong> Handle async rendering and update priority; &lt;Activity /&gt; handles <strong>visibility + lifecycle</strong>.</li></ul><h3>Caveats</h3><ul><li>Hidden subtrees still <strong>re-render at low priority</strong> — don’t background giant, fast-changing trees unnecessarily.</li><li>Effects at higher levels (outside the Activity) won’t be paused.</li><li>When combined with <strong>View Transitions</strong>, showing an &lt;Activity /&gt; inside a transition will trigger enter/exit animations.</li></ul><h3>Try It Today</h3><p>Install the canary version</p><pre>npm install react@canary react-dom@canary</pre><p>And test the new feature</p><pre>&lt;Activity mode={isOpen ? &quot;visible&quot; : &quot;hidden&quot;}&gt;<br>  &lt;Panel /&gt;<br>&lt;/Activity&gt;</pre><blockquote><em>Note: import via </em><em>unstable_Activity in Canary. The API will stabilize before semver release.</em></blockquote><h3>Bottom Line</h3><p>React’s &lt;Activity /&gt; is a <strong>new primitive for visibility management</strong>:</p><ul><li><strong>Hide without unmounting</strong></li><li><strong>Preserve DOM and state</strong></li><li><strong>Pause side effects while hidden</strong></li></ul><p>It’s a small API, but it solves one of the most common UI pain points. With &lt;Activity /&gt;, React continues its trend of making <strong>async and stateful UI a first-class concern</strong>.</p><p><strong>Juan Andrés Leiva</strong><br> I write about .NET, React, and cloud architecture.<br> 👉 Follow me for deep dives and production-ready strategies.<br> 💬 Share your thoughts in the comments — I reply to all.<br><a href="https://github.com/jandresleiva">GitHub</a> · <a href="https://www.linkedin.com/in/juan-andres-leiva">LinkedIn</a> · <a href="https://medium.com/@andresleiva.4">Medium</a></p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce879d1ee063" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/react-canary-introduces-activity-a-new-primitive-for-async-state-ce879d1ee063">React Canary &lt;Activity /&gt;: Hide UI Without Unmounting and Preserve State Instantly</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>
    </channel>
</rss>